Verified contractPartialMIT
UserVault_V4
Address0x96ec38c84d896b0fbc481b687a9199d4d3933ed0
- Balance
0 ETH
- Transactions
33
- Compiler
solc 0.8.28
- Same code
42 more contracts
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- paris
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,303,777
- Creation transaction
- 0xa2fa5114b2…e79ef97903
- Libraries
- contracts/UserVaultV4.sol:BridgeLib0xab71…cce284contracts/UserVaultV4.sol:BundlerLib0x84be…24c99bcontracts/UserVaultV4.sol:DirectDepositLib0x8888…4b9178
26 files
- contracts/UserVaultV4.solmain592 B
- @openzeppelin/contracts/interfaces/IERC1363.sol4.45 KB
- @openzeppelin/contracts/interfaces/IERC165.sol193 B
- @openzeppelin/contracts/interfaces/IERC20.sol182 B
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol10.08 KB
- @openzeppelin/contracts/utils/ReentrancyGuard.sol3.38 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol871 B
- contracts/Interfaces/IBundler.sol261 B
- contracts/Interfaces/IERC20Extended.sol330 B
- contracts/Interfaces/IMerklDistributor.sol427 B
- contracts/Interfaces/IMetaMorpho.sol1.4 KB
- contracts/Interfaces/IVaultRegistry.sol1.86 KB
- contracts/libraries/BridgeLib.sol4.88 KB
- contracts/libraries/BundlerLib.sol5.63 KB
- contracts/libraries/DirectDepositLib.sol2.63 KB
- contracts/libraries/Errors.sol1.17 KB
- contracts/modules/VaultAccessControl.sol2.25 KB
- contracts/modules/VaultAssetManager.sol714 B
- contracts/modules/VaultBridge.sol7.53 KB
- contracts/modules/VaultCore.sol2.46 KB
- contracts/modules/VaultDepositWithdraw.sol11.25 KB
- contracts/modules/VaultMerkl.sol7.44 KB
- contracts/modules/VaultRebalance.sol6.25 KB
- contracts/modules/VaultStorage.sol4.3 KB
- contracts/modules/VaultViews.sol10.91 KB
contracts/UserVaultV4.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "./modules/VaultViews.sol";
import "./Interfaces/IVaultRegistry.sol";
/**
* @title UserVault_V4
* @dev Multi-asset individual user vault contract for yield optimization
*/
contract UserVault_V4 is VaultViews {
constructor(address _registry, address _owner) {
if (_registry == address(0)) revert ZeroAddress();
if (_registry.code.length == 0) revert MustBeContract();
if (_owner == address(0)) revert ZeroAddress();
registry = IVaultRegistry(_registry);
owner = _owner;
}
}
@openzeppelin/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
@openzeppelin/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
@openzeppelin/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
@openzeppelin/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);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
contracts/Interfaces/IBundler.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
struct Call {
address to;
bytes data;
uint256 value;
bool skipRevert;
bytes32 callbackHash;
}
interface IBundler3 {
function multicall(Call[] calldata calls) external payable;
}
contracts/Interfaces/IERC20Extended.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IERC20Extended is IERC20 {
function decimals() external view returns (uint8);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
}
contracts/Interfaces/IMerklDistributor.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IMerklDistributor {
function claim(
address[] calldata users,
address[] calldata tokens,
uint256[] calldata amounts,
bytes32[][] calldata proofs
) external;
function toggleOperator(address user, address operator) external;
function operators(address user, address operator) external view returns (uint256);
}
contracts/Interfaces/IMetaMorpho.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IMetaMorpho is IERC20 {
function asset() external view returns (address);
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
function mint(uint256 shares, address receiver) external returns (uint256 assets);
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
function convertToShares(uint256 assets) external view returns (uint256 shares);
function convertToAssets(uint256 shares) external view returns (uint256 assets);
function previewDeposit(uint256 assets) external view returns (uint256 shares);
function previewMint(uint256 shares) external view returns (uint256 assets);
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
function previewRedeem(uint256 shares) external view returns (uint256 assets);
function maxDeposit(address receiver) external view returns (uint256);
function maxMint(address receiver) external view returns (uint256);
function maxWithdraw(address owner) external view returns (uint256);
function maxRedeem(address owner) external view returns (uint256);
}
contracts/Interfaces/IVaultRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IVaultRegistry {
function admin() external view returns (address);
function isAdmin(address account) external view returns (bool);
function operator() external view returns (address);
function isAllowedAsset(address asset) external view returns (bool);
function isAllowedVault(address vault) external view returns (bool);
function wasEverVault(address vault) external view returns (bool);
function isVaultAvailableForAsset(address asset, address vault) external view returns (bool);
function getAllowedAssets() external view returns (address[] memory);
function getAllowedVaults() external view returns (address[] memory);
function getAssetAvailableVaults(address asset) external view returns (address[] memory);
function vaultToExpectedAsset(address vault) external view returns (address);
function revenueAddress() external view returns (address);
function feePercentage() external view returns (uint256);
function rebalanceFeePercentage() external view returns (uint256);
function merklClaimFeePercentage() external view returns (uint256);
function sharePriceSlippageTolerance() external view returns (uint256);
function isBridgeRouterWhitelisted(address router) external view returns (bool);
function bridgeRouterType(address router) external view returns (uint8);
function getBridgeRouters() external view returns (address[] memory);
function isAllowedDestChain(uint256 chainId) external view returns (bool);
function bundlerAddress() external view returns (address);
function adapterAddress() external view returns (address);
function pendingFactoryUpgrade() external view returns (address);
function getVaultType(address vault) external view returns (uint8);
}
contracts/libraries/BridgeLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../Interfaces/IVaultRegistry.sol";
/**
* @title BridgeLib
* @dev Library for bridge router interactions to reduce contract size
*/
library BridgeLib {
using SafeERC20 for IERC20;
error BridgeRouterNotWhitelisted();
error BridgeCallFailed();
error BridgeBalanceNotReduced();
error BridgeZeroAmount();
error BridgeOverspend();
error BridgeRecipientMismatch();
error UnsupportedRouterType();
error InvalidReceiverLength();
/**
* @dev Validate that the bridge calldata encodes this vault as the recipient (SL-C01 fix)
* @param registry The vault registry for router type lookup
* @param bridgeRouter The bridge router contract address
* @param bridgeCalldata The calldata to forward to the bridge router
*/
function _validateRecipient(
IVaultRegistry registry,
address bridgeRouter,
bytes calldata bridgeCalldata
) internal view {
uint8 routerType = registry.bridgeRouterType(bridgeRouter);
address recipient;
// Skip the 4-byte function selector to get to ABI-encoded parameters
uint256 paramsStart;
assembly { paramsStart := add(bridgeCalldata.offset, 4) }
if (routerType == 1) {
// LI.FI: BridgeData.receiver is at word 5 of first param tuple
// Step 1: read tuple offset (first ABI param is offset pointer to BridgeData struct)
uint256 tupleOffset;
assembly { tupleOffset := calldataload(paramsStart) }
// Step 2: read receiver at tupleStart + 0xA0 (word 5)
// tupleOffset is relative to paramsStart
assembly { recipient := calldataload(add(add(paramsStart, tupleOffset), 0xA0)) }
} else if (routerType == 2) {
// deBridge: OrderCreation.receiverDst is bytes at word 5 (offset pointer)
uint256 tupleOffset;
assembly { tupleOffset := calldataload(paramsStart) }
uint256 tupleStart;
assembly { tupleStart := add(paramsStart, tupleOffset) }
// word 5 = offset to receiverDst bytes data (relative to tuple start)
uint256 receiverBytesOffset;
assembly { receiverBytesOffset := calldataload(add(tupleStart, 0xA0)) }
uint256 receiverDataStart;
assembly { receiverDataStart := add(tupleStart, receiverBytesOffset) }
// Read length, verify 20 bytes (EVM address)
uint256 receiverLen;
assembly { receiverLen := calldataload(receiverDataStart) }
if (receiverLen != 20) revert InvalidReceiverLength();
// Read 20-byte address (left-aligned, shift right 96 bits)
assembly { recipient := shr(96, calldataload(add(receiverDataStart, 0x20))) }
} else {
revert UnsupportedRouterType();
}
if (recipient != address(this)) revert BridgeRecipientMismatch();
}
/**
* @dev Execute a bridge call through a whitelisted router
* @param registry The vault registry for whitelist checks
* @param bridgeRouter The bridge router contract address
* @param asset The token being bridged
* @param amount The amount to approve for bridging
* @param bridgeCalldata The calldata to forward to the bridge router
* @return spent The amount of tokens consumed by the bridge
*/
function executeBridge(
IVaultRegistry registry,
address bridgeRouter,
address asset,
uint256 amount,
bytes calldata bridgeCalldata
) external returns (uint256 spent) {
if (amount == 0) revert BridgeZeroAmount();
if (!registry.isBridgeRouterWhitelisted(bridgeRouter)) revert BridgeRouterNotWhitelisted();
// Validate bridge recipient is this vault (SL-C01 fix)
_validateRecipient(registry, bridgeRouter, bridgeCalldata);
uint256 balanceBefore = IERC20(asset).balanceOf(address(this));
// Approve exact amount to router
IERC20(asset).forceApprove(bridgeRouter, amount);
// Call bridge router with provided calldata
(bool success,) = bridgeRouter.call{value: msg.value}(bridgeCalldata);
if (!success) revert BridgeCallFailed();
// Revoke approval
IERC20(asset).forceApprove(bridgeRouter, 0);
uint256 balanceAfter = IERC20(asset).balanceOf(address(this));
// Verify tokens were consumed
if (balanceAfter >= balanceBefore) revert BridgeBalanceNotReduced();
spent = balanceBefore - balanceAfter;
// SL-02: Enforce spend cap — router must not consume more than approved amount
if (spent > amount) revert BridgeOverspend();
}
}
contracts/libraries/BundlerLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../Interfaces/IBundler.sol";
import "../Interfaces/IMetaMorpho.sol";
import "../Interfaces/IERC20Extended.sol";
import "../Interfaces/IVaultRegistry.sol";
/**
* @title BundlerLib
* @dev Library for bundler interactions to reduce contract size
*/
library BundlerLib {
using SafeERC20 for IERC20;
error InsufficientSharesReceived();
error VaultAssetMismatch();
error VaultNotAvailable();
error VaultNotRegistered();
error ZeroShares();
/**
* @dev Deposit to vault using bundler
*/
function depositToVault(
IVaultRegistry registry,
address vault,
uint256 amount,
address vaultAsset
) external {
if (!registry.isVaultAvailableForAsset(vaultAsset, vault)) revert VaultNotAvailable();
if (registry.vaultToExpectedAsset(vault) != vaultAsset) revert VaultAssetMismatch();
if (IMetaMorpho(vault).asset() != vaultAsset) revert VaultAssetMismatch();
address adapterAddr = registry.adapterAddress();
address bundlerAddr = registry.bundlerAddress();
uint256 expectedShares = IMetaMorpho(vault).previewDeposit(amount);
uint256 slippageTolerance = registry.sharePriceSlippageTolerance();
uint256 minExpectedShares = (expectedShares * (10000 - slippageTolerance)) / 10000;
IERC20(vaultAsset).forceApprove(adapterAddr, amount);
uint256 shareDecimals = _getTokenDecimals(vault);
uint256 shareUnit = 10 ** shareDecimals;
uint256 currentSharePrice = IMetaMorpho(vault).convertToAssets(shareUnit);
uint256 maxSharePriceE27 = (currentSharePrice * 1e27 * (10000 + slippageTolerance)) / (shareUnit * 10000);
Call[] memory calls = new Call[](2);
calls[0] = Call({
to: adapterAddr,
data: abi.encodeWithSelector(
// Morpho Adapter: transferFrom helper (selector 0xd96ca0b9)
bytes4(0xd96ca0b9),
vaultAsset,
adapterAddr,
amount
),
value: 0,
skipRevert: false,
callbackHash: bytes32(0)
});
calls[1] = Call({
to: adapterAddr,
data: abi.encodeWithSelector(
// Morpho Adapter: deposit (selector 0x6ef5eeae)
bytes4(0x6ef5eeae),
vault,
amount,
maxSharePriceE27,
address(this)
),
value: 0,
skipRevert: false,
callbackHash: bytes32(0)
});
uint256 balanceBefore = IERC20(vault).balanceOf(address(this));
IBundler3(bundlerAddr).multicall(calls);
uint256 balanceAfter = IERC20(vault).balanceOf(address(this));
uint256 sharesReceived = balanceAfter - balanceBefore;
if (sharesReceived < minExpectedShares) revert InsufficientSharesReceived();
IERC20(vaultAsset).forceApprove(adapterAddr, 0);
}
/**
* @dev Redeem from vault using bundler
*/
function redeemFromVault(
IVaultRegistry registry,
address vault,
uint256 shares
) external returns (uint256) {
if (shares == 0) revert ZeroShares();
address expectedAsset = registry.vaultToExpectedAsset(vault);
if (expectedAsset == address(0)) revert VaultNotRegistered();
if (IMetaMorpho(vault).asset() != expectedAsset) revert VaultAssetMismatch();
address adapterAddr = registry.adapterAddress();
address bundlerAddr = registry.bundlerAddress();
uint256 balanceBefore = IERC20(expectedAsset).balanceOf(address(this));
IERC20(vault).forceApprove(adapterAddr, shares);
uint256 expectedAssets = IMetaMorpho(vault).previewRedeem(shares);
uint256 slippageTolerance = registry.sharePriceSlippageTolerance();
uint256 minAssets = (expectedAssets * (10000 - slippageTolerance)) / 10000;
uint256 minSharePriceE27 = (minAssets * 1e27) / shares;
Call[] memory calls = new Call[](2);
calls[0] = Call({
to: adapterAddr,
data: abi.encodeWithSelector(
// Morpho Adapter: transferFrom helper (selector 0xd96ca0b9)
bytes4(0xd96ca0b9),
vault,
adapterAddr,
shares
),
value: 0,
skipRevert: false,
callbackHash: bytes32(0)
});
calls[1] = Call({
to: adapterAddr,
data: abi.encodeWithSelector(
// Morpho Adapter: redeem (selector 0xa7f6e606)
bytes4(0xa7f6e606),
vault,
shares,
minSharePriceE27,
address(this),
adapterAddr
),
value: 0,
skipRevert: false,
callbackHash: bytes32(0)
});
IBundler3(bundlerAddr).multicall(calls);
IERC20(vault).forceApprove(adapterAddr, 0);
uint256 balanceAfter = IERC20(expectedAsset).balanceOf(address(this));
return balanceAfter - balanceBefore;
}
function _getTokenDecimals(address tokenAddress) private view returns (uint256) {
try IERC20Extended(tokenAddress).decimals() returns (uint8 decimals) {
if (decimals > 18) return 18;
return uint256(decimals);
} catch {
return 18;
}
}
}
contracts/libraries/DirectDepositLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../Interfaces/IMetaMorpho.sol";
import "../Interfaces/IVaultRegistry.sol";
/**
* @title DirectDepositLib
* @dev Library for direct ERC4626 deposit/redeem into Morpho V2 vaults (no bundler needed)
*/
library DirectDepositLib {
using SafeERC20 for IERC20;
error InsufficientSharesReceived();
error InsufficientAssetsReceived();
error VaultAssetMismatch();
error VaultNotAvailable();
error VaultNotRegistered();
error ZeroShares();
/**
* @dev Deposit to V2 vault using direct ERC4626 deposit
*/
function depositToVault(
IVaultRegistry registry,
address vault,
uint256 amount,
address vaultAsset
) external {
if (!registry.isVaultAvailableForAsset(vaultAsset, vault)) revert VaultNotAvailable();
if (registry.vaultToExpectedAsset(vault) != vaultAsset) revert VaultAssetMismatch();
if (IMetaMorpho(vault).asset() != vaultAsset) revert VaultAssetMismatch();
uint256 expectedShares = IMetaMorpho(vault).previewDeposit(amount);
uint256 slippageTolerance = registry.sharePriceSlippageTolerance();
uint256 minExpectedShares = (expectedShares * (10000 - slippageTolerance)) / 10000;
IERC20(vaultAsset).forceApprove(vault, amount);
uint256 sharesReceived = IMetaMorpho(vault).deposit(amount, address(this));
if (sharesReceived < minExpectedShares) revert InsufficientSharesReceived();
IERC20(vaultAsset).forceApprove(vault, 0);
}
/**
* @dev Redeem from V2 vault using direct ERC4626 redeem
*/
function redeemFromVault(
IVaultRegistry registry,
address vault,
uint256 shares
) external returns (uint256) {
if (shares == 0) revert ZeroShares();
address expectedAsset = registry.vaultToExpectedAsset(vault);
if (expectedAsset == address(0)) revert VaultNotRegistered();
if (IMetaMorpho(vault).asset() != expectedAsset) revert VaultAssetMismatch();
uint256 expectedAssets = IMetaMorpho(vault).previewRedeem(shares);
uint256 slippageTolerance = registry.sharePriceSlippageTolerance();
uint256 minAssets = (expectedAssets * (10000 - slippageTolerance)) / 10000;
uint256 assetsReceived = IMetaMorpho(vault).redeem(shares, address(this), address(this));
if (assetsReceived < minAssets) revert InsufficientAssetsReceived();
return assetsReceived;
}
}
contracts/libraries/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
// Custom errors to reduce contract size
// Access Control Errors
error OnlyOwner();
error OnlyAdmin();
error OnlyOperator();
error OnlyOwnerOrOperator();
error OnlyRevenue();
error NotPendingOwner();
error NoPendingTransfer();
// Asset/Vault Errors
error AssetNotAllowed();
error VaultNotAllowed();
error InvalidAsset();
error InvalidVault();
error InvalidOwner();
error VaultAlreadyExists();
error SameVault();
error NoDeposits();
error NoFunds();
// Validation Errors
error ZeroAmount();
error ZeroAddress();
error InvalidAmount();
error InsufficientBalance();
error MustBeEOA();
error MustBeContract();
error AlreadyOwner();
// Operation Errors
error InitialDepositMade();
error NoInitialDeposit();
error CooldownNotPassed();
error ArrayMismatch();
error EmptyArray();
error BatchSizeExceeded();
error DuplicateToken();
error CannotWithdrawVaultShares();
error VaultAlreadyIdle();
error VaultNotEmpty();
error OwnerAlreadyHasVault();
error InvalidDestChain();
error DestChainAlreadyAllowed();
error DestChainNotAllowed();
// Upgrade Errors
error UpgradeNotApproved();
error UpgradeAddressMismatch();
contracts/modules/VaultAccessControl.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "./VaultStorage.sol";
/**
* @title VaultAccessControl
* @dev Handles access control, modifiers, and ownership management
*
* Role hierarchy:
* - Owner: EOA user who owns the vault (can withdraw, claim rewards)
* - Admin: Multisig approvals via registry for critical functions
* - Operator: Rebalance executor (via registry)
*/
abstract contract VaultAccessControl is VaultStorage {
// ============ Modifiers ============
modifier onlyOwner() {
if (msg.sender != owner) revert OnlyOwner();
_;
}
modifier onlyAdmin() {
if (!registry.isAdmin(msg.sender)) revert OnlyAdmin();
_;
}
modifier onlyOperator() {
if (msg.sender != registry.operator()) revert OnlyOperator();
_;
}
modifier onlyOwnerOrOperator() {
if (msg.sender != owner && msg.sender != registry.operator()) revert OnlyOwnerOrOperator();
_;
}
modifier onlyRevenue() {
if (msg.sender != registry.revenueAddress()) revert OnlyRevenue();
_;
}
modifier onlyAllowedAsset(address asset) {
if (!registry.isAllowedAsset(asset)) revert AssetNotAllowed();
_;
}
modifier onlyAllowedVault(address vault) {
if (!registry.isAllowedVault(vault)) revert VaultNotAllowed();
_;
}
// ============ Ownership Transfer (Two-Step) ============
function transferOwnership(address newOwner) external onlyOwner {
if (newOwner == address(0)) revert ZeroAddress();
if (newOwner == owner) revert AlreadyOwner();
pendingOwner = newOwner;
emit OwnershipTransferInitiated(owner, newOwner);
}
function acceptOwnership() external {
if (msg.sender != pendingOwner) revert NotPendingOwner();
address oldOwner = owner;
owner = pendingOwner;
pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, owner);
}
function cancelOwnershipTransfer() external onlyOwner {
if (pendingOwner == address(0)) revert NoPendingTransfer();
address cancelled = pendingOwner;
pendingOwner = address(0);
emit OwnershipTransferCancelled(cancelled);
}
}
contracts/modules/VaultAssetManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "./VaultAccessControl.sol";
/**
* @title VaultAssetManager
* @dev Registry-backed asset/vault helpers for per-user vaults
*/
abstract contract VaultAssetManager is VaultAccessControl {
/**
* @dev Get the active vault for an asset (per-user)
*/
function getAssetActiveVault(address asset) external view returns (address) {
return assetToVault[asset];
}
/**
* @dev Check if a vault is available for a specific asset via registry
*/
function isVaultAvailableForAsset(address asset, address vault) public view returns (bool) {
return registry.isVaultAvailableForAsset(asset, vault);
}
}
contracts/modules/VaultBridge.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./VaultRebalance.sol";
import "../libraries/BridgeLib.sol";
/**
* @title VaultBridge
* @dev Handles cross-chain bridge operations for vault assets
* @notice Supports generic bridge routers (LI.FI, Socket/Bungee, deBridge) via whitelist
*/
abstract contract VaultBridge is VaultRebalance {
using SafeERC20 for IERC20;
// ============ Bridge State ============
// Per-asset per-chain tracking
mapping(address => mapping(uint256 => uint256)) public assetBridgedOut; // asset => destChainId => total
mapping(address => mapping(uint256 => uint256)) public assetBridgedIn; // asset => srcChainId => total
// Monotonic nonce for tracking bridge operations
uint256 public bridgeNonce;
// ============ Bridge Events ============
event BridgeWithdraw(
uint256 indexed nonce,
address indexed asset,
uint256 amount,
uint256 spent,
address bridgeRouter,
uint256 destChainId,
uint256 feeAmount
);
event BridgeDepositAcknowledged(
uint256 indexed nonce,
address indexed asset,
uint256 amount,
uint256 srcChainId
);
// ============ Bridge Functions ============
/**
* @dev Withdraw from vault and bridge to another chain
* @notice Mirrors withdraw() accounting: redeems shares, calculates profit fee, then bridges
* @param asset The asset to withdraw and bridge
* @param assetAmount Amount of asset tokens to withdraw (0 for full withdrawal).
* Uses the asset's native decimals (e.g. 6 for USDC, 18 for WETH).
* Internally converted to Morpho vault shares via convertToShares().
* @param bridgeRouter The whitelisted bridge router to use
* @param destChainId The destination chain ID
* @param bridgeCalldata The calldata for the bridge router
*/
function bridgeWithdraw(
address asset,
uint256 assetAmount,
address bridgeRouter,
uint256 destChainId,
bytes calldata bridgeCalldata
) external payable onlyOwnerOrOperator nonReentrant {
if (!assetHasInitialDeposit[asset]) revert NoDeposits();
if (bridgeRouter == address(0)) revert ZeroAddress();
if (!registry.isAllowedDestChain(destChainId)) revert InvalidDestChain();
address vault = assetToVault[asset];
if (vault == address(0)) revert InvalidVault();
uint256 totalShares = _getVaultBalance(vault);
if (totalShares == 0) revert NoFunds();
// Convert asset amount to shares, or use all shares for full withdrawal
uint256 sharesToRedeem;
uint256 totalAssets = _getVaultAssets(vault);
if (assetAmount == 0 || assetAmount >= totalAssets) {
sharesToRedeem = totalShares; // Full withdrawal
} else {
// Proportional share calculation using our own balance
sharesToRedeem = (totalShares * assetAmount) / totalAssets;
if (sharesToRedeem == 0) revert ZeroAmount();
if (sharesToRedeem > totalShares) {
sharesToRedeem = totalShares;
}
}
// Calculate principal portion (same as withdraw())
uint256 principalPortion;
if (sharesToRedeem >= totalShares) {
principalPortion = assetTotalDeposited[asset];
} else {
principalPortion = (assetTotalDeposited[asset] * sharesToRedeem) / totalShares;
}
// EFFECTS - Update deposit state before external calls (CEI pattern)
if (principalPortion >= assetTotalDeposited[asset]) {
assetTotalDeposited[asset] = 0;
// Keep assetHasInitialDeposit and assetToVault so bridge-acknowledge can work
} else {
assetTotalDeposited[asset] -= principalPortion;
}
// Reduce rebalance base proportionally
uint256 baseAmount = assetRebalanceBaseAmount[asset];
if (baseAmount > 0) {
uint256 basePortion;
if (sharesToRedeem >= totalShares) {
basePortion = baseAmount;
} else {
basePortion = (baseAmount * sharesToRedeem) / totalShares;
}
assetRebalanceBaseAmount[asset] = baseAmount - basePortion;
}
// Increment bridge nonce
uint256 currentNonce = ++bridgeNonce;
// INTERACTIONS - Redeem from vault (shares)
uint256 redeemedAmount = _redeemFromVault(vault, sharesToRedeem);
// Calculate fee on profit
uint256 feeAmount = 0;
uint256 userAmount = redeemedAmount;
if (principalPortion > 0 && redeemedAmount > principalPortion) {
uint256 profit = redeemedAmount - principalPortion;
feeAmount = (profit * registry.feePercentage()) / 10000;
userAmount = redeemedAmount - feeAmount;
}
// Accrue protocol fee
if (feeAmount > 0) {
protocolFees[asset] += feeAmount;
assetTotalFeesCollected[asset] += feeAmount;
}
// Execute bridge with user amount (after fee deduction)
uint256 spent = BridgeLib.executeBridge(
registry,
bridgeRouter,
asset,
userAmount,
bridgeCalldata
);
// Update bridge tracking
assetBridgedOut[asset][destChainId] += spent;
emit BridgeWithdraw(currentNonce, asset, userAmount, spent, bridgeRouter, destChainId, feeAmount);
}
/**
* @dev Acknowledge tokens that arrived at this vault via a bridge
* @notice Admin calls this after verifying tokens arrived on-chain
* @param asset The bridged asset
* @param amount The amount of tokens that arrived
* @param srcChainId The source chain ID
* @param morphoVault Target Morpho vault for deposit (used for first-deposit-via-bridge)
*/
function adminAcknowledgeBridgeDeposit(
address asset,
uint256 amount,
uint256 srcChainId,
address morphoVault
) external onlyAdmin onlyAllowedAsset(asset) nonReentrant {
if (amount == 0) revert ZeroAmount();
// Handle first deposit via bridge (no prior initialDeposit needed)
address vault = assetToVault[asset];
if (!assetHasInitialDeposit[asset]) {
if (!registry.isVaultAvailableForAsset(asset, morphoVault)) revert InvalidVault();
assetToVault[asset] = morphoVault;
assetHasInitialDeposit[asset] = true;
vault = morphoVault;
}
// Verify contract actually has the tokens (minus reserved protocol fees)
uint256 balance = IERC20(asset).balanceOf(address(this));
uint256 reserved = protocolFees[asset];
uint256 available = balance > reserved ? balance - reserved : 0;
if (available < amount) revert InsufficientBalance();
// Increment bridge nonce
uint256 currentNonce = ++bridgeNonce;
// EFFECTS - Update tracking
assetTotalDeposited[asset] += amount;
assetRebalanceBaseAmount[asset] += amount;
assetBridgedIn[asset][srcChainId] += amount;
// INTERACTIONS - Deposit into active Morpho vault via bundler
_depositToVault(vault, amount, asset);
emit BridgeDepositAcknowledged(currentNonce, asset, amount, srcChainId);
}
}
contracts/modules/VaultCore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./VaultAssetManager.sol";
import "../Interfaces/IMetaMorpho.sol";
import "../libraries/BundlerLib.sol";
import "../libraries/DirectDepositLib.sol";
/**
* @title VaultCore
* @dev Core functionality including vault deposit/redeem routing (V1 bundler vs V2 direct)
*/
abstract contract VaultCore is VaultAssetManager {
using SafeERC20 for IERC20;
// ============ Internal Helper Functions ============
/**
* @dev Deposit to vault — routes to BundlerLib (V1) or DirectDepositLib (V2)
*/
function _depositToVault(
address vault,
uint256 amount,
address vaultAsset
) internal {
if (registry.getVaultType(vault) == 1) {
DirectDepositLib.depositToVault(registry, vault, amount, vaultAsset);
} else {
BundlerLib.depositToVault(registry, vault, amount, vaultAsset);
}
}
/**
* @dev Redeem from vault — routes to BundlerLib (V1) or DirectDepositLib (V2)
*/
function _redeemFromVault(address vault, uint256 shares)
internal
returns (uint256)
{
if (registry.getVaultType(vault) == 1) {
return DirectDepositLib.redeemFromVault(registry, vault, shares);
} else {
return BundlerLib.redeemFromVault(registry, vault, shares);
}
}
/**
* @dev Calculate fee from profit
*/
function calculateFeeFromProfit(address asset, uint256 totalAmount)
public
view
returns (uint256 feeAmount, uint256 userAmount)
{
if (!assetHasInitialDeposit[asset] || assetTotalDeposited[asset] <= 0 || totalAmount <= assetTotalDeposited[asset]) {
return (0, totalAmount);
}
uint256 profit = totalAmount - assetTotalDeposited[asset];
feeAmount = (profit * registry.feePercentage()) / 10000;
userAmount = totalAmount - feeAmount;
return (feeAmount, userAmount);
}
function _getVaultBalance(address vault) internal view returns (uint256) {
return IMetaMorpho(vault).balanceOf(address(this));
}
function _getVaultAssets(address vault) internal view returns (uint256) {
uint256 shares = _getVaultBalance(vault);
return IMetaMorpho(vault).convertToAssets(shares);
}
}
contracts/modules/VaultDepositWithdraw.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./VaultCore.sol";
/**
* @title VaultDepositWithdraw
* @dev Handles all deposit and withdrawal operations
*/
abstract contract VaultDepositWithdraw is VaultCore {
using SafeERC20 for IERC20;
// ============ Deposit Functions ============
/**
* @dev Initial deposit for a specific asset
* @notice Follows CEI (Checks-Effects-Interactions) pattern for reentrancy safety
* @param asset The asset to deposit
* @param vault The vault to deposit into (must be in assetAvailableVaults for this asset)
* @param amount Amount to deposit
*/
function initialDeposit(address asset, address vault, uint256 amount)
external
onlyOwner
onlyAllowedAsset(asset)
nonReentrant
{
// CHECKS
if (assetHasInitialDeposit[asset]) revert InitialDepositMade();
if (amount == 0) revert ZeroAmount();
if (vault == address(0)) revert ZeroAddress();
if (!isVaultAvailableForAsset(asset, vault)) revert VaultNotAllowed();
// EFFECTS - Update state before external calls
assetToVault[asset] = vault;
assetTotalDeposited[asset] = amount;
assetHasInitialDeposit[asset] = true;
assetLastDepositTime[asset] = block.timestamp;
assetRebalanceBaseAmount[asset] = amount;
// INTERACTIONS - External calls after state updates
IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);
_depositToVault(vault, amount, asset);
emit InitialDeposit(asset, vault, amount);
}
/**
* @dev User deposit function - allows owner to deposit more of a specific asset
* @param asset The asset to deposit
* @param amount Amount to deposit
*/
function userDeposit(address asset, uint256 amount)
external
onlyOwner
onlyAllowedAsset(asset)
nonReentrant
{
if (!assetHasInitialDeposit[asset]) revert NoInitialDeposit();
if (amount == 0) revert ZeroAmount();
address vault = assetToVault[asset];
if (vault == address(0)) revert InvalidVault();
if (!registry.isVaultAvailableForAsset(asset, vault)) revert VaultNotAllowed();
// Update tracking before external calls (CEI)
assetTotalDeposited[asset] += amount;
assetLastDepositTime[asset] = block.timestamp;
assetRebalanceBaseAmount[asset] += amount; // Increase base amount for rebalance profit calculation
// Transfer asset from user to this contract
IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);
// Deposit to vault using bundler
_depositToVault(vault, amount, asset);
emit UserDeposit(asset, vault, amount);
}
/**
* @dev Admin deposit function - allows admin to deposit on behalf of user
* @notice Only callable by admin (multisig approvals via registry)
* @notice This function is designed for user benefit, where the admin provides extra benefit to users
* by depositing tokens on their behalf. Admin deposits are treated as additional principal
* and increase the user's total deposited amount, providing users with extra value.
* @notice Admin deposits affect the profit base amount and are included in assetTotalDeposited
* @param asset The asset to deposit
* @param amount Amount to deposit (admin provides this as extra benefit to the user)
*/
function adminDeposit(address asset, uint256 amount)
external
onlyAdmin
onlyAllowedAsset(asset)
nonReentrant
{
if (!assetHasInitialDeposit[asset]) revert NoInitialDeposit();
if (amount == 0) revert ZeroAmount();
address vault = assetToVault[asset];
if (vault == address(0)) revert InvalidVault();
if (!registry.isVaultAvailableForAsset(asset, vault)) revert VaultNotAllowed();
// Update tracking before external calls (CEI)
assetTotalDeposited[asset] += amount;
assetLastDepositTime[asset] = block.timestamp;
assetRebalanceBaseAmount[asset] += amount; // Increase base amount for rebalance profit calculation
// Transfer asset from admin to this contract
IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);
// Deposit to vault using bundler
_depositToVault(vault, amount, asset);
emit AdminDeposit(msg.sender, asset, vault, amount);
}
// ============ Withdrawal Functions ============
/**
* @dev Withdraw from a specific asset's vault
* @notice Correctly tracks principal vs profit to prevent accounting issues
* @param asset The asset to withdraw
* @param assetAmount Amount of asset tokens to withdraw (0 for full withdrawal).
* Uses the asset's native decimals (e.g. 6 for USDC, 18 for WETH).
* Internally converted to Morpho vault shares via convertToShares().
*/
function withdraw(address asset, uint256 assetAmount)
external
onlyOwner
nonReentrant
{
if (!assetHasInitialDeposit[asset]) revert NoDeposits();
address vault = assetToVault[asset];
// Handle idle state: funds sitting as ERC20 in contract (after emergency redeem)
if (vault == address(0)) {
_withdrawIdle(asset, assetAmount);
return;
}
uint256 totalShares = _getVaultBalance(vault);
if (totalShares == 0) revert NoFunds();
// Convert asset amount to shares, or use all shares for full withdrawal
uint256 sharesToRedeem;
uint256 totalAssets = _getVaultAssets(vault);
if (assetAmount == 0 || assetAmount >= totalAssets) {
sharesToRedeem = totalShares; // Full withdrawal
} else {
// Proportional share calculation using our own balance
// (avoids external convertToShares which can miscompile under viaIR)
sharesToRedeem = (totalShares * assetAmount) / totalAssets;
if (sharesToRedeem == 0) revert ZeroAmount();
// Ensure we don't exceed available shares
if (sharesToRedeem > totalShares) {
sharesToRedeem = totalShares;
}
}
// Calculate principal portion being withdrawn (proportional to shares)
// This must be done BEFORE the redeem to get accurate share proportion
uint256 principalPortion;
if (sharesToRedeem >= totalShares) {
// Full withdrawal - all remaining principal
principalPortion = assetTotalDeposited[asset];
} else {
// Partial withdrawal - proportional principal
principalPortion = (assetTotalDeposited[asset] * sharesToRedeem) / totalShares;
}
// EFFECTS - Update state before external calls (CEI pattern)
// Update total deposited (reduce by principal portion only, not profit) before external call
if (principalPortion >= assetTotalDeposited[asset]) {
assetTotalDeposited[asset] = 0;
assetHasInitialDeposit[asset] = false;
assetToVault[asset] = address(0);
} else {
assetTotalDeposited[asset] -= principalPortion;
}
// Reduce rebalance base proportionally to shares withdrawn
uint256 baseAmount = assetRebalanceBaseAmount[asset];
if (baseAmount > 0) {
uint256 basePortion;
if (sharesToRedeem >= totalShares) {
basePortion = baseAmount;
} else {
basePortion = (baseAmount * sharesToRedeem) / totalShares;
}
assetRebalanceBaseAmount[asset] = baseAmount - basePortion;
}
// INTERACTIONS - Redeem from vault using bundler (shares)
uint256 redeemedAmount = _redeemFromVault(vault, sharesToRedeem);
// Calculate fee and user amount using proportional principal for accurate fee calculation
uint256 feeAmount = 0;
uint256 userAmount = redeemedAmount;
if (principalPortion > 0 && redeemedAmount > principalPortion) {
// There's profit, calculate fee on profit
uint256 profit = redeemedAmount - principalPortion;
feeAmount = (profit * registry.feePercentage()) / 10000;
userAmount = redeemedAmount - feeAmount;
}
// Accrue protocol fee (pull-based) if there's a fee
if (feeAmount > 0) {
protocolFees[asset] += feeAmount;
assetTotalFeesCollected[asset] += feeAmount;
emit FeeCollected(asset, vault, feeAmount, userAmount);
}
// Transfer remaining amount to owner
IERC20(asset).safeTransfer(owner, userAmount);
emit Withdrawal(asset, vault, owner, userAmount);
}
/**
* @dev Withdraw when funds are idle in the contract (after emergency redeem)
* @notice Properly updates all accounting — principal, base amount, fees
*/
function _withdrawIdle(address asset, uint256 assetAmount) internal {
uint256 balance = IERC20(asset).balanceOf(address(this));
uint256 reserved = protocolFees[asset];
uint256 available = balance > reserved ? balance - reserved : 0;
if (available == 0) revert NoFunds();
uint256 withdrawAmount = (assetAmount == 0 || assetAmount >= available)
? available
: assetAmount;
// Calculate principal portion (proportional to withdrawal)
uint256 principalPortion;
if (withdrawAmount >= available) {
principalPortion = assetTotalDeposited[asset];
} else {
principalPortion = (assetTotalDeposited[asset] * withdrawAmount) / available;
}
// EFFECTS — update accounting
if (principalPortion >= assetTotalDeposited[asset]) {
assetTotalDeposited[asset] = 0;
assetHasInitialDeposit[asset] = false;
assetRebalanceBaseAmount[asset] = 0;
} else {
assetTotalDeposited[asset] -= principalPortion;
uint256 baseAmount = assetRebalanceBaseAmount[asset];
uint256 basePortion = (baseAmount * withdrawAmount) / available;
assetRebalanceBaseAmount[asset] = baseAmount > basePortion ? baseAmount - basePortion : 0;
}
// Fee on profit (if any)
uint256 feeAmount = 0;
uint256 userAmount = withdrawAmount;
if (principalPortion > 0 && withdrawAmount > principalPortion) {
uint256 profit = withdrawAmount - principalPortion;
feeAmount = (profit * registry.feePercentage()) / 10000;
userAmount = withdrawAmount - feeAmount;
}
if (feeAmount > 0) {
protocolFees[asset] += feeAmount;
assetTotalFeesCollected[asset] += feeAmount;
emit FeeCollected(asset, address(0), feeAmount, userAmount);
}
// INTERACTIONS
IERC20(asset).safeTransfer(owner, userAmount);
emit Withdrawal(asset, address(0), owner, userAmount);
}
}
contracts/modules/VaultMerkl.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./VaultBridge.sol";
/**
* @title VaultMerkl
* @dev Handles Merkl reward claiming and distribution
* @notice Owner or operator can claim rewards. When operator claims, rewards go to operator wallet.
*/
abstract contract VaultMerkl is VaultBridge {
using SafeERC20 for IERC20;
/**
* @dev Claim single Merkl reward token
* @notice Owner or operator can claim. Rewards go to caller-appropriate recipient:
* owner calls → rewards to owner, operator calls → rewards to operator.
* @dev Deducts merklClaimFeePercentage from claimed amount, accrues fee in protocolFees
* @param token The reward token address to claim
* @param claimable The amount to claim (from Merkl proof)
* @param proof The Merkle proof for claiming
*/
function claimMerklReward(
address token,
uint256 claimable,
bytes32[] calldata proof
) external onlyOwnerOrOperator nonReentrant {
if (token == address(0)) revert ZeroAddress();
if (claimable == 0) revert ZeroAmount();
// Prepare arrays for batch call (single item)
address[] memory users = new address[](1);
address[] memory tokens = new address[](1);
uint256[] memory amounts = new uint256[](1);
bytes32[][] memory proofs = new bytes32[][](1);
users[0] = address(this);
tokens[0] = token;
amounts[0] = claimable;
proofs[0] = proof;
// Get balance before claim
uint256 balanceBefore = IERC20(token).balanceOf(address(this));
// Claim rewards
merklDistributor.claim(users, tokens, amounts, proofs);
// Calculate claimed amount
uint256 balanceAfter = IERC20(token).balanceOf(address(this));
uint256 claimedAmount = balanceAfter - balanceBefore;
// Split claimed reward: fee accrued, rest to recipient
if (claimedAmount > 0) {
_distributeReward(token, claimedAmount);
}
}
/**
* @dev Internal: distribute a claimed reward — fee to protocol, remainder to recipient
* @notice Recipient is owner when owner calls, operator when operator calls
*/
function _distributeReward(address token, uint256 claimedAmount) internal {
uint256 feeAmount = (claimedAmount * registry.merklClaimFeePercentage()) / 10000;
uint256 userAmount = claimedAmount - feeAmount;
// Accrue protocol fee (pull-based)
if (feeAmount > 0) {
protocolFees[token] += feeAmount;
}
// Always send rewards to owner — operator can trigger claim but cannot redirect
address recipient = owner;
// Transfer remaining to recipient
if (userAmount > 0) {
IERC20(token).safeTransfer(recipient, userAmount);
}
emit MerklTokensClaimed(token, claimedAmount, feeAmount, userAmount);
}
/**
* @dev Internal: distribute reward with try/catch for batch safety
* @notice If transfer fails (e.g. token with transfer restrictions), emits MerklClaimFailed
* and the fee+reward stay in the contract for later manual rescue
*/
function _distributeRewardSafe(address token, uint256 balanceBefore) internal {
uint256 balanceAfter = IERC20(token).balanceOf(address(this));
uint256 claimedAmount = balanceAfter - balanceBefore;
if (claimedAmount > 0) {
uint256 feeAmount = (claimedAmount * registry.merklClaimFeePercentage()) / 10000;
uint256 userAmount = claimedAmount - feeAmount;
// Accrue protocol fee (pull-based)
if (feeAmount > 0) {
protocolFees[token] += feeAmount;
}
// Determine recipient: owner calls → owner, operator calls → operator
address recipient = (msg.sender == owner) ? owner : registry.operator();
// Try transferring — if the token has transfer restrictions, don't revert the batch
// Uses low-level call to handle non-standard tokens (USDT) that don't return bool
if (userAmount > 0) {
(bool ok, bytes memory ret) = token.call(
abi.encodeWithSelector(IERC20.transfer.selector, recipient, userAmount)
);
// Success if: call didn't revert AND (returned true OR returned nothing)
bool transferred = ok && (ret.length == 0 || abi.decode(ret, (bool)));
if (transferred) {
emit MerklTokensClaimed(token, claimedAmount, feeAmount, userAmount);
} else {
// Transfer failed — undo fee accrual, tokens stay in contract for later recovery
if (feeAmount > 0) {
protocolFees[token] -= feeAmount;
}
emit MerklClaimFailed(token, claimedAmount, "transfer_failed");
}
} else {
// No user amount (100% fee edge case), still emit success
emit MerklTokensClaimed(token, claimedAmount, feeAmount, userAmount);
}
}
}
/**
* @dev Claim multiple Merkl reward tokens in a single transaction
* @notice Owner or operator can claim. Uses try/catch per token so one failing
* token doesn't block the entire batch.
* @notice Batch size limited to MAX_MERKL_BATCH_SIZE to bound gas costs
* @dev Deducts merklClaimFeePercentage from each claimed token amount
* @param tokens Array of reward token addresses to claim
* @param claimables Array of amounts to claim for each token
* @param proofs Array of Merkle proofs for each claim
*/
function claimMerklRewardsBatch(
address[] calldata tokens,
uint256[] calldata claimables,
bytes32[][] calldata proofs
) external onlyOwnerOrOperator nonReentrant {
if (tokens.length != claimables.length || tokens.length != proofs.length) revert ArrayMismatch();
if (tokens.length == 0) revert EmptyArray();
if (tokens.length > MAX_MERKL_BATCH_SIZE) revert BatchSizeExceeded();
address[] memory accounts = new address[](tokens.length);
uint256[] memory balancesBefore = new uint256[](tokens.length);
address[] memory seenTokens = new address[](tokens.length);
uint256 seenCount = 0;
for (uint256 i = 0; i < tokens.length; i++) {
if (tokens[i] == address(0)) revert ZeroAddress();
if (claimables[i] == 0) revert ZeroAmount();
bool isDuplicate = false;
for (uint256 j = 0; j < seenCount; j++) {
if (seenTokens[j] == tokens[i]) {
isDuplicate = true;
break;
}
}
if (isDuplicate) revert DuplicateToken();
seenTokens[seenCount] = tokens[i];
seenCount++;
balancesBefore[i] = IERC20(tokens[i]).balanceOf(address(this));
accounts[i] = address(this);
}
merklDistributor.claim(accounts, tokens, claimables, proofs);
for (uint256 i = 0; i < tokens.length; i++) {
_distributeRewardSafe(tokens[i], balancesBefore[i]);
}
}
}
contracts/modules/VaultRebalance.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./VaultDepositWithdraw.sol";
/**
* @title VaultRebalance
* @dev Handles vault rebalancing operations with profit-based fee collection
*/
abstract contract VaultRebalance is VaultDepositWithdraw {
using SafeERC20 for IERC20;
// ============ Operator Functions ============
/**
* @dev Rebalance a specific asset to a new vault
* @notice Also handles idle state (fromVault == address(0)) after emergency redeem
*/
function rebalanceToVault(address asset, address toVault)
external
onlyOperator
onlyAllowedAsset(asset)
onlyAllowedVault(toVault)
nonReentrant
{
if (!assetHasInitialDeposit[asset]) revert NoDeposits();
if (!isVaultAvailableForAsset(asset, toVault)) revert VaultNotAllowed();
if (block.timestamp < assetLastRebalanceTime[asset] + REBALANCE_COOLDOWN) revert CooldownNotPassed();
_verifyToVault(asset, toVault);
_doRebalance(asset, toVault, true);
}
/**
* @dev Operator emergency redeem — pull all funds from Morpho vault and hold idle
*/
function operatorEmergencyRedeem(address asset)
external
onlyOperator
onlyAllowedAsset(asset)
nonReentrant
{
if (!assetHasInitialDeposit[asset]) revert NoDeposits();
if (block.timestamp < assetLastRebalanceTime[asset] + REBALANCE_COOLDOWN) revert CooldownNotPassed();
address fromVault = assetToVault[asset];
if (fromVault == address(0)) revert VaultAlreadyIdle();
uint256 balance = _getVaultBalance(fromVault);
if (balance == 0) revert NoFunds();
uint256 baseAmount = assetRebalanceBaseAmount[asset];
// EFFECTS
assetLastRebalanceTime[asset] = block.timestamp;
assetToVault[asset] = address(0);
// INTERACTIONS
uint256 redeemedAmount = _redeemFromVault(fromVault, balance);
// Fee + state
_applyFeeAndUpdateBase(asset, redeemedAmount, baseAmount);
emit EmergencyRedeem(asset, fromVault, redeemedAmount);
}
// ============ Admin Functions ============
/**
* @dev Admin emergency rebalance — bypasses cooldown, requires multisig
*/
function emergencyRebalance(address asset, address toVault)
external
onlyAdmin
onlyAllowedAsset(asset)
onlyAllowedVault(toVault)
nonReentrant
{
if (!assetHasInitialDeposit[asset]) revert NoDeposits();
if (!isVaultAvailableForAsset(asset, toVault)) revert VaultNotAllowed();
_verifyToVault(asset, toVault);
address fromVault = assetToVault[asset];
// No cooldown check — bypasses cooldown for emergency
// But DOES reset cooldown to prevent operator from immediately rebalancing again (double slippage)
_doRebalance(asset, toVault, true);
emit EmergencyRebalanced(asset, fromVault, toVault, 0);
}
/**
* @dev Clear stale vault reference when deposits are 0
*/
function clearStaleVault(address asset) external onlyAdmin {
address vault = assetToVault[asset];
if (vault == address(0)) revert VaultAlreadyIdle();
if (_getVaultBalance(vault) > 0) revert VaultNotEmpty();
assetToVault[asset] = address(0);
assetHasInitialDeposit[asset] = false;
assetTotalDeposited[asset] = 0;
assetRebalanceBaseAmount[asset] = 0;
emit StaleVaultCleared(asset, vault);
}
// ============ Internal ============
function _verifyToVault(address asset, address toVault) internal view {
address fromVault = assetToVault[asset];
if (fromVault == toVault) revert SameVault();
if (registry.vaultToExpectedAsset(toVault) != asset) revert InvalidVault();
if (IMetaMorpho(toVault).asset() != asset) revert InvalidVault();
}
/**
* @dev Unified rebalance: handles both vault→vault and idle→vault
*/
function _doRebalance(address asset, address toVault, bool updateCooldown) internal {
address fromVault = assetToVault[asset];
uint256 baseAmount = assetRebalanceBaseAmount[asset];
uint256 amount;
// EFFECTS (pre-interaction)
if (updateCooldown) {
assetLastRebalanceTime[asset] = block.timestamp;
}
assetToVault[asset] = toVault;
if (fromVault == address(0)) {
// Idle state: use ERC20 balance minus reserved fees
uint256 bal = IERC20(asset).balanceOf(address(this));
uint256 reserved = protocolFees[asset];
amount = bal > reserved ? bal - reserved : 0;
} else {
// Vault state: redeem all shares
uint256 shares = _getVaultBalance(fromVault);
if (shares == 0) revert NoFunds();
amount = _redeemFromVault(fromVault, shares);
}
if (amount == 0) revert NoFunds();
// Fee calculation
uint256 amountToDeposit = _applyFeeAndUpdateBase(asset, amount, baseAmount);
// Deposit into new vault
_depositToVault(toVault, amountToDeposit, asset);
emit Rebalanced(asset, fromVault, toVault, amountToDeposit);
}
/**
* @dev Apply rebalance fee on profit and update base amount
* @return amountAfterFee The amount after fee deduction
*/
function _applyFeeAndUpdateBase(address asset, uint256 amount, uint256 baseAmount)
internal
returns (uint256 amountAfterFee)
{
if (amount > baseAmount && baseAmount > 0) {
uint256 profit = amount - baseAmount;
uint256 fee = (profit * registry.rebalanceFeePercentage()) / 10000;
amountAfterFee = amount - fee;
if (fee > 0) {
protocolFees[asset] += fee;
assetTotalRebalanceFees[asset] += fee;
}
emit RebalanceFeeCollected(asset, profit, fee, amountAfterFee);
} else {
amountAfterFee = amount;
}
assetRebalanceBaseAmount[asset] = amountAfterFee;
}
}
contracts/modules/VaultStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../Interfaces/IMerklDistributor.sol";
import "../Interfaces/IVaultRegistry.sol";
import "../libraries/Errors.sol";
/**
* @title VaultStorage
* @dev Base contract containing per-user state variables for the vault system
*/
abstract contract VaultStorage is ReentrancyGuard {
using SafeERC20 for IERC20;
// ============ Constants ============
// Merkl Distributor address
address public constant MERKL_DISTRIBUTOR = 0x3Ef3D8bA38EBe18DB133cEc108f4D14CE00Dd9Ae;
IMerklDistributor public constant merklDistributor = IMerklDistributor(MERKL_DISTRIBUTOR);
// Rebalance cooldown period (12 hours)
uint256 public constant REBALANCE_COOLDOWN = 12 hours;
// Maximum batch size for Merkl claims (bounds O(n²) duplicate check)
uint256 public constant MAX_MERKL_BATCH_SIZE = 20;
// ============ State Variables ============
// Access control
address public owner; // EOA user who owns the vault
address public pendingOwner;
// Registry/config contract (shared across all vaults)
IVaultRegistry public registry;
// Multi-asset support: each asset has its own vault and tracking
mapping(address => address) public assetToVault; // asset => current active vault for that asset
mapping(address => uint256) public assetTotalDeposited; // asset => total deposited amount
mapping(address => bool) public assetHasInitialDeposit; // asset => initial deposit status
mapping(address => uint256) public assetLastDepositTime; // asset => last deposit timestamp
mapping(address => uint256) public assetTotalFeesCollected; // asset => total fees collected
// Rebalance profit tracking: base amount from which profit is calculated during rebalance
mapping(address => uint256) public assetRebalanceBaseAmount; // asset => base amount for profit calculation
mapping(address => uint256) public assetTotalRebalanceFees; // asset => total rebalance fees collected
// Rebalance cooldown tracking
mapping(address => uint256) public assetLastRebalanceTime; // asset => last rebalance timestamp
// Protocol fee accrual (pull-based)
mapping(address => uint256) public protocolFees; // token => accrued protocol fees
// ============ Events ============
event InitialDeposit(address indexed asset, address indexed vault, uint256 amount);
event UserDeposit(address indexed asset, address indexed vault, uint256 amount);
event AdminDeposit(address indexed admin, address indexed asset, address indexed vault, uint256 amount);
event Withdrawal(
address indexed asset,
address indexed vault,
address indexed recipient,
uint256 amount
);
event Rebalanced(
address indexed asset,
address indexed fromVault,
address indexed toVault,
uint256 amount
);
event RebalanceFeeCollected(
address indexed asset,
uint256 profitAmount,
uint256 feeAmount,
uint256 newBaseAmount
);
event FeeCollected(
address indexed asset,
address indexed vault,
uint256 feeAmount,
uint256 userAmount
);
event ProtocolFeesClaimed(address indexed token, uint256 amount, address indexed recipient);
// Emergency events
event EmergencyRedeem(address indexed asset, address indexed fromVault, uint256 amount);
event EmergencyRebalanced(address indexed asset, address indexed fromVault, address indexed toVault, uint256 amount);
event StaleVaultCleared(address indexed asset, address indexed clearedVault);
// Merkl events
event MerklTokensClaimed(address indexed token, uint256 totalAmount, uint256 feeAmount, uint256 userAmount);
event MerklClaimFailed(address indexed token, uint256 amount, string reason);
// Ownership events
event OwnershipTransferInitiated(address indexed currentOwner, address indexed pendingOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferCancelled(address indexed pendingOwner);
}
contracts/modules/VaultViews.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./VaultMerkl.sol";
/**
* @title VaultViews
* @dev View functions and emergency operations
*/
abstract contract VaultViews is VaultMerkl {
using SafeERC20 for IERC20;
// ============ View Functions ============
/**
* @dev Get current vault balance for an asset
*/
function getAssetVaultBalance(address asset) external view returns (uint256) {
address vault = assetToVault[asset];
if (vault == address(0)) return 0;
return _getVaultBalance(vault);
}
/**
* @dev Get current vault assets (underlying tokens) for an asset
*/
function getAssetVaultAssets(address asset) external view returns (uint256) {
address vault = assetToVault[asset];
if (vault == address(0)) return 0;
return _getVaultAssets(vault);
}
/**
* @dev Get profit for a specific asset
*/
function getAssetProfit(address asset) external view returns (int256) {
// assetTotalDeposited can have small non-zero remainders due to integer division rounding
if (!assetHasInitialDeposit[asset] || assetTotalDeposited[asset] <= 0) return 0;
address vault = assetToVault[asset];
if (vault == address(0)) return 0;
uint256 currentValue = _getVaultAssets(vault);
if (currentValue >= assetTotalDeposited[asset]) {
return int256(currentValue - assetTotalDeposited[asset]);
} else {
return -int256(assetTotalDeposited[asset] - currentValue);
}
}
/**
* @dev Get profit percentage for a specific asset (with 6 decimals precision)
*/
function getAssetProfitPercentage(address asset) external view returns (int256) {
// assetTotalDeposited can have small non-zero remainders due to integer division rounding
if (!assetHasInitialDeposit[asset] || assetTotalDeposited[asset] <= 0) return 0;
address vault = assetToVault[asset];
if (vault == address(0)) return 0;
uint256 currentValue = _getVaultAssets(vault);
if (currentValue >= assetTotalDeposited[asset]) {
uint256 profit = currentValue - assetTotalDeposited[asset];
return int256((profit * 1000000) / assetTotalDeposited[asset]);
} else {
uint256 loss = assetTotalDeposited[asset] - currentValue;
return -int256((loss * 1000000) / assetTotalDeposited[asset]);
}
}
/**
* @dev Get all allowed assets
*/
function getAllowedAssets() external view returns (address[] memory) {
return registry.getAllowedAssets();
}
/**
* @dev Get all allowed vaults
*/
function getAllowedVaults() external view returns (address[] memory) {
return registry.getAllowedVaults();
}
/**
* @dev Get summary of all assets with deposits
* @notice Optimized single-pass iteration; returns activeCount for array bounds
* @return assets Array of asset addresses (use activeCount for valid entries)
* @return deposited Array of deposited amounts
* @return currentValues Array of current vault values
* @return profits Array of profit/loss values
* @return activeCount Number of valid entries in the arrays
*/
function getPortfolioSummary()
external
view
returns (
address[] memory assets,
uint256[] memory deposited,
uint256[] memory currentValues,
int256[] memory profits,
uint256 activeCount
)
{
address[] memory registryAssets = registry.getAllowedAssets();
uint256 totalAssets = registryAssets.length;
assets = new address[](totalAssets);
deposited = new uint256[](totalAssets);
currentValues = new uint256[](totalAssets);
profits = new int256[](totalAssets);
// Single-pass iteration
for (uint256 i = 0; i < totalAssets; i++) {
address asset = registryAssets[i];
if (assetHasInitialDeposit[asset]) {
assets[activeCount] = asset;
deposited[activeCount] = assetTotalDeposited[asset];
address vault = assetToVault[asset];
if (vault == address(0)) {
currentValues[activeCount] = 0;
profits[activeCount] = 0;
} else {
uint256 currentValue = _getVaultAssets(vault);
currentValues[activeCount] = currentValue;
if (currentValue >= assetTotalDeposited[asset]) {
profits[activeCount] = int256(currentValue - assetTotalDeposited[asset]);
} else {
profits[activeCount] = -int256(assetTotalDeposited[asset] - currentValue);
}
}
activeCount++;
}
}
return (assets, deposited, currentValues, profits, activeCount);
}
/**
* @dev Get rebalance base amount for a specific asset
*/
function getAssetRebalanceBaseAmount(address asset) external view returns (uint256) {
return assetRebalanceBaseAmount[asset];
}
/**
* @dev Get current rebalance profit for a specific asset (unrealized)
* @return profit The profit amount (can be negative for loss)
*/
function getAssetRebalanceProfit(address asset) external view returns (int256 profit) {
// Use <= 0 instead of == 0 to handle rounding errors
// assetRebalanceBaseAmount can have small non-zero remainders due to integer division rounding
if (!assetHasInitialDeposit[asset] || assetRebalanceBaseAmount[asset] <= 0) {
return 0;
}
address vault = assetToVault[asset];
if (vault == address(0)) return 0;
uint256 currentValue = _getVaultAssets(vault);
uint256 baseAmount = assetRebalanceBaseAmount[asset];
if (currentValue >= baseAmount) {
return int256(currentValue - baseAmount);
} else {
return -int256(baseAmount - currentValue);
}
}
/**
* @dev Get total rebalance fees collected for an asset
*/
function getAssetTotalRebalanceFees(address asset) external view returns (uint256) {
return assetTotalRebalanceFees[asset];
}
/**
* @dev Get rebalance info for a specific asset
* @return baseAmount The current base amount used for profit calculation
* @return currentValue The current value in the vault
* @return profit The unrealized profit/loss
* @return totalFees The total rebalance fees collected
*/
function getAssetRebalanceInfo(address asset)
external
view
returns (
uint256 baseAmount,
uint256 currentValue,
int256 profit,
uint256 totalFees
)
{
baseAmount = assetRebalanceBaseAmount[asset];
address vault = assetToVault[asset];
if (vault == address(0)) {
currentValue = 0;
profit = 0;
} else {
currentValue = _getVaultAssets(vault);
if (!assetHasInitialDeposit[asset] || baseAmount <= 0) {
profit = 0;
} else if (currentValue >= baseAmount) {
profit = int256(currentValue - baseAmount);
} else {
profit = -int256(baseAmount - currentValue);
}
}
totalFees = assetTotalRebalanceFees[asset];
return (baseAmount, currentValue, profit, totalFees);
}
/**
* @dev Get fee information
*/
function getFeeInfo()
external
view
returns (
address _revenueAddress,
uint256 _feePercentage,
uint256 _rebalanceFeePercentage,
uint256 _merklClaimFeePercentage
)
{
return (
registry.revenueAddress(),
registry.feePercentage(),
registry.rebalanceFeePercentage(),
registry.merklClaimFeePercentage()
);
}
/**
* @dev Get total fees collected for an asset
*/
function getAssetFeesCollected(address asset) external view returns (uint256) {
return assetTotalFeesCollected[asset];
}
/**
* @dev Get all available vaults for a specific asset
*/
function getAssetAvailableVaults(address asset) external view returns (address[] memory) {
return registry.getAssetAvailableVaults(asset);
}
// ============ Emergency Functions ============
/**
* @dev Get balance of any ERC20 token held by this contract
*/
function getTokenBalance(address token) external view returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
/**
* @dev Emergency function to withdraw any ERC20 tokens stuck in contract
* @notice Cannot withdraw vault shares to prevent bypassing fee calculations and accounting
* @notice This function is intended for recovering stuck tokens (e.g., airdrops, wrong tokens sent)
* @param token The token address to withdraw
* @param amount Amount to withdraw (0 for full balance)
*/
function emergencyTokenWithdraw(address token, uint256 amount)
external
onlyOwner
nonReentrant
{
if (token == address(0)) revert ZeroAddress();
if (registry.isAllowedVault(token) || registry.wasEverVault(token)) revert CannotWithdrawVaultShares();
uint256 balance = IERC20(token).balanceOf(address(this));
uint256 reserved = protocolFees[token];
uint256 available = balance > reserved ? balance - reserved : 0;
if (available == 0) revert NoFunds();
uint256 withdrawAmount = amount == 0 ? available : amount;
if (withdrawAmount > available) revert InsufficientBalance();
IERC20(token).safeTransfer(owner, withdrawAmount);
}
/**
* @dev Claim accrued protocol fees for a token (pull-based)
* @param token The token address to claim
* @param amount Amount to claim (0 for full accrued balance)
*/
function claimProtocolFees(address token, uint256 amount)
external
onlyRevenue
nonReentrant
{
if (token == address(0)) revert ZeroAddress();
uint256 balance = protocolFees[token];
if (balance == 0) revert NoFunds();
uint256 claimAmount = amount == 0 ? balance : amount;
if (claimAmount > balance) revert InsufficientBalance();
protocolFees[token] = balance - claimAmount;
IERC20(token).safeTransfer(msg.sender, claimAmount);
emit ProtocolFeesClaimed(token, claimAmount, msg.sender);
}
}
Compiler settingsShow
{
"viaIR": true,
"libraries": {
"contracts/UserVaultV4.sol": {
"BridgeLib": "0xab71119e39d1d51b8dc0d0b72ab5e31539cce284",
"BundlerLib": "0x84be6e2916c614c183b9b603073187bbbd24c99b",
"DirectDepositLib": "0x8888db40e2732a66610c52e74f525258344b9178"
}
},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.