Проверенный контрактЧастичное
AccountingEngine
Адрес0xbe01bae7d3328cc5ddc5437dcc41f8f803bd73f4
- Баланс
0 ETH
- Транзакций
2
- Компилятор
solc 0.8.35
- Тот же код
Только этот контракт
Подробности
- Компилятор
- solc 0.8.35+commit.47b9dedd
- Язык
- solidity
- Оптимизация
- Да, 200 прогонов
- Версия EVM
- osaka
- Через IR
- да
- Лицензия
- Не указана
- Совпадение
- Частичноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 26 382 787
- Транзакция создания
- 0x3cad9e0132…d33a74262e
17 файлов
- src/accounting/AccountingEngine.solглавный21,11 КБ
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4,45 КБ
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 Б
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 Б
- lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol12,21 КБ
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2,78 КБ
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 Б
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol13,31 КБ
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 Б
- src/interfaces/IAccountingEngine.sol4,74 КБ
- src/interfaces/IAllocator.sol6,15 КБ
- src/interfaces/IFeeModel.sol723 Б
- src/interfaces/IHypercoreTradingAdapter.sol1,62 КБ
- src/interfaces/IOwlVault.sol3,59 КБ
- src/interfaces/IPermissionManager.sol774 Б
- src/interfaces/IStrategyAdapter.sol821 Б
- src/libraries/Roles.sol287 Б
src/accounting/AccountingEngine.sol
pragma solidity ^0.8.20;
import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import {IERC4626} from "openzeppelin-contracts/contracts/interfaces/IERC4626.sol";
import {SafeERC20} from "openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {IAccountingEngine} from "../interfaces/IAccountingEngine.sol";
import {IFeeModel} from "../interfaces/IFeeModel.sol";
import {IAllocator} from "../interfaces/IAllocator.sol";
import {IStrategyAdapter} from "../interfaces/IStrategyAdapter.sol";
import {IPermissionManager} from "../interfaces/IPermissionManager.sol";
import {IOwlVault} from "../interfaces/IOwlVault.sol";
import {Roles} from "../libraries/Roles.sol";
contract AccountingEngine is IAccountingEngine {
using SafeERC20 for IERC20;
uint256 private constant WAD = 1e18;
address public deployer;
address public vault;
address public hyperliquidAdapter;
IFeeModel public feeModel;
IPermissionManager public permissionManager;
uint256 public managementFeeRate;
uint256 public performanceFeeRate;
uint256 public entranceFeeRate;
uint256 public exitFeeRate;
uint256 public lastSettleTime;
uint256 public override lastCheckpointSharePrice;
uint256 public override maxSettleInterval;
address public platformManagementFeeRecipient;
address public managerManagementFeeRecipient;
address public entranceFeeRecipient;
address public exitFeeRecipient;
address public platformPerformanceFeeRecipient;
address public managerPerformanceFeeRecipient;
uint16 public platformManagementFeeSplitBps;
uint16 public managerManagementFeeSplitBps;
uint16 public platformPerformanceFeeSplitBps;
uint16 public managerPerformanceFeeSplitBps;
uint256 public override entranceFeeAssetsAccrued;
uint256 public override exitFeeAssetsAccrued;
uint256 public override managementFeeAssetsAccrued;
uint256 public override performanceFeeAssetsAccrued;
uint256 public override entranceFeeSharesMinted;
uint256 public override exitFeeSharesMinted;
uint256 public override managementFeeSharesMinted;
uint256 public override performanceFeeSharesMinted;
mapping(address => uint256) public override feeSharesMintedByRecipient;
bool public initialized;
mapping(address recipient => mapping(FeeType feeType => uint256)) public override feeAssetsByRecipient;
function init() external {
require(deployer == address(0), "Already initialized");
deployer = msg.sender;
lastSettleTime = block.timestamp;
}
modifier onlyVault() {
require(msg.sender == vault, "Only vault");
_;
}
modifier onlyAdmin() {
require(permissionManager.hasRole(Roles.ADMIN, msg.sender), "Not admin");
_;
}
modifier onlyAdminOrAllocator() {
require(
permissionManager.hasRole(Roles.ADMIN, msg.sender) || permissionManager.hasRole(Roles.ALLOCATOR, msg.sender),
"Not admin or allocator"
);
_;
}
function totalAssets() public view override returns (uint256) {
return _grossAssets();
}
function _validatedAdapterAssets() internal view returns (uint256) {
address allocator = IOwlVault(vault).allocator();
if (allocator != address(0)) {
return IAllocator(allocator).totalAdapterAssets();
}
if (hyperliquidAdapter == address(0)) return 0;
return IStrategyAdapter(hyperliquidAdapter).totalAssets();
}
function sharePrice() external view override returns (uint256) {
uint256 totalSupply = IERC4626(vault).totalSupply();
if (totalSupply == 0) return WAD;
return totalAssets() * WAD / totalSupply;
}
function beforeDepositOrWithdraw() external override onlyVault {
_settleFees();
}
function beforeDepositOrWithdraw(uint256 nav) external override onlyVault {
_settleFees(nav);
}
function guardNewEntry() external override onlyVault {
address a = IOwlVault(vault).allocator();
if (a == address(0)) return;
require(!IAllocator(a).entryValuationBroken(), "Valuation broken");
}
function forceSettleFees() external override onlyAdminOrAllocator {
require(block.timestamp > lastSettleTime + maxSettleInterval, "Settle interval not reached");
_settleFees();
}
function recordEntranceFee(uint256 amount, address recipient, uint256 shares) external override onlyVault {
entranceFeeAssetsAccrued += amount;
_recordFeeRevenue(recipient, FeeType.Entrance, amount, shares);
if (shares > 0) {
entranceFeeSharesMinted += shares;
}
}
function recordExitFee(uint256 amount, address recipient, uint256 shares) external override onlyVault {
exitFeeAssetsAccrued += amount;
_recordFeeRevenue(recipient, FeeType.Exit, amount, shares);
if (shares > 0) {
exitFeeSharesMinted += shares;
}
}
function feeRevenueOf(address recipient)
external
view
returns (
uint256 entranceAssets,
uint256 exitAssets,
uint256 managementAssets,
uint256 performanceAssets,
uint256 totalShares
)
{
entranceAssets = feeAssetsByRecipient[recipient][FeeType.Entrance];
exitAssets = feeAssetsByRecipient[recipient][FeeType.Exit];
managementAssets = feeAssetsByRecipient[recipient][FeeType.Management];
performanceAssets = feeAssetsByRecipient[recipient][FeeType.Performance];
totalShares = feeSharesMintedByRecipient[recipient];
}
function _recordFeeRevenue(address recipient, FeeType feeType, uint256 assets, uint256 shares) internal {
if (recipient == address(0)) return;
if (assets == 0 && shares == 0) return;
if (assets > 0) feeAssetsByRecipient[recipient][feeType] += assets;
if (shares > 0) feeSharesMintedByRecipient[recipient] += shares;
emit FeeRevenueRecorded(recipient, uint8(feeType), assets, shares);
}
function _splitAssets(uint256 amount, uint16 platformBps) internal pure returns (uint256 platform, uint256 manager) {
platform = amount * platformBps / 10_000;
manager = amount - platform;
}
function calculateEntranceFee(uint256 assets) external view override returns (uint256) {
if (address(feeModel) == address(0)) return 0;
return feeModel.calculateInOutFee(assets, entranceFeeRate);
}
function calculateExitFee(uint256 assets) external view override returns (uint256) {
if (address(feeModel) == address(0)) return 0;
return feeModel.calculateInOutFee(assets, exitFeeRate);
}
function setFeeRates(
uint256 _managementFeeRate,
uint256 _performanceFeeRate,
uint256 _entranceFeeRate,
uint256 _exitFeeRate
) external override onlyAdminOrAllocator {
require(_managementFeeRate <= 3e16, "Management fee too high");
require(_performanceFeeRate <= 40e16, "Performance fee too high");
require(_entranceFeeRate <= 2e16, "Entrance fee too high");
require(_exitFeeRate <= 2e16, "Exit fee too high");
if (_managementFeeRate > 0 || _performanceFeeRate > 0 || _entranceFeeRate > 0 || _exitFeeRate > 0) {
require(address(feeModel) != address(0), "FeeModel required for non-zero fees");
}
_settleFees();
managementFeeRate = _managementFeeRate;
performanceFeeRate = _performanceFeeRate;
entranceFeeRate = _entranceFeeRate;
exitFeeRate = _exitFeeRate;
emit FeeRatesUpdated(_managementFeeRate, _performanceFeeRate, _entranceFeeRate, _exitFeeRate);
}
struct InitConfig {
address permissionManager;
address vault;
address hyperliquidAdapter;
address feeModel;
uint256 maxSettleInterval;
uint256 managementFeeRate;
uint256 performanceFeeRate;
uint256 entranceFeeRate;
uint256 exitFeeRate;
}
function initialize(InitConfig calldata cfg) external {
require(!initialized, "Already initialized");
if (address(permissionManager) != address(0)) {
require(permissionManager.hasRole(Roles.ADMIN, msg.sender), "Not admin");
} else {
require(msg.sender == deployer, "Only deployer");
}
if (cfg.permissionManager != address(0)) {
permissionManager = IPermissionManager(cfg.permissionManager);
}
if (cfg.vault != address(0)) vault = cfg.vault;
if (cfg.hyperliquidAdapter != address(0)) hyperliquidAdapter = cfg.hyperliquidAdapter;
if (cfg.feeModel != address(0)) feeModel = IFeeModel(cfg.feeModel);
if (cfg.maxSettleInterval > 0) maxSettleInterval = cfg.maxSettleInterval;
if (cfg.managementFeeRate > 0 || cfg.performanceFeeRate > 0 || cfg.entranceFeeRate > 0 || cfg.exitFeeRate > 0) {
require(address(feeModel) != address(0), "FeeModel required for non-zero fees");
require(cfg.managementFeeRate <= 3e16, "Management fee too high");
require(cfg.performanceFeeRate <= 40e16, "Performance fee too high");
require(cfg.entranceFeeRate <= 2e16, "Entrance fee too high");
require(cfg.exitFeeRate <= 2e16, "Exit fee too high");
managementFeeRate = cfg.managementFeeRate;
performanceFeeRate = cfg.performanceFeeRate;
entranceFeeRate = cfg.entranceFeeRate;
exitFeeRate = cfg.exitFeeRate;
}
initialized = true;
}
function getFeeRates() external view override returns (uint256, uint256, uint256, uint256) {
return (managementFeeRate, performanceFeeRate, entranceFeeRate, exitFeeRate);
}
function setPermissionManager(address pm) external {
require(pm != address(0), "Zero address");
if (address(permissionManager) != address(0)) {
require(permissionManager.hasRole(Roles.ADMIN, msg.sender), "Not admin");
} else {
require(msg.sender == deployer, "Not deployer");
}
address oldPm = address(permissionManager);
permissionManager = IPermissionManager(pm);
emit PermissionManagerUpdated(oldPm, pm);
}
function setFeeModel(address _feeModel) external override onlyAdmin {
require(_feeModel != address(0), "Zero address");
_settleFees();
address oldModel = address(feeModel);
feeModel = IFeeModel(_feeModel);
emit FeeModelUpdated(oldModel, _feeModel);
}
function setHyperliquidAdapter(address adapter) external override onlyAdmin {
require(adapter != address(0), "Zero address");
_settleFees();
address oldAdapter = hyperliquidAdapter;
hyperliquidAdapter = adapter;
emit HyperliquidAdapterUpdated(oldAdapter, adapter);
}
function setVault(address _vault) external override onlyAdmin {
require(_vault != address(0), "Zero address");
_settleFees();
require(IOwlVault(_vault).accountingEngine() == address(this), "Vault back-pointer mismatch");
address oldVault = vault;
vault = _vault;
emit VaultUpdated(oldVault, _vault);
}
function setMaxSettleInterval(uint256 interval) external onlyAdminOrAllocator {
require(interval >= 1 hours, "Interval too short");
uint256 oldInterval = maxSettleInterval;
maxSettleInterval = interval;
emit MaxSettleIntervalUpdated(oldInterval, interval);
}
function getFeeModel() external view override returns (address) {
return address(feeModel);
}
function setFeeRecipients(
address _platformManagementFeeRecipient,
address _managerManagementFeeRecipient,
address _entranceFeeRecipient,
address _exitFeeRecipient,
address _platformPerformanceFeeRecipient,
address _managerPerformanceFeeRecipient
) external override onlyAdminOrAllocator {
_settleFees();
require(_platformManagementFeeRecipient != address(0), "Zero platform mgmt recipient");
require(_managerManagementFeeRecipient != address(0), "Zero manager mgmt recipient");
require(_entranceFeeRecipient != address(0), "Zero entrance fee recipient");
require(_exitFeeRecipient != address(0), "Zero exit fee recipient");
require(_platformPerformanceFeeRecipient != address(0), "Zero platform perf recipient");
require(_managerPerformanceFeeRecipient != address(0), "Zero manager perf recipient");
platformManagementFeeRecipient = _platformManagementFeeRecipient;
managerManagementFeeRecipient = _managerManagementFeeRecipient;
entranceFeeRecipient = _entranceFeeRecipient;
exitFeeRecipient = _exitFeeRecipient;
platformPerformanceFeeRecipient = _platformPerformanceFeeRecipient;
managerPerformanceFeeRecipient = _managerPerformanceFeeRecipient;
emit FeeRecipientsUpdated();
}
function setManagementFeeSplit(uint16 _platformBps, uint16 _managerBps) external override onlyAdminOrAllocator {
_settleFees();
require(_platformBps + _managerBps == 10_000, "Split bps must sum to 10000");
platformManagementFeeSplitBps = _platformBps;
managerManagementFeeSplitBps = _managerBps;
emit ManagementFeeSplitUpdated(_platformBps, _managerBps);
}
function setPerformanceFeeSplit(uint16 _platformBps, uint16 _managerBps) external override onlyAdminOrAllocator {
_settleFees();
require(_platformBps + _managerBps == 10_000, "Split bps must sum to 10000");
platformPerformanceFeeSplitBps = _platformBps;
managerPerformanceFeeSplitBps = _managerBps;
emit PerformanceFeeSplitUpdated(_platformBps, _managerBps);
}
function _settleFees() internal {
_settleFees(0, false);
}
function _settleFees(uint256 nav) internal {
_settleFees(nav, true);
}
function _settleFees(uint256 suppliedNav, bool useSuppliedNav) internal {
uint256 timeDelta = block.timestamp - lastSettleTime;
lastSettleTime = block.timestamp;
if (managementFeeRate == 0 && performanceFeeRate == 0) return;
uint256 totalSupply = IERC4626(vault).totalSupply();
if (totalSupply == 0) {
lastCheckpointSharePrice = 0;
return;
}
if (timeDelta == 0 && lastCheckpointSharePrice != 0) return;
uint256 grossNav = useSuppliedNav ? suppliedNav : _grossAssets();
if (grossNav == 0) return;
if (lastCheckpointSharePrice == 0) {
lastCheckpointSharePrice = grossNav * WAD / totalSupply;
return;
}
if (address(feeModel) == address(0)) return;
IFeeModel.FeeResult memory result = feeModel.settle(
IFeeModel.FeeContext({
grossNav: grossNav,
timeDelta: timeDelta,
totalSupply: totalSupply,
managementFeeRate: managementFeeRate,
performanceFeeRate: performanceFeeRate,
lastCheckpointSharePrice: lastCheckpointSharePrice
})
);
managementFeeAssetsAccrued += result.managementFeeAssets;
performanceFeeAssetsAccrued += result.performanceFeeAssets;
lastCheckpointSharePrice = result.nextCheckpointSharePrice;
if (result.totalFeeAssets > 0) {
_mintFeeSharesForMgmtAndPerf(result.managementFeeAssets, result.performanceFeeAssets, totalSupply, grossNav);
}
uint256 netNavAfterAllFees = grossNav - result.totalFeeAssets;
emit FeeSettled(result.profitAboveHighWatermark, result.totalFeeAssets, netNavAfterAllFees);
}
function _mintFeeSharesForMgmtAndPerf(uint256 mgmtFee, uint256 perfFee, uint256 totalSupply, uint256 grossNav)
internal
{
uint256 totalFeeAssets = mgmtFee + perfFee;
if (totalFeeAssets == 0) return;
(uint256 platformMgmtAssets, uint256 managerMgmtAssets) =
mgmtFee > 0 ? _splitAssets(mgmtFee, platformManagementFeeSplitBps) : (uint256(0), uint256(0));
(uint256 platformPerfAssets, uint256 managerPerfAssets) =
perfFee > 0 ? _splitAssets(perfFee, platformPerformanceFeeSplitBps) : (uint256(0), uint256(0));
if (totalFeeAssets >= grossNav) {
_recordMgmtPerfAssetsOnly(platformMgmtAssets, managerMgmtAssets, platformPerfAssets, managerPerfAssets);
return;
}
uint256 totalShares = _assetsToFeeShares(grossNav, totalSupply, totalFeeAssets);
if (totalShares == 0) {
_recordMgmtPerfAssetsOnly(platformMgmtAssets, managerMgmtAssets, platformPerfAssets, managerPerfAssets);
return;
}
uint256 mgmtShares = mgmtFee > 0 ? totalShares * mgmtFee / totalFeeAssets : 0;
uint256 perfShares = totalShares - mgmtShares;
uint256 platformMgmtShares = mgmtShares * platformManagementFeeSplitBps / 10_000;
uint256 managerMgmtShares = mgmtShares > 0 ? mgmtShares - platformMgmtShares : 0;
uint256 platformPerfShares = perfShares * platformPerformanceFeeSplitBps / 10_000;
uint256 managerPerfShares = perfShares - platformPerfShares;
bool mgmtMint =
mgmtShares > 0 && platformManagementFeeRecipient != address(0) && managerManagementFeeRecipient != address(0);
bool perfMint = perfShares > 0 && platformPerformanceFeeRecipient != address(0)
&& managerPerformanceFeeRecipient != address(0);
_recordFeeRevenue(
platformManagementFeeRecipient, FeeType.Management, platformMgmtAssets, mgmtMint ? platformMgmtShares : 0
);
_recordFeeRevenue(
managerManagementFeeRecipient, FeeType.Management, managerMgmtAssets, mgmtMint ? managerMgmtShares : 0
);
_recordFeeRevenue(
platformPerformanceFeeRecipient, FeeType.Performance, platformPerfAssets, perfMint ? platformPerfShares : 0
);
_recordFeeRevenue(
managerPerformanceFeeRecipient, FeeType.Performance, managerPerfAssets, perfMint ? managerPerfShares : 0
);
if (mgmtMint) {
managementFeeSharesMinted += mgmtShares;
address[] memory recipients = new address[](2);
uint256[] memory shares = new uint256[](2);
recipients[0] = platformManagementFeeRecipient;
recipients[1] = managerManagementFeeRecipient;
shares[0] = platformMgmtShares;
shares[1] = managerMgmtShares;
IOwlVault(vault).mintFeeSharesBatch(recipients, shares);
emit ManagementFeeSettled(mgmtFee, mgmtShares, platformManagementFeeRecipient);
}
if (perfMint) {
performanceFeeSharesMinted += perfShares;
address[] memory recipients = new address[](2);
uint256[] memory shares = new uint256[](2);
recipients[0] = platformPerformanceFeeRecipient;
recipients[1] = managerPerformanceFeeRecipient;
shares[0] = platformPerfShares;
shares[1] = managerPerfShares;
IOwlVault(vault).mintFeeSharesBatch(recipients, shares);
emit PerformanceFeeSettled(
perfFee,
perfShares,
platformPerformanceFeeRecipient,
platformPerfShares,
managerPerformanceFeeRecipient,
managerPerfShares
);
}
}
function _recordMgmtPerfAssetsOnly(
uint256 platformMgmtAssets,
uint256 managerMgmtAssets,
uint256 platformPerfAssets,
uint256 managerPerfAssets
) internal {
_recordFeeRevenue(platformManagementFeeRecipient, FeeType.Management, platformMgmtAssets, 0);
_recordFeeRevenue(managerManagementFeeRecipient, FeeType.Management, managerMgmtAssets, 0);
_recordFeeRevenue(platformPerformanceFeeRecipient, FeeType.Performance, platformPerfAssets, 0);
_recordFeeRevenue(managerPerformanceFeeRecipient, FeeType.Performance, managerPerfAssets, 0);
}
function _assetsToFeeShares(uint256 totalAssetsBeforeFee, uint256 totalSupplyBeforeFee, uint256 feeAssets)
internal
pure
returns (uint256)
{
if (feeAssets == 0 || totalSupplyBeforeFee == 0) {
return 0;
}
require(feeAssets < totalAssetsBeforeFee, "Fee exceeds total assets");
return totalSupplyBeforeFee * feeAssets / (totalAssetsBeforeFee - feeAssets);
}
function _grossAssets() internal view returns (uint256) {
uint256 idleBalance = IOwlVault(vault).idleBalance();
uint256 fee = IOwlVault(vault).bridgeFeeAccrued();
uint256 idle = idleBalance > fee ? idleBalance - fee : 0;
uint256 deployed = _validatedAdapterAssets();
return idle + deployed;
}
}
lib/openzeppelin-contracts/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);
}
lib/openzeppelin-contracts/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";
lib/openzeppelin-contracts/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";
lib/openzeppelin-contracts/contracts/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 "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../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);
}
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/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.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 {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 _safeTransfer(token, to, value, false);
}
/**
* @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 _safeTransferFrom(token, from, to, value, false);
}
/**
* @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 {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 relies 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 relies 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}.
* Oppositely, 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 `token.transfer(to, value)` call, 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 to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
lib/openzeppelin-contracts/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);
}
src/interfaces/IAccountingEngine.sol
pragma solidity ^0.8.20;
interface IAccountingEngine {
function totalAssets() external view returns (uint256);
function sharePrice() external view returns (uint256);
function beforeDepositOrWithdraw() external;
function beforeDepositOrWithdraw(uint256 nav) external;
function guardNewEntry() external;
function forceSettleFees() external;
function recordEntranceFee(uint256 amount, address recipient, uint256 shares) external;
function recordExitFee(uint256 amount, address recipient, uint256 shares) external;
function calculateEntranceFee(uint256 assets) external view returns (uint256);
function calculateExitFee(uint256 assets) external view returns (uint256);
function setFeeRates(
uint256 managementFeeRate,
uint256 performanceFeeRate,
uint256 entranceFeeRate,
uint256 exitFeeRate
) external;
function getFeeRates()
external view
returns (
uint256 managementFeeRate,
uint256 performanceFeeRate,
uint256 entranceFeeRate,
uint256 exitFeeRate
);
function lastSettleTime() external view returns (uint256);
function lastCheckpointSharePrice() external view returns (uint256);
function maxSettleInterval() external view returns (uint256);
function setPermissionManager(address pm) external;
function setFeeModel(address feeModel) external;
function setHyperliquidAdapter(address adapter) external;
function setVault(address vault) external;
function setMaxSettleInterval(uint256 interval) external;
function getFeeModel() external view returns (address);
function setFeeRecipients(
address platformManagementFeeRecipient,
address managerManagementFeeRecipient,
address entranceFeeRecipient,
address exitFeeRecipient,
address platformPerformanceFeeRecipient,
address managerPerformanceFeeRecipient
) external;
function setManagementFeeSplit(uint16 platformBps, uint16 managerBps) external;
function setPerformanceFeeSplit(uint16 platformBps, uint16 managerBps) external;
function entranceFeeRecipient() external view returns (address);
function exitFeeRecipient() external view returns (address);
function entranceFeeAssetsAccrued() external view returns (uint256);
function exitFeeAssetsAccrued() external view returns (uint256);
function managementFeeAssetsAccrued() external view returns (uint256);
function performanceFeeAssetsAccrued() external view returns (uint256);
function entranceFeeSharesMinted() external view returns (uint256);
function exitFeeSharesMinted() external view returns (uint256);
function managementFeeSharesMinted() external view returns (uint256);
function performanceFeeSharesMinted() external view returns (uint256);
function feeSharesMintedByRecipient(address recipient) external view returns (uint256);
enum FeeType {
Entrance,
Exit,
Management,
Performance
}
function feeAssetsByRecipient(address recipient, FeeType feeType) external view returns (uint256);
function feeRevenueOf(address recipient)
external
view
returns (
uint256 entranceAssets,
uint256 exitAssets,
uint256 managementAssets,
uint256 performanceAssets,
uint256 totalShares
);
event FeeSettled(uint256 profit, uint256 fee, uint256 netNavAfterAllFees);
event FeeRatesUpdated(
uint256 managementFeeRate,
uint256 performanceFeeRate,
uint256 entranceFeeRate,
uint256 exitFeeRate
);
event MaxSettleIntervalUpdated(uint256 oldInterval, uint256 newInterval);
event PermissionManagerUpdated(address oldPm, address newPm);
event FeeModelUpdated(address oldModel, address newModel);
event HyperliquidAdapterUpdated(address oldAdapter, address newAdapter);
event VaultUpdated(address oldVault, address newVault);
event FeeRecipientsUpdated();
event ManagementFeeSplitUpdated(uint16 platformBps, uint16 managerBps);
event PerformanceFeeSplitUpdated(uint16 platformBps, uint16 managerBps);
event ManagementFeeSettled(
uint256 assetsEquivalent,
uint256 sharesMinted,
address indexed recipient
);
event PerformanceFeeSettled(
uint256 assetsEquivalent,
uint256 totalSharesMinted,
address indexed platformRecipient,
uint256 platformShares,
address indexed managerRecipient,
uint256 managerShares
);
event FeeRevenueRecorded(address indexed recipient, uint8 indexed feeType, uint256 assets, uint256 shares);
}
src/interfaces/IAllocator.sol
pragma solidity ^0.8.20;
import {IHypercoreTradingAdapter} from "./IHypercoreTradingAdapter.sol";
interface IAllocator {
struct AdapterSwapParams {
uint256 orderId;
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 minAmountOut;
uint24 fee;
}
function deployToAdapter(address adapter, uint256 amount) external;
function withdrawFromAdapter(address adapter, uint256 amount) external;
function withdrawAvailableFromAdapter(address adapter) external returns (uint256 recoveredAmount);
function placeOrder(
address adapter,
IHypercoreTradingAdapter.OrderRequest calldata order
) external;
function cancelOrder(
address adapter,
IHypercoreTradingAdapter.CancelRequest calldata cancel
) external;
function setAdapterMarketAllowed(address adapter, uint32 marketId, bool allowed) external;
function setAdapterMarketsAllowed(address adapter, uint32[] calldata marketIds, bool allowed) external;
function setAdapterAccountAbstraction(address adapter, uint8 mode) external;
function addAdapterPerpDex(address adapter, uint32 dex) external;
function removeAdapterPerpDex(address adapter, uint32 dex) external;
function reportAdapterActiveSpotMarkets(address adapter, uint32[] calldata marketIds) external;
function pruneAdapterZeroBalanceSpotMarkets(address adapter) external returns (uint256 removed);
function pruneAdapterZeroBalanceSpotMarkets(address adapter, uint32[] calldata marketIds)
external
returns (uint256 removed);
function registerAdapterToken(address adapter, address token, address pool) external;
function registerAdapterTokens(address adapter, address[] calldata tokens, address[] calldata pools) external;
function unregisterAdapterToken(address adapter, address token) external;
function unregisterAdapterTokens(address adapter, address[] calldata tokens) external;
function setAdapterTwapWindow(address adapter, uint32 window) external;
function transferAdapterPerpToSpot(address adapter, uint64 ntl) external;
function transferAdapterPerpToSpot(address adapter, uint32 marketId, uint64 ntl) external;
function transferAdapterSpotToPerp(address adapter, uint64 ntl) external;
function transferAdapterSpotToPerp(address adapter, uint32 marketId, uint64 ntl) external;
function bridgeAdapterToCoreSpot(address adapter, uint256 evmAmount) external;
function bridgeAdapterSpotToEvm(address adapter, uint64 coreAmount) external;
function swapAdapterToken(address adapter, AdapterSwapParams calldata params) external returns (uint256 amountOut);
struct AdapterSwapPathParams {
uint256 orderId;
bytes path;
uint256 amountIn;
uint256 minAmountOut;
}
function swapAdapterPath(address adapter, AdapterSwapPathParams calldata params) external returns (uint256 amountOut);
function adapterAssets(address adapter) external view returns (uint256);
function totalAdapterAssets() external view returns (uint256);
function entryValuationBroken() external view returns (bool);
function pause() external;
function unpause() external;
function addAdapter(address adapter) external;
function removeAdapter(address adapter, bool acceptRemainingFunds) external;
function addAdapterApiWallet(address adapter, address agent, string calldata name) external;
function setAdapterAllocator(address adapter, address newAllocator) external;
function isAdapterWhitelisted(address adapter) external view returns (bool);
function setPermissionManager(address pm) external;
function setVault(address vault) external;
function setAccountingEngine(address engine) external;
event AdapterDeployed(address indexed adapter, uint256 amount);
event AdapterWithdrawn(address indexed adapter, uint256 amount);
event OrderPlaced(
address indexed adapter, uint32 indexed marketId, bool isBuy, uint128 size, uint128 limitPrice, uint128 cloid
);
event OrderCancelled(address indexed adapter, uint32 indexed marketId, uint64 orderId);
event AdapterMarketAllowedSet(address indexed adapter, uint32 indexed marketId, bool allowed);
event AdapterAccountAbstractionSet(address indexed adapter, uint8 mode);
event AdapterPerpDexAdded(address indexed adapter, uint32 dex);
event AdapterPerpDexRemoved(address indexed adapter, uint32 dex);
event AdapterActiveSpotMarketsReported(address indexed adapter, uint32[] marketIds);
event AdapterZeroBalanceSpotMarketsPruned(address indexed adapter);
event AdapterTokenRegistered(address indexed adapter, address indexed token, address indexed pool);
event AdapterTokenUnregistered(address indexed adapter, address indexed token);
event AdapterTokensRegistered(address indexed adapter, address[] tokens);
event AdapterTokensUnregistered(address indexed adapter, address[] tokens);
event AdapterTwapWindowUpdated(address indexed adapter, uint32 window);
event AdapterTransferredPerpToSpot(address indexed adapter, uint64 ntl);
event AdapterTransferredPerpToSpotMarket(address indexed adapter, uint32 marketId, uint64 ntl);
event AdapterTransferredSpotToPerp(address indexed adapter, uint64 ntl);
event AdapterTransferredSpotToPerpMarket(address indexed adapter, uint32 marketId, uint64 ntl);
event AdapterBridgedToCoreSpot(address indexed adapter, uint256 evmAmount);
event AdapterBridgedSpotToEvm(address indexed adapter, uint64 coreAmount);
event AdapterSwapExecuted(address indexed adapter, uint256 indexed orderId, address indexed tokenIn, uint256 amountIn, uint256 amountOut);
event AdapterAdded(address indexed adapter);
event AdapterRemoved(address indexed adapter, uint256 remaining);
event AdapterAllocatorUpdated(address indexed adapter, address newAllocator);
event PermissionManagerUpdated(address oldPm, address newPm);
event VaultUpdated(address oldVault, address newVault);
event AccountingEngineUpdated(address oldEngine, address newEngine);
}
src/interfaces/IFeeModel.sol
pragma solidity ^0.8.20;
interface IFeeModel {
struct FeeContext {
uint256 grossNav;
uint256 timeDelta;
uint256 totalSupply;
uint256 managementFeeRate;
uint256 performanceFeeRate;
uint256 lastCheckpointSharePrice;
}
struct FeeResult {
uint256 managementFeeAssets;
uint256 performanceFeeAssets;
uint256 totalFeeAssets;
uint256 profitAboveHighWatermark;
uint256 nextCheckpointSharePrice;
}
function calculateInOutFee(
uint256 assets,
uint256 feeRate
) external pure returns (uint256 feeAmount);
function settle(FeeContext calldata ctx) external pure returns (FeeResult memory result);
}
src/interfaces/IHypercoreTradingAdapter.sol
pragma solidity ^0.8.20;
interface IHypercoreTradingAdapter {
struct OrderRequest {
uint32 marketId;
bool isBuy;
uint128 size;
uint128 limitPrice;
bool reduceOnly;
uint8 tif;
uint128 cloid;
}
struct CancelRequest {
uint32 marketId;
uint64 orderId;
}
function bridgeToCoreSpot(uint256 evmAmount) external;
function bridgeSpotToEvm(uint64 coreAmount) external;
function transferSpotToPerp(uint64 ntl) external;
function transferSpotToPerp(uint32 marketId, uint64 ntl) external;
function transferPerpToSpot(uint64 ntl) external;
function transferPerpToSpot(uint32 marketId, uint64 ntl) external;
function quoteOrderNotional(OrderRequest calldata order) external view returns (uint256);
function projectedMarketExposure(OrderRequest calldata order) external view returns (uint256);
function addPerpDex(uint32 dex) external;
function removePerpDex(uint32 dex) external;
function reportActiveSpotMarkets(uint32[] calldata marketIds) external;
function pruneZeroBalanceSpotMarkets() external returns (uint256 removed);
function pruneZeroBalanceSpotMarkets(uint32[] calldata marketIds) external returns (uint256 removed);
function placeOrder(OrderRequest calldata order) external;
function cancelOrder(CancelRequest calldata cancel) external;
function setAllowedMarket(uint32 marketId, bool allowed) external;
function setAllowedMarkets(uint32[] calldata marketIds, bool allowed) external;
function setAccountAbstraction(uint8 mode) external;
}
src/interfaces/IOwlVault.sol
pragma solidity ^0.8.20;
import {IERC4626} from "openzeppelin-contracts/contracts/interfaces/IERC4626.sol";
interface IOwlVault is IERC4626 {
function FIRST_DEPOSIT_BRIDGE_FEE() external view returns (uint256);
function requestWithdraw(
uint256 shares,
address receiver
) external returns (bytes32 requestId);
function executeWithdraw(bytes32 requestId) external;
function getWithdrawRequest(bytes32 requestId)
external view
returns (
address receiver,
uint256 shares,
uint256 assets,
uint256 requestTime
);
function getWithdrawRequester(bytes32 requestId) external view returns (address);
function getUserWithdrawRequests(address user) external view returns (bytes32[] memory);
function lockedSharesOf(address user) external view returns (uint256);
function withdrawDelay() external view returns (uint256);
function pause() external;
function unpause() external;
function paused() external view returns (bool);
function setWithdrawDelay(uint256 newDelay) external;
function setMinimumDeposit(uint256 newMinimum) external;
function setDepositLockPeriod(uint256 newPeriod) external;
function depositLockPeriod() external view returns (uint256);
function depositUnlockTimeOf(address user) external view returns (uint256);
function setShareTransferEnabled(bool enabled) external;
function shareTransferEnabled() external view returns (bool);
function idleBalance() external view returns (uint256);
function bridgeFeeAccrued() external view returns (uint256);
function increaseIdleBalance(uint256 amount) external;
function sharePrice() external view returns (uint256);
function setPermissionManager(address pm) external;
function setAccountingEngine(address engine) external;
function setAllocator(address allocator) external;
function allocator() external view returns (address);
function accountingEngine() external view returns (address);
function deployToAdapter(uint256 amount) external;
function mintFeeSharesBatch(address[] calldata recipients, uint256[] calldata shares) external;
event WithdrawRequested(
bytes32 indexed requestId,
address indexed receiver,
uint256 shares,
uint256 assets,
uint256 unlockTime,
uint256 timestamp
);
event WithdrawExecuted(
bytes32 indexed requestId,
address indexed receiver,
uint256 assets,
uint256 exitFee,
uint256 timestamp
);
event WithdrawDelayUpdated(uint256 oldDelay, uint256 newDelay);
event MinimumDepositUpdated(uint256 oldMinimum, uint256 newMinimum);
event DepositLockPeriodUpdated(uint256 oldPeriod, uint256 newPeriod);
event ShareTransferEnabledUpdated(bool oldEnabled, bool newEnabled);
event PermissionManagerUpdated(address oldPm, address newPm);
event AccountingEngineUpdated(address oldEngine, address newEngine);
event AllocatorUpdated(address oldAllocator, address newAllocator);
event IdleBalanceIncreased(uint256 amount, uint256 newBalance);
event EntranceFeeSettled(uint256 assetsEquivalent, uint256 sharesMinted, address indexed recipient);
event ExitFeeSettled(uint256 assetsEquivalent, uint256 sharesMinted, address indexed recipient);
event ExitFeeWaived(bytes32 indexed requestId, uint256 grossAssets);
event VaultDeposit(address indexed sender, address indexed receiver, uint256 assets, uint256 shares, uint256 fee);
}
src/interfaces/IPermissionManager.sol
pragma solidity ^0.8.20;
interface IPermissionManager {
function validate(
bytes32 action,
address caller,
bytes calldata params,
bytes32[] calldata proof
) external view returns (bool approved);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function hasRole(bytes32 role, address account) external view returns (bool);
function setMerkleRoot(bytes32 newRoot) external;
function merkleRoot() external view returns (bytes32);
event RoleGranted(bytes32 indexed role, address indexed account);
event RoleRevoked(bytes32 indexed role, address indexed account);
event MerkleRootUpdated(bytes32 oldRoot, bytes32 newRoot);
}
src/interfaces/IStrategyAdapter.sol
pragma solidity ^0.8.20;
import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
interface IStrategyAdapter {
function deposit(IERC20 asset, uint256 amount) external;
function withdraw(IERC20 asset, uint256 amount) external;
function totalAssets() external view returns (uint256);
function availableLiquidity() external view returns (uint256);
function asset() external view returns (address);
function protocolName() external view returns (string memory);
function leverage() external view returns (uint256);
function healthRatio() external view returns (uint256);
function setAllocator(address allocator) external;
event AdapterDeposit(IERC20 indexed asset, uint256 amount);
event AdapterWithdraw(IERC20 indexed asset, uint256 amount);
}
src/libraries/Roles.sol
pragma solidity ^0.8.20;
library Roles {
bytes32 public constant ADMIN = keccak256("ADMIN");
bytes32 public constant ALLOCATOR = keccak256("ALLOCATOR");
bytes32 public constant EMERGENCY = keccak256("EMERGENCY");
bytes32 public constant TRADER = keccak256("TRADER");
}
Настройки компилятораПоказать
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "osaka",
"remappings": [
"@hyper-evm-lib/=lib/hyper-evm-lib/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"forge-std/=lib/forge-std/src/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"hyper-evm-lib/=lib/hyper-evm-lib/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.