Verified contractPartialMIT
ZenjiWstEthPmUsd
Address0x86c4fcc641dd06da93ac159e063f88f6eff085e1
- Balance
0 ETH
- Transactions
3
- Compiler
solc 0.8.34
- Same code
3 more contracts
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,702,362
- Creation transaction
- 0x41551cb90f…35bfe8ebd4
- Libraries
- src/implementations/ZenjiWstEthPmUsd.sol:ZenjiCoreLib0xd581…b0b069
16 files
- src/implementations/ZenjiWstEthPmUsd.solmain1.44 KB
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol6.54 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol10.8 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- src/Zenji.sol48.21 KB
- src/ZenjiViewHelper.sol7.75 KB
- src/interfaces/IERC20.sol777 B
- src/interfaces/IERC4626.sol12.29 KB
- src/interfaces/ILoanManager.sol6.06 KB
- src/interfaces/ISwapper.sol1.05 KB
- src/interfaces/IYieldStrategy.sol3.1 KB
- src/libraries/SafeTransferLib.sol2.56 KB
- src/libraries/TimelockLib.sol3.39 KB
- src/libraries/ZenjiCoreLib.sol19.13 KB
src/implementations/ZenjiWstEthPmUsd.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
import { Zenji } from "../Zenji.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/// @notice Zenji vault implementation for wstETH/USDT using pmUSD/crvUSD strategy
contract ZenjiWstEthPmUsd is Zenji {
address private constant WSTETH = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;
address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
constructor(
address _loanManager,
address _yieldStrategy,
address _swapper,
address _owner,
address _viewHelper
) Zenji(WSTETH, USDT, _loanManager, _yieldStrategy, _swapper, _owner, _viewHelper) { }
function name() public pure override(ERC20, IERC20Metadata) returns (string memory) {
return "Zen wstETH (pmUSD/crvUSD StakeDao)";
}
function symbol() public pure override(ERC20, IERC20Metadata) returns (string memory) {
return "zenWstETH-pmUSDcrvUSDStake";
}
/// @notice wstETH has 18 decimals — the base 1e5 provides zero protection.
/// 3e16 = 0.03 wstETH ≈ $114 dead capital (at $3,800/wstETH).
/// Matches WBTC's ~$100 dead capital. Dilution: ~11 bps at $100K TVL, ~1 bp at $1M TVL.
function VIRTUAL_SHARE_OFFSET() public pure override returns (uint256) {
return 3e16;
}
}
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 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/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
src/Zenji.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { IERC20 } from "./interfaces/IERC20.sol";
import { IERC4626 } from "./interfaces/IERC4626.sol";
import { IYieldStrategy } from "./interfaces/IYieldStrategy.sol";
import { ILoanManager } from "./interfaces/ILoanManager.sol";
import { ISwapper } from "./interfaces/ISwapper.sol";
import { TimelockLib } from "./libraries/TimelockLib.sol";
import { SafeTransferLib } from "./libraries/SafeTransferLib.sol";
import { ZenjiCoreLib } from "./libraries/ZenjiCoreLib.sol";
import { ZenjiViewHelper } from "./ZenjiViewHelper.sol";
interface IStrategySlippageConfig {
function setSlippage(uint256 newSlippage) external;
}
/// @title Zenji
/// @notice ERC4626-compliant conservative collateral yield vault using loan managers and yield strategies
/// @dev Deposits collateral to a loan manager, borrows debt asset, deposits to yield strategy
contract Zenji is ERC20, IERC4626 {
using TimelockLib for TimelockLib.AddressTimelockData;
using SafeTransferLib for IERC20;
// ============ Constants ============
uint256 public constant PRECISION = 1e18;
uint256 public constant DEADBAND_SPREAD = 3e16; // 3%
uint256 public constant MIN_TARGET_LTV = 15e16; // 15%
uint256 public constant MAX_TARGET_LTV = 65e16; // 65%
uint256 internal constant DEFAULT_LOAN_BANDS = 4; // TODO: This should live in llamaloanmanager
uint256 internal constant MIN_DEPOSIT = 1e4;
uint256 public constant MAX_FEE_RATE = 2e17; // 20%
// VIRTUAL_SHARE_OFFSET is now a virtual function — see bottom of contract
uint256 public constant COOLDOWN_BLOCKS = 1;
uint256 public constant MAX_REBALANCE_BOUNTY = 1e18; // 100%
uint256 public constant TIMELOCK_DELAY = 1 weeks;
uint256 public constant MAX_VAULT_SLIPPAGE = 1e17; // 10% cap
uint256 public constant MIN_STRATEGY_DEBT_RATIO = 5e17; // 50%
uint256 public constant MAX_STRATEGY_DEBT_RATIO = 2e18; // 200%
// ============ Immutables ============
IERC20 public immutable collateralAsset;
IERC20 public immutable debtAsset;
ZenjiViewHelper public immutable viewHelper;
ILoanManager public immutable loanManager;
ISwapper public swapper;
// ============ State ============
uint256 public targetLtv;
address public strategist;
address public gov;
address public guardian;
bool public idle;
bool public emergencyMode;
bool public liquidationComplete;
/// @notice Bitmask: bit 0 = step 0 resolved, bit 1 = step 1 resolved.
/// Both bits must be set (via emergencyStep or emergencySkipStep) before step 2 is allowed.
uint8 public emergencyStepsCompleted;
uint256 public accumulatedFees;
uint256 public feeRate;
uint256 public lastStrategyBalance;
uint256 private _status;
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
address public pendingStrategist;
address public pendingGov;
address public pendingGuardian;
uint256 public rebalanceBountyRate;
uint256 public depositCap;
uint256 public maxSlippage;
uint256 public minStrategyToDebtRatioForBorrow;
uint256 public maxStrategyToDebtRatioForBorrow;
uint256 public feesAtLastRebalance;
// Tracks the last block where an address received shares (mint or transfer).
// Caveat: because any incoming share transfer updates this value, a third party can
// send dust shares and force a 1-block cooldown on the recipient (dust-grief vector).
mapping(address => uint256) public lastInBlock;
// Yield strategy
IYieldStrategy public immutable yieldStrategy;
// Timelock state (using TimelockLib)
TimelockLib.AddressTimelockData internal _swapperTimelock;
// ============ Events ============
// Keeper actions
event Rebalance(uint256 oldLtv, uint256 newLtv, bool increased);
event RebalanceBountyPaid(address indexed keeper, uint256 amount);
// Capital management
event CapitalDeployed(uint256 collateralAmount, uint256 debtBorrowed);
event CapitalUnwound(uint256 collateralNeeded, uint256 collateralReceived);
// Role transfers
event StrategistTransferStarted(
address indexed previousStrategist, address indexed newStrategist
);
event StrategistUpdated(address indexed newStrategist);
event GovernanceTransferStarted(address indexed previousGov, address indexed newGov);
event GovernanceUpdated(address indexed newGov);
event GuardianTransferStarted(address indexed previousGuardian, address indexed newGuardian);
event GuardianUpdated(address indexed newGuardian);
event IdleModeEntered();
event IdleModeExited();
event ParamUpdated(uint8 indexed param, uint256 oldValue, uint256 newValue);
event FeesWithdrawn(address indexed recipient, uint256 amount);
event SwapperUpdated(address indexed oldSwapper, address indexed newSwapper);
event SwapperChangeProposed(
address indexed currentSwapper, address indexed newSwapper, uint256 effectiveTime
);
event SwapperChangeCancelled(address indexed cancelledSwapper);
event StrategySlippageUpdated(address indexed strategy, uint256 newSlippage);
// Fee/LTV change events use ParamUpdated above
// Strategy events
error SwapperUnderperformed(uint256 expected, uint256 received);
event StrategyDeposit(
address indexed strategy, uint256 debtAssetAmount, uint256 underlyingDeposited
);
// Emergency
event EmergencyModeEntered();
event LiquidationComplete(uint256 collateralRecovered, uint256 flashloanAmount);
event EmergencyStepSkipped(uint8 indexed step);
event AssetsRescued(address indexed token, address indexed recipient, uint256 amount);
event FeesAccrued(uint256 profit, uint256 fees, uint256 totalAccumulatedFees);
event YieldHarvested(address indexed caller, uint256 rewardsValue);
event EmergencyCollateralTransferred(uint256 amount);
event EmergencyDebtTransferred(uint256 amount);
event EmergencyYieldRedeemed(uint256 debtAssetReceived);
/// @notice Emitted when loan unwinding is attempted in emergency mode
event EmergencyLoanUnwound(uint256 collateralRecovered, uint256 debtRecovered);
// ============ Errors ============
error Unauthorized();
error ZeroAmount();
error InsufficientShares();
error RebalanceNotNeeded();
error InvalidAddress();
error AmountTooSmall();
error ReentrancyError();
error InvalidFeeRate();
error InvalidTargetLtv();
error EmergencyModeActive();
error EmergencyModeNotActive();
error InvalidBountyRate();
error DepositCapExceeded();
error InvalidStrategy();
error LiquidationAlreadyComplete();
error InsufficientCollateral();
error InsufficientDeposit();
error InsufficientWithdrawal();
error EmergencyStepsIncomplete();
error InvalidEmergencyStep();
error InvalidSlippage();
error InvalidCoverageRatio();
error StrategyDebtCoverageTooLow(uint256 currentRatio, uint256 minRatio);
error ActionDelayActive();
// ============ Modifiers ============
modifier onlyStrategist() {
if (msg.sender != strategist) revert Unauthorized();
_;
}
modifier onlyGov() {
if (msg.sender != gov) revert Unauthorized();
_;
}
modifier onlyGuardian() {
if (msg.sender != guardian) revert Unauthorized();
_;
}
modifier nonReentrant() {
if (_status == _ENTERED) revert ReentrancyError();
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
// ============ Constructor ============
/// @param _yieldStrategy Yield strategy address (immutable)
/// @param _swapper Swapper contract address (required)
/// @param _owner Initial address for all three roles (strategist, gov, guardian)
constructor(
address _collateralAsset,
address _debtAsset,
address _loanManager,
address _yieldStrategy,
address _swapper,
address _owner,
address _viewHelper
) ERC20("Zen WBTC", "zenWBTC") {
if (
_collateralAsset == address(0) || _debtAsset == address(0) || _loanManager == address(0)
|| _yieldStrategy == address(0) || _swapper == address(0) || _owner == address(0)
|| _viewHelper == address(0)
) {
revert InvalidAddress();
}
collateralAsset = IERC20(_collateralAsset);
debtAsset = IERC20(_debtAsset);
loanManager = ILoanManager(_loanManager);
swapper = ISwapper(_swapper);
viewHelper = ZenjiViewHelper(_viewHelper);
// Validate loan manager assets match vault assets
if (
loanManager.collateralAsset() != address(collateralAsset)
|| loanManager.debtAsset() != address(debtAsset)
) {
revert InvalidAddress();
}
// Validate strategy accepts the debt asset and is bound (or bindable) to this vault
if (IYieldStrategy(_yieldStrategy).asset() != address(debtAsset)) {
revert InvalidStrategy();
}
address stratVault = IYieldStrategy(_yieldStrategy).vault();
if (stratVault != address(0) && stratVault != address(this)) {
revert InvalidStrategy();
}
yieldStrategy = IYieldStrategy(_yieldStrategy);
strategist = _owner;
gov = _owner;
guardian = _owner;
idle = false;
targetLtv = 65e16; // 65% default target LTV
// Liquidation starts at ~90%
// Vault can handle about 25% price move in testing without rebalancing.
rebalanceBountyRate = 2e17; // 20% default rebalance bounty
feeRate = 0; // Default fee rate disabled
maxSlippage = 1e16; // 1% default vault slippage
minStrategyToDebtRatioForBorrow = 95e16; // 95% default strategy/debt coverage guard
maxStrategyToDebtRatioForBorrow = 105e16; // 105% default upper strategy/debt guard
_status = _NOT_ENTERED;
// Loan manager is provided externally and immutable for this vault
}
// ============ ERC4626 Required Functions ============
/// @notice Returns the address of the underlying collateral asset
function asset() external view override returns (address) {
return address(collateralAsset);
}
/// @notice Returns total collateral managed by the vault
function totalAssets() public view override returns (uint256) {
return getTotalCollateral();
}
/// @notice Convert assets to shares
function convertToShares(uint256 assets) public view override returns (uint256) {
return _calculateSharesForDeposit(assets);
}
/// @notice Convert shares to assets
function convertToAssets(uint256 shareAmount) public view override returns (uint256) {
return _calculateCollateralForShares(shareAmount);
}
/// @notice Maximum deposit allowed for receiver
function maxDeposit(address) external view override returns (uint256) {
if (emergencyMode) return 0;
if (depositCap == 0) return type(uint256).max;
uint256 totalCollateral = getTotalCollateral();
return totalCollateral >= depositCap ? 0 : depositCap - totalCollateral;
}
/// @notice Maximum mint allowed for receiver
function maxMint(address receiver) external view override returns (uint256) {
uint256 maxAssets = this.maxDeposit(receiver);
if (maxAssets == type(uint256).max) return type(uint256).max;
return convertToShares(maxAssets);
}
/// @notice Maximum withdraw allowed for share holder
function maxWithdraw(address owner_) external view override returns (uint256) {
if (emergencyMode && !liquidationComplete) return 0;
if (emergencyMode && liquidationComplete) {
uint256 supply = totalSupply();
if (supply < 1) return 0;
return (collateralAsset.balanceOf(address(this)) * balanceOf(owner_)) / supply;
}
return convertToAssets(balanceOf(owner_));
}
/// @notice Maximum redeem allowed for share holder
function maxRedeem(address owner_) external view override returns (uint256) {
if (emergencyMode && !liquidationComplete) return 0;
return balanceOf(owner_);
}
/// @notice Preview shares for deposit
function previewDeposit(uint256 assets) external view override returns (uint256) {
return convertToShares(assets);
}
/// @notice Preview assets for mint (rounds up per ERC4626)
function previewMint(uint256 shareAmount) external view override returns (uint256) {
return _convertToAssetsRoundUp(shareAmount);
}
/// @notice Preview shares for withdraw
function previewWithdraw(uint256 assets) external view override returns (uint256) {
uint256 supply = totalSupply();
if (emergencyMode && liquidationComplete) {
uint256 availableCollateral = collateralAsset.balanceOf(address(this));
if (availableCollateral < 1 || supply < 1) return 0;
return (assets * supply + availableCollateral - 1) / availableCollateral;
}
uint256 totalCollateral = getTotalCollateral();
if (totalCollateral < 1 || supply < 1) return assets;
return (assets * (supply + VIRTUAL_SHARE_OFFSET()) + totalCollateral - 1)
/ (totalCollateral + VIRTUAL_SHARE_OFFSET());
}
/// @notice Preview assets for redeem
function previewRedeem(uint256 shareAmount) external view override returns (uint256) {
if (emergencyMode && liquidationComplete) {
uint256 supply = totalSupply();
if (supply < 1) return 0;
return (collateralAsset.balanceOf(address(this)) * shareAmount) / supply;
}
return convertToAssets(shareAmount);
}
/// @notice ERC4626 deposit - deposit assets and receive shares
function deposit(uint256 assets, address receiver)
external
override
nonReentrant
returns (uint256 sharesMinted)
{
_accrueYieldFees();
sharesMinted = _calculateSharesForDeposit(assets);
_deposit(assets, sharesMinted, receiver);
}
/// @notice ERC4626 mint - mint exact shares by depositing assets
function mint(uint256 shareAmount, address receiver)
external
override
nonReentrant
returns (uint256 assets)
{
if (shareAmount == 0) revert ZeroAmount();
_accrueYieldFees();
assets = _convertToAssetsRoundUp(shareAmount);
_deposit(assets, shareAmount, receiver);
}
/// @notice ERC4626 withdraw - withdraw exact assets by burning shares
function withdraw(uint256 assets, address receiver, address owner_)
external
override
nonReentrant
returns (uint256 shareAmount)
{
if (assets == 0) revert ZeroAmount();
if (emergencyMode && !liquidationComplete) revert EmergencyModeActive();
if (emergencyMode && liquidationComplete) {
uint256 availableCollateral = collateralAsset.balanceOf(address(this));
if (availableCollateral < 1) revert ZeroAmount();
shareAmount = (assets * totalSupply() + availableCollateral - 1) / availableCollateral;
} else {
// Accrue fees before pricing to prevent fee bypass
_accrueYieldFees();
// Calculate shares to burn (round up)
uint256 totalCollateral = getTotalCollateral();
uint256 supply = totalSupply();
shareAmount = (assets * (supply + VIRTUAL_SHARE_OFFSET()) + totalCollateral - 1)
/ (totalCollateral + VIRTUAL_SHARE_OFFSET());
// If requested assets correspond to (or exceed) all holder shares,
// snap to full share burn so the final-withdraw path can execute.
// This avoids rounding edge-cases where withdraw(convertToAssets(allShares))
// computes slightly fewer shares and falls into partial unwind.
uint256 ownerShares = balanceOf(owner_);
if (ownerShares > 0 && assets >= convertToAssets(ownerShares)) {
shareAmount = ownerShares;
}
}
(, shareAmount) = _redeem(shareAmount, receiver, owner_);
}
/// @notice ERC4626 redeem - redeem exact shares for assets
function redeem(uint256 shareAmount, address receiver, address owner_)
external
override
nonReentrant
returns (uint256 collateralAmount)
{
if (emergencyMode && !liquidationComplete) revert EmergencyModeActive();
(collateralAmount,) = _redeem(shareAmount, receiver, owner_);
}
// ============ Keeper Functions ============
/// @notice Deploy idle collateral into yield strategy
function _deployCapital() internal {
if (idle || emergencyMode) return;
uint256 idleCollateral = collateralAsset.balanceOf(address(this));
if (idleCollateral < 1) revert ZeroAmount();
uint256 borrowAmount = loanManager.calculateBorrowAmount(idleCollateral, targetLtv);
if (borrowAmount < 1) return;
loanManager.checkOracleFreshness();
collateralAsset.safeTransfer(address(loanManager), idleCollateral);
if (!loanManager.loanExists()) {
loanManager.createLoan(idleCollateral, borrowAmount, DEFAULT_LOAN_BANDS);
} else {
loanManager.addCollateral(idleCollateral);
loanManager.borrowMore(0, borrowAmount);
}
// Get debt asset from loan manager and deploy to yield vault
uint256 debtBalance = loanManager.getDebtBalance();
if (debtBalance > 0) {
loanManager.transferDebt(address(this), debtBalance);
_deployDebtToYield(debtBalance);
}
emit CapitalDeployed(idleCollateral, borrowAmount);
}
/// @notice Rebalance LTV and/or strategy-debt coverage
function rebalance() external nonReentrant {
if (!loanManager.loanExists()) revert RebalanceNotNeeded();
uint256 currentLtv = 0;
uint256 lowerBand = targetLtv - DEADBAND_SPREAD;
uint256 upperBand = targetLtv + DEADBAND_SPREAD;
uint256 strategyDebtRatio = strategyToDebtRatio();
bool ratioTooLow =
strategyDebtRatio != type(uint256).max
&& strategyDebtRatio < minStrategyToDebtRatioForBorrow;
bool ratioTooHigh =
strategyDebtRatio != type(uint256).max
&& strategyDebtRatio > maxStrategyToDebtRatioForBorrow;
loanManager.checkOracleFreshness();
currentLtv = loanManager.getCurrentLTV();
bool ltvOutOfBand = currentLtv < lowerBand || currentLtv > upperBand;
if (!ltvOutOfBand && !ratioTooLow && !ratioTooHigh) {
revert RebalanceNotNeeded();
}
// Accrue fees and pay keeper bounty before adjusting LTV
// (must happen before deposit to avoid IPOR lock conflict)
_accrueYieldFees();
uint256 bountyPaid;
(feesAtLastRebalance, lastStrategyBalance, bountyPaid) = ZenjiCoreLib.processRebalanceBounty(
yieldStrategy,
debtAsset,
accumulatedFees,
feesAtLastRebalance,
rebalanceBountyRate,
PRECISION,
msg.sender
);
if (bountyPaid > 0) {
accumulatedFees -= bountyPaid;
}
uint256 newLtv = 0;
bool increased = false;
if (ltvOutOfBand && currentLtv < lowerBand) {
increased = true;
_adjustLtv(targetLtv, true, true);
newLtv = loanManager.getCurrentLTV();
} else if (ltvOutOfBand && currentLtv > upperBand) {
increased = false;
_adjustLtv(targetLtv, false, true);
newLtv = loanManager.getCurrentLTV();
} else if (ratioTooLow) {
increased = false;
lastStrategyBalance = ZenjiCoreLib.rebalanceCoverageUp(
loanManager, yieldStrategy, debtAsset, maxSlippage, PRECISION
);
newLtv = loanManager.getCurrentLTV();
} else if (ratioTooHigh) {
increased = true;
lastStrategyBalance = ZenjiCoreLib.rebalanceCoverageDown(
loanManager,
yieldStrategy,
debtAsset,
maxStrategyToDebtRatioForBorrow,
upperBand,
maxSlippage,
PRECISION
);
newLtv = loanManager.getCurrentLTV();
}
emit Rebalance(currentLtv, newLtv, increased);
}
/// @notice Accrue outstanding fees from yield vault profits
/// @dev Permissionless - anyone can trigger fee accrual
function accrueYieldFees() external nonReentrant {
_accrueYieldFees();
}
/// @notice Harvest and compound yield strategy rewards
/// @dev Permissionless - anyone can trigger harvest
function harvestYield() external nonReentrant {
if (emergencyMode) revert EmergencyModeActive();
if (address(yieldStrategy) == address(0)) revert InvalidStrategy();
_accrueYieldFees();
uint256 harvested = yieldStrategy.harvest();
_accrueYieldFees();
emit YieldHarvested(msg.sender, harvested);
}
// ============ Strategist Functions ============
/// @notice Enter/exit idle mode (unwind carry trade, hold collateral)
/// @dev Strategist-only. Entering idle automatically unwinds position. Exiting idle redeploys.
function setIdle(bool idle_) external nonReentrant onlyStrategist {
if (idle_ == idle) return;
if (idle_) {
_accrueYieldFees();
uint256 debtBefore = debtAsset.balanceOf(address(this));
uint256 withdrawn = 0;
if (address(yieldStrategy) != address(0)) {
uint256 strategyBalance = yieldStrategy.balanceOf();
if (strategyBalance > 0) {
withdrawn = yieldStrategy.withdrawAll();
}
}
lastStrategyBalance = 0;
uint256 debtBalance = debtBefore + withdrawn;
if (debtBalance > 0) {
debtAsset.safeTransfer(address(loanManager), debtBalance);
}
if (loanManager.loanExists()) {
loanManager.unwindPosition(type(uint256).max);
}
_swapRemainingDebtToCollateral(true);
idle = true;
emit IdleModeEntered();
} else {
idle = false;
emit IdleModeExited();
_deployCapital();
}
}
// ============ Gov Functions ============
/// @notice Propose a new swapper contract (requires timelock)
/// @dev Gov-only. 1-week timelock for critical infrastructure changes.
function proposeSwapper(address newSwapper) external onlyGov {
if (newSwapper == address(0)) revert InvalidAddress();
if (newSwapper == address(swapper)) revert InvalidAddress();
_swapperTimelock.proposeAddress(newSwapper, TIMELOCK_DELAY);
emit SwapperChangeProposed(address(swapper), newSwapper, _swapperTimelock.timestamp);
}
/// @notice Execute pending swapper change after timelock
function executeSwapper() external onlyGov {
address oldSwapper = address(swapper);
swapper = ISwapper(_swapperTimelock.executeAddress());
emit SwapperUpdated(oldSwapper, address(swapper));
}
/// @notice Cancel pending swapper change
function cancelSwapper() external onlyGov {
address cancelled = _swapperTimelock.cancelAddress();
emit SwapperChangeCancelled(cancelled);
}
// ============ Role Management (Gov-only) ============
/// @notice Transfer role: 0=strategist, 1=gov, 2=guardian (only gov can initiate all transfers)
function transferRole(uint8 role, address to) external onlyGov {
if (to == address(0)) revert InvalidAddress();
if (role == 0) {
pendingStrategist = to;
emit StrategistTransferStarted(strategist, to);
} else if (role == 1) {
pendingGov = to;
emit GovernanceTransferStarted(gov, to);
} else {
pendingGuardian = to;
emit GuardianTransferStarted(guardian, to);
}
}
/// @notice Accept role: 0=strategist, 1=gov, 2=guardian
function acceptRole(uint8 role) external {
if (role == 0) {
if (msg.sender != pendingStrategist) revert Unauthorized();
strategist = msg.sender;
pendingStrategist = address(0);
emit StrategistUpdated(msg.sender);
} else if (role == 1) {
if (msg.sender != pendingGov) revert Unauthorized();
gov = msg.sender;
pendingGov = address(0);
emit GovernanceUpdated(msg.sender);
} else {
if (msg.sender != pendingGuardian) revert Unauthorized();
guardian = msg.sender;
pendingGuardian = address(0);
emit GuardianUpdated(msg.sender);
}
}
/// @notice Withdraw accumulated strategy fees
/// @dev Strategist-only. Accrues pending fees before withdrawal.
function withdrawFees(address recipient) external nonReentrant onlyStrategist {
if (recipient == address(0)) revert InvalidAddress();
_accrueYieldFees();
(accumulatedFees, lastStrategyBalance) =
ZenjiCoreLib.processWithdrawFees(recipient, yieldStrategy, debtAsset, accumulatedFees);
feesAtLastRebalance = accumulatedFees;
}
// ============ Guardian Functions ============
/// @notice Enter emergency mode - one-way latch, no exit
/// @dev Guardian-only. Blocks deposits permanently. Withdrawals resume after liquidation completes.
function enterEmergencyMode() external onlyGuardian {
if (emergencyMode) revert EmergencyModeActive();
emergencyMode = true;
emit EmergencyModeEntered();
}
/// @notice Emergency step: 0=withdrawYield, 1=unwindLoan, 2=completeLiquidation
function emergencyStep(uint8 step) external nonReentrant onlyGuardian {
if (step > 2) revert InvalidEmergencyStep();
if (!emergencyMode) revert EmergencyModeNotActive();
if (liquidationComplete) revert LiquidationAlreadyComplete();
// Step 2: requires both prior steps to be resolved (run or explicitly skipped)
if (step == 2 && emergencyStepsCompleted & 0x3 != 0x3) revert EmergencyStepsIncomplete();
(uint256 newLSB, uint256 newFees, bool setLiq) = ZenjiCoreLib.executeEmergencyStep(
step,
yieldStrategy,
loanManager,
collateralAsset,
debtAsset,
swapper,
lastStrategyBalance,
accumulatedFees
);
lastStrategyBalance = newLSB;
accumulatedFees = newFees;
if (setLiq) liquidationComplete = true;
if (step == 0) {
feesAtLastRebalance = 0;
emergencyStepsCompleted |= 0x1;
} else if (step == 1) {
emergencyStepsCompleted |= 0x2;
}
}
/// @notice Explicitly mark an emergency step as resolved without executing it.
/// Use when a component (yield strategy or loan manager) is bricked and cannot be unwound.
/// Guardian accepts that funds in the bricked component may be unrecoverable.
/// After skipping step 1 (loan unwind), users can only redeem collateral already in the vault.
/// @param step 0 (skip yield withdraw) or 1 (skip loan unwind)
function emergencySkipStep(uint8 step) external nonReentrant onlyGuardian {
if (!emergencyMode) revert EmergencyModeNotActive();
if (liquidationComplete) revert LiquidationAlreadyComplete();
if (step > 1) revert InvalidEmergencyStep();
emergencyStepsCompleted |= (step == 0 ? uint8(0x1) : uint8(0x2));
emit EmergencyStepSkipped(step);
}
/// @notice Rescue stuck tokens from the vault (emergency mode only)
/// @dev Cannot rescue collateral after liquidation — that belongs to shareholders
function rescueAssets(address token, address recipient) external onlyGuardian {
if (!emergencyMode) revert EmergencyModeNotActive();
ZenjiCoreLib.executeRescueAssets(token, recipient, collateralAsset, debtAsset);
}
/// @notice Emergency rescue: 0=transferCollateral, 1=transferDebt, 2=redeemYield
/// @dev Guardian-only fallback when standard emergency steps fail.
function emergencyRescue(uint8 action) external nonReentrant onlyGuardian {
if (!emergencyMode) revert EmergencyModeNotActive();
(accumulatedFees, lastStrategyBalance) = ZenjiCoreLib.executeEmergencyRescue(
action,
collateralAsset,
debtAsset,
loanManager,
yieldStrategy,
swapper,
accumulatedFees,
lastStrategyBalance
);
}
/// @notice Set vault parameter:
/// 0=feeRate, 1=targetLtv, 2=depositCap, 3=bountyRate, 4=maxSlippage,
/// 5=minStrategyToDebtRatioForBorrow, 6=maxStrategyToDebtRatioForBorrow
/// @dev Gov-only. All parameter changes take effect immediately.
function setParam(uint8 p, uint256 v) external onlyGov {
if (p == 0) {
if (v > MAX_FEE_RATE) revert InvalidFeeRate();
emit ParamUpdated(p, feeRate, v);
feeRate = v;
} else if (p == 1) {
if (v < MIN_TARGET_LTV || v > MAX_TARGET_LTV) {
revert InvalidTargetLtv();
}
emit ParamUpdated(p, targetLtv, v);
targetLtv = v;
} else if (p == 2) {
emit ParamUpdated(p, depositCap, v);
depositCap = v;
} else if (p == 3) {
if (v > MAX_REBALANCE_BOUNTY) revert InvalidBountyRate();
emit ParamUpdated(p, rebalanceBountyRate, v);
rebalanceBountyRate = v;
} else if (p == 4) {
if (v == 0 || v > MAX_VAULT_SLIPPAGE) revert InvalidSlippage();
emit ParamUpdated(p, maxSlippage, v);
maxSlippage = v;
} else if (p == 5) {
if (
v < MIN_STRATEGY_DEBT_RATIO || v > MAX_STRATEGY_DEBT_RATIO
|| v >= maxStrategyToDebtRatioForBorrow
) {
revert InvalidCoverageRatio();
}
emit ParamUpdated(p, minStrategyToDebtRatioForBorrow, v);
minStrategyToDebtRatioForBorrow = v;
} else if (p == 6) {
if (
v < MIN_STRATEGY_DEBT_RATIO || v > MAX_STRATEGY_DEBT_RATIO
|| v <= minStrategyToDebtRatioForBorrow
) {
revert InvalidCoverageRatio();
}
emit ParamUpdated(p, maxStrategyToDebtRatioForBorrow, v);
maxStrategyToDebtRatioForBorrow = v;
}
}
/// @notice Forward slippage config updates to strategies that expose setSlippage(uint256)
function setStrategySlippage(uint256 newSlippage) external onlyGov {
IStrategySlippageConfig(address(yieldStrategy)).setSlippage(newSlippage);
emit StrategySlippageUpdated(address(yieldStrategy), newSlippage);
}
// ============ View Functions ============
/// @notice Estimate total value locked in collateral terms
function getTotalCollateral() public view returns (uint256 totalCollateral) {
if (idle) {
return collateralAsset.balanceOf(address(this));
}
return viewHelper.getTotalCollateralValue(address(this));
}
/// @notice Strategy balance to loan debt ratio in debt-asset terms (1e18 = 1.0)
/// @dev Returns max uint when debt is zero.
function strategyToDebtRatio() public view returns (uint256 ratio) {
uint256 debt = loanManager.getCurrentDebt();
if (debt == 0) return type(uint256).max;
uint256 strategyBalance = yieldStrategy.balanceOf();
return (strategyBalance * PRECISION) / debt;
}
/// @notice True when strategy/debt coverage is below configured keeper-rebalance threshold
function strategyDebtRebalanceNeeded() public view returns (bool) {
uint256 ratio = strategyToDebtRatio();
return ratio != type(uint256).max
&& (ratio < minStrategyToDebtRatioForBorrow || ratio > maxStrategyToDebtRatioForBorrow);
}
// ============ Internal Functions ============
/// @notice Swap debt asset in the vault to collateral using swapper (if set)
/// @param force If true, swap any positive debt balance (used on full unwind/final exits)
function _swapRemainingDebtToCollateral(bool force) internal {
if (address(swapper) == address(0)) return;
uint256 debtBal = debtAsset.balanceOf(address(this));
if (debtBal == 0) return;
uint256 oneDebtUnit = 10 ** debtAsset.decimals();
if (!force && debtBal <= oneDebtUnit) return;
bool allowZeroOut = force && debtBal <= oneDebtUnit;
uint256 collateralBefore = collateralAsset.balanceOf(address(this));
debtAsset.safeTransfer(address(swapper), debtBal);
swapper.swapDebtForCollateral(debtBal);
uint256 collateralAfter = collateralAsset.balanceOf(address(this));
uint256 collateralReceived = collateralAfter - collateralBefore;
if (!allowZeroOut) {
uint256 oracleExpected = loanManager.getDebtValue(debtBal);
// Use 2x maxSlippage for the vault-level check. The swapper already
// enforces its own oracle floor per hop. Multi-hop swappers (e.g. cbBTC
// via WBTC) compound slippage across hops and use different oracle
// price paths than loanManager.getDebtValue, causing small divergence.
uint256 effectiveSlippage = maxSlippage * 2;
if (effectiveSlippage > PRECISION) effectiveSlippage = PRECISION;
uint256 minOut = (oracleExpected * (PRECISION - effectiveSlippage)) / PRECISION;
if (collateralReceived < minOut) {
revert SwapperUnderperformed(minOut, collateralReceived);
}
}
}
/// @notice Calculate shares to mint for a deposit
function _calculateSharesForDeposit(uint256 collateralAmount) internal view returns (uint256) {
return (collateralAmount * (totalSupply() + VIRTUAL_SHARE_OFFSET()))
/ (getTotalCollateral() + VIRTUAL_SHARE_OFFSET());
}
/// @notice Calculate collateral to return for shares (rounds down)
function _calculateCollateralForShares(uint256 shareAmount) internal view returns (uint256) {
return (shareAmount * (getTotalCollateral() + VIRTUAL_SHARE_OFFSET()))
/ (totalSupply() + VIRTUAL_SHARE_OFFSET());
}
/// @notice Convert shares to assets rounding up (for mint/previewMint per ERC4626)
function _convertToAssetsRoundUp(uint256 shareAmount) internal view returns (uint256) {
uint256 supply = totalSupply() + VIRTUAL_SHARE_OFFSET();
uint256 totalCollateral = getTotalCollateral() + VIRTUAL_SHARE_OFFSET();
return (shareAmount * totalCollateral + supply - 1) / supply;
}
/// @notice Internal deposit logic shared by deposit() and mint()
function _deposit(uint256 assets, uint256 sharesToMint, address receiver) internal {
if (assets < MIN_DEPOSIT) revert AmountTooSmall();
if (sharesToMint == 0) revert AmountTooSmall();
if (emergencyMode) revert EmergencyModeActive();
if (depositCap > 0 && getTotalCollateral() + assets > depositCap) {
revert DepositCapExceeded();
}
collateralAsset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, sharesToMint);
if (!idle) {
_deployCapital();
}
emit Deposit(msg.sender, receiver, assets, sharesToMint);
}
/// @notice Internal redeem logic shared by withdraw(), redeem(), and legacy withdraw()
/// @return collateralAmount Amount of collateral returned
/// @return actualShareAmount Amount of shares actually burned
function _redeem(uint256 shareAmount, address receiver, address owner_)
internal
returns (uint256 collateralAmount, uint256 actualShareAmount)
{
if (shareAmount < 1) revert ZeroAmount();
if (balanceOf(owner_) < shareAmount) revert InsufficientShares();
if (_cooling(owner_)) {
revert ActionDelayActive();
}
if (emergencyMode) {
(collateralAmount, actualShareAmount) = _redeemEmergency(shareAmount, receiver, owner_);
return (collateralAmount, actualShareAmount);
}
(collateralAmount, actualShareAmount) = _redeemStandard(shareAmount, receiver, owner_);
return (collateralAmount, actualShareAmount);
}
function _cooling(address a) internal view returns (bool) {
uint256 b = lastInBlock[a];
return b != 0 && block.number <= b + COOLDOWN_BLOCKS - 1;
}
function _redeemEmergency(uint256 shareAmount, address receiver, address owner_)
internal
returns (uint256 collateralAmount, uint256 actualShareAmount)
{
if (!liquidationComplete) revert EmergencyModeActive();
// Handle allowance if caller is not share holder
if (msg.sender != owner_) {
_spendAllowance(owner_, msg.sender, shareAmount);
}
actualShareAmount = shareAmount;
uint256 supply = totalSupply();
if (supply < 1) return (0, 0);
uint256 availableCollateral = collateralAsset.balanceOf(address(this));
collateralAmount = (availableCollateral * actualShareAmount) / supply;
_burn(owner_, actualShareAmount);
if (collateralAmount > 0) {
collateralAsset.safeTransfer(receiver, collateralAmount);
}
emit Withdraw(msg.sender, receiver, owner_, collateralAmount, actualShareAmount);
return (collateralAmount, actualShareAmount);
}
function _redeemStandard(uint256 shareAmount, address receiver, address owner_)
internal
returns (uint256 collateralAmount, uint256 actualShareAmount)
{
// Accrue fees before pricing to prevent fee bypass on redemption
_accrueYieldFees();
// Detect final withdrawal: only when this redemption burns every real share.
// Note: allowance-based redemptions (msg.sender != share holder) must also trigger final
// withdrawal when burning the entire supply, otherwise residual value is stranded
// with totalSupply() == 0 and can be captured by the next depositor.
bool isFinalWithdraw = (totalSupply() == shareAmount);
// Handle allowance if caller is not share holder
if (msg.sender != owner_) {
_spendAllowance(owner_, msg.sender, shareAmount);
}
actualShareAmount = isFinalWithdraw ? balanceOf(owner_) : shareAmount;
collateralAmount = _calculateCollateralForShares(actualShareAmount);
_burn(owner_, actualShareAmount);
if (isFinalWithdraw) {
_unwindPosition(type(uint256).max);
collateralAmount = collateralAsset.balanceOf(address(this));
if (collateralAmount > 0) {
collateralAsset.safeTransfer(receiver, collateralAmount);
}
} else {
uint256 availableCollateral = collateralAsset.balanceOf(address(this));
if (availableCollateral < collateralAmount) {
uint256 needed = collateralAmount - availableCollateral;
uint256 balanceBefore = collateralAsset.balanceOf(address(this));
_unwindPosition(needed);
uint256 balanceAfter = collateralAsset.balanceOf(address(this));
uint256 gained = balanceAfter > balanceBefore ? balanceAfter - balanceBefore : 0;
uint256 totalAvailable = availableCollateral + gained;
if (totalAvailable < collateralAmount) {
// Allow slippage-adjusted withdrawal: multi-hop strategies
// lose value to swap slippage during unwind. Rather than
// reverting (shares are already burned), send what we recovered
// as long as the shortfall is within maxSlippage.
uint256 minAcceptable =
(collateralAmount * (PRECISION - maxSlippage)) / PRECISION;
if (totalAvailable < minAcceptable) {
revert InsufficientCollateral();
}
collateralAmount = totalAvailable;
}
}
collateralAsset.safeTransfer(receiver, collateralAmount);
}
emit Withdraw(msg.sender, receiver, owner_, collateralAmount, actualShareAmount);
}
/// @notice Accrue fees from yield strategy profits using checkpoint delta
/// @dev Fees are only charged on incremental balance gains since the last checkpoint.
/// The checkpoint (lastStrategyBalance) always updates regardless of feeRate,
/// so changing feeRate from 0 to non-zero never retroactively charges old gains.
function _accrueYieldFees() internal {
if (address(yieldStrategy) == address(0)) return;
uint256 currentBalance = yieldStrategy.balanceOf();
if (feeRate > 0 && currentBalance > lastStrategyBalance) {
uint256 delta = currentBalance - lastStrategyBalance;
uint256 fees = (delta * feeRate) / PRECISION;
if (fees > 0) {
accumulatedFees += fees;
emit FeesAccrued(delta, fees, accumulatedFees);
}
}
lastStrategyBalance = currentBalance;
// Cap fees to actual strategy balance to prevent phantom fee accumulation after losses
if (accumulatedFees > currentBalance) {
accumulatedFees = currentBalance;
}
if (feesAtLastRebalance > accumulatedFees) {
feesAtLastRebalance = accumulatedFees;
}
}
/// @notice Deploy debt asset to yield strategy
function _deployDebtToYield(uint256 debtAmount) internal {
if (idle) return;
address stratVault = yieldStrategy.vault();
if (stratVault != address(0) && stratVault != address(this)) revert InvalidStrategy();
_accrueYieldFees();
IERC20(address(debtAsset)).ensureApproval(address(yieldStrategy), debtAmount);
uint256 balBefore = yieldStrategy.balanceOf();
yieldStrategy.deposit(debtAmount);
uint256 balAfter = yieldStrategy.balanceOf();
uint256 deposited = balAfter > balBefore ? balAfter - balBefore : 0;
if (deposited < (debtAmount * (PRECISION - maxSlippage)) / PRECISION) {
revert InsufficientDeposit();
}
emit StrategyDeposit(address(yieldStrategy), debtAmount, deposited);
lastStrategyBalance = balAfter;
}
/// @notice Withdraw debt asset from yield strategy
function _withdrawFromYieldStrategy(uint256 debtNeeded) internal returns (uint256) {
if (address(yieldStrategy) == address(0)) return 0;
uint256 strategyBalance = yieldStrategy.balanceOf();
if (strategyBalance == 0) return 0;
_accrueYieldFees();
uint256 toWithdraw = debtNeeded > strategyBalance ? strategyBalance : debtNeeded;
uint256 received = 0;
if (toWithdraw > 0) {
received = yieldStrategy.withdraw(toWithdraw);
uint256 minReceived = (toWithdraw * (PRECISION - maxSlippage)) / PRECISION;
if (received < minReceived) revert InsufficientWithdrawal();
}
lastStrategyBalance = yieldStrategy.balanceOf();
return received;
}
/// @notice Unified position unwind for both partial and full withdrawals
/// @param collateralNeeded Amount of collateral to free, or type(uint256).max for full close
function _unwindPosition(uint256 collateralNeeded) internal {
bool fullyClose = (collateralNeeded >= type(uint256).max);
// 1. Accrue yield fees
_accrueYieldFees();
// 2. Withdraw from yield strategy
uint256 debtBalance;
if (fullyClose) {
uint256 debtBefore = debtAsset.balanceOf(address(this));
uint256 withdrawn = 0;
if (address(yieldStrategy) != address(0)) {
withdrawn = yieldStrategy.withdrawAll();
lastStrategyBalance = 0;
}
debtBalance = debtBefore + withdrawn;
} else {
if (loanManager.loanExists()) {
(uint256 positionCollateral, uint256 positionDebt) = loanManager.getPositionValues();
uint256 debtToRepay = positionCollateral > 0
? (positionDebt * collateralNeeded) / positionCollateral
: 0;
if (debtToRepay > 0) {
// Add 5% buffer for slippage/rounding — multi-hop strategies
// (e.g. PmUsd: LP → crvUSD → USDT) need headroom to cover
// swap slippage so the loan manager can repay proportional debt.
uint256 debtNeeded = (debtToRepay * 105) / 100;
_withdrawFromYieldStrategy(debtNeeded);
}
}
debtBalance = debtAsset.balanceOf(address(this));
}
// 3. Transfer idle debt asset to loan manager
if (debtBalance > 0) {
debtAsset.safeTransfer(address(loanManager), debtBalance);
}
// 4. Loan manager handles everything and sends collateral back
loanManager.unwindPosition(collateralNeeded);
// 5. Recover surplus debt from loan manager (yield profits / buffer surplus)
uint256 lmDebtBalance = loanManager.getDebtBalance();
if (lmDebtBalance > 0) {
loanManager.transferDebt(address(this), lmDebtBalance);
}
_swapRemainingDebtToCollateral(fullyClose);
emit CapitalUnwound(collateralNeeded, collateralAsset.balanceOf(address(this)));
}
/// @notice Adjust LTV toward target by borrowing more or repaying debt
function _adjustLtv(uint256 _targetLtv, bool increase, bool enforceCoverageAfterIncrease)
internal
{
lastStrategyBalance = ZenjiCoreLib.adjustLtv(
loanManager,
yieldStrategy,
debtAsset,
_targetLtv,
minStrategyToDebtRatioForBorrow,
maxSlippage,
PRECISION,
increase,
enforceCoverageAfterIncrease
);
}
// Cooldown is enforced at transfer time to block same-block transfer->redeem bypasses.
// Caveat: any third party can send dust shares to an address and set its cooldown for
// the current block (dust-grief). Keep COOLDOWN_BLOCKS minimal (1 block) and prefer
// private orderflow for sensitive exits.
function _update(address from, address to, uint256 value) internal override {
if (from != address(0) && value > 0 && _cooling(from)) revert ActionDelayActive();
super._update(from, to, value);
if (to != address(0) && value > 0) {
lastInBlock[to] = block.number;
}
}
// ============ ERC20 Overrides for decimals ============
/// @notice Returns collateral decimals to match ERC4626 asset
function decimals() public view override(ERC20, IERC20Metadata) returns (uint8) {
return IERC20Metadata(address(collateralAsset)).decimals();
}
// ============ Virtual share offset ============
/// @notice Virtual share offset for ERC4626 inflation attack mitigation
/// @dev Override in implementation contracts to customize per collateral type
function VIRTUAL_SHARE_OFFSET() public pure virtual returns (uint256) {
return 1e5;
}
}
src/ZenjiViewHelper.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
import { ILoanManager } from "./interfaces/ILoanManager.sol";
import { IYieldStrategy } from "./interfaces/IYieldStrategy.sol";
import { IERC20 } from "./interfaces/IERC20.sol";
interface IZenjiView {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function getTotalCollateral() external view returns (uint256);
function loanManager() external view returns (ILoanManager);
function collateralAsset() external view returns (IERC20);
function debtAsset() external view returns (IERC20);
function idle() external view returns (bool);
function targetLtv() external view returns (uint256);
function DEADBAND_SPREAD() external view returns (uint256);
function feeRate() external view returns (uint256);
function PRECISION() external view returns (uint256);
function accumulatedFees() external view returns (uint256);
function lastStrategyBalance() external view returns (uint256);
function yieldStrategy() external view returns (IYieldStrategy);
function VIRTUAL_SHARE_OFFSET() external view returns (uint256);
}
/// @title ZenjiViewHelper
/// @notice External helper for view utilities to reduce Zenji bytecode size
contract ZenjiViewHelper {
function getUserValue(address vault, address user)
external
view
returns (uint256 collateralValue)
{
IZenjiView v = IZenjiView(vault);
uint256 supply = v.totalSupply();
if (supply == 0) return 0;
uint256 userShares = v.balanceOf(user);
uint256 offset = v.VIRTUAL_SHARE_OFFSET();
return (userShares * (v.getTotalCollateral() + offset)) / (supply + offset);
}
function getHealth(address vault) external view returns (int256 health) {
return IZenjiView(vault).loanManager().getHealth();
}
function isRebalanceNeeded(address vault) external view returns (bool needed) {
ILoanManager lm = IZenjiView(vault).loanManager();
if (!lm.loanExists()) return false;
uint256 ltv = lm.getCurrentLTV();
uint256 target = IZenjiView(vault).targetLtv();
uint256 deadband = IZenjiView(vault).DEADBAND_SPREAD();
return ltv < (target - deadband) || ltv > (target + deadband);
}
function getLtvBounds(address vault)
external
view
returns (uint256 lowerBand, uint256 upperBand)
{
IZenjiView v = IZenjiView(vault);
uint256 target = v.targetLtv();
uint256 deadband = v.DEADBAND_SPREAD();
lowerBand = target - deadband;
upperBand = target + deadband;
}
function getPendingFees(address vault)
external
view
returns (uint256 totalFees, uint256 pendingFees)
{
IZenjiView v = IZenjiView(vault);
IYieldStrategy strategy = v.yieldStrategy();
uint256 strategyBalance = strategy.balanceOf();
uint256 lastBalance = v.lastStrategyBalance();
if (strategyBalance > lastBalance) {
uint256 delta = strategyBalance - lastBalance;
pendingFees = (delta * v.feeRate()) / v.PRECISION();
}
totalFees = v.accumulatedFees() + pendingFees;
}
/// @notice Get total value in collateral asset units (e.g., WBTC satoshis)
/// @dev Computes all values natively in collateral terms to avoid double conversion errors
function getTotalCollateralValue(address vault) external view returns (uint256 totalValue) {
IZenjiView v = IZenjiView(vault);
ILoanManager lm = v.loanManager();
if (v.idle()) {
return v.collateralAsset().balanceOf(vault);
}
// Idle collateral in vault (native units)
totalValue = v.collateralAsset().balanceOf(vault);
// Net collateral value in loan manager (collateral - debt in collateral terms)
totalValue += lm.getNetCollateralValue();
// Yield strategy balance converted to collateral (excluding fees)
IYieldStrategy strategy = v.yieldStrategy();
if (address(strategy) != address(0)) {
uint256 strategyBalance = strategy.balanceOf();
uint256 accFees = v.accumulatedFees();
if (strategyBalance > accFees) {
totalValue += lm.getDebtValue(strategyBalance - accFees);
}
}
// Idle debt asset in vault converted to collateral
uint256 idleDebt = v.debtAsset().balanceOf(vault);
if (idleDebt > 0) {
totalValue += lm.getDebtValue(idleDebt);
}
// Raw collateral in loan manager (not yet supplied)
totalValue += lm.getCollateralBalance();
// Raw debt asset in loan manager converted to collateral
uint256 lmDebt = lm.getDebtBalance();
if (lmDebt > 0) {
totalValue += lm.getDebtValue(lmDebt);
}
}
/// @notice Get total value in debt asset units (for diagnostics/logging)
/// @dev This is a diagnostic function - use getTotalCollateralValue for actual accounting
function getTotalDebtValue(address vault) external view returns (uint256 totalValue) {
IZenjiView v = IZenjiView(vault);
ILoanManager lm = v.loanManager();
if (v.idle()) {
return lm.getCollateralValue(v.collateralAsset().balanceOf(vault));
}
// Idle collateral converted to debt units
totalValue = lm.getCollateralValue(v.collateralAsset().balanceOf(vault));
// Position value in debt terms
if (lm.loanExists()) {
(uint256 collateral, uint256 debt) = lm.getPositionValues();
uint256 collateralInDebt = lm.getCollateralValue(collateral);
if (collateralInDebt > debt) {
totalValue += collateralInDebt - debt;
}
}
// Strategy balance (already in debt units, minus fees)
IYieldStrategy strategy = v.yieldStrategy();
if (address(strategy) != address(0)) {
uint256 strategyBalance = strategy.balanceOf();
uint256 accFees = v.accumulatedFees();
if (strategyBalance > accFees) {
totalValue += strategyBalance - accFees;
}
}
// Idle debt in vault
totalValue += v.debtAsset().balanceOf(vault);
// Raw collateral in loan manager converted to debt
uint256 lmCollateral = lm.getCollateralBalance();
if (lmCollateral > 0) {
totalValue += lm.getCollateralValue(lmCollateral);
}
// Raw debt in loan manager
totalValue += lm.getDebtBalance();
}
function yieldCostBasis(address vault) external view returns (uint256) {
return IZenjiView(vault).yieldStrategy().costBasis();
}
function getYieldStrategyStats(address vault)
external
view
returns (
string memory strategyName,
uint256 currentValue,
uint256 costBasis,
uint256 unrealizedProfit
)
{
IYieldStrategy strategy = IZenjiView(vault).yieldStrategy();
strategyName = strategy.name();
currentValue = strategy.balanceOf();
costBasis = strategy.costBasis();
unrealizedProfit = strategy.unrealizedProfit();
}
function getYieldVaultStats(address vault)
external
view
returns (
uint256 yieldShares,
uint256 currentValue,
uint256 costBasis,
uint256 unrealizedProfit
)
{
IYieldStrategy strategy = IZenjiView(vault).yieldStrategy();
return (0, strategy.balanceOf(), strategy.costBasis(), strategy.unrealizedProfit());
}
}
src/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
/// @title IERC20
/// @notice Standard ERC20 interface
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
}
src/interfaces/IERC4626.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/IERC4626.sol)
pragma solidity >=0.6.2;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC-4626 "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 Deposit `assets` underlying tokens and send the corresponding number of vault shares (`shares`) to `receiver`.
*
* - 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` in exchange for `assets` 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 redemption 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);
}
src/interfaces/ILoanManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
/// @title ILoanManager
/// @notice Interface for loan managers that handle collateralized borrowing
interface ILoanManager {
// ============ Events ============
event LoanCreated(uint256 collateral, uint256 debt, uint256 bands);
event CollateralAdded(uint256 amount);
event LoanBorrowedMore(uint256 collateral, uint256 debt);
event LoanRepaid(uint256 amount);
event CollateralRemoved(uint256 amount);
// ============ Errors ============
error Unauthorized();
error InvalidAddress();
error InvalidPrice();
error StaleOracle();
error DebtNotFullyRepaid();
error ZeroAmount();
error TransferFailed();
// ============ Loan Management Functions ============
/// @notice Create a new loan with collateral
/// @param collateral Amount of collateral asset
/// @param debt Amount of debt asset to borrow
/// @param bands Number of bands for the loan (if applicable)
function createLoan(uint256 collateral, uint256 debt, uint256 bands) external;
/// @notice Add collateral to an existing loan
/// @param collateral Amount of collateral asset
function addCollateral(uint256 collateral) external;
/// @notice Borrow more against existing collateral
/// @param collateral Additional collateral (can be 0)
/// @param debt Additional debt to borrow
function borrowMore(uint256 collateral, uint256 debt) external;
/// @notice Repay debt
/// @param amount Amount of debt asset to repay
function repayDebt(uint256 amount) external;
/// @notice Remove collateral from the loan
/// @param amount Amount of collateral asset to remove
function removeCollateral(uint256 amount) external;
/// @notice Unified position unwind for both partial and full withdrawals
/// @dev Pass type(uint256).max for collateralNeeded to fully close the position.
/// @param collateralNeeded Amount of collateral to free, or type(uint256).max for full close
function unwindPosition(uint256 collateralNeeded) external;
// ============ View Functions ============
/// @notice Get current LTV ratio
/// @return ltv Current LTV (1e18 = 100%)
function getCurrentLTV() external view returns (uint256 ltv);
/// @notice Get current collateral amount
/// @return collateral Current collateral amount
function getCurrentCollateral() external view returns (uint256 collateral);
/// @notice Get current debt amount
/// @return debt Current debt amount
function getCurrentDebt() external view returns (uint256 debt);
/// @notice Collateral asset used by this loan manager
function collateralAsset() external view returns (address);
/// @notice Debt asset used by this loan manager
function debtAsset() external view returns (address);
/// @notice Get vault health factor
/// @return health Health factor (positive = healthy)
function getHealth() external view returns (int256 health);
/// @notice Check if loan exists
/// @return exists True if loan exists
function loanExists() external view returns (bool exists);
/// @notice Get collateral value in debt asset terms
/// @param collateralAmount Amount of collateral asset
/// @return value Value in debt asset (18 decimals unless specified by implementation)
function getCollateralValue(uint256 collateralAmount) external view returns (uint256 value);
/// @notice Get debt asset value in collateral terms
/// @param debtAmount Amount of debt asset
/// @return value Value in collateral asset (collateral decimals)
function getDebtValue(uint256 debtAmount) external view returns (uint256 value);
/// @notice Calculate borrow amount for given collateral and target LTV
/// @param collateral Amount of collateral asset
/// @param targetLtv Target LTV (1e18 = 100%)
/// @return borrowAmount Amount of debt asset to borrow
function calculateBorrowAmount(uint256 collateral, uint256 targetLtv)
external
view
returns (uint256 borrowAmount);
/// @notice Calculate health after hypothetical changes
/// @param dCollateral Change in collateral
/// @param dDebt Change in debt
/// @return health Projected health factor
function healthCalculator(int256 dCollateral, int256 dDebt)
external
view
returns (int256 health);
/// @notice Get minimum collateral required for a debt amount
/// @param debt_ Desired debt amount
/// @param bands Number of bands
/// @return Minimum collateral required
function minCollateral(uint256 debt_, uint256 bands) external view returns (uint256);
/// @notice Get position values (collateral and debt)
/// @return collateralValue Current collateral value
/// @return debtValue Current debt value
function getPositionValues() external view returns (uint256 collateralValue, uint256 debtValue);
/// @notice Get net collateral value (collateral - debt in collateral terms)
/// @return value Net value in collateral asset
function getNetCollateralValue() external view returns (uint256 value);
/// @notice Check oracle freshness
function checkOracleFreshness() external view;
// ============ Token Management ============
/// @notice Transfer collateral from this contract
/// @param to Recipient address
/// @param amount Amount to transfer
function transferCollateral(address to, uint256 amount) external;
/// @notice Transfer debt asset from this contract
/// @param to Recipient address
/// @param amount Amount to transfer
function transferDebt(address to, uint256 amount) external;
/// @notice Get collateral balance of this contract
/// @return balance Collateral balance
function getCollateralBalance() external view returns (uint256 balance);
/// @notice Get debt balance of this contract
/// @return balance Debt balance
function getDebtBalance() external view returns (uint256 balance);
}
src/interfaces/ISwapper.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
/// @title ISwapper
/// @notice Optional swapper for collateral/debt conversions
interface ISwapper {
error SlippageExceeded();
error InvalidAddress();
error TransferFailed();
/// @notice Quote collateral needed for a given debt amount
/// @param debtAmount Amount of debt asset
/// @return collateralNeeded Estimated collateral required
function quoteCollateralForDebt(uint256 debtAmount) external view returns (uint256);
/// @notice Swap collateral for debt asset
/// @param collateralAmount Amount of collateral to swap
/// @return debtReceived Amount of debt asset received
function swapCollateralForDebt(uint256 collateralAmount) external returns (uint256 debtReceived);
/// @notice Swap debt asset for collateral
/// @param debtAmount Amount of debt asset to swap
/// @return collateralReceived Amount of collateral received
function swapDebtForCollateral(uint256 debtAmount) external returns (uint256 collateralReceived);
}
src/interfaces/IYieldStrategy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
/// @title IYieldStrategy
/// @notice Interface for yield strategies used by Zenji
/// @dev All strategies accept the debt asset from the vault and deploy to yield-generating protocols
interface IYieldStrategy {
// ============ Events ============
event Deposited(uint256 debtAssetAmount, uint256 underlyingDeposited);
event Withdrawn(uint256 debtAssetAmount, uint256 debtAssetReceived);
event Harvested(uint256 rewardsValue);
event EmergencyWithdrawn(uint256 debtAssetReceived);
// ============ Errors ============
error Unauthorized();
error ZeroAmount();
error SlippageExceeded();
error TransferFailed();
error InvalidAddress();
// ============ Core Functions ============
/// @notice Deposit debt asset into the yield strategy
/// @param debtAssetAmount Amount of debt asset to deposit
/// @return underlyingDeposited Amount deposited into the underlying protocol
function deposit(uint256 debtAssetAmount) external returns (uint256 underlyingDeposited);
/// @notice Withdraw debt asset from the yield strategy
/// @param debtAssetAmount Amount of debt asset to withdraw
/// @return debtAssetReceived Actual debt asset received (may differ due to slippage)
function withdraw(uint256 debtAssetAmount) external returns (uint256 debtAssetReceived);
/// @notice Withdraw all assets from the yield strategy
/// @return debtAssetReceived Total debt asset received
function withdrawAll() external returns (uint256 debtAssetReceived);
/// @notice Harvest rewards and compound them back into the strategy
/// @return rewardsValue Value of rewards harvested (in debt asset terms)
function harvest() external returns (uint256 rewardsValue);
/// @notice Emergency withdraw all assets, bypassing slippage checks
/// @return debtAssetReceived Total debt asset received
function emergencyWithdraw() external returns (uint256 debtAssetReceived);
// ============ View Functions ============
/// @notice Returns the asset accepted by the strategy (debt asset)
function asset() external view returns (address);
/// @notice Returns the underlying asset of the yield protocol (debt asset or swapped asset)
function underlyingAsset() external view returns (address);
/// @notice Returns the current value of the strategy holdings in debt asset terms
function balanceOf() external view returns (uint256);
/// @notice Returns the total debt asset deposited (cost basis)
function costBasis() external view returns (uint256);
/// @notice Returns unrealized profit (current value - cost basis)
function unrealizedProfit() external view returns (uint256);
/// @notice Returns pending rewards value in debt asset terms
function pendingRewards() external view returns (uint256);
/// @notice Returns the strategy name
function name() external view returns (string memory);
/// @notice Returns the vault address
function vault() external view returns (address);
}
src/libraries/SafeTransferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
import { IERC20 } from "../interfaces/IERC20.sol";
/// @title SafeTransferLib
/// @notice Gas-efficient safe transfer functions for ERC20 tokens
library SafeTransferLib {
error TransferFailed();
/// @notice Safe transfer that reverts on failure
function safeTransfer(IERC20 token, address to, uint256 amount) internal {
(bool success, bytes memory data) =
address(token).call(abi.encodeWithSelector(token.transfer.selector, to, amount));
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert TransferFailed();
}
}
/// @notice Safe transferFrom that reverts on failure
function safeTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
(bool success, bytes memory data) = address(token)
.call(abi.encodeWithSelector(token.transferFrom.selector, from, to, amount));
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert TransferFailed();
}
}
/// @notice Ensure approval is sufficient, set to max if not
/// @dev Uses safeApprove pattern for USDT compatibility (non-standard ERC20)
function ensureApproval(IERC20 token, address spender, uint256 amount) internal {
if (token.allowance(address(this), spender) < amount) {
safeApprove(token, spender, type(uint256).max);
}
}
/// @notice Safe approve that handles non-standard ERC20 tokens like USDT
/// @dev USDT requires setting allowance to 0 first before setting a new non-zero value
/// and returns void instead of bool
function safeApprove(IERC20 token, address spender, uint256 amount) internal {
// For USDT: first reset to 0 if there's existing allowance and we're setting non-zero
if (amount > 0 && token.allowance(address(this), spender) > 0) {
(bool resetSuccess,) =
address(token).call(abi.encodeWithSelector(token.approve.selector, spender, 0));
// Ignore return value for void-returning tokens like USDT
if (!resetSuccess) revert TransferFailed();
}
(bool success, bytes memory data) =
address(token).call(abi.encodeWithSelector(token.approve.selector, spender, amount));
// Handle both standard (returns bool) and non-standard (returns nothing) ERC20
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert TransferFailed();
}
}
}
src/libraries/TimelockLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
/// @title TimelockLib
/// @notice Library for managing timelocked parameter changes
library TimelockLib {
struct TimelockData {
uint256 pendingValue;
uint256 timestamp;
}
/// @notice Expiry window after timelock becomes ready (7 days)
uint256 internal constant TIMELOCK_EXPIRY = 7 days;
error NoTimelockPending();
error TimelockNotReady();
error TimelockExpired();
/// @notice Propose a new value with timelock delay
function propose(TimelockData storage data, uint256 newValue, uint256 delay) internal {
data.pendingValue = newValue;
data.timestamp = block.timestamp + delay;
}
/// @notice Execute pending value change after timelock
/// @return newValue The new value that was set
function execute(TimelockData storage data) internal returns (uint256 newValue) {
if (data.timestamp == 0) revert NoTimelockPending();
if (block.timestamp < data.timestamp) revert TimelockNotReady();
if (block.timestamp > data.timestamp + TIMELOCK_EXPIRY) revert TimelockExpired();
newValue = data.pendingValue;
data.pendingValue = 0;
data.timestamp = 0;
}
/// @notice Cancel pending value change
/// @return cancelledValue The value that was cancelled
function cancel(TimelockData storage data) internal returns (uint256 cancelledValue) {
if (data.timestamp == 0) revert NoTimelockPending();
cancelledValue = data.pendingValue;
data.pendingValue = 0;
data.timestamp = 0;
}
/// @notice Check if timelock is pending
function isPending(TimelockData storage data) internal view returns (bool) {
return data.timestamp != 0;
}
/// @notice Check if timelock is ready to execute
function isReady(TimelockData storage data) internal view returns (bool) {
return data.timestamp != 0 && block.timestamp >= data.timestamp;
}
// ============ Address Timelock Functions ============
struct AddressTimelockData {
address pendingValue;
uint256 timestamp;
}
/// @notice Propose a new address value with timelock delay
function proposeAddress(AddressTimelockData storage data, address newValue, uint256 delay)
internal
{
data.pendingValue = newValue;
data.timestamp = block.timestamp + delay;
}
/// @notice Execute pending address change after timelock
/// @return newValue The new address that was set
function executeAddress(AddressTimelockData storage data) internal returns (address newValue) {
if (data.timestamp == 0) revert NoTimelockPending();
if (block.timestamp < data.timestamp) revert TimelockNotReady();
if (block.timestamp > data.timestamp + TIMELOCK_EXPIRY) revert TimelockExpired();
newValue = data.pendingValue;
data.pendingValue = address(0);
data.timestamp = 0;
}
/// @notice Cancel pending address change
/// @return cancelledValue The address that was cancelled
function cancelAddress(AddressTimelockData storage data)
internal
returns (address cancelledValue)
{
if (data.timestamp == 0) revert NoTimelockPending();
cancelledValue = data.pendingValue;
data.pendingValue = address(0);
data.timestamp = 0;
}
}
src/libraries/ZenjiCoreLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.33;
import { IERC20 } from "../interfaces/IERC20.sol";
import { IYieldStrategy } from "../interfaces/IYieldStrategy.sol";
import { ILoanManager } from "../interfaces/ILoanManager.sol";
import { ISwapper } from "../interfaces/ISwapper.sol";
import { SafeTransferLib } from "./SafeTransferLib.sol";
/// @title ZenjiCoreLib
/// @notice External library for Zenji admin and emergency operations
/// @dev Functions are `external` so they deploy separately and reduce Zenji bytecode.
/// Called via DELEGATECALL, so `address(this)` is the vault and token transfers work correctly.
library ZenjiCoreLib {
using SafeTransferLib for IERC20;
error InvalidAddress();
error InsufficientWithdrawal();
error InsufficientDeposit();
error StrategyDebtCoverageTooLow(uint256 actual, uint256 minimum);
event EmergencyYieldRedeemed(uint256 debtAssetReceived);
event EmergencyLoanUnwound(uint256 collateralRecovered, uint256 debtRecovered);
event LiquidationComplete(uint256 collateralRecovered, uint256 flashloanAmount);
event EmergencyCollateralTransferred(uint256 amount);
event EmergencyDebtTransferred(uint256 amount);
event AssetsRescued(address indexed token, address indexed recipient, uint256 amount);
event FeesWithdrawn(address indexed recipient, uint256 amount);
event RebalanceBountyPaid(address indexed keeper, uint256 amount);
event StrategyDeposit(address indexed strategy, uint256 debtAmount, uint256 depositedAmount);
/// @notice Execute emergency step: 0=withdrawYield, 1=unwindLoan, 2=completeLiquidation
/// @return newLastStrategyBalance Updated lastStrategyBalance value
/// @return newAccumulatedFees Updated accumulatedFees value
/// @return setLiquidationComplete Whether to set liquidationComplete = true
function executeEmergencyStep(
uint8 step,
IYieldStrategy yieldStrategy,
ILoanManager loanManager,
IERC20 collateralAsset,
IERC20 debtAsset,
ISwapper swapper,
uint256 lastStrategyBalance,
uint256 accumulatedFees
)
external
returns (
uint256 newLastStrategyBalance,
uint256 newAccumulatedFees,
bool setLiquidationComplete
)
{
newLastStrategyBalance = lastStrategyBalance;
newAccumulatedFees = accumulatedFees;
if (step == 0) {
uint256 withdrawn = 0;
if (address(yieldStrategy) != address(0)) {
try yieldStrategy.withdrawAll() returns (uint256 r) {
withdrawn = r;
} catch {
try yieldStrategy.emergencyWithdraw() returns (uint256 r) {
withdrawn = r;
} catch { }
}
}
newLastStrategyBalance = 0;
newAccumulatedFees = 0;
emit EmergencyYieldRedeemed(withdrawn);
} else if (step == 1) {
if (!loanManager.loanExists()) {
_recoverLoanManagerFunds(loanManager);
_swapRemainingDebtToCollateral(debtAsset, swapper);
emit EmergencyLoanUnwound(collateralAsset.balanceOf(address(this)), 0);
return (newLastStrategyBalance, newAccumulatedFees, false);
}
uint256 totalDebt = loanManager.getCurrentDebt();
uint256 availableDebt = debtAsset.balanceOf(address(this));
if (availableDebt >= totalDebt) {
if (totalDebt > 0) {
debtAsset.safeTransfer(address(loanManager), totalDebt);
loanManager.repayDebt(totalDebt);
}
// Debt is fully repaid; withdraw collateral (e.g. aTokens) from the lending protocol.
// unwindPosition handles zero-debt by skipping the flashloan and calling withdraw directly.
loanManager.unwindPosition(type(uint256).max);
} else {
if (availableDebt > 0) {
debtAsset.safeTransfer(address(loanManager), availableDebt);
}
loanManager.unwindPosition(type(uint256).max);
}
_recoverLoanManagerFunds(loanManager);
_swapRemainingDebtToCollateral(debtAsset, swapper);
emit EmergencyLoanUnwound(collateralAsset.balanceOf(address(this)), 0);
} else {
setLiquidationComplete = true;
emit LiquidationComplete(collateralAsset.balanceOf(address(this)), 0);
}
}
/// @notice Emergency rescue: 0=transferCollateral, 1=transferDebt, 2=redeemYield
/// @return newAccumulatedFees Updated accumulatedFees value
/// @return newLastStrategyBalance Updated lastStrategyBalance value
function executeEmergencyRescue(
uint8 action,
IERC20 collateralAsset,
IERC20 debtAsset,
ILoanManager loanManager,
IYieldStrategy yieldStrategy,
ISwapper swapper,
uint256 accumulatedFees,
uint256 lastStrategyBalance
) external returns (uint256 newAccumulatedFees, uint256 newLastStrategyBalance) {
newAccumulatedFees = accumulatedFees;
newLastStrategyBalance = lastStrategyBalance;
if (action == 0) {
uint256 amount = collateralAsset.balanceOf(address(loanManager));
loanManager.transferCollateral(address(this), amount);
emit EmergencyCollateralTransferred(amount);
} else if (action == 1) {
uint256 amount = debtAsset.balanceOf(address(loanManager));
loanManager.transferDebt(address(this), amount);
emit EmergencyDebtTransferred(amount);
} else {
uint256 withdrawn = yieldStrategy.emergencyWithdraw();
newAccumulatedFees = 0;
newLastStrategyBalance = 0;
_swapRemainingDebtToCollateral(debtAsset, swapper);
emit EmergencyYieldRedeemed(withdrawn);
}
}
/// @notice Rescue stuck tokens (not collateral/debt) from the vault
function executeRescueAssets(
address token,
address recipient,
IERC20 collateralAsset,
IERC20 debtAsset
) external {
if (recipient == address(0)) revert InvalidAddress();
if (token == address(collateralAsset) || token == address(debtAsset)) {
revert InvalidAddress();
}
uint256 balance = IERC20(token).balanceOf(address(this));
if (balance > 0) {
IERC20(token).safeTransfer(recipient, balance);
}
emit AssetsRescued(token, recipient, balance);
}
/// @notice Withdraw accumulated fees from yield strategy
/// @return newAccumulatedFees Updated accumulatedFees value
/// @return newLastStrategyBalance Updated lastStrategyBalance value
function processWithdrawFees(
address recipient,
IYieldStrategy yieldStrategy,
IERC20 debtAsset,
uint256 accumulatedFees
) external returns (uint256 newAccumulatedFees, uint256 newLastStrategyBalance) {
uint256 fees = accumulatedFees;
if (fees == 0) return (0, yieldStrategy.balanceOf());
newAccumulatedFees = 0;
uint256 strategyBalance = yieldStrategy.balanceOf();
uint256 debtBefore = debtAsset.balanceOf(address(this));
if (strategyBalance > 0 && fees > 0) {
uint256 toWithdraw = fees > strategyBalance ? strategyBalance : fees;
if (toWithdraw > 0) {
uint256 received = yieldStrategy.withdraw(toWithdraw);
debtBefore += received;
}
}
newLastStrategyBalance = yieldStrategy.balanceOf();
uint256 toTransfer = fees > debtBefore ? debtBefore : fees;
if (toTransfer > 0) {
debtAsset.safeTransfer(recipient, toTransfer);
}
emit FeesWithdrawn(recipient, toTransfer);
}
/// @notice Process rebalance keeper bounty payment
/// @dev Keeper gets bountyRate% of fees accrued since last rebalance. Admin fees stay in strategy.
/// @return newFeesAtLastRebalance Updated feesAtLastRebalance value
/// @return newLastStrategyBalance Updated lastStrategyBalance value
/// @return bountyPaid Actual bounty amount withdrawn and paid to keeper (must be deducted from accumulatedFees)
function processRebalanceBounty(
IYieldStrategy yieldStrategy,
IERC20 debtAsset,
uint256 accumulatedFees,
uint256 feesAtLastRebalance,
uint256 rebalanceBountyRate,
uint256 precision,
address keeper
)
external
returns (uint256 newFeesAtLastRebalance, uint256 newLastStrategyBalance, uint256 bountyPaid)
{
newFeesAtLastRebalance = feesAtLastRebalance;
if (rebalanceBountyRate > 0 && accumulatedFees > feesAtLastRebalance) {
uint256 feesSinceLastRebalance = accumulatedFees - feesAtLastRebalance;
uint256 bounty = (feesSinceLastRebalance * rebalanceBountyRate) / precision;
if (bounty > 0) {
uint256 strategyBalance = yieldStrategy.balanceOf();
uint256 toWithdraw = bounty > strategyBalance ? strategyBalance : bounty;
if (toWithdraw > 0) {
uint256 withdrawn = yieldStrategy.withdraw(toWithdraw);
bountyPaid = withdrawn > bounty ? bounty : withdrawn;
if (bountyPaid > 0) {
debtAsset.safeTransfer(keeper, bountyPaid);
emit RebalanceBountyPaid(keeper, bountyPaid);
}
}
}
newFeesAtLastRebalance = accumulatedFees;
}
newLastStrategyBalance = yieldStrategy.balanceOf();
}
/// @notice Increase strategy/debt coverage when strategy assets fall below debt.
/// @dev Withdraws from strategy, repays debt, then does a simplified partial unwind
/// (triggering the loan manager flashloan path) if a deficit still remains.
/// NOTE: _accrueYieldFees is intentionally skipped — rebalance() already called it.
/// @return newLastStrategyBalance Updated strategy balance for vault to store.
function rebalanceCoverageUp(
ILoanManager loanManager,
IYieldStrategy yieldStrategy,
IERC20 debtAsset,
uint256 maxSlippage,
uint256 precision
) external returns (uint256 newLastStrategyBalance) {
uint256 debt = loanManager.getCurrentDebt();
if (debt == 0) return yieldStrategy.balanceOf();
uint256 strategyBalance = yieldStrategy.balanceOf();
if (strategyBalance >= debt) return strategyBalance;
uint256 deficit = debt - strategyBalance;
// Step 1: withdraw from strategy toward the deficit
if (strategyBalance > 0) {
uint256 toWithdraw = deficit > strategyBalance ? strategyBalance : deficit;
uint256 minReceived = (toWithdraw * (precision - maxSlippage)) / precision;
uint256 received = yieldStrategy.withdraw(toWithdraw);
if (received < minReceived) revert InsufficientWithdrawal();
}
// Step 2: repay as much debt as possible
uint256 debtBalance = debtAsset.balanceOf(address(this));
uint256 repayAmount = debtBalance < deficit ? debtBalance : deficit;
if (repayAmount > 0) {
debtAsset.safeTransfer(address(loanManager), repayAmount);
loanManager.repayDebt(repayAmount);
}
// Step 3: simplified partial unwind if deficit remains
uint256 remainingDeficit = deficit > repayAmount ? deficit - repayAmount : 0;
if (remainingDeficit > 0 && loanManager.loanExists()) {
(uint256 positionCollateral, uint256 positionDebt) = loanManager.getPositionValues();
if (positionCollateral > 0 && positionDebt > 0) {
uint256 collateralNeeded =
(positionCollateral * remainingDeficit + positionDebt - 1) / positionDebt;
if (collateralNeeded > positionCollateral) collateralNeeded = positionCollateral;
debtBalance = debtAsset.balanceOf(address(this));
if (debtBalance > 0) debtAsset.safeTransfer(address(loanManager), debtBalance);
loanManager.unwindPosition(collateralNeeded);
uint256 lmDebt = loanManager.getDebtBalance();
if (lmDebt > 0) loanManager.transferDebt(address(this), lmDebt);
}
}
return yieldStrategy.balanceOf();
}
/// @notice Decrease strategy/debt coverage when strategy assets are too far above debt.
/// @dev Borrows additional debt bounded by LTV upper deadband and deploys to strategy.
/// NOTE: _accrueYieldFees is intentionally skipped — rebalance() already called it.
/// @return newLastStrategyBalance Updated strategy balance for vault to store.
function rebalanceCoverageDown(
ILoanManager loanManager,
IYieldStrategy yieldStrategy,
IERC20 debtAsset,
uint256 maxStrategyToDebtRatioForBorrow,
uint256 maxLtvTarget,
uint256 maxSlippage,
uint256 precision
) external returns (uint256 newLastStrategyBalance) {
uint256 debt = loanManager.getCurrentDebt();
if (debt == 0) return yieldStrategy.balanceOf();
uint256 strategyBalance = yieldStrategy.balanceOf();
if (strategyBalance <= debt) return strategyBalance;
uint256 targetDebtAtMaxRatio = (strategyBalance * precision) / maxStrategyToDebtRatioForBorrow;
if (targetDebtAtMaxRatio <= debt) return strategyBalance;
(uint256 collateral,) = loanManager.getPositionValues();
uint256 collateralValue = loanManager.getCollateralValue(collateral);
uint256 maxDebtByLtv = (collateralValue * maxLtvTarget) / precision;
if (maxDebtByLtv <= debt) return strategyBalance;
uint256 requiredBorrow = targetDebtAtMaxRatio - debt;
uint256 ltvRoom = maxDebtByLtv - debt;
uint256 borrowAmount = requiredBorrow < ltvRoom ? requiredBorrow : ltvRoom;
if (borrowAmount == 0) return strategyBalance;
loanManager.borrowMore(0, borrowAmount);
uint256 debtBalance = loanManager.getDebtBalance();
if (debtBalance == 0) return yieldStrategy.balanceOf();
loanManager.transferDebt(address(this), debtBalance);
// Inline _deployDebtToYield without re-accruing fees
debtAsset.ensureApproval(address(yieldStrategy), debtBalance);
uint256 balBefore = yieldStrategy.balanceOf();
yieldStrategy.deposit(debtBalance);
uint256 balAfter = yieldStrategy.balanceOf();
uint256 deposited = balAfter > balBefore ? balAfter - balBefore : 0;
if (deposited < (debtBalance * (precision - maxSlippage)) / precision) {
revert InsufficientDeposit();
}
return balAfter;
}
/// @notice Adjust LTV toward target by borrowing more or repaying debt.
/// @dev Inlines the strategy deposit/withdraw logic without re-accruing fees because
/// `rebalance()` already accrued them before calling into the library.
function adjustLtv(
ILoanManager loanManager,
IYieldStrategy yieldStrategy,
IERC20 debtAsset,
uint256 targetLtv,
uint256 minStrategyToDebtRatioForBorrow,
uint256 maxSlippage,
uint256 precision,
bool increase,
bool enforceCoverageAfterIncrease
) external returns (uint256 newLastStrategyBalance) {
(uint256 collateral, uint256 currentDebt) = loanManager.getPositionValues();
uint256 collateralValue = loanManager.getCollateralValue(collateral);
uint256 targetDebt = (collateralValue * targetLtv) / precision;
if (increase) {
if (targetDebt <= currentDebt) return yieldStrategy.balanceOf();
uint256 additionalBorrow = targetDebt - currentDebt;
loanManager.borrowMore(0, additionalBorrow);
uint256 debtBalance = loanManager.getDebtBalance();
if (debtBalance == 0) return yieldStrategy.balanceOf();
loanManager.transferDebt(address(this), debtBalance);
debtAsset.ensureApproval(address(yieldStrategy), debtBalance);
uint256 balBefore = yieldStrategy.balanceOf();
yieldStrategy.deposit(debtBalance);
uint256 balAfter = yieldStrategy.balanceOf();
uint256 deposited = balAfter > balBefore ? balAfter - balBefore : 0;
if (deposited < (debtBalance * (precision - maxSlippage)) / precision) {
revert InsufficientDeposit();
}
emit StrategyDeposit(address(yieldStrategy), debtBalance, deposited);
if (enforceCoverageAfterIncrease) {
uint256 debt = loanManager.getCurrentDebt();
if (debt > 0) {
uint256 ratio = (balAfter * precision) / debt;
if (ratio < minStrategyToDebtRatioForBorrow) {
revert StrategyDebtCoverageTooLow(ratio, minStrategyToDebtRatioForBorrow);
}
}
}
return balAfter;
}
if (targetDebt >= currentDebt) return yieldStrategy.balanceOf();
uint256 toRepay = currentDebt - targetDebt;
uint256 strategyBalance = yieldStrategy.balanceOf();
if (strategyBalance > 0) {
uint256 toWithdraw = toRepay > strategyBalance ? strategyBalance : toRepay;
if (toWithdraw > 0) {
uint256 received = yieldStrategy.withdraw(toWithdraw);
uint256 minReceived = (toWithdraw * (precision - maxSlippage)) / precision;
if (received < minReceived) revert InsufficientWithdrawal();
}
}
newLastStrategyBalance = yieldStrategy.balanceOf();
uint256 availableDebtBalance = debtAsset.balanceOf(address(this));
uint256 repayAmount = toRepay < availableDebtBalance ? toRepay : availableDebtBalance;
if (repayAmount > 0) {
debtAsset.safeTransfer(address(loanManager), repayAmount);
loanManager.repayDebt(repayAmount);
}
}
// ============ Internal Helpers ============
function _recoverLoanManagerFunds(ILoanManager loanManager) private {
uint256 lmCollateral = loanManager.getCollateralBalance();
if (lmCollateral > 0) {
loanManager.transferCollateral(address(this), lmCollateral);
}
uint256 lmDebt = loanManager.getDebtBalance();
if (lmDebt > 0) loanManager.transferDebt(address(this), lmDebt);
}
function _swapRemainingDebtToCollateral(IERC20 debtAsset, ISwapper swapper) private {
uint256 debtBal = debtAsset.balanceOf(address(this));
if (debtBal > 10 ** debtAsset.decimals() && address(swapper) != address(0)) {
debtAsset.safeTransfer(address(swapper), debtBal);
swapper.swapDebtForCollateral(debtBal);
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {
"src/implementations/ZenjiWstEthPmUsd.sol": {
"ZenjiCoreLib": "0xd58112d6c18b621431958af7116da6c3cbb0b069"
}
},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.