Verified contractExactGPL-2.0-or-later
AccountableYield
Address0x4f4ec9e4ddcadcda2e9cd79c54da4e39c5210019
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.27
- Same code
Only this contract
Details
- Compiler
- solc 0.8.27+commit.40a35a09
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- GPL-2.0-or-later
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,383,542
- Creation transaction
- 0x41ed78b1d9…ea26f11e3b
32 files
- src/strategies/AccountableYield.solmain32.37 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol8.91 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol6.59 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.19 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol3.86 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol4.36 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol12.18 KB
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol880 B
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol6.72 KB
- lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol472 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol5.77 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.26 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol3.93 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol869 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol15.12 KB
- src/constants/Errors.sol12.4 KB
- src/interfaces/IAccess.sol4.73 KB
- src/interfaces/IAccountableAsyncVault.sol12.19 KB
- src/interfaces/IAccountableStrategy.sol22.53 KB
- src/interfaces/IAccountableWithdrawalQueue.sol3.85 KB
- src/interfaces/IAccountableYield.sol5.24 KB
- src/interfaces/IAsyncVaultFactory.sol1.19 KB
- src/interfaces/IDepositGateway.sol8.09 KB
- src/interfaces/IFeeManager.sol7.13 KB
- src/interfaces/IGlobalRegistry.sol2.52 KB
- src/interfaces/IRecoverable.sol446 B
- src/strategies/AccountableStrategy.sol17.71 KB
- src/strategies/storage/StrategyStorage.sol2.25 KB
- src/strategies/storage/YieldStorage.sol2.32 KB
src/strategies/AccountableYield.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;
import "../constants/Errors.sol";
import {IFeeManager} from "../interfaces/IFeeManager.sol";
import {IDepositGateway} from "../interfaces/IDepositGateway.sol";
import {IAccountableVault} from "../interfaces/IAccountableAsyncVault.sol";
import {IAccountableYield, YieldInitParams} from "../interfaces/IAccountableYield.sol";
import {IAccountableWithdrawalQueue} from "../interfaces/IAccountableWithdrawalQueue.sol";
import {
IAccountableStrategy,
IStrategyVaultHooks,
IFeeManagerHooks,
IAccountableLoan,
LoanState,
LoanTerms
} from "../interfaces/IAccountableStrategy.sol";
import {YieldStorage} from "./storage/YieldStorage.sol";
import {AccountableStrategy} from "./AccountableStrategy.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
/// @title AccountableYield
/// @custom:security-contact [email protected]
/// @notice NAV-based yield strategy with sync deposits and async redemptions
contract AccountableYield is UUPSUpgradeable, ReentrancyGuardUpgradeable, AccountableStrategy, YieldStorage {
using Math for uint256;
using SafeERC20 for IERC20;
/// @notice Minimum NAV grace period (1 hour)
uint256 public constant MIN_NAV_GRACE_PERIOD = 1 hours;
/// @notice Default NAV grace period (24 hours)
uint256 public constant DEFAULT_NAV_GRACE_PERIOD = 24 hours;
/// @notice Sentinel: instant fulfillment disabled in OngoingDynamic (queue only)
uint256 public constant INSTANT_REDEEM_DISABLED = type(uint256).max;
/// @dev Reverts if NAV is stale (grace period expired)
modifier whenNotStale() {
if (_navIsStale()) revert NAVGracePeriodExpired();
_;
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/// @notice Initialize the yield strategy
/// @param params Initialization parameters
function initialize(YieldInitParams memory params) external initializer {
__Pausable_init();
__UUPSUpgradeable_init();
__ReentrancyGuard_init();
if (params.asset == address(0)) revert ZeroAddress();
if (params.globals == address(0)) revert ZeroAddress();
if (params.feeManager == address(0)) revert ZeroAddress();
if (params.investmentManager == address(0)) revert ZeroAddress();
asset = params.asset;
globals = params.globals;
feeManager = params.feeManager;
loanState = LoanState.Initialized;
investmentManager = params.investmentManager;
managerFeeRecipient = params.investmentManager;
penaltiesEnabled = true;
peakSharePrice = PRECISION;
navGracePeriod = DEFAULT_NAV_GRACE_PERIOD;
_makeVault(IERC20(params.asset), params.sharesTransferable, params.permissionLevel, params.name, params.symbol);
IERC20(params.asset).forceApprove(vault, type(uint256).max);
IERC20(params.asset).forceApprove(params.feeManager, type(uint256).max);
}
/// @notice Reinitializes the peak ratio
function reinitialize(uint256 shares) external onlyManagerOrSecurityAdmin reinitializer(2) {
address vault_ = vault;
if (shares > 0) {
address treasury = IFeeManager(feeManager).treasury();
IAccountableVault(vault_).mintShares(shares, treasury);
emit FeeSharesMinted(treasury, shares);
}
uint256 supply = IAccountableVault(vault_).totalSupply();
peakSharePrice = supply == 0 ? PRECISION : _totalAssets(vault_).mulDiv(PRECISION, supply);
emit PeakSharePriceReset(peakSharePrice);
}
/// @inheritdoc IAccountableLoan
/// @dev Uses _loan struct for: minDeposit, minRedeem, maxCapacity, interestInterval, lateInterestPenalty
function setTerms(LoanTerms memory terms) public onlyManager {
_requireLoanTermsNotSet();
if (borrower == address(0)) revert ZeroAddress();
if (dvnPublisher == address(0)) revert ZeroAddress();
if (terms.interestInterval == 0) revert InvalidIntervalLength();
_loan.minRedeem = terms.minRedeem;
_loan.minDeposit = terms.minDeposit;
_loan.maxCapacity = terms.maxCapacity;
_loan.interestInterval = terms.interestInterval;
_loan.lateInterestPenalty = terms.lateInterestPenalty;
_loan.lateInterestGracePeriod = terms.lateInterestGracePeriod;
loanState = LoanState.TermsSet;
_loan.termsSetTime = block.timestamp;
emit LoanTermsSet(
terms.minCapacity,
terms.maxCapacity,
terms.interestRate,
terms.lateInterestPenalty,
terms.interestInterval,
terms.duration
);
}
/// @inheritdoc IAccountableLoan
function updateTerms(LoanTerms memory terms) external onlyManager {
_requireLoanOngoing();
_accruePenalties();
_accrueFees();
_pendingTerms = terms;
emit LoanTermsSet(
terms.minCapacity,
terms.maxCapacity,
terms.interestRate,
terms.lateInterestPenalty,
terms.interestInterval,
terms.duration
);
}
/// @inheritdoc IAccountableYield
function acceptTerms() external nonReentrant onlyBorrower whenNotPaused {
if (loanState == LoanState.TermsSet) {
loanState = LoanState.OngoingDynamic;
_lastFeeTime = block.timestamp;
_loan.startTime = block.timestamp;
navGraceDeadline = block.timestamp + navGracePeriod;
emit TermsAccepted();
return;
}
LoanTerms memory terms = _pendingTerms;
delete _pendingTerms;
uint256 totalAssets = _totalPrincipalAssets(vault);
if (terms.maxCapacity < totalAssets) revert CapacityTooLow();
_accruePenalties();
_loan.minRedeem = terms.minRedeem;
_loan.minDeposit = terms.minDeposit;
_loan.maxCapacity = terms.maxCapacity;
_loan.interestInterval = terms.interestInterval;
_loan.lateInterestPenalty = terms.lateInterestPenalty;
_loan.lateInterestGracePeriod = terms.lateInterestGracePeriod;
_loan.termsUpdateTime = block.timestamp;
_updateDelinquentStatus();
emit TermsAccepted();
}
/// @inheritdoc IAccountableYield
function rejectTerms() external onlyBorrower whenNotPaused {
if (loanState == LoanState.TermsSet) {
delete _loan;
loanState = LoanState.Initialized;
emit TermsRejected();
return;
}
delete _pendingTerms;
emit TermsRejected();
}
/// @inheritdoc IAccountableStrategy
function setReserveThreshold(uint256 threshold)
external
override(AccountableStrategy, IAccountableStrategy)
onlyManager
{
if (threshold > BASIS_POINTS) revert ThresholdTooHigh();
_loan.reserveThreshold = threshold;
_updateDelinquentStatus();
emit ReserveThresholdSet(threshold);
}
/// @inheritdoc IAccountableStrategy
function setDVNPublisher(address publisher) external onlyOperationsAdmin {
if (publisher == address(0)) revert ZeroAddress();
dvnPublisher = publisher;
emit DVNPublisherSet(publisher);
}
/// @inheritdoc IAccountableStrategy
/// @dev Rejects stale measurements to prevent DVN updates from overwriting recent borrow/repay accounting
function publishRate(uint256 newDeployedValue, uint256 measuredAt) external {
if (msg.sender != dvnPublisher) revert Unauthorized();
_requireLoanOngoing();
// Must be newer than last accepted measurement and must be measured after the last flow operation
if (measuredAt <= lastNavMeasuredAt || measuredAt < lastFlowTimestamp) revert StaleMeasurement();
uint256 oldValue = deployedAssets;
deployedAssets = newDeployedValue;
lastNavMeasuredAt = measuredAt;
_accruePenalties();
_accrueFees();
navGraceDeadline = block.timestamp + navGracePeriod;
_updateDelinquentStatus();
emit RatePublished(msg.sender, oldValue, newDeployedValue);
// Notify the deposit gateway so it can close the open epoch at this NAV
// Failure can never block the NAV path, the gateway self-heals via forcePassEpoch
address gateway = depositGateway;
if (gateway != address(0)) {
try IDepositGateway(gateway).onNavUpdate() {}
catch {
emit GatewayNavUpdateFailed(lastNavMeasuredAt);
}
}
}
/// @inheritdoc IAccountableYield
function setNavGracePeriod(uint256 period) external onlyManager {
if (period < MIN_NAV_GRACE_PERIOD) revert InvalidNavGracePeriod();
emit NavGracePeriodSet(navGracePeriod, period);
navGracePeriod = period;
}
/// @inheritdoc IAccountableYield
function setInstantRedeemMaxAge(uint256 maxAge, bool disable) external onlyManager {
uint256 newMaxAge;
if (disable) {
newMaxAge = INSTANT_REDEEM_DISABLED;
} else if (maxAge == 0) {
newMaxAge = 0;
} else {
if (maxAge >= navGracePeriod) revert InvalidInstantRedeemMaxAge();
newMaxAge = maxAge;
}
emit InstantRedeemMaxAgeSet(instantRedeemMaxAge, newMaxAge);
instantRedeemMaxAge = newMaxAge;
}
/// @notice Set the deposit gateway permitted to deposit on behalf of users
/// @dev Once set, onDeposit/onMint reject any other controller, blocking direct deposits; address(0) reopens them
function setDepositGateway(address gateway_) external onlyManager {
// Wiring a gateway bound to a different strategy would block all deposits and strand escrowed funds
if (gateway_ != address(0) && IDepositGateway(gateway_).strategy() != address(this)) {
revert GatewayStrategyMismatch();
}
emit DepositGatewaySet(depositGateway, gateway_);
depositGateway = gateway_;
}
/// @inheritdoc IAccountableLoan
/// @dev This should be callable when paused
/// It is safer to pause and then default to first prevent other operations
function defaultLoan() external onlySafetyModuleOrManager {
_requireLoanOngoing();
// Prevent resetting the timer if default is already pending
if (_defaultValidAt != 0) revert DefaultAlreadyPending();
_defaultValidAt = block.timestamp + 1 days;
emit LoanDefaultInitiated();
}
/// @inheritdoc IAccountableLoan
/// @dev This should be callable when paused
/// Default coverage should be possible at all times if loan is in default
function coverDefault(uint256 assets) external nonReentrant onlySafetyModuleOrManager {
_requireLoanInDefault();
loanState = LoanState.InDefaultClaims;
IAccountableVault(vault).lockAssets(assets, msg.sender);
_updateDelinquentStatus();
emit DefaultCovered(safetyModule, msg.sender, assets);
}
/// @inheritdoc IAccountableLoan
/// @dev Releases assets from vault to borrower for deployment to yield sources
function borrow(uint256 assets) external nonReentrant onlyBorrower whenNotPaused {
_requireLoanOngoing();
_accrueFees();
_accruePenalties();
uint256 available = _availableForRelease();
uint256 maxBorrowable = Math.min(available, assets);
if (maxBorrowable == 0) revert InsufficientAmount();
// Track flow timestamp to prevent stale DVN updates
lastFlowTimestamp = block.timestamp;
// Track outstanding principal
deployedAssets += maxBorrowable;
_loan.outstandingPrincipal += maxBorrowable;
address vault_ = vault;
IAccountableVault(vault_).releaseAssets(maxBorrowable, msg.sender);
_updateDelinquentStatus();
emit Borrowed(msg.sender, maxBorrowable);
}
/// @inheritdoc IAccountableLoan
/// @dev Returns assets to vault from yield sources
/// @dev Borrower can repay more than deployedAssets
/// @dev Payment priority: penalties first, then principal and deployed reduction
function repay(uint256 assets) external nonReentrant onlyBorrower whenNotStale whenNotPaused {
_requireLoanOngoing();
if (assets == 0) revert InsufficientAmount();
_accrueFees();
_accruePenalties();
// Track flow timestamp to prevent stale DVN updates
lastFlowTimestamp = block.timestamp;
uint256 remaining = assets;
// Pay off penalties first
uint256 penalties = accruedPenalties;
if (penalties > 0) {
uint256 penaltyPayment = Math.min(remaining, penalties);
accruedPenalties = penalties - penaltyPayment;
remaining -= penaltyPayment;
}
// Reduce outstanding principal
if (remaining > 0) {
// Assets are moving from external → vault
uint256 deployed = deployedAssets;
deployedAssets -= Math.min(remaining, deployed);
uint256 outstanding = _loan.outstandingPrincipal;
_loan.outstandingPrincipal = outstanding > remaining ? outstanding - remaining : 0;
}
IERC20(asset).safeTransferFrom(msg.sender, address(this), assets);
address vault_ = vault;
IAccountableVault(vault_).lockAssets(assets, address(this));
_processAvailableWithdrawals();
if (_loan.outstandingPrincipal == 0 && accruedPenalties == 0 && deployedAssets == 0) {
loanState = LoanState.Repaid;
_defaultValidAt = 0; // cancel any pending default so it cannot be accepted later
}
_updateDelinquentStatus();
emit LoanRepaid(assets);
}
/// @inheritdoc IAccountableLoan
/// @dev Not applicable for yield strategy
function prepay() external pure {
revert NotSupportedByStrategy();
}
/// @inheritdoc IAccountableLoan
/// @dev Not applicable for yield strategy
function pay(uint256) external pure {
revert NotSupportedByStrategy();
}
/// @inheritdoc IAccountableLoan
function timeDelinquent() external view returns (uint256) {
uint256 start = delinquencyStartTime;
return start > 0 ? block.timestamp - start : 0;
}
/// @inheritdoc IAccountableYield
function accrueAndProcess() external nonReentrant whenNotStale whenNotPaused returns (uint256 usedAssets) {
_requireLoanOngoing();
_accruePenalties();
_accrueFees();
if (!_maxAgeElapsed()) {
usedAssets = _processAvailableWithdrawals();
}
_updateDelinquentStatus();
}
/// @dev Deposit hook - sync deposit at current NAV price
function onDeposit(address share, uint256 assets, address, address controller)
public
override(AccountableStrategy, IStrategyVaultHooks)
nonReentrant
onlyVault
whenNotStale
whenNotPaused
returns (uint256 price)
{
_requireFromGateway(controller);
_requireMinDepositAmount(assets);
_requireCanDeposit();
_accruePenalties();
_accrueFees();
_requireBelowMaxCapacity(assets);
price = _sharePrice(share);
}
/// @dev Mint hook - sync mint at current NAV price
/// @dev In the current gateway configuration, the hook is never called due to settlement relying on onDeposit
/// The hook is kept with the same revert condition (_requireFromGateway) for future potential compatibility
function onMint(address share, uint256 shares, address, address controller)
public
override(AccountableStrategy, IStrategyVaultHooks)
nonReentrant
onlyVault
whenNotStale
whenNotPaused
returns (uint256 price)
{
_requireFromGateway(controller);
_requireCanDeposit();
_accruePenalties();
_accrueFees();
price = _sharePrice(share);
uint256 assets = shares.mulDiv(price, PRECISION, Math.Rounding.Ceil);
_requireMinDepositAmount(assets);
_requireBelowMaxCapacity(assets);
}
/// @dev Request redeem hook - queue based async
function onRequestRedeem(address share, uint256 shares, address, address)
public
override(AccountableStrategy, IStrategyVaultHooks)
nonReentrant
onlyVault
whenNotPaused
returns (bool canFulfill, uint256 price)
{
if (shares < _loan.minRedeem) revert InsufficientShares();
_accruePenalties();
_accrueFees();
price = _sharePrice(share);
uint256 assets = shares.mulDiv(price, PRECISION);
if (_isInstantRedeem()) {
canFulfill = true;
} else {
uint256 liquidity = _getAvailableLiquidity();
canFulfill = liquidity >= assets && !_navIsStale() && _instantRedeemAllowedByMaxAge();
}
}
function onFeeStructureChange() public override(AccountableStrategy, IFeeManagerHooks) nonReentrant {
super.onFeeStructureChange();
if (loanState == LoanState.OngoingDynamic) {
_accruePenalties();
_accrueFees();
}
}
/// @dev Max deposit based on capacity
function maxDeposit(address, address)
public
view
override(AccountableStrategy, IStrategyVaultHooks)
returns (uint256 maxAssets)
{
uint256 maxCapacity = _loan.maxCapacity;
uint256 totalAssets = _totalPrincipalAssets(vault);
maxAssets = totalAssets < maxCapacity ? maxCapacity - totalAssets : 0;
}
/// @dev Updates the late status of the loan
function updateLateStatus() external whenNotPaused whenNotStale {
_requireLoanOngoing();
_updateDelinquentStatus();
}
/// @dev Accrues fees by minting shares split between manager and treasury
function _accrueFees() internal {
(uint256 performanceFeeShares, uint256 managementFeeShares, uint256 newTotalAssets, uint256 supply) =
_accruedFeeShares();
_lastFeeTime = block.timestamp;
// Advance the high-water mark (a share-price ratio) using the POST-fee price, so the
// same gain is never taxed twice (the fee shares about to be minted dilute the price)
// Only when fee shares are actually minted — skip the degenerate path where computed
// fees meet or exceed total assets (zero shares returned, no gain was taxed)
if (performanceFeeShares + managementFeeShares > 0) {
uint256 hwmSupply = supply + performanceFeeShares + managementFeeShares;
if (hwmSupply != 0) {
uint256 postFeePrice = newTotalAssets.mulDiv(PRECISION, hwmSupply);
if (postFeePrice > peakSharePrice) peakSharePrice = postFeePrice;
}
}
IFeeManager fm = IFeeManager(feeManager);
address vault_ = vault;
address treasury_ = fm.treasury();
address managerFeeRecipient_ = managerFeeRecipient;
uint256 managerShares = 0;
uint256 protocolShares = 0;
// Mint performance fee shares with performance fee split
if (performanceFeeShares > 0) {
uint256 managerPerformanceFeeShares =
performanceFeeShares.mulDiv(fm.managerSplit(address(this), true), BASIS_POINTS);
managerShares += managerPerformanceFeeShares;
protocolShares += performanceFeeShares - managerPerformanceFeeShares;
}
// Mint management fee shares with management fee split
if (managementFeeShares > 0) {
uint256 managerManagementFeeShares =
managementFeeShares.mulDiv(fm.managerSplit(address(this), false), BASIS_POINTS);
managerShares += managerManagementFeeShares;
protocolShares += managementFeeShares - managerManagementFeeShares;
}
if (managerShares > 0) {
IAccountableVault(vault_).mintShares(managerShares, managerFeeRecipient_);
emit FeeSharesMinted(managerFeeRecipient_, managerShares);
}
if (protocolShares > 0) {
IAccountableVault(vault_).mintShares(protocolShares, treasury_);
emit FeeSharesMinted(treasury_, protocolShares);
}
}
/// @dev Calculates accrued fee shares for both performance and management fees
/// @return performanceFeeShares Shares to mint for performance fees
/// @return managementFeeShares Shares to mint for management fees
/// @return newTotalAssets Current total assets
/// @return supply Vault share supply at accrual time (before fee-share mints)
function _accruedFeeShares()
internal
view
returns (uint256 performanceFeeShares, uint256 managementFeeShares, uint256 newTotalAssets, uint256 supply)
{
address vault_ = vault;
newTotalAssets = _totalAssets(vault_);
supply = IAccountableVault(vault_).totalSupply();
if (supply == 0) return (0, 0, newTotalAssets, 0);
IFeeManager fm = IFeeManager(feeManager);
uint256 performanceFeeAssets;
uint256 managementFeeAssets;
// Performance fee on per-share gains above the high-water mark
uint256 peakPrice = peakSharePrice;
uint256 currentPrice = newTotalAssets.mulDiv(PRECISION, supply);
if (currentPrice > peakPrice) {
uint256 gain = (currentPrice - peakPrice).mulDiv(supply, PRECISION);
performanceFeeAssets = gain.mulDiv(fm.performanceFee(address(this)), BASIS_POINTS);
}
// Management fee (time-based annualized fee on total assets)
uint256 timeElapsed = block.timestamp - _lastFeeTime;
if (timeElapsed > 0) {
managementFeeAssets =
newTotalAssets.mulDiv(fm.managementFee(address(this)) * timeElapsed, DAYS_365_SECONDS * BASIS_POINTS);
}
uint256 totalFeeAssets = performanceFeeAssets + managementFeeAssets;
// If no fees or fees are greater than total assets, return early to avoid div by zero
if (totalFeeAssets == 0 || totalFeeAssets >= newTotalAssets) return (0, 0, newTotalAssets, supply);
// Convert fee assets to shares
// shares = feeAssets * supply / (totalAssets - feeAssets)
// This ensures fee recipients receive exactly feeAssets worth of shares
uint256 denominator = newTotalAssets - totalFeeAssets;
if (performanceFeeAssets > 0) {
performanceFeeShares = performanceFeeAssets.mulDiv(supply, denominator, Math.Rounding.Floor);
}
if (managementFeeAssets > 0) {
managementFeeShares = managementFeeAssets.mulDiv(supply, denominator, Math.Rounding.Floor);
}
}
/// @dev Total assets managed = vault assets + deployed assets + accrued penalties
function _totalAssets(address vault_) internal view returns (uint256) {
return IAccountableVault(vault_).totalAssets() + deployedAssets + accruedPenalties;
}
/// @dev Total principal assets = vault assets + outstanding principal
/// Returns total assets not accounting for accrued yield in deployed assets
function _totalPrincipalAssets(address vault_) internal view returns (uint256) {
return IAccountableVault(vault_).totalAssets() + _loan.outstandingPrincipal;
}
/// @dev Share price accounting for pending fees; pro-rata in wind-down states
function _sharePrice(address vault_) internal view override returns (uint256) {
if (loanState == LoanState.Repaid || loanState == LoanState.InDefaultClaims) {
return IAccountableVault(vault_).assetShareRatio();
}
(uint256 performanceFeeShares, uint256 managementFeeShares, uint256 totalAssets, uint256 supply) =
_accruedFeeShares();
supply += performanceFeeShares + managementFeeShares;
if (supply == 0) return PRECISION;
return totalAssets.mulDiv(PRECISION, supply);
}
/// @dev No separate accrued assets for yield strategy
function _accruedAssets(address) internal pure override returns (uint256) {
return 0;
}
/// @dev Available liquidity for withdrawals (vault assets minus reserved)
function _getAvailableLiquidityForProcessing(address vault_) internal view returns (uint256) {
uint256 vaultAssets = IAccountableVault(vault_).totalAssets();
uint256 reservedLiquidity = IAccountableWithdrawalQueue(vault_).reservedLiquidity();
return vaultAssets > reservedLiquidity ? vaultAssets - reservedLiquidity : 0;
}
// @dev Returns the available liquidity after accounting for the required reserves
function _getAvailableLiquidity() internal view returns (uint256) {
address vault_ = vault;
uint256 totalAssets = IAccountableVault(vault_).totalAssets();
uint256 queuedShares = IAccountableWithdrawalQueue(vault_).totalQueuedShares();
uint256 processedWithdrawals = IAccountableWithdrawalQueue(vault_).reservedLiquidity();
uint256 requiredReserves = queuedShares.mulDiv(_sharePrice(vault_), PRECISION) + processedWithdrawals;
return totalAssets > requiredReserves ? totalAssets - requiredReserves : 0;
}
/// @dev Available for release (respects reserves + queue + threshold)
function _availableForRelease() internal view returns (uint256) {
address vault_ = vault;
uint256 vaultAssets = IAccountableVault(vault_).totalAssets();
uint256 requiredLiquidity = _calculateRequiredLiquidity(vault_);
return vaultAssets > requiredLiquidity ? vaultAssets - requiredLiquidity : 0;
}
/// @dev Calculates the required liquidity accounting for the queued/processed withdrawals
function _calculateRequiredLiquidity(address vault_) internal view returns (uint256) {
uint256 queuedShares = IAccountableWithdrawalQueue(vault_).totalQueuedShares();
uint256 queuedValue = queuedShares.mulDiv(_sharePrice(vault_), PRECISION);
uint256 reservedLiquidity = IAccountableWithdrawalQueue(vault_).reservedLiquidity();
uint256 reserveThresholdAmount = _totalAssets(vault_).mulDiv(_loan.reserveThreshold, BASIS_POINTS);
return queuedValue + reservedLiquidity + reserveThresholdAmount;
}
/// @dev Process available withdrawals at current price
function _processAvailableWithdrawals() internal returns (uint256 assetsUsed) {
address vault_ = vault;
uint256 liquidity = _getAvailableLiquidityForProcessing(vault_);
if (liquidity == 0) return 0;
IAccountableWithdrawalQueue q = IAccountableWithdrawalQueue(vault_);
(uint256 maxShares,) = q.previewRequiredShares(liquidity);
if (maxShares == 0) return 0;
assetsUsed = q.processUpToShares(maxShares);
}
/// @dev Returns whether the loan is delinquent based on reserves available
function _isDelinquent() internal view returns (bool) {
address vault_ = vault;
uint256 vaultAssets = IAccountableVault(vault_).totalAssets();
uint256 requiredLiquidity = _calculateRequiredLiquidity(vault_);
return vaultAssets < requiredLiquidity;
}
/// @dev Update delinquency status and accrue penalties
function _updateDelinquentStatus() internal {
bool wasDelinquent = delinquencyStartTime > 0;
bool isCurrentlyDelinquent = _isDelinquent();
// Accrue penalties if currently delinquent
if (wasDelinquent) {
_accruePenalties();
}
if (isCurrentlyDelinquent && !wasDelinquent) {
delinquencyStartTime = block.timestamp;
emit DelinquencyStatusChanged(true, block.timestamp);
} else if (!isCurrentlyDelinquent && wasDelinquent) {
delinquencyStartTime = 0;
emit DelinquencyStatusChanged(false, block.timestamp);
}
}
/// @dev Accrues penalties based on time delinquent past grace period
function _accruePenalties() internal {
if (!penaltiesEnabled) return;
uint256 delinquencyStart_ = delinquencyStartTime;
uint256 lateInterestPenalty_ = _loan.lateInterestPenalty;
if (delinquencyStart_ == 0 || lateInterestPenalty_ == 0) return;
uint256 graceEnd = delinquencyStart_ + _loan.lateInterestGracePeriod;
if (block.timestamp <= graceEnd) return;
uint256 penaltyStart = Math.max(_lastPenaltyTime, graceEnd);
uint256 penaltyTime = block.timestamp - penaltyStart;
if (penaltyTime == 0) return;
// Simple interest on the principal base, exclude already-accrued penalties
address vault_ = vault;
uint256 penaltyBase = IAccountableVault(vault_).totalAssets() + deployedAssets;
uint256 penaltyAmount = penaltyBase.mulDiv(lateInterestPenalty_ * penaltyTime, DAYS_1_SECONDS * BASIS_POINTS);
if (penaltyAmount > 0) {
accruedPenalties += penaltyAmount;
_lastPenaltyTime = block.timestamp;
emit PenaltiesAccrued(penaltyAmount, accruedPenalties);
}
}
/// @dev True when redemptions bypass the async queue and NAV staleness gate
function _isInstantRedeem() internal view returns (bool) {
return loanState == LoanState.Repaid || loanState == LoanState.InDefaultClaims;
}
/// @dev OngoingDynamic instant path: optional tighter window after lastNavMeasuredAt
/// @dev 0 = unset; type(uint256).max = disabled; lastNavMeasuredAt == 0 does not block unless disabled
function _instantRedeemAllowedByMaxAge() internal view returns (bool) {
if (instantRedeemMaxAge == INSTANT_REDEEM_DISABLED) return false;
return !_maxAgeElapsed();
}
/// @dev True when a configured window (0 < N < max) has elapsed since lastNavMeasuredAt
/// @dev unset (0) and disabled (max) never block - used by permissionless accrueAndProcess only
function _maxAgeElapsed() internal view returns (bool) {
uint256 maxAge = instantRedeemMaxAge;
if (maxAge == 0 || maxAge == INSTANT_REDEEM_DISABLED) return false;
uint256 measuredAt = lastNavMeasuredAt;
if (measuredAt == 0) return false;
return block.timestamp > measuredAt + maxAge;
}
/// @dev Returns whether the NAV is stale
function _navIsStale() internal view returns (bool) {
return block.timestamp > navGraceDeadline;
}
/// @dev Checks that deposits are allowed
function _requireCanDeposit() internal view {
if (loanState != LoanState.OngoingDynamic) revert DepositNotAllowed();
}
/// @dev When a deposit gateway is set, only it may be the deposit controller (blocks direct retail deposits).
/// Backwards compatible: with no gateway set, deposits are unrestricted.
function _requireFromGateway(address controller) internal view {
address gateway = depositGateway;
if (gateway != address(0) && controller != gateway) revert DepositNotFromGateway();
}
/// @dev Checks that the deposit amount is below the max capacity
function _requireBelowMaxCapacity(uint256 assets) internal view {
if (assets > maxDeposit(address(0), address(0))) revert ExceedsMaxDeposit();
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) external pure override returns (bool) {
return interfaceId == type(IAccountableYield).interfaceId || interfaceId == type(IAccountableLoan).interfaceId
|| interfaceId == type(IAccountableStrategy).interfaceId || interfaceId == type(IERC165).interfaceId;
}
/// @dev UUPS authorization
function _authorizeUpgrade(address) internal override onlyManagerOrSecurityAdmin {}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @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 Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 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 in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._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 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._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() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @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 {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.20;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC1967-compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
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;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Pausable
struct PausableStorage {
bool _paused;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;
function _getPausableStorage() private pure returns (PausableStorage storage $) {
assembly {
$.slot := PausableStorageLocation
}
}
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
PausableStorage storage $ = _getPausableStorage();
return $._paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
emit Unpaused(_msgSender());
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
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;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._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 {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// 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) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.20;
import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*/
library ERC1967Utils {
// We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
// This will be fixed in Solidity 0.8.21. At that point we should remove these events.
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* 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.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) 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 FailedInnerCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
src/constants/Errors.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;
// ========================================================================== //
// Authorization Errors //
// ========================================================================== //
/// @notice Error thrown when unauthorized
error Unauthorized();
/// @notice Thrown when a signature verification fails due to invalid signer
error InvalidSigner();
/// @notice Thrown when a nonce verification fails due to invalid nonce
error InvalidNonce();
/// @notice Thrown when an operation is attempted with invalid operator permissions
error InvalidOperator();
/// @notice Error thrown when invalid pending borrower is provided
error InvalidPendingBorrower();
/// @notice Thrown when KYC status is not verified
error KYCNotVerified();
/// @notice Thrown when a block expiration is invalid (e.g. in the past)
error InvalidBlockExpiration();
/// @notice Thrown when a signature verification fails
error InvalidSignature();
/// @notice Thrown when a message data length is invalid
error InvalidMsgDataLength();
/// @notice Thrown when an accounts array is empty
error EmptyAccountsArray();
/// @notice Error thrown when the state is invalid
error InvalidState();
/// @notice Error thrown when a value is invalid
error InvalidValue();
// ========================================================================== //
// Vault operations errors //
// ========================================================================== //
/// @notice Error thrown when trying to cancel a redeem request failed
error CancelRedeemRequestFailed();
/// @notice Error thrown when deposit amount exceeds max deposit
error ExceedsMaxDeposit();
/// @notice Error thrown when assets exceed redemption limits
error ExceedsRedeemLimit();
/// @notice Error thrown when redeem amount exceeds max redeem
error ExceedsMaxRedeem();
/// @notice Error thrown when deposit/withdraw amount is insufficient
error InsufficientAmount();
/// @notice Error thrown when redeem share amount is insufficient
error InsufficientShares();
/// @notice Error thrown when no redeem request exists
error NoRedeemRequest();
/// @notice Error thrown when no pending redeem request exists
error NoPendingRedeemRequest();
/// @notice Thrown when attempting to transfer shares that are not transferable
error SharesNotTransferable();
/// @notice Error thrown when withdrawal queue is not empty
error WithdrawalQueueNotEmpty();
/// @notice Error thrown when no queue request exists
error NoQueueRequest();
/// @notice Error thrown when redeem amount exceeds liquidity
error InsufficientLiquidity();
/// @notice Error thrown when asset is not whitelisted
error AssetNotWhitelisted();
/// @notice Thrown when cancellation requests are not accepted
error CancellationNotAllowed();
/// @notice Thrown when a cancellation is already pending for the request
error CancelAlreadyPending();
/// @notice Thrown when approving a request with no pending cancellation
error CancelNotPending();
/// @notice Thrown when settling an epoch that is not in `Passed` status
error EpochNotPassed();
/// @notice Thrown when cancelling a request whose epoch is no longer `Open`
error EpochNotOpen();
/// @notice Thrown when the request id does not exist
error RequestNotFound();
/// @notice Thrown when acting on a request that is already settled or refunded
error AlreadyFinalized();
/// @notice Thrown when a refund is not permitted (epoch still open, or self-refund in a healthy fund)
error NotRefundable();
/// @notice Thrown by the recovery path when no NAV was published since the open epoch opened
error NoMissedNavUpdate();
/// @notice Thrown when a gateway is deployed with signature authentication not supported
error SigAuthNotSupported();
/// @notice Thrown when wiring a gateway whose strategy does not point back to the current strategy
error GatewayStrategyMismatch();
/// @notice Error thrown when deregistering a vault that still has staked shares
error VaultNotEmpty();
/// @notice Thrown when updateTerms attempts to increase minRedeem
error MinRedeemTooHigh();
/// @notice Thrown when updateTerms attempts to increase depositPeriod
error DepositPeriodTooLong();
// ========================================================================== //
// Loan operations errors //
// ========================================================================== //
/// @notice Error thrown when loan terms are already set
error LoanTermsAlreadySet();
/// @notice Error thrown when loan terms are not set
error LoanTermsNotSet();
/// @notice Error thrown when loan is ongoing
error LoanOngoing();
/// @notice Error thrown when loan is not ongoing
error LoanNotOngoing();
/// @notice Error thrown when the loan escrow has already completed its single funding round
error AlreadyFunded();
/// @notice Error thrown when loan is not in default
error LoanNotInDefault();
/// @notice Error thrown when default is already pending
error DefaultAlreadyPending();
/// @notice Error thrown when loan terms are not met
error LoanTermsNotMet();
/// @notice Error thrown when loan has not matured
error LoanNotMatured();
/// @notice Error thrown when loan has not been repaid
error LoanNotRepaid();
/// @notice Error thrown when repayment terms are not met
error LoanCannotBeRepaid();
/// @notice Error thrown when there are outstanding interest payments
error OutstandingInterestPayments();
/// @notice Thrown when an operation is attempted with invalid controller permissions
error InvalidController();
/// @notice Thrown when an operation is attempted with invalid interval duration pair
error InvalidIntervalDurationPair();
/// @notice Thrown when an operation is attempted with invalid interval length
error InvalidIntervalLength();
/// @notice Thrown when an operation is attempted with invalid withdrawal period
error InvalidWithdrawalPeriod();
/// @notice Error thrown when capacity is set to a lower value than acceptable
error CapacityTooLow();
/// @notice Error thrown when accept grace period is longer than acceptable for the loan
error AcceptGracePeriodTooLong();
/// @notice Error thrown when a threshold exceeds the max bound
error ThresholdTooHigh();
/// @notice Error thrown when attempting to pay when no payment is due
error NoPaymentDue();
/// @notice Error thrown when NAV is stale
error NAVGracePeriodExpired();
/// @notice Error thrown when DVN measurement is stale relative to state changes
error StaleMeasurement();
/// @notice Error thrown when early exit debt mismatch
error EarlyExitDebtMismatch();
/// @notice Thrown when an account has no claimed balance
error NothingToRepay();
/// @notice Invalid grace period for reclaiming shares after loan repayment
error InvalidGracePeriod();
/// @notice Thrown when an LP attempts to reclaim shares before the grace period expires
error GracePeriodNotExpired();
/// @notice Thrown when an LP is notified of their repayment status more than once
error AlreadyNotified();
/// @notice Thrown when an LP attempts to reclaim shares but has no shares to reclaim
error NothingToReclaim();
/// @notice Thrown when an LP attempts to reclaim shares but he wants to reclaim more than the outstanding debt
error ExceedsOutstanding();
/// @notice Thrown when an LP has no loanClaimed balance
error AlreadyRepaid();
/// @notice Thrown when loanToken collides with the vault share token or underlying asset
error InvalidLoanToken();
// ========================================================================== //
// General errors //
// ========================================================================== //
/// @notice Thrown when an index is out of bounds
error OutOfBounds();
/// @notice Thrown when an invalid range is provided
error InvalidRange();
/// @notice Thrown when an input address is address(0)
error ZeroAddress();
/// @notice Thrown when a value is zero
error ZeroValue();
/// @notice Thrown when deployment of a loan proxy contract fails
/// @param reason The reason for the failed deployment
error FailedDeployment(string reason);
/// @notice Thrown when a deposit is not allowed
error DepositNotAllowed();
/// @notice Thrown when a deposit's controller is not the configured deposit gateway
error DepositNotFromGateway();
/// @notice Thrown when a redeem is not allowed
error RedeemNotAllowed();
/// @notice Thrown when input arrays lengths don't match
error ArrayLengthMismatch();
/// @notice Error thrown when an operation is not required/allowed for the current permission level
error PermissionLevelMismatch();
/// @notice Error thrown when an operation is not supported by the strategy
error NotSupportedByStrategy();
/// @notice Thrown when a claim is not allwed
error ClaimNotAllowed();
/// @notice Thrown when a repay is not allowed
error RepayNotAllowed();
/// @notice Thrown when escrow was already set
error EscrowAlreadySet();
// ========================================================================== //
// Fee Manager errors //
// ========================================================================== //
/// @notice Error thrown when manager split is invalid
error InvalidManagerSplit();
/// @notice Error thrown when prepayment fee is invalid
error InvalidPrepaymentFee();
/// @notice Error thrown when establishment and management fees are set together
error InvalidFeeStructure();
/// @notice Error thrown when establishment fee is invalid
error InvalidEstablishmentFee();
/// @notice Error thrown when performance fee is invalid
error InvalidPerformanceFee();
/// @notice Error thrown when management fee is invalid
error InvalidManagementFee();
// ========================================================================== //
// Rewards errors //
// ========================================================================== //
/// @notice Error thrown when a root is already set
error RootAlreadySet();
/// @notice Error thrown when no root is set
error RootNotSet();
/// @notice Error thrown when a root is already pending
error RootAlreadyPending();
/// @notice Error thrown when no pending root is set
error NoPendingRoot();
/// @notice Error thrown when timelock is not expired
error TimelockNotExpired();
/// @notice Error thrown when a proof is invalid
error InvalidProof();
/// @notice Error thrown when the amount to claim is not enough
error NotEnoughClaimableAmount();
/// @notice Error thrown when an invalid rewards type is provided
error InvalidRewardsType();
// ========================================================================== //
// Rate change errors //
// ========================================================================== //
/// @notice Error thrown when rollback window has expired
error RollbackWindowExpired();
/// @notice Error thrown when rate is too high
error RateTooHigh();
// ========================================================================== //
// Publisher errors //
// ========================================================================== //
/// @notice Error thrown when threshold is too high
error InvalidThreshold();
/// @notice Error thrown when the threshold is not reached
error ThresholdNotReached();
/// @notice Error thrown when no batch has been published yet
error NoBatchPublished();
/// @notice Error thrown when request targets wrong batch
error InvalidBatchId();
/// @notice Error thrown when a publish request has expired (too stale)
error RequestExpired();
/// @notice Error thrown when too many pending requests exist
error TooManyRequests();
/// @notice Error thrown when deviation from previous value is too high
error DeviationTooHigh();
/// @notice Error thrown when request timestamp is in the future
error InvalidTimestamp();
/// @notice Error thrown when NAV grace period is invalid
error InvalidNavGracePeriod();
/// @notice Error thrown when instant-redeem max age is invalid (must be 0 or < navGracePeriod unless disabled)
error InvalidInstantRedeemMaxAge();
src/interfaces/IAccess.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @notice Struct containing transaction authentication data (EIP-712 typed)
/// @dev Chain ID is part of the EIP-712 domain separator, not this struct
struct TxAuthData {
/// @notice The calldata of the function being called (selector + encoded args)
bytes functionCallData;
/// @notice The address of the contract where the transaction is being executed
address contractAddress;
/// @notice The address of the account executing/controlling the transaction
address account;
/// @notice The per-account nonce (prevents replay)
uint256 nonce;
/// @notice The block number after which the transaction is considered expired
uint256 blockExpiration;
}
/// @notice Struct containing verification data for verifyMany function
struct VerifyManyData {
/// @notice The function call data extracted from msgData
bytes argsWithSelector;
/// @notice The block expiration timestamp
uint256 blockExpiration;
/// @notice The start position of signatures in msgData
uint256 signaturesStart;
/// @notice The number of signatures to verify
uint256 numSignatures;
}
/// @notice Enum representing different permission levels
enum PermissionLevel {
/// @notice No permission
None,
/// @notice KYC based permission
KYC,
/// @notice Whitelist based permission
Whitelist
}
/// @title Whitelistable Interface
/// @notice Interface for managing whitelisted accounts
interface IWhitelistable {
/// @notice Emitted when allowed status is set for an account
/// @param account The address of the account
/// @param allowed The allowed status
event AllowedSet(address indexed account, bool allowed);
/// @notice Set allowed accounts
/// @param accounts Array of account addresses
/// @param allowed Array of allowed status corresponding to acounts
function setAllowed(address[] calldata accounts, bool[] calldata allowed) external;
/// @notice Check if an account is allowed
/// @param account The address to check allowed status for
/// @return bool True if the account is allowed, false otherwise
function allowed(address account) external view returns (bool);
/// @notice Check if multiple accounts are allowed
/// @param accounts Array of account addresses
/// @return bool True if the accounts are allowed, false otherwise
function allowedMany(address[] calldata accounts) external view returns (bool);
}
/// @title Authorizable Interface
/// @notice Interface for managing authorizable accounts
interface IAuthorizable {
/// @notice Emitted when the signer address is changed
/// @param oldSigner The old signer address
/// @param newSigner The new signer address
event SignerChanged(address indexed oldSigner, address indexed newSigner);
/// @notice Emitted when a transaction authentication data is verified
/// @param chainID The chain ID where the transaction is intended to be processed
/// @param nonce The nonce of the user being verified to prevent replay attacks
/// @param blockExpiration The block number after which the transaction is considered expired
/// @param contractAddress The address of the contract where the transaction is being executed
/// @param userAddress The address of the user executing the transaction
/// @param functionCallData The calldata of the function being called
event TxAuthDataVerified(
uint256 chainID,
uint256 nonce,
uint256 blockExpiration,
address indexed contractAddress,
address indexed userAddress,
bytes functionCallData
);
/// @notice Set the signer address
/// @param signer The address of the signer
function setSigner(address signer) external;
/// @notice Get the signer address
/// @return The signer address
function signer() external view returns (address);
/// @notice Get the nonce for a given user
/// @param user The address of the user
/// @return The nonce of the user
function nonces(address user) external view returns (uint256);
/// @notice Get the message hash for a given transaction authentication data
/// @param txAuthData The transaction authentication data
/// @return The message hash
function getMessageHash(TxAuthData calldata txAuthData) external view returns (bytes32);
}
/// @title Access Interface
/// @notice Interface for managing access to a contract
interface IAccess is IAuthorizable, IWhitelistable {
/// @notice Get the permission level for the loan
/// @return The permission level enum value
function permissionLevel() external view returns (PermissionLevel);
}
src/interfaces/IAccountableAsyncVault.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/// @notice Struct tracking vault state for a controller
struct VaultState {
/// @notice Maximum shares that can be minted
uint256 maxMint;
/// @notice Maximum assets that can be withdrawn
uint256 maxWithdraw;
/// @notice Total accumulated assets unclaimed
uint256 depositAssets;
/// @notice Total accumulated shares unclaimed
uint256 redeemShares;
/// @notice Share price floored for deposit
uint256 depositPrice;
/// @notice Share price ceiled for mint
uint256 mintPrice;
/// @notice Share price floored for redeem
uint256 redeemPrice;
/// @notice Share price ceiled for withdraw
uint256 withdrawPrice;
/// @notice Pending deposit amount
uint256 pendingDepositRequest;
/// @notice Pending redeem amount
uint256 pendingRedeemRequest;
}
interface IControllerOperator {
/// @notice Emitted when an operator's approval status is updated
/// @param controller The controller address that approved/revoked
/// @param operator The operator address being approved/revoked
/// @param approved The new approval status
event OperatorSet(address indexed controller, address indexed operator, bool approved);
/// @notice Sets or revokes operator approval for a caller
/// @param operator The address to set approval for
/// @param approved True to approve, false to revoke
/// @return bool True if successful
function setOperator(address operator, bool approved) external returns (bool);
/// @notice Checks if an address is an approved operator for a controller
/// @param controller The controller address to check
/// @param operator The operator address to check
/// @return status True if operator is approved for controller
function isOperator(address controller, address operator) external view returns (bool status);
}
interface IAsyncDeposit {
/// @notice Emitted when a deposit request is created
/// @param controller The controller address for the deposit
/// @param owner The owner address that will receive shares
/// @param requestId The unique ID for tracking the request
/// @param sender The address that initiated the request
/// @param assets The amount of assets being deposited
event DepositRequest(
address indexed controller, address indexed owner, uint256 indexed requestId, address sender, uint256 assets
);
/// @notice Requests a deposit of assets
/// @param assets Amount of assets to deposit
/// @param controller Address controlling the deposit
/// @param owner Address that will own the shares
/// @return uint256 Request ID for tracking the deposit
function requestDeposit(uint256 assets, address controller, address owner) external returns (uint256);
/// @notice Gets pending deposit amount for a request
/// @param requestId ID of the deposit request
/// @param controller Controller address for the request
/// @return uint256 Amount of assets pending deposit
function pendingDepositRequest(uint256 requestId, address controller) external view returns (uint256);
/// @notice Gets claimable deposit amount for a request
/// @param requestId ID of the deposit request
/// @param controller Controller address for the request
/// @return uint256 Amount of assets claimable
function claimableDepositRequest(uint256 requestId, address controller) external view returns (uint256);
}
interface IAsyncRedeem {
/// @notice Emitted when a redeem request is created
/// @param controller The controller address for the redemption
/// @param owner The owner of the shares being redeemed
/// @param requestId The unique ID for tracking the request
/// @param sender The address that initiated the request
/// @param assets The amount of assets being redeemed
event RedeemRequest(
address indexed controller, address indexed owner, uint256 indexed requestId, address sender, uint256 assets
);
/// @notice Requests redemption of shares
/// @param shares Amount of shares to redeem
/// @param controller Controller address for redemption
/// @param owner Owner of the shares
/// @return uint256 Request ID for tracking redemption
function requestRedeem(uint256 shares, address controller, address owner) external returns (uint256);
/// @notice Gets pending redeem amount for a request
/// @param requestId ID of the redeem request
/// @param controller Controller address for the request
/// @return uint256 Amount of shares pending redemption
function pendingRedeemRequest(uint256 requestId, address controller) external view returns (uint256);
/// @notice Gets claimable redeem amount for a request
/// @param requestId ID of the redeem request
/// @param controller Controller address for the request
/// @return uint256 Amount of shares claimable
function claimableRedeemRequest(uint256 requestId, address controller) external view returns (uint256);
}
interface IAsyncCancelDeposit {
/// @notice Emitted when a deposit request is cancelled
/// @param controller The controller address for the deposit
/// @param receiver The address that received the cancelled deposit
/// @param requestId The ID of the cancelled request
/// @param sender The address that initiated the cancellation
event CancelDepositRequest(address indexed controller, address indexed receiver, uint256 requestId, address sender);
/// @notice Cancels a pending deposit request
/// @param controller Controller address for the request
/// @param receiver The address that received the cancelled deposit
function cancelDepositRequest(address controller, address receiver) external;
}
interface IAsyncCancelRedeem {
/// @notice Emitted when a redeem request is cancelled
/// @param controller The controller address for the redemption
/// @param receiver The address that received the cancelled redeem
/// @param requestId The ID of the cancelled request
/// @param sender The address that initiated the cancellation
event CancelRedeemRequest(address indexed controller, address indexed receiver, uint256 requestId, address sender);
/// @notice Cancels a pending redeem request
/// @param controller Controller address for the request
/// @param receiver The address that received the cancelled redeem
function cancelRedeemRequest(address controller, address receiver) external;
}
interface IAccountableVault is IERC20, IERC20Metadata, IERC4626, IControllerOperator {
/// @notice Emitted when assets are locked in the vault
/// @param caller The address that locked the assets
/// @param assets The amount of assets locked
event LockAssets(address indexed caller, uint256 assets);
/// @notice Emitted when locked assets are released
/// @param caller The address that released the assets
/// @param assets The amount of assets released
event ReleaseAssets(address indexed caller, uint256 assets);
/// @notice Emitted when shares transferability is changed
/// @param oldStatus The old transferability status
/// @param newStatus The new transferability status
event SharesTransferableSet(bool oldStatus, bool newStatus);
/// @notice Deposits assets and mints shares to receiver
/// @dev Added for ERC7540 compatibility
/// @param assets Amount of assets to deposit
/// @param receiver Address receiving the shares
/// @param controller Controller address for the deposit
/// @return uint256 Amount of shares minted
function deposit(uint256 assets, address receiver, address controller) external returns (uint256);
/// @notice Mints exact amount of shares by depositing assets
/// @dev Added for ERC7540 compatibility
/// @param shares Amount of shares to mint
/// @param receiver Address receiving the shares
/// @param controller Controller address for the mint
/// @return uint256 Amount of assets deposited
function mint(uint256 shares, address receiver, address controller) external returns (uint256);
/// @notice Locks assets in the vault
/// @param assets Amount of assets to lock
function lockAssets(uint256 assets, address sender) external;
/// @notice Releases previously locked assets
/// @param assets Amount of assets to release
function releaseAssets(uint256 assets, address receiver) external;
/// @notice Issues shares to a receiver
/// @param shares Amount of shares to issue
/// @param receiver Address to receive the shares
function mintShares(uint256 shares, address receiver) external;
/// @notice Repossesses shares from a sender
/// @param shares Amount of shares to repossess
/// @param sender Address to repossess the shares from
function burnShares(uint256 shares, address sender) external;
/// @notice Forces a transfer of shares from one address to another
/// @param from The address to transfer shares from
/// @param to The address to transfer shares to
/// @param shares The amount of shares to transfer
function forceTransferShares(address from, address to, uint256 shares) external;
/// @notice Sets the transferability of shares
/// @param transferable True to set shares transferable, false to set them non-transferable
function setSharesTransferable(bool transferable) external;
/// @notice Checks if shares can be transferred
/// @return bool True if shares are transferable
function transferableShares() external view returns (bool);
/// @notice Current asset share ratio
/// @return uint256 Asset share ratio
function assetShareRatio() external view returns (uint256);
/// @notice Gets the current share price
/// @return uint256 Price per share in assets
function sharePrice() external view returns (uint256);
/// @notice The share token address
/// @return address Share token address
function share() external view returns (address);
/// @notice Gets the state of the vault
/// @param controller The controller address for the vault
/// @return state The state of the vault given the controller
function getState(address controller) external view returns (VaultState memory state);
}
interface IAccountableAsyncRedeemVault is IAccountableVault, IAsyncRedeem, IAsyncCancelRedeem, IERC165 {
/// @notice Emitted when a redeem becomes claimable
/// @param controller The controller address for the redemption
/// @param requestId The ID of the redeem request
/// @param assets The amount of assets to be received
/// @param shares The amount of shares redeemed
event RedeemClaimable(address indexed controller, uint256 indexed requestId, uint256 assets, uint256 shares);
}
interface IAccountableAsyncVault is
IAccountableVault,
IAsyncDeposit,
IAsyncRedeem,
IAsyncCancelDeposit,
IAsyncCancelRedeem,
IERC165
{
/// @notice Emitted when a deposit becomes claimable
/// @param controller The controller address for the deposit
/// @param requestId The ID of the deposit request
/// @param assets The amount of assets deposited
/// @param shares The amount of shares to be minted
event DepositClaimable(address indexed controller, uint256 indexed requestId, uint256 assets, uint256 shares);
/// @notice Emitted when a redeem becomes claimable
/// @param controller The controller address for the redemption
/// @param requestId The ID of the redeem request
/// @param assets The amount of assets to be received
/// @param shares The amount of shares redeemed
event RedeemClaimable(address indexed controller, uint256 indexed requestId, uint256 assets, uint256 shares);
}
src/interfaces/IAccountableStrategy.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/// @notice Struct containing loan terms and state
struct Loan {
/// @notice Minimum deposit amount allowed
uint256 minDeposit;
/// @notice Minimum redeem amount allowed
uint256 minRedeem;
/// @notice Maximum loan amount that can be drawn
/// The full threshold can be met after deposit period if the loan is not locked
uint256 maxCapacity;
/// @notice Minimum loan amount for the loan to be accepted
/// The threshold needs to be met during deposit period or loan can be rejected
uint256 minCapacity;
/// @notice Liquidity ratio that has to be maintained in the vault at all times
/// Expressed in basis points and cannot exceed 1e6, defaults to 0
uint256 reserveThreshold;
/// @notice Principal amount still to be repaid
uint256 outstandingPrincipal;
/// @notice Interest amount still to be paid
uint256 outstandingInterest;
/// @notice all funds accepted and available for borrowing
uint256 drawableFunds;
/// @notice Annual interest rate in basis points
uint256 interestRate;
/// @notice Late interest penalty in basis points
uint256 lateInterestPenalty;
/// @notice Total claimable interest available for users
uint256 claimableInterest;
/// @notice Time interval between interest payments
uint256 interestInterval;
/// @notice Time of loan start
uint256 startTime;
/// @notice Time of terms set
uint256 termsSetTime;
/// @notice Time of terms update
uint256 termsUpdateTime;
/// @notice Loan duration in seconds
uint256 duration;
/// @notice Deposit period in seconds
uint256 depositPeriod;
/// @notice Grace period after deposit period for borrower to accept loan
uint256 acceptGracePeriod;
/// @notice Withdrawal window period in seconds
/// If set it allows redemption requests
uint256 withdrawalPeriod;
/// @notice Late interest payment grace period in seconds
/// This is the time period before a loan is considered delinquent
uint256 lateInterestGracePeriod;
}
/// @notice Struct containing loan terms
struct LoanTerms {
/// @notice Minimum deposit amount allowed
uint256 minDeposit;
/// @notice Minimum redeem amount allowed
uint256 minRedeem;
/// @notice Maximum loan capacity
uint256 maxCapacity;
/// @notice Minimum loan capacity
uint256 minCapacity;
/// @notice Annual interest rate in basis points
uint256 interestRate;
/// @notice Late interest penalty in basis points
uint256 lateInterestPenalty;
/// @notice Late interest grace period in seconds
uint256 lateInterestGracePeriod;
/// @notice Time interval between interest payments
uint256 interestInterval;
/// @notice Duration of the loan in seconds
uint256 duration;
/// @notice Deposit period in seconds
uint256 depositPeriod;
/// @notice Grace period after deposit period for borrower to accept loan
uint256 acceptGracePeriod;
/// @notice Withdrawal window period in seconds
uint256 withdrawalPeriod;
}
/// @notice Struct containing DVN proof data
struct DVNProof {
/// @notice Merkle root of the DVN merkle tree
bytes32 root;
/// @notice Signature of the DVN payload
bytes32 signature;
/// @notice Message hash that was signed
bytes32 messageHash;
}
/// @notice Enum representing different loan states
enum LoanState {
/// @notice Loan terms are not set
Initialized,
/// @notice Loan terms are set
TermsSet,
/// @notice Loan is accepted by borrower and locked
OngoingLocked,
/// @notice Loan is accepted by borrower and dynamic deposits are allowed
OngoingDynamic,
/// @notice Loan is rejected
Rejected,
/// @notice Loan is repaid
Repaid,
/// @notice Loan is in default
InDefault,
/// @notice Loan is in default claims
InDefaultClaims
}
/// @notice Interface for managing strategy vault hooks
interface IStrategyVaultHooks {
/// @notice Hook for handling deposit requests
/// @param share The address of the share token
/// @param assets The amount of assets requested
/// @param controller The address of the controller
/// @param owner The address of the owner of the assets
/// @return canFulfill Whether the deposit can be fulfilled instantly
/// @return price The price of the share
function onRequestDeposit(address share, uint256 assets, address controller, address owner)
external
returns (bool canFulfill, uint256 price);
/// @notice Hook for handling redeem requests
/// @param share The address of the share token
/// @param shares The amount of shares requested
/// @param controller The address of the controller
/// @param owner The address of the owner of the shares
/// @return canFulfill Whether the redeem can be fulfilled instantly
/// @return price The price of the share
function onRequestRedeem(address share, uint256 shares, address controller, address owner)
external
returns (bool canFulfill, uint256 price);
/// @notice Hook for handling cancel deposit requests
/// @param share The address of the share token
/// @param controller The address of the controller
/// @return canCancel Whether the deposit can be cancelled instantly
function onCancelDepositRequest(address share, address controller) external returns (bool canCancel);
/// @notice Hook for handling cancel redeem requests
/// @param share The address of the share token
/// @param controller The address of the controller
/// @return canCancel Whether the redeem can be cancelled instantly
function onCancelRedeemRequest(address share, address controller) external returns (bool canCancel);
/// @notice Hook for handling deposit requests
/// @param share The address of the share token
/// @param assets The amount of assets to deposit
/// @param receiver The address of the receiver
/// @param controller The address of the controller
function onDeposit(address share, uint256 assets, address receiver, address controller)
external
returns (uint256 price);
/// @notice Hook for handling mint requests
/// @param share The address of the share token
/// @param shares The amount of shares to mint
/// @param receiver The address of the receiver
/// @param controller The address of the controller
function onMint(address share, uint256 shares, address receiver, address controller)
external
returns (uint256 price);
/// @notice Hook for handling redeem requests
/// @param share The address of the share token
/// @param shares The amount of shares to redeem
/// @param receiver The address of the receiver
function onRedeem(address share, uint256 shares, address receiver, address controller) external;
/// @notice Hook for handling withdraw requests
/// @param share The address of the share token
/// @param assets The amount of assets to withdraw
/// @param receiver The address of the receiver
/// @param controller The address of the controller
function onWithdraw(address share, uint256 assets, address receiver, address controller) external;
/// @notice Hook for handling vault transfers
/// @param from The address of the sender
/// @param to The address of the receiver
/// @param amount The amount of shares to transfer
function onTransfer(address share, address from, address to, uint256 amount) external;
/// @notice Operator authorization
/// @param operator The address of the operator
/// @dev Reverts for unauthorized operator. Operator should not be an input value of another call
function authOperator(address operator) external;
/// @notice Centralized share price
/// @param share The address of the share token
function sharePrice(address share) external view returns (uint256 price);
/// @notice Centralized accrued assets
/// @param share The address of the share token
/// @return assets The accrued assets to be distributed
function accruedAssets(address share) external view returns (uint256 assets);
/// @notice Centralized max deposit capacity
/// @param share The address of the share token
/// @param controller The address of the controller
/// @return maxAssets The maximum amount of assets that can be deposited
function maxDeposit(address share, address controller) external view returns (uint256 maxAssets);
/// @notice Centralized max redeem capacity
/// @param share The address of the share token
/// @param controller The address of the controller
/// @return maxShares The maximum amount of shares that can be redeemed
function maxRedeem(address share, address controller) external view returns (uint256 maxShares);
}
/// @notice Interface for managing fee manager hooks
interface IFeeManagerHooks {
/// @notice Hook for handling fee structure changes
function onFeeStructureChange() external;
}
interface IUpdateLateStatus {
/// @notice Updates the late status of the loan
function updateLateStatus() external;
}
/// @notice Interface for managing base strategy components
interface IAccountableStrategy is IStrategyVaultHooks, IFeeManagerHooks, IERC165 {
/// @notice Event emitted when the borrower is changed
event BorrowerChanged(address indexed oldBorrower, address indexed newBorrower);
/// @notice Event emitted when the pending borrower is set
event PendingBorrowerSet(address indexed pendingBorrower);
/// @notice Event emitted when the safety module is set
event SafetyModuleSet(address indexed safetyModule);
/// @notice Event emitted when the investment manager is set
event InvestmentManagerSet(address indexed investmentManager);
/// @notice Event emitted when the proof signer is set
event ProofSignerSet(address indexed proofSigner);
/// @notice Event emitted when the DVN publisher is set
event DVNPublisherSet(address indexed publisher);
/// @notice Event emitted when the manager fee recipient is set
event ManagerFeeRecipientSet(address indexed managerFeeRecipient);
/// @notice Event emitted when the DVN proof is published
event DVNProofPublished(bytes32 indexed root, bytes32 indexed signature, bytes32 indexed messageHash);
/// @notice Event emitted when a rate is published
event RatePublished(address indexed publisher, uint256 oldRate, uint256 newRate);
/// @notice Event emitted when the default is rejected
event LoanDefaultRejected();
/// @notice Event emitted when the default is accepted
event LoanDefaulted(uint256 principal, uint256 collateral);
/// @notice Event emitted when the penalties enabled flag is set
event PenaltiesEnabledSet(bool enabled);
/// @notice Event emitted when the security admin enabled flag is set
event SecurityAdminEnabledSet(bool enabled);
/// @notice Event emitted when the operations admin enabled flag is set
event OperationsAdminEnabledSet(bool enabled);
/// @notice Event emitted when the reserve threshold is set
event ReserveThresholdSet(uint256 threshold);
/// @notice Event emitted when the rewards distributor is set
event RewardsDistributorSet(address indexed rewardsDistributor);
/// @notice Event emitted when the price oracle is set
event PriceOracleSet(address indexed priceOracle);
/// @notice Set a new pending borrower
/// @param newBorrower Address of the new pending borrower
function setPendingBorrower(address newBorrower) external;
/// @notice Accept the borrower role as pending borrower
function acceptBorrowerRole() external;
/// @notice Set a new safety module contract
/// @dev It can act as a factory in a deploy-and-set manner
/// @param safetyModule Address of the new safety module
function setSafetyModule(address safetyModule) external;
/// @notice Set a new rewards distributor contract
/// @dev It can act as a factory in a deploy-and-set manner
/// @param rewards Address of the new rewards distributor
function setRewardsDistributor(address rewards) external;
/// @notice Set a new price oracle contract
/// @param priceOracle Address of the new price oracle
function setPriceOracle(address priceOracle) external;
/// @notice Set a new investment manager contract
/// @param investmentManager Address of the new investment manager
function setInvestmentManager(address investmentManager) external;
/// @notice Set the auth signer address
/// @dev This is function relays data to the vault's access module
/// It sets the kyc verification signer when permission level is `KYC`
/// @param authSigner Address of the new auth signer
function setAuthSigner(address authSigner) external;
/// @notice Set the lenders addresses and permissions
/// @dev This is function relays data to the vault's access module
/// It whitelists lenders when permission level is `Whitelist`
/// @param lenders Addresses of the lenders to be whitelisted
/// @param allowed Whether the lenders are allowed to perform actions
function setLenders(address[] calldata lenders, bool[] calldata allowed) external;
/// @notice Set the proof signer address
/// @param proofSigner Address of the new proof signer
function setProofSigner(address proofSigner) external;
/// @notice Set the DVN publisher address
/// @param publisher Address of the new DVN publisher
function setDVNPublisher(address publisher) external;
/// @notice Set the manager fee recipient address
/// @param managerFeeRecipient Address of the new manager fee recipient
function setManagerFeeRecipient(address managerFeeRecipient) external;
/// @notice Publish a new DVN proof
/// @param proof Latest DVN proof data
function publishDVNProof(DVNProof memory proof) external;
/// @notice Publish a new rate
/// @param newRate The new rate to publish (can be interest rate, NAV etc.)
/// @param measuredAt The timestamp of the measurement being published
function publishRate(uint256 newRate, uint256 measuredAt) external;
/// @notice Accept the default of the loan
function acceptDefault() external;
/// @notice Reject the default of the loan
function rejectDefault() external;
/// @notice Set the penalties enabled flag
/// @param enabled Whether penalties are enabled
function setPenaltiesEnabled(bool enabled) external;
/// @notice Set the security admin enabled flag
/// @param enabled Whether security admin is enabled
function setSecurityAdminEnabled(bool enabled) external;
/// @notice Set the operations admin enabled flag
/// @param enabled Whether operations admin is enabled
function setOperationsAdminEnabled(bool enabled) external;
/// @notice Set the shares transferable flag
/// @param transferable Whether shares are transferable
function setSharesTransferable(bool transferable) external;
/// @notice Set the min reserve threshold required in the vault
/// @param threshold The threshold expressed in basis points
function setReserveThreshold(uint256 threshold) external;
/// @notice Get the global registry contract address
/// @return The global registry address
function globals() external view returns (address);
/// @notice Get the current borrower address
/// @return The borrower address
function borrower() external view returns (address);
/// @notice Get the pending borrower address
/// @return The pending borrower address
function pendingBorrower() external view returns (address);
/// @notice Get the investment manager contract address
/// @return The investment manager address
function investmentManager() external view returns (address);
/// @notice Get the fee manager contract address
/// @return The fee manager address
function feeManager() external view returns (address);
/// @notice Get the safety module contract address
/// @return The safety module address
function safetyModule() external view returns (address);
/// @notice Get the rewards distributor contract address
/// @return The rewards distributor address
function rewards() external view returns (address);
/// @notice Get the price oracle contract address
/// @return The price oracle address
function priceOracle() external view returns (address);
/// @notice Get the DVN publisher contract address
/// @return The DVN publisher address
function dvnPublisher() external view returns (address);
/// @notice Get the manager fee recipient address
/// @return The manager fee recipient address
function managerFeeRecipient() external view returns (address);
/// @notice Get the proof signer address
/// @return The proof signer address
/// @dev Returns the pub key of the node signing proofs
function proofSigner() external view returns (address);
/// @notice Get the vault contract address
/// @return The vault address
function vault() external view returns (address);
/// @notice Get the current loan state
/// @return The loan struct
function loan() external view returns (Loan memory);
/// @notice Get the DVN proof
/// @return The latest DVN proof data
function dvnProof() external view returns (DVNProof memory);
/// @notice Get the loan state
/// @return The loan state enum value
function loanState() external view returns (LoanState);
/// @notice Get the penalties enabled flag
/// @return The penalties enabled flag
function penaltiesEnabled() external view returns (bool);
/// @notice Get the security admin enabled flag
/// @return The security admin enabled flag
function securityAdminEnabled() external view returns (bool);
/// @notice Get the operations admin enabled flag
/// @return The operations admin enabled flag
function operationsAdminEnabled() external view returns (bool);
/// @notice Get the precision for the strategy
/// @return The precision
function PRECISION() external view returns (uint256);
/// @notice Get the basis points for the strategy
/// @return The basis points
function BASIS_POINTS() external view returns (uint256);
/// @notice Get the version of the strategy
/// @dev Increment when upgrading the strategy
function version() external view returns (uint256);
}
/// @notice Interface for managing loan lifecycle and payments
interface IAccountableLoan is IAccountableStrategy {
/// @notice Event emitted when the loan is initialized
/// @param minCapacity The minimum loan capacity
/// @param maxCapacity The maximum loan capacity
/// @param interestRate The interest rate of the loan
/// @param lateInterestPenalty The late interest penalty
/// @param interestInterval The interest interval
/// @param duration The duration of the loan
event LoanTermsSet(
uint256 minCapacity,
uint256 maxCapacity,
uint256 interestRate,
uint256 lateInterestPenalty,
uint256 interestInterval,
uint256 duration
);
/// @notice Event emitted when the default is initiated
event LoanDefaultInitiated();
/// @notice Event emitted when a default is covered by safety collateral
/// @param safetyModule The address of the safety module
/// @param provider The address of the provider
/// @param collateral The amount of collateral covered
event DefaultCovered(address indexed safetyModule, address indexed provider, uint256 collateral);
/// @notice Event emitted when funds are borrowed
/// @param borrower The address of the borrower
/// @param assets The amount of funds borrowed
event Borrowed(address indexed borrower, uint256 assets);
/// @notice Event emitted when the loan is repaid
/// @param assets The amount of funds repaid
event LoanRepaid(uint256 assets);
/// @notice Event emitted when the loan is partially repaid
/// @param amount The amount of funds repaid to close loan
/// @param remainingInterest The remaining interest amount
event LoanPrepaid(uint256 amount, uint256 remainingInterest);
/// @notice Event emitted when interest is paid
/// @param borrower The address of the borrower
/// @param totalAmount The total amount paid
/// @param interestPenalty The interest penalty amount paid
/// @param performanceFee The performance fee amount paid
/// @param managementFee The management fee amount paid
/// @param paymentInterval The interval of the payment
event InterestPaid(
address indexed borrower,
uint256 totalAmount,
uint256 interestPenalty,
uint256 performanceFee,
uint256 establishmentFee,
uint256 managementFee,
uint256 paymentInterval
);
/// @notice Initialize a new loan with the given terms
/// @param terms The loan terms to initialize with
function setTerms(LoanTerms memory terms) external;
/// @notice Update an existing loan with new terms
/// @param terms The new loan terms to update to
function updateTerms(LoanTerms memory terms) external;
/// @notice Initialize loan default state
function defaultLoan() external;
/// @notice Cover the default of the loan
/// @param assets The amount of assets to cover
function coverDefault(uint256 assets) external;
/// @notice Borrow funds from the loan
/// @param assets The amount of funds to borrow
function borrow(uint256 assets) external;
/// @notice Repay the loan amount
/// @param assets The amount of funds to repay
function repay(uint256 assets) external;
/// @notice Make a partial loan repayment
function prepay() external;
/// @notice Make an interest payment
/// @param assets The interest amount to pay
function pay(uint256 assets) external;
/// @notice Get the period of time the loan has been delinquent
/// @return The period of time the loan has been delinquent
function timeDelinquent() external view returns (uint256);
}
src/interfaces/IAccountableWithdrawalQueue.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;
/// @notice Struct tracking a withdrawal request
struct WithdrawalRequest {
/// @notice The number of shares requested
uint256 shares;
/// @notice The controller of the request
address controller;
}
/// @notice Struct tracking the withdrawal queue
struct WithdrawalQueue {
/// @notice The next request ID to be processed
uint128 nextRequestId;
/// @notice The last request ID to be processed
uint128 lastRequestId;
/// @notice The mapping of request IDs to withdrawal requests
mapping(uint128 requestId => WithdrawalRequest request) requests;
}
/// @notice Interface for the withdrawal queue
interface IAccountableWithdrawalQueue {
/// @notice Fulfill a redeem request
/// @param controller The controller of the request
/// @param shares The number of shares to fulfill
function fulfillRedeemRequest(address controller, uint256 shares) external;
/// @notice Process up to `maxShares` shares
/// @param maxShares The maximum number of shares to process
/// @return assetsUsed The number of assets used to process the shares
function processUpToShares(uint256 maxShares) external returns (uint256 assetsUsed);
/// @notice Process up to `maxRequestId` request
/// @param maxRequestId The last request ID to process
/// @return processedShares The number of shares that were processed
/// @return assetsUsed The number of assets used to process the shares
function processUpToRequestId(uint256 maxRequestId)
external
returns (uint256 processedShares, uint256 assetsUsed);
/// @notice Preview required shares that can be processed with `maxAssets`
/// @param maxAssets The maximum number of assets to be matched with `maxAssets`
/// @return processedShares The number of shares that can be processed with the assets
/// @return assetsUsed The number of assets used to process the shares
function previewRequiredShares(uint256 maxAssets)
external
view
returns (uint256 processedShares, uint256 assetsUsed);
/// @notice Preview the last request ID that can be processed with `maxAssets`
/// @param maxAssets The maximum number of assets to be matched with `maxAssets`
/// @return maxRequestId The last request ID that can be processed with the assets
/// @return assetsUsed The number of assets used to process the shares
function previewMaxRequestId(uint256 maxAssets) external view returns (uint256 maxRequestId, uint256 assetsUsed);
/// @notice Get the total number of shares queued
/// @return totalQueuedShares The total number of shares queued
function totalQueuedShares() external view returns (uint256 totalQueuedShares);
/// @notice Get the reserved liquidity
/// @return reservedLiquidity The reserved liquidity
function reservedLiquidity() external view returns (uint256 reservedLiquidity);
/// @notice Get the withdrawal queue indices
/// @return nextRequestId The next request ID to be processed
/// @return lastRequestId The last request ID to be processed
function queue() external view returns (uint128 nextRequestId, uint128 lastRequestId);
/// @notice Get the withdrawal request for a controller
/// @param controller The controller of the request
/// @return request The withdrawal request
function withdrawalRequest(address controller) external view returns (WithdrawalRequest memory request);
/// @notice Get the withdrawal requests
/// @param start The start index of the queue
/// @param end The end index of the queue
/// @return requests The withdrawal requests
function withdrawalRequests(uint128 start, uint128 end)
external
view
returns (WithdrawalRequest[] memory requests);
}
src/interfaces/IAccountableYield.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;
import {PermissionLevel} from "./IAccess.sol";
import {IAccountableLoan} from "./IAccountableStrategy.sol";
/// @notice Initialization parameters for yield strategy
struct YieldInitParams {
/// @notice The asset of the yield strategy
address asset;
/// @notice The globals registry address
address globals;
/// @notice The fee manager address
address feeManager;
/// @notice The investment manager address
address investmentManager;
/// @notice Whether the shares are transferable
bool sharesTransferable;
/// @notice The permission level of the yield strategy
PermissionLevel permissionLevel;
/// @notice The name of the share token
string name;
/// @notice The symbol of the share token
string symbol;
}
/// @title IAccountableYield
/// @notice Interface for NAV-based yield strategy
interface IAccountableYield is IAccountableLoan {
/// @notice Emitted when borrower accepts terms
event TermsAccepted();
/// @notice Emitted when borrower rejects terms
event TermsRejected();
/// @notice Emitted when fee shares are minted
/// @param recipient The address of the recipient
/// @param shares The amount of fee shares minted
event FeeSharesMinted(address indexed recipient, uint256 shares);
/// @notice Emitted when delinquency status changes
/// @param isDelinquent Whether the loan is currently delinquent
/// @param timestamp The timestamp of the delinquency status change
event DelinquencyStatusChanged(bool isDelinquent, uint256 timestamp);
/// @notice Emitted when NAV grace period is updated
/// @param oldPeriod The old NAV grace period
/// @param newPeriod The new NAV grace period
event NavGracePeriodSet(uint256 oldPeriod, uint256 newPeriod);
/// @notice Emitted when the instant-redeem freshness window is updated
/// @param oldMaxAge Previous value (0 = unset, type(uint256).max = disabled)
/// @param newMaxAge New value
event InstantRedeemMaxAgeSet(uint256 oldMaxAge, uint256 newMaxAge);
/// @notice Emitted when penalties are accrued
/// @param amount The amount of penalties accrued
/// @param totalAccrued The total accrued penalties
event PenaltiesAccrued(uint256 amount, uint256 totalAccrued);
/// @notice Emitted when the deposit gateway is set
event DepositGatewaySet(address indexed oldGateway, address indexed newGateway);
/// @notice Emitted when the performance-fee high-water mark is reset during migration
/// @param peakSharePrice The new peakSharePrice after reinitialization
event PeakSharePriceReset(uint256 peakSharePrice);
/// @notice Emitted when the deposit gateway's onNavUpdate hook reverted during publishRate
/// @dev The NAV publish still succeeds and the gateway can recover via forcePassEpoch / auto-heal
event GatewayNavUpdateFailed(uint256 navMeasuredAt);
/// @notice Accept initial or pending terms
/// @dev Can only be called by borrower
function acceptTerms() external;
/// @notice Reject initial or pending terms
/// @dev Can only be called by borrower
function rejectTerms() external;
/// @notice Set the NAV grace period
/// @param period Duration in seconds that NAV remains fresh after update
function setNavGracePeriod(uint256 period) external;
/// @notice Set the instant-redeem freshness window for OngoingDynamic redemptions
/// @param maxAge 0 = unset when disable is false, otherwise must be < navGracePeriod
/// @param disable When true, instant redeem is disabled (queue only), maxAge is ignored
function setInstantRedeemMaxAge(uint256 maxAge, bool disable) external;
/// @notice Accrue fees and process withdrawals
/// @dev Can be called by anyone to trigger fee accrual
function accrueAndProcess() external returns (uint256 usedAssets);
/// @notice [DEPRECATED] Get last recorded total assets
/// @return The last recorded total assets
function lastTotalAssets() external view returns (uint256);
/// @notice [DEPRECATED] Get lost assets (realized losses)
/// @return The lost assets
function lostAssets() external view returns (uint256);
/// @notice Get the performance fee high-water mark, expressed as a share-price ratio
function peakSharePrice() external view returns (uint256);
/// @notice Get deployed assets value
/// @return The value of assets deployed outside the vault
function deployedAssets() external view returns (uint256);
/// @notice Get NAV grace period deadline
/// @return The NAV grace period deadline
function navGraceDeadline() external view returns (uint256);
/// @notice Get NAV grace period duration
/// @return The NAV grace period duration
function navGracePeriod() external view returns (uint256);
/// @notice Instant-redeem max age for OngoingDynamic (0 unset, max uint disabled)
function instantRedeemMaxAge() external view returns (uint256);
/// @notice Get the accumulated penalties from delinquency
/// @return The accumulated penalties
function accruedPenalties() external view returns (uint256);
}
src/interfaces/IAsyncVaultFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;
import {PermissionLevel} from "./IAccess.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title IAsyncVaultFactory
/// @notice Interface for creating async vaults
interface IAsyncVaultFactory {
/// @notice Emitted when a new async redeem vault is created
/// @param vault The address of the created vault
event AsyncRedeemVaultCreated(address indexed vault);
/// @notice Creates a new async redeem vault
/// @param asset The asset token address for the vault
/// @param proxy The proxy address for the vault
/// @param sharesTransferable Whether shares are transferable
/// @param permissionLevel The permission level for the vault
/// @param name The name of the vault
/// @param symbol The symbol of the vault
/// @param precision The precision for the vault
function createAsyncRedeemVault(
IERC20 asset,
address proxy,
bool sharesTransferable,
PermissionLevel permissionLevel,
string memory name,
string memory symbol,
uint256 precision
) external returns (address);
}
src/interfaces/IDepositGateway.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;
import {IRecoverable} from "./IRecoverable.sol";
import {Loan, LoanState} from "./IAccountableStrategy.sol";
/// @notice Lifecycle status of an epoch
/// @dev `None` is the default for unseen ids, so a non-existent epoch is never read as `Open`
enum EpochStatus {
/// @notice Epoch id never opened
None,
/// @notice Accepting deposits
Open,
/// @notice Closed at NAV publish, awaiting settlement
Passed,
/// @notice Settlement window missed, a newer NAV landed before the epoch settled
Invalid,
/// @notice Every request minted or refunded
Settled
}
/// @notice A subscription window
/// @dev Deposit are escrowed and only converted to shares at the post-NAV price
struct Epoch {
/// @notice Sum of live (non-cancelled) request assets; fixed once the epoch passes
uint256 totalAssets;
/// @notice Assets successfully minted into the vault during settlement
uint256 settledAssets;
/// @notice NAV measurement timestamp stamped at pass (strategy.lastNavMeasuredAt())
uint256 navMeasuredAt;
/// @notice strategy.lastNavMeasuredAt() snapshotted when the epoch opened. a strictly larger current
/// value means a NAV was published after the epoch opened (used to detect a missed onNavUpdate)
uint256 openNavMeasuredAt;
/// @notice Timestamp the epoch opened
uint256 openedAt;
/// @notice Timestamp the epoch passed
uint256 passedAt;
/// @notice Timestamp the epoch fully settled
uint256 settledAt;
/// @notice Requests not yet settled or refunded
uint256 pendingCount;
/// @notice Current status
EpochStatus status;
}
/// @notice A single user's escrowed deposit
struct DepositRequest {
/// @notice Epoch the request belongs to
uint256 epochId;
/// @notice Depositor (and share recipient at settle)
address user;
/// @notice Escrowed asset amount
uint256 assets;
/// @notice Whether shares have been minted to the user
bool settled;
/// @notice Whether the escrow has been returned (cancel or refund)
bool refunded;
/// @notice Whether the depositor has requested cancellation pending manager approval
bool cancelPending;
}
/// @notice Minimal view of the yield strategy used by the gateway
interface IMinimalStrategy {
/// @notice The vault that mints shares
function vault() external view returns (address);
/// @notice The investment manager of the strategy
function investmentManager() external view returns (address);
/// @notice The loan of the strategy
function loan() external view returns (Loan memory);
/// @notice The state of the loan
function loanState() external view returns (LoanState);
/// @notice The last NAV measurement timestamp
function lastNavMeasuredAt() external view returns (uint256);
/// @notice The maximum deposit amount for a given share and controller
function maxDeposit(address share, address controller) external view returns (uint256 maxAssets);
/// @notice The deposit gateway currently wired to the strategy (address(0) leaves deposits open)
function depositGateway() external view returns (address);
}
/// @title IDepositGateway
/// @notice Batches subscriptions into epochs so deposits enter the vault only at the post-NAV price
interface IDepositGateway {
/// @notice Emitted when an epoch opens on the first request after none is open
event EpochOpened(uint256 indexed epochId, uint256 openedAt);
/// @notice Emitted when an epoch is closed by a NAV publish
event EpochPassed(uint256 indexed epochId, uint256 navMeasuredAt);
/// @notice Emitted when an epoch is closed by the recovery path because onNavUpdate was missed
event EpochForcePassed(uint256 indexed epochId, uint256 navMeasuredAt);
/// @notice Emitted when settlement is skipped because a newer NAV was published after the epoch closed
event EpochInvalidated(uint256 indexed epochId, uint256 epochNavMeasuredAt, uint256 lastNavMeasuredAt);
/// @notice Emitted when every request in an epoch is settled or refunded
/// @param settledAssets Total assets minted into the vault across all settled requests
event EpochSettled(uint256 indexed epochId, uint256 settledAssets);
/// @notice Emitted when a deposit is escrowed
event DepositRequested(uint256 indexed requestId, uint256 indexed epochId, address indexed user, uint256 assets);
/// @notice Emitted when a request is cancelled while its epoch is open
event DepositCancelled(uint256 indexed requestId, address indexed user, uint256 assets);
/// @notice Emitted when a depositor requests cancellation pending manager approval
event DepositCancelRequested(uint256 indexed requestId, address indexed user, uint256 assets);
/// @notice Emitted when a manager approves a pending cancellation
event DepositCancelApproved(uint256 indexed requestId, address indexed user, uint256 assets);
/// @notice Emitted when a request is settled and shares are minted to the user
event RequestSettled(uint256 indexed requestId, uint256 indexed epochId, address indexed user, uint256 shares);
/// @notice Emitted when an undeliverable request is refunded
event DepositRefunded(uint256 indexed requestId, address indexed user, uint256 assets);
/// @notice Emitted when the request pause flag is changed
event AcceptingRequestsSet(bool accepting);
/// @notice Emitted when the cancellation pause flag is changed
event AcceptingCancellationsSet(bool accepting);
/// @notice Called by the strategy at the end of publishRate. Marks the open epoch `Passed` and stamps the
/// closing NAV. Must never revert (no-op on anything unexpected) so it cannot block the NAV path
function onNavUpdate() external;
/// @notice Recovery path: close the open epoch when a NAV was published after it opened but the
/// onNavUpdate hook did not record it (e.g. it reverted inside publishRate and was caught)
/// @dev Permissionless and safe: only succeeds when a strictly newer NAV exists than the one snapshotted
function forcePassEpoch() external;
/// @notice Escrow a deposit into the current open epoch (opening one if needed)
function requestDeposit(uint256 assets) external returns (uint256 requestId);
/// @notice Request cancellation of an escrowed deposit while its epoch is still open
/// @dev Succeeds only when `acceptingCancellations` is true; escrow is returned after manager approval
function requestCancelDeposit(uint256 requestId) external;
/// @notice Approve a pending cancellation and return escrow to the depositor
function approveCancelDeposit(uint256 requestId) external;
/// @notice Settle a passed epoch by minting shares directly to each request's user
/// @dev Permissionless and paginated. Off-epoch / already-handled ids are skipped
/// per-request failure (e.g. a de-whitelisted user) is skipped and left refundable
function settle(uint256 epochId, uint256[] calldata requestIds) external;
/// @notice Return the escrow of an undeliverable request to its depositor
/// @dev Permissionless when objectively undeliverable; pause/stale-NAV refunds require the depositor
function refund(uint256 requestId) external;
/// @notice Pause or resume new requests
function setAcceptingRequests(bool accepting) external;
/// @notice Pause or resume cancellations
function setAcceptingCancellations(bool accepting) external;
/// @notice The strategy that wired this gateway
function strategy() external view returns (address);
/// @notice Status of an epoch
function epochStatus(uint256 epochId) external view returns (EpochStatus);
/// @notice The currently open epoch id, or 0 if none
function openEpochId() external view returns (uint256);
/// @notice The request ids recorded for an epoch
function epochRequestIds(uint256 epochId) external view returns (uint256[] memory);
}
src/interfaces/IFeeManager.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;
import {IRecoverable} from "./IRecoverable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/// @notice The fee structure for a strategy
struct FeeStructure {
/// @notice The establishment fee
uint256 establishmentFee;
/// @notice The management fee
uint256 managementFee;
/// @notice The performance fee
uint256 performanceFee;
/// @notice The manager performance fee split
uint256 managerPerformanceFeeSplit;
/// @notice The manager management fee split
uint256 managerManagementFeeSplit;
/// @notice Whether to override the default fees
bool overrideDefaults;
}
interface IFeeManager is IRecoverable, IERC165 {
/// @notice An event that is emitted when fees are collected
event Collected(address indexed asset, address indexed strategy, uint256 performanceFee, uint256 managementFee, uint256 establishmentFee);
/// @notice An event that is emitted when protocol fees are withdrawn
event Withdraw(address indexed asset, address indexed strategy, address indexed receiver, uint256 amount);
/// @notice An event that is emitted when the fee structure is set
event FeeStructureSet(address indexed strategy, FeeStructure feeStructure);
/// @notice An event that is emitted when the pending fee structure is set
event PendingFeeStructureSet(address indexed strategy, FeeStructure feeStructure);
/// @notice An event that is emitted when the performance fee is set
event PerformanceFeeSet(address indexed strategy, uint256 performanceFee);
/// @notice An event that is emitted when the prepayment fee is set
event PrepaymentFeeSet(address indexed strategy, uint256 prepaymentFee);
/// @notice An event that is emitted when the treasury is set
event TreasurySet(address indexed oldTreasury, address indexed newTreasury);
/// @notice Collects strategy fees
/// @param asset The address of the asset
/// @param performanceFee The performance fee
/// @param managementFee The management fee
/// @param establishmentFee The establishment fee
function collect(address asset, uint256 performanceFee, uint256 managementFee, uint256 establishmentFee) external;
/// @notice Approves the pending fee structure
/// @param strategy The address of the strategy
function approvePendingFeeStructure(address strategy) external;
/// @notice Withdraws protocol fees
/// @param asset The address of the asset
function withdrawProtocolFee(address asset) external;
/// @notice Withdraws manager fees
/// @param receiver The address of the receiver
/// @param asset The address of the asset
/// @param strategy The address of the strategy
function withdrawManagerFee(address receiver, address asset, address strategy) external;
/// @notice Sets the fee structure
/// @param strategy The address of the strategy
/// @param feeStructure The fee structure
function setFeeStructure(address strategy, FeeStructure memory feeStructure) external;
/// @notice Sets the pending fee structure
/// @param strategy The address of the strategy
/// @param feeStructure The fee structure
function setPendingFeeStructure(address strategy, FeeStructure memory feeStructure) external;
/// @notice Sets the performance fee
/// @param strategy The address of the strategy
/// @param performanceFee The performance fee
function setPerformanceFee(address strategy, uint256 performanceFee) external;
/// @notice Sets the prepayment fee
/// @param strategy The address of the strategy
/// @param prepaymentFee The prepayment fee
function setPrepaymentFee(address strategy, uint256 prepaymentFee) external;
/// @notice Sets the treasury
/// @param treasury The address of the treasury
function setTreasury(address treasury) external;
/// @notice Returns the establishment fee
/// @param strategy The address of the strategy
/// @return The establishment fee
function establishmentFee(address strategy) external view returns (uint256);
/// @notice Returns the management fee
/// @param strategy The address of the strategy
/// @return The management fee
function managementFee(address strategy) external view returns (uint256);
/// @notice Returns the performance fee
/// @param strategy The address of the strategy
/// @return The performance fee
function performanceFee(address strategy) external view returns (uint256);
/// @notice Returns the manager split
/// @param strategy The address of the strategy
/// @param isPerformanceFee Whether the fee is a performance fee
/// @return The manager split
function managerSplit(address strategy, bool isPerformanceFee) external view returns (uint256);
/// @notice Returns the protocol split
/// @param strategy The address of the strategy
/// @param isPerformanceFee Whether the fee is a performance fee
/// @return The protocol split
function protocolSplit(address strategy, bool isPerformanceFee) external view returns (uint256);
/// @notice Returns the prepayment fee
/// @param strategy The address of the strategy
/// @return The prepayment fee
function prepaymentFee(address strategy) external view returns (uint256);
/// @notice Returns the fee structure
/// @param strategy The address of the strategy
/// @return The fees percentages for the strategy
function feeStructure(address strategy) external view returns (FeeStructure memory);
/// @notice Returns the pending fee structure
/// @param strategy The address of the strategy
/// @return The pending fee structure
function pendingFeeStructure(address strategy) external view returns (FeeStructure memory);
/// @notice Returns the treasury
/// @return The treasury
function treasury() external view returns (address);
/// @notice Returns the manager fees
/// @param manager The address of the manager
/// @param asset The address of the asset
/// @param strategy The address of the strategy
/// @return The manager fees of a given strategy
function managerFees(address manager, address asset, address strategy) external view returns (uint256);
/// @notice Returns the total manager fees
/// @param manager The address of the manager
/// @param asset The address of the asset
/// @param strategies The addresses of the strategies
/// @return The total manager fees of a given asset and strategies
function managerTotalFees(address manager, address asset, address[] calldata strategies)
external
view
returns (uint256);
/// @notice Returns the protocol fees
/// @param asset The address of the asset
/// @return The protocol fees
function protocolFees(address asset) external view returns (uint256);
/// @notice The basis points for the fee manager
/// @return The basis points
function BASIS_POINTS() external pure returns (uint256);
}
src/interfaces/IGlobalRegistry.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;
interface IGlobalRegistry {
/// @notice Emitted when the security admin is set
/// @param securityAdmin The address of the security admin
event SecurityAdminSet(address securityAdmin);
/// @notice Emitted when the operations admin is set
/// @param operationsAdmin The address of the operations admin
event OperationsAdminSet(address operationsAdmin);
/// @notice Emitted when the treasury is set
/// @param treasury The address of the treasury
event TreasurySet(address treasury);
/// @notice Emitted when the vault factory is set
/// @param vaultFactory The address of the vault factory
event VaultFactorySet(address vaultFactory);
/// @notice Emitted when the rewards factory is set
/// @param rewardsFactory The address of the rewards factory
event RewardsFactorySet(address rewardsFactory);
/// @notice Sets the security admin
/// @param securityAdmin The address of the security admin
function setSecurityAdmin(address securityAdmin) external;
/// @notice Sets the operations admin
/// @param operationsAdmin The address of the operations admin
function setOperationsAdmin(address operationsAdmin) external;
/// @notice Sets the treasury
/// @param treasury The address of the treasury
function setTreasury(address treasury) external;
/// @notice Sets the vault factory
/// @param vaultFactory The address of the vault factory
function setVaultFactory(address vaultFactory) external;
/// @notice Sets the rewards factory
/// @param rewardsFactory The address of the rewards factory
function setRewardsFactory(address rewardsFactory) external;
/// @notice Protocol security admin
/// @return The address of the Accountablesecurity admin
function securityAdmin() external view returns (address);
/// @notice Protocol operations admin
/// @return The address of the Accountable operations admin
function operationsAdmin() external view returns (address);
/// @notice Protocol treasury
/// @return The address of the treasury
function treasury() external view returns (address);
/// @notice Vault factory
/// @return The address of the vault factory
function vaultFactory() external view returns (address);
/// @notice Rewards distributor factory
/// @return The address of the rewards factory
function rewardsFactory() external view returns (address);
}
src/interfaces/IRecoverable.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;
/// @notice Interface for recoverable tokens
interface IRecoverable {
/// @notice Recovers tokens from the contract
/// @param token The address of the token to recover
/// @param to The address to send the recovered tokens to
/// @param amount The amount of tokens to recover
function recoverTokens(address token, address to, uint256 amount) external;
}
src/strategies/AccountableStrategy.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;
import "../constants/Errors.sol";
import {IAccess, PermissionLevel} from "../interfaces/IAccess.sol";
import {IAsyncVaultFactory} from "../interfaces/IAsyncVaultFactory.sol";
import {IGlobalRegistry} from "../interfaces/IGlobalRegistry.sol";
import {IAccountableVault} from "../interfaces/IAccountableAsyncVault.sol";
import {
IAccountableStrategy,
IStrategyVaultHooks,
IFeeManagerHooks,
LoanState,
LoanTerms,
DVNProof,
Loan
} from "../interfaces/IAccountableStrategy.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {StrategyStorage} from "./storage/StrategyStorage.sol";
/// @title AccountableStrategy
/// @notice Abstract contract that implements the IAccountableStrategy interface
/// @dev It holds the state of an accountable strategy and implements the IAccountableStrategy interface
/// @custom:security-contact [email protected]
abstract contract AccountableStrategy is PausableUpgradeable, StrategyStorage {
// ========================================================================== //
// Constants //
// ========================================================================== //
/// @dev precision for calculations
uint256 public constant PRECISION = 1e36;
/// @dev 1e6 basis points representing 100%
uint256 public constant BASIS_POINTS = 1e6;
/// @dev seconds in a days
uint256 public constant DAYS_1_SECONDS = 1 days;
/// @dev seconds in a year considered 365 days
uint256 public constant DAYS_365_SECONDS = 365 days;
// ========================================================================== //
// Modifiers //
// ========================================================================== //
/// @notice modifier to check if caller is the borrower
modifier onlyBorrower() {
if (msg.sender != borrower) revert Unauthorized();
_;
}
/// @notice modifier to check if caller is the investment manager
modifier onlyManager() {
if (msg.sender != investmentManager) revert Unauthorized();
_;
}
/// @notice modifier to check if caller is the operations admin
modifier onlyOperationsAdmin() {
if (!operationsAdminEnabled) revert Unauthorized();
if (msg.sender != IGlobalRegistry(globals).operationsAdmin()) revert Unauthorized();
_;
}
/// @notice modifier to check if caller is the safety module or the manager
modifier onlySafetyModuleOrManager() {
if (safetyModule != address(0)) {
revert_AtLeastOne(safetyModule, investmentManager);
} else {
if (msg.sender != investmentManager) revert Unauthorized();
}
_;
}
/// @notice modifier to check if caller is the manager or the security admin (if enabled)
modifier onlyManagerOrSecurityAdmin() {
if (securityAdminEnabled) {
revert_AtLeastOne(IGlobalRegistry(globals).securityAdmin(), investmentManager);
} else {
if (msg.sender != investmentManager) revert Unauthorized();
}
_;
}
/// @notice modifier to check if caller is the manager or the operations admin (if enabled)
modifier onlyManagerOrOperationsAdmin() {
if (operationsAdminEnabled) {
revert_AtLeastOne(IGlobalRegistry(globals).operationsAdmin(), investmentManager);
} else {
if (msg.sender != investmentManager) revert Unauthorized();
}
_;
}
/// @notice modifier to check if caller is the proof signer
modifier onlyProofSigner() {
if (msg.sender != proofSigner) revert Unauthorized();
_;
}
/// @notice modifier to check if caller is the vault
modifier onlyVault() {
if (msg.sender != vault) revert Unauthorized();
_;
}
/// @dev Reverts if the caller is not one of the two addresses
function revert_AtLeastOne(address a, address b) internal view {
if (msg.sender != a && msg.sender != b) revert Unauthorized();
}
// ========================================================================== //
// Pausable Functions //
// ========================================================================== //
/// @dev Pauses the contract
function pause() public onlyManagerOrSecurityAdmin {
if (msg.sender == IGlobalRegistry(globals).securityAdmin()) {
_pausedByAdmin = true;
}
_pause();
}
/// @dev Unpauses the contract and checks whether msg.sender is admin when loan was paused by admin
function unpause() public onlyManagerOrSecurityAdmin {
if (_pausedByAdmin && msg.sender != IGlobalRegistry(globals).securityAdmin()) {
revert Unauthorized();
}
_pausedByAdmin = false;
_unpause();
}
// ========================================================================== //
// Configuration Functions //
// ========================================================================== //
/// @inheritdoc IAccountableStrategy
function setPendingBorrower(address newBorrower) external virtual onlyManager {
if (newBorrower == address(0)) revert ZeroAddress();
pendingBorrower = newBorrower;
emit PendingBorrowerSet(newBorrower);
}
/// @inheritdoc IAccountableStrategy
function acceptBorrowerRole() external virtual {
if (msg.sender != pendingBorrower) revert InvalidPendingBorrower();
emit BorrowerChanged(borrower, msg.sender);
borrower = msg.sender;
pendingBorrower = address(0);
}
/// @inheritdoc IAccountableStrategy
function setInvestmentManager(address investmentManager_) external virtual onlyManager {
if (investmentManager_ == address(0)) revert ZeroAddress();
investmentManager = investmentManager_;
emit InvestmentManagerSet(investmentManager_);
}
/// @inheritdoc IAccountableStrategy
function setAuthSigner(address authSigner_) external onlyManager {
IAccess(vault).setSigner(authSigner_);
}
/// @inheritdoc IAccountableStrategy
function setLenders(address[] calldata lenders, bool[] calldata allowed) external onlyManager {
IAccess(vault).setAllowed(lenders, allowed);
}
/// @inheritdoc IAccountableStrategy
function setProofSigner(address proofSigner_) external virtual onlyManager {
if (proofSigner_ == address(0)) revert ZeroAddress();
proofSigner = proofSigner_;
emit ProofSignerSet(proofSigner_);
}
/// @inheritdoc IAccountableStrategy
function setManagerFeeRecipient(address managerFeeRecipient_) external virtual onlyManager {
if (managerFeeRecipient_ == address(0)) revert ZeroAddress();
managerFeeRecipient = managerFeeRecipient_;
emit ManagerFeeRecipientSet(managerFeeRecipient_);
}
/// @inheritdoc IAccountableStrategy
function publishDVNProof(DVNProof memory proof) external virtual onlyProofSigner {
_dvnProof = proof;
emit DVNProofPublished(proof.root, proof.signature, proof.messageHash);
}
/// @inheritdoc IAccountableStrategy
function acceptDefault() public virtual {
if (block.timestamp < _defaultValidAt || _defaultValidAt == 0) revert TimelockNotExpired();
_requireLoanOngoing(); // a repaid loan is no longer default-eligible
loanState = LoanState.InDefault;
emit LoanDefaulted(_loan.outstandingPrincipal, IAccountableVault(vault).totalAssets());
}
/// @inheritdoc IAccountableStrategy
function rejectDefault() external onlyManager {
_defaultValidAt = 0;
emit LoanDefaultRejected();
}
/// @inheritdoc IAccountableStrategy
function setPenaltiesEnabled(bool enabled) external virtual onlyManager {
penaltiesEnabled = enabled;
emit PenaltiesEnabledSet(enabled);
}
/// @inheritdoc IAccountableStrategy
function setSecurityAdminEnabled(bool enabled) external virtual onlyManager {
securityAdminEnabled = enabled;
emit SecurityAdminEnabledSet(enabled);
}
/// @inheritdoc IAccountableStrategy
function setOperationsAdminEnabled(bool enabled) external virtual onlyManager {
operationsAdminEnabled = enabled;
emit OperationsAdminEnabledSet(enabled);
}
/// @inheritdoc IAccountableStrategy
function setSharesTransferable(bool transferable) external virtual onlyManager {
IAccountableVault(vault).setSharesTransferable(transferable);
}
/// @inheritdoc IAccountableStrategy
function setReserveThreshold(uint256 threshold) external virtual onlyManager {
if (threshold > BASIS_POINTS) revert ThresholdTooHigh();
_loan.reserveThreshold = threshold;
emit ReserveThresholdSet(threshold);
}
/// @inheritdoc IAccountableStrategy
function setSafetyModule(address safetyModule_) external virtual onlyManager {
if (safetyModule_ == address(0)) revert ZeroAddress();
safetyModule = safetyModule_;
emit SafetyModuleSet(safetyModule_);
}
/// @inheritdoc IAccountableStrategy
function setRewardsDistributor(address rewards_) external virtual onlyManager {
if (rewards_ == address(0)) revert ZeroAddress();
rewards = rewards_;
emit RewardsDistributorSet(rewards_);
}
/// @inheritdoc IAccountableStrategy
function setPriceOracle(address priceOracle_) external virtual onlyManager {
_requireLoanNotOngoing();
if (priceOracle_ == address(0)) revert ZeroAddress();
priceOracle = priceOracle_;
emit PriceOracleSet(priceOracle_);
}
// ========================================================================== //
// View Functions //
// ========================================================================== //
/// @inheritdoc IAccountableStrategy
function loan() external view returns (Loan memory) {
return _loan;
}
/// @inheritdoc IAccountableStrategy
function dvnProof() external view returns (DVNProof memory) {
return _dvnProof;
}
// ========================================================================== //
// Strategy Vault Hooks //
// ========================================================================== //
/// @inheritdoc IStrategyVaultHooks
function onRequestDeposit(address share, uint256, address, address)
public
virtual
onlyVault
whenNotPaused
returns (bool canFulfill, uint256 price)
{
return (false, _sharePrice(share));
}
/// @inheritdoc IStrategyVaultHooks
function onRequestRedeem(address share, uint256, address, address)
public
virtual
onlyVault
whenNotPaused
returns (bool canFulfill, uint256 price)
{
return (false, _sharePrice(share));
}
/// @inheritdoc IStrategyVaultHooks
function onCancelDepositRequest(address, address) public virtual onlyVault whenNotPaused returns (bool canCancel) {
return true;
}
/// @inheritdoc IStrategyVaultHooks
function onCancelRedeemRequest(address, address) public virtual onlyVault whenNotPaused returns (bool canCancel) {
return true;
}
/// @inheritdoc IStrategyVaultHooks
function onDeposit(address share, uint256, address, address)
public
virtual
onlyVault
whenNotPaused
returns (uint256 price)
{
price = _sharePrice(share);
}
/// @inheritdoc IStrategyVaultHooks
function onMint(address share, uint256, address, address)
public
virtual
onlyVault
whenNotPaused
returns (uint256 price)
{
price = _sharePrice(share);
}
/// @inheritdoc IStrategyVaultHooks
function onRedeem(address, uint256, address, address) public virtual onlyVault whenNotPaused {}
/// @inheritdoc IStrategyVaultHooks
function onWithdraw(address, uint256, address, address) public virtual onlyVault whenNotPaused {}
/// @inheritdoc IStrategyVaultHooks
function onTransfer(address, address, address, uint256) public virtual onlyVault whenNotPaused {}
/// @inheritdoc IStrategyVaultHooks
function authOperator(address operator) external virtual {
if (msg.sender != vault) revert Unauthorized();
if (operator != investmentManager && operator != borrower) revert Unauthorized();
}
/// @inheritdoc IStrategyVaultHooks
function sharePrice(address share) external view virtual returns (uint256 price) {
return _sharePrice(share);
}
/// @dev Computes the share price. To be overridden by the derived strategy
function _sharePrice(address share) internal view virtual returns (uint256 price);
/// @inheritdoc IStrategyVaultHooks
function accruedAssets(address share) external view virtual returns (uint256 assets) {
assets = _accruedAssets(share);
}
/// @dev Computes the accrued assets. To be overridden by the derived strategy
function _accruedAssets(address share) internal view virtual returns (uint256 assets);
/// @inheritdoc IStrategyVaultHooks
function maxDeposit(address, address) public view virtual returns (uint256 maxAssets) {
return type(uint256).max;
}
/// @inheritdoc IStrategyVaultHooks
function maxRedeem(address, address) public view virtual returns (uint256 maxShares) {
return type(uint256).max;
}
// ========================================================================== //
// Fee Manager Hooks //
// ========================================================================== //
/// @inheritdoc IFeeManagerHooks
function onFeeStructureChange() public virtual whenNotPaused {
if (msg.sender != feeManager) revert Unauthorized();
}
/// @inheritdoc IAccountableStrategy
function version() external view virtual returns (uint256) {
return 2;
}
// ========================================================================== //
// Internal Helper Functions //
// ========================================================================== //
/// @dev Calls the factory to create a new async redeem vault
function _makeVault(
IERC20 asset_,
bool sharesTransferable_,
PermissionLevel permissionLevel_,
string memory name_,
string memory symbol_
) internal {
vault = IAsyncVaultFactory(IGlobalRegistry(globals).vaultFactory()).createAsyncRedeemVault(
asset_, address(this), sharesTransferable_, permissionLevel_, name_, symbol_, PRECISION
);
}
/// @dev Sets the loan terms and initializes the loan state
function _setTerms(LoanTerms memory terms) internal {
_loan = Loan({
lateInterestGracePeriod: terms.lateInterestGracePeriod == 0 ? 2 days : terms.lateInterestGracePeriod,
acceptGracePeriod: terms.acceptGracePeriod == 0 ? 2 days : terms.acceptGracePeriod,
depositPeriod: terms.depositPeriod,
withdrawalPeriod: terms.withdrawalPeriod,
lateInterestPenalty: terms.lateInterestPenalty,
interestInterval: terms.interestInterval,
interestRate: terms.interestRate,
minDeposit: terms.minDeposit,
minRedeem: terms.minRedeem,
maxCapacity: terms.maxCapacity,
minCapacity: terms.minCapacity,
duration: terms.duration,
reserveThreshold: 0,
outstandingPrincipal: 0,
outstandingInterest: 0,
claimableInterest: 0,
drawableFunds: 0,
termsSetTime: 0,
termsUpdateTime: 0,
startTime: 0
});
}
/// @dev Checks that the loan terms have been set
function _requireLoanTermsSet() internal view {
if (loanState != LoanState.TermsSet) revert LoanTermsNotSet();
}
/// @dev Checks that the loan terms have not been set
function _requireLoanTermsNotSet() internal view {
if (loanState != LoanState.Initialized) revert LoanTermsAlreadySet();
}
/// @dev Checks that the loan is not ongoing
function _requireLoanNotOngoing() internal view {
if (loanState == LoanState.OngoingLocked || loanState == LoanState.OngoingDynamic) revert LoanOngoing();
}
/// @dev Checks that the loan is ongoing
function _requireLoanOngoing() internal view {
if (loanState != LoanState.OngoingLocked && loanState != LoanState.OngoingDynamic) revert LoanNotOngoing();
}
/// @dev Checks that the loan is in default
function _requireLoanInDefault() internal view {
if (loanState != LoanState.InDefault) revert LoanNotInDefault();
}
/// @dev Checks that the deposit amount is greater than the minimum deposit amount
function _requireMinDepositAmount(uint256 amount) internal view {
if (amount < _loan.minDeposit) revert InsufficientAmount();
}
}
src/strategies/storage/StrategyStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {IAccountableStrategy, Loan, DVNProof, LoanState} from "../../interfaces/IAccountableStrategy.sol";
/// @title StrategyStorage
/// @notice Storage layout for AccountableStrategy with upgrade safety gap
/// @dev Centralizes storage to avoid collisions and simplify upgradeable contract development
/// All storage variables MUST be declared here
abstract contract StrategyStorage is IAccountableStrategy {
/// @dev whether paused by admin
bool internal _pausedByAdmin;
/// @dev loan terms and state
Loan internal _loan;
/// @dev DVN proof
DVNProof internal _dvnProof;
/// @dev timestamp when the default is valid
uint256 internal _defaultValidAt;
/// @dev whether penalties are enabled
bool public penaltiesEnabled;
/// @dev whether security admin is enabled
bool public securityAdminEnabled;
/// @dev whether operations admin is enabled
bool public operationsAdminEnabled;
/// @notice loan borrower
address public borrower;
/// @notice pending loan borrower
address public pendingBorrower;
/// @dev loan state
LoanState public loanState;
/// @notice address of global registry
address public globals;
/// @notice address of fee manager
address public feeManager;
/// @notice address of safety module
address public safetyModule;
/// @notice address of proof signer
/// @dev This is the public key of the DVN proof signer
/// It can be used to verify the published DVN proofs
address public proofSigner;
/// @notice address of vault
address public vault;
/// @notice address of investment manager
address public investmentManager;
/// @notice address of rewards distributor
address public rewards;
/// @notice address of price oracle
address public priceOracle;
/// @notice address of DVN publisher
address public dvnPublisher;
/// @notice address of manager fee recipient
address public managerFeeRecipient;
/// @dev Gap for future storage variables in base contract
/// @dev Reserves 50 slots for future additions to AccountableStrategy
uint256[48] private __gap;
}
src/strategies/storage/YieldStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {LoanTerms} from "../../interfaces/IAccountableStrategy.sol";
import {IAccountableYield} from "../../interfaces/IAccountableYield.sol";
/// @title YieldStorage
/// @notice Storage layout for AccountableYield with upgrade safety gap
/// @dev Centralizes storage to avoid collisions and simplify upgradeable contract development
abstract contract YieldStorage is IAccountableYield {
/// @notice Last fee accrual timestamp
uint256 internal _lastFeeTime;
/// @notice Last timestamp when penalties were accrued
uint256 internal _lastPenaltyTime;
/// @notice Pending terms awaiting borrower acceptance
LoanTerms internal _pendingTerms;
/// @notice Underlying asset address
address public asset;
/// @notice Time when delinquency started
uint256 public delinquencyStartTime;
/// @notice Last recorded total assets
uint256 public lastTotalAssets;
/// @notice Performance fee high-water mark, expressed as a share-price ratio
uint256 public peakSharePrice;
/// @notice Value of assets deployed outside the vault
uint256 public deployedAssets;
/// @notice Realized losses that should not generate fees on recovery (cumulative, never resets)
uint256 public lostAssets;
/// @notice Timestamp when NAV grace period expires
uint256 public navGraceDeadline;
/// @notice Duration of NAV grace period after update
uint256 public navGracePeriod;
/// @notice Accumulated penalties from delinquency past grace period
uint256 public accruedPenalties;
/// @notice Timestamp of the last accepted DVN measurement
uint256 public lastNavMeasuredAt;
/// @notice Timestamp of the last borrow/repay operation
uint256 public lastFlowTimestamp;
/// @notice Deposit gateway permitted to deposit on behalf of users; address(0) leaves deposits open
address public depositGateway;
/// @notice Max seconds after lastNavMeasuredAt for instant redeem in OngoingDynamic
/// @dev 0 = unset (navGracePeriod only), type(uint256).max = instant disabled (queue only)
uint256 public instantRedeemMaxAge;
/// @dev Gap for future storage variables
/// @dev Reserves slots for future additions to YieldStorage
uint256[48] private __gap;
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"murky/=lib/murky/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
"solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/",
"safe-smart-account/=lib/safe-smart-account/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.