Verified contractExactMIT
AlchemistAllocator
Address0x23a3c27bb007887fd8cbfeaf323799093a450e7e
- Balance
0 ETH
- Transactions
73
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 800 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,875,899
- Creation transaction
- 0xcc099c40f5…682f9128bf
9 files
- src/AlchemistAllocator.solmain7.89 KB
- lib/vault-v2/src/interfaces/IERC20.sol800 B
- lib/vault-v2/src/interfaces/IERC2612.sol403 B
- lib/vault-v2/src/interfaces/IERC4626.sol1.52 KB
- lib/vault-v2/src/interfaces/IVaultV2.sol5.52 KB
- src/interfaces/IAllocator.sol1.18 KB
- src/interfaces/IMYTStrategy.sol4.76 KB
- src/interfaces/IStrategyClassifier.sol649 B
- src/utils/PermissionedProxy.sol2.03 KB
src/AlchemistAllocator.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {IVaultV2} from "lib/vault-v2/src/interfaces/IVaultV2.sol";
import {PermissionedProxy} from "./utils/PermissionedProxy.sol";
import {IAllocator} from "./interfaces/IAllocator.sol";
import {IMYTStrategy} from "./interfaces/IMYTStrategy.sol";
import {IStrategyClassifier} from "./interfaces/IStrategyClassifier.sol";
/**
* @title AlchemistAllocator
* @notice This contract is used to allocate and deallocate funds to and from MYT strategies
* @notice The MYT is a Morpho V2 Vault, and each strategy is just a vault adapter which interfaces with a third party protocol
*/
contract AlchemistAllocator is PermissionedProxy, IAllocator {
IVaultV2 immutable public vault;
IStrategyClassifier immutable public strategyClassifier;
constructor(address _vault, address _admin, address _operator, address _classifier) PermissionedProxy(_admin, _operator) {
require(IVaultV2(_vault).asset() != address(0), "IV");
require(_classifier != address(0), "IC");
vault = IVaultV2(_vault);
strategyClassifier = IStrategyClassifier(_classifier);
}
/**
* @notice Allocate (uses ActionType.direct)
* @param adapter The strategy adapter address
* @param amount The amount to allocate
*/
function allocate(address adapter, uint256 amount) external {
require(msg.sender == admin || operators[msg.sender], "PD");
_validateCaps(adapter, amount);
IMYTStrategy.VaultAdapterParams memory params;
params.action = IMYTStrategy.ActionType.direct;
bytes memory data = abi.encode(params);
vault.allocate(adapter, data, amount);
}
/**
* @notice Deallocate (uses ActionType.direct)
* @param adapter The strategy adapter address
* @param amount The amount to deallocate
*/
function deallocate(address adapter, uint256 amount) external {
require(msg.sender == admin || operators[msg.sender], "PD");
IMYTStrategy.VaultAdapterParams memory params;
params.action = IMYTStrategy.ActionType.direct;
bytes memory data = abi.encode(params);
vault.deallocate(adapter, data, amount);
}
/**
* @notice Allocate with swap (uses ActionType.swap)
* @param adapter The strategy adapter address
* @param amount The amount to allocate
* @param txData The 0x swap calldata
*/
function allocateWithSwap(address adapter, uint256 amount, bytes memory txData) external {
require(msg.sender == admin || operators[msg.sender], "PD");
_validateCaps(adapter, amount);
IMYTStrategy.SwapParams memory swapParams = IMYTStrategy.SwapParams({
txData: txData,
minIntermediateOut: 0
});
IMYTStrategy.VaultAdapterParams memory params = IMYTStrategy.VaultAdapterParams(
{action: IMYTStrategy.ActionType.swap, swapParams: swapParams});
bytes memory data = abi.encode(params);
vault.allocate(adapter, data, amount);
}
/**
* @notice Deallocate with dex swap (uses ActionType.swap)
* @param adapter The strategy adapter address
* @param amount The amount to deallocate
* @param txData The 0x swap calldata
*/
function deallocateWithSwap(address adapter, uint256 amount, bytes memory txData) external {
require(msg.sender == admin || operators[msg.sender], "PD");
IMYTStrategy.SwapParams memory swapParams = IMYTStrategy.SwapParams({
txData: txData,
minIntermediateOut: 0
});
IMYTStrategy.VaultAdapterParams memory params = IMYTStrategy.VaultAdapterParams(
{action: IMYTStrategy.ActionType.swap, swapParams: swapParams});
bytes memory data = abi.encode(params);
vault.deallocate(adapter, data, amount);
}
/**
* @notice Deallocate with unwrap + dex swap (uses ActionType.unwrapAndSwap)
* @param adapter The strategy adapter address
* @param amount The amount to deallocate
* @param txData The 0x swap calldata
* @param minIntermediateOut The intermediate asset to produce from unwrap (use quote's sellAmount)
*/
function deallocateWithUnwrapAndSwap(address adapter, uint256 amount, bytes memory txData, uint256 minIntermediateOut) external {
require(msg.sender == admin || operators[msg.sender], "PD");
IMYTStrategy.SwapParams memory swapParams = IMYTStrategy.SwapParams({
txData: txData,
minIntermediateOut: minIntermediateOut
});
IMYTStrategy.VaultAdapterParams memory params = IMYTStrategy.VaultAdapterParams(
{action: IMYTStrategy.ActionType.unwrapAndSwap, swapParams: swapParams});
bytes memory data = abi.encode(params);
vault.deallocate(adapter, data, amount);
}
/// @notice Set the vault liquidity adapter and calldata used by deposit/withdraw flows.
function setLiquidityAdapter(address adapter, bytes memory data) external {
require(msg.sender == admin || operators[msg.sender], "PD");
vault.setLiquidityAdapterAndData(adapter, data);
}
/**
* @notice Validate the caps for the given adapter and amount
* @param adapter The strategy adapter address
* @param amount The amount to validate
*/
function _validateCaps(address adapter, uint256 amount) internal view {
bytes32 id = IMYTStrategy(adapter).adapterId();
uint256 absoluteCap = vault.absoluteCap(id);
uint256 relativeCap = vault.relativeCap(id);
// get risk caps
uint256 strategyId = uint256(id);
uint8 riskLevel = strategyClassifier.getStrategyRiskLevel(strategyId);
uint256 globalRiskCapPct = strategyClassifier.getGlobalCap(riskLevel);
uint256 localRiskCapPct = strategyClassifier.getIndividualCap(strategyId);
// Convert relativeCap (WAD) to absolute value (WEI)
uint256 totalAssets = vault.totalAssets();
uint256 absoluteValueOfRelativeCap = (totalAssets * relativeCap) / 1e18;
// Convert risk caps from WAD percentages to absolute values
uint256 globalRiskCap = (totalAssets * globalRiskCapPct) / 1e18;
uint256 localRiskCap = (totalAssets * localRiskCapPct) / 1e18;
// Calculate limit cap as the minimum of vault caps
uint256 limit = absoluteCap < absoluteValueOfRelativeCap ? absoluteCap : absoluteValueOfRelativeCap;
// Enforce global risk cap (aggregate across all strategies in this risk class)
uint256 currentRiskAllocation = 0;
uint256 len = vault.adaptersLength();
for (uint256 i = 0; i < len; i++) {
address stratAdapter = vault.adapters(i);
bytes32 stratId = IMYTStrategy(stratAdapter).adapterId();
// Check if the strategy belongs to the same risk level
if (strategyClassifier.getStrategyRiskLevel(uint256(stratId)) == riskLevel) {
currentRiskAllocation += vault.allocation(stratId);
}
}
// Check if the proposed allocation exceeds the remaining capacity of the global risk cap
uint256 remainingGlobal = currentRiskAllocation < globalRiskCap ? globalRiskCap - currentRiskAllocation : 0;
require(amount <= remainingGlobal, EffectiveCap(amount, remainingGlobal));
// Apply local risk cap constraint for operators
if (msg.sender != admin) {
// caller is operator, further constrain by local risk cap
limit = limit < localRiskCap ? limit : localRiskCap;
}
// Ensure the requested amount does not exceed the calculated individual strategy limit
require(vault.allocation(id) + amount <= limit, EffectiveCap(amount, limit));
}
function setMaxRate(uint256 rate) external onlyAdmin {
vault.setMaxRate(rate);
}
}
lib/vault-v2/src/interfaces/IERC20.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2025 Morpho Association
pragma solidity >=0.5.0;
interface IERC20 {
function decimals() external view returns (uint8);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 shares) external returns (bool success);
function transferFrom(address from, address to, uint256 shares) external returns (bool success);
function approve(address spender, uint256 shares) external returns (bool success);
function allowance(address owner, address spender) external view returns (uint256);
}
lib/vault-v2/src/interfaces/IERC2612.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2025 Morpho Association
pragma solidity >=0.5.0;
interface IERC2612 {
function permit(address owner, address spender, uint256 shares, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
external;
function nonces(address owner) external view returns (uint256);
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/vault-v2/src/interfaces/IERC4626.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2025 Morpho Association
pragma solidity >=0.5.0;
import {IERC20} from "./IERC20.sol";
interface IERC4626 is IERC20 {
function asset() external view returns (address);
function totalAssets() external view returns (uint256);
function convertToAssets(uint256 shares) external view returns (uint256 assets);
function convertToShares(uint256 assets) external view returns (uint256 shares);
function deposit(uint256 assets, address onBehalf) external returns (uint256 shares);
function mint(uint256 shares, address onBehalf) external returns (uint256 assets);
function withdraw(uint256 assets, address onBehalf, address receiver) external returns (uint256 shares);
function redeem(uint256 shares, address onBehalf, address receiver) external 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 onBehalf) external view returns (uint256 assets);
function maxMint(address onBehalf) external view returns (uint256 shares);
function maxWithdraw(address onBehalf) external view returns (uint256 assets);
function maxRedeem(address onBehalf) external view returns (uint256 shares);
}
lib/vault-v2/src/interfaces/IVaultV2.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2025 Morpho Association
pragma solidity >=0.5.0;
import {IERC20} from "./IERC20.sol";
import {IERC4626} from "./IERC4626.sol";
import {IERC2612} from "./IERC2612.sol";
struct Caps {
uint256 allocation;
uint128 absoluteCap;
uint128 relativeCap;
}
interface IVaultV2 is IERC4626, IERC2612 {
// State variables
function virtualShares() external view returns (uint256);
function owner() external view returns (address);
function curator() external view returns (address);
function receiveSharesGate() external view returns (address);
function sendSharesGate() external view returns (address);
function receiveAssetsGate() external view returns (address);
function sendAssetsGate() external view returns (address);
function adapterRegistry() external view returns (address);
function isSentinel(address account) external view returns (bool);
function isAllocator(address account) external view returns (bool);
function firstTotalAssets() external view returns (uint256);
function _totalAssets() external view returns (uint128);
function lastUpdate() external view returns (uint64);
function maxRate() external view returns (uint64);
function adapters(uint256 index) external view returns (address);
function adaptersLength() external view returns (uint256);
function isAdapter(address account) external view returns (bool);
function allocation(bytes32 id) external view returns (uint256);
function absoluteCap(bytes32 id) external view returns (uint256);
function relativeCap(bytes32 id) external view returns (uint256);
function forceDeallocatePenalty(address adapter) external view returns (uint256);
function liquidityAdapter() external view returns (address);
function liquidityData() external view returns (bytes memory);
function timelock(bytes4 selector) external view returns (uint256);
function abdicated(bytes4 selector) external view returns (bool);
function executableAt(bytes memory data) external view returns (uint256);
function performanceFee() external view returns (uint96);
function performanceFeeRecipient() external view returns (address);
function managementFee() external view returns (uint96);
function managementFeeRecipient() external view returns (address);
// Gating
function canSendShares(address account) external view returns (bool);
function canReceiveShares(address account) external view returns (bool);
function canSendAssets(address account) external view returns (bool);
function canReceiveAssets(address account) external view returns (bool);
// Multicall
function multicall(bytes[] memory data) external;
// Owner functions
function setOwner(address newOwner) external;
function setCurator(address newCurator) external;
function setIsSentinel(address account, bool isSentinel) external;
function setName(string memory newName) external;
function setSymbol(string memory newSymbol) external;
// Timelocks for curator functions
function submit(bytes memory data) external;
function revoke(bytes memory data) external;
// Curator functions
function setIsAllocator(address account, bool newIsAllocator) external;
function setReceiveSharesGate(address newReceiveSharesGate) external;
function setSendSharesGate(address newSendSharesGate) external;
function setReceiveAssetsGate(address newReceiveAssetsGate) external;
function setSendAssetsGate(address newSendAssetsGate) external;
function setAdapterRegistry(address newAdapterRegistry) external;
function addAdapter(address account) external;
function removeAdapter(address account) external;
function increaseTimelock(bytes4 selector, uint256 newDuration) external;
function decreaseTimelock(bytes4 selector, uint256 newDuration) external;
function abdicate(bytes4 selector) external;
function setPerformanceFee(uint256 newPerformanceFee) external;
function setManagementFee(uint256 newManagementFee) external;
function setPerformanceFeeRecipient(address newPerformanceFeeRecipient) external;
function setManagementFeeRecipient(address newManagementFeeRecipient) external;
function increaseAbsoluteCap(bytes memory idData, uint256 newAbsoluteCap) external;
function decreaseAbsoluteCap(bytes memory idData, uint256 newAbsoluteCap) external;
function increaseRelativeCap(bytes memory idData, uint256 newRelativeCap) external;
function decreaseRelativeCap(bytes memory idData, uint256 newRelativeCap) external;
function setMaxRate(uint256 newMaxRate) external;
function setForceDeallocatePenalty(address adapter, uint256 newForceDeallocatePenalty) external;
// Allocator functions
function allocate(address adapter, bytes memory data, uint256 assets) external;
function deallocate(address adapter, bytes memory data, uint256 assets) external;
function setLiquidityAdapterAndData(address newLiquidityAdapter, bytes memory newLiquidityData) external;
// Exchange rate
function accrueInterest() external;
function accrueInterestView()
external
view
returns (uint256 newTotalAssets, uint256 performanceFeeShares, uint256 managementFeeShares);
// Force deallocate
function forceDeallocate(address adapter, bytes memory data, uint256 assets, address onBehalf)
external
returns (uint256 penaltyShares);
}
src/interfaces/IAllocator.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
interface IAllocator {
/// @notice Allocate with direct allocation (uses ActionType.direct)
function allocate(address adapter, uint256 amount) external;
/// @notice Deallocate with direct allocation (uses ActionType.direct)
function deallocate(address adapter, uint256 amount) external;
/// @notice Allocate with swap (uses ActionType.swap)
function allocateWithSwap(address adapter, uint256 amount, bytes memory txData) external;
/// @notice Deallocate with direct swap (uses ActionType.swap)
function deallocateWithSwap(address adapter, uint256 amount, bytes memory txData) external;
/// @notice Deallocate with unwrap + swap (uses ActionType.unwrapAndSwap)
function deallocateWithUnwrapAndSwap(address adapter, uint256 amount, bytes memory txData, uint256 minIntermediateOut) external;
/// @notice Set the vault liquidity adapter used on deposit/withdraw paths
function setLiquidityAdapter(address adapter, bytes memory data) external;
/// @notice Thrown when the effectice cap is exceeded during allocation
error EffectiveCap(uint256 amount, uint256 limit);
}
src/interfaces/IMYTStrategy.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
interface IMYTStrategy {
// Enums
enum RiskClass {
LOW,
MEDIUM,
HIGH
}
// Structs
struct StrategyParams {
address owner;
string name;
string protocol;
RiskClass riskClass;
uint256 cap;
uint256 globalCap;
uint256 estimatedYield;
bool additionalIncentives;
uint256 slippageBPS;
}
enum ActionType {
direct, // for wrap/unwrap
swap, // for dex swap
unwrapAndSwap // for unwrap -> dex swap
}
struct VaultAdapterParams {
ActionType action;
SwapParams swapParams;
}
struct SwapParams {
bytes txData; // 0x swap calldata
uint256 minIntermediateOut; // Minimum intermediate token out (e.g., stETH from unwrap)
} // Only used for ActionType.unwrapAndSwap
// Events
event Allocate(uint256 indexed amount, address indexed strategy);
event Deallocate(uint256 indexed amount, address indexed strategy);
event DeallocateDex(uint256 indexed amount);
event YieldUpdated(uint256 indexed yield);
event RiskClassUpdated(RiskClass indexed class);
event IncentivesUpdated(bool indexed enabled);
event SlippageBPSUpdated(uint256 indexed newSlippageBPS);
event MinAllocationOutBpsUpdated(uint256 indexed newMinAllocationOutBps);
event Emergency(bool indexed isEmergency);
event StrategyAllocationLoss(string message, uint256 amountRequested, uint256 actualAmountAllocated);
event WithdrawToVault(uint256 indexed amount);
event RewardsClaimed(address indexed token, uint256 indexed amount);
event TokensRescued(address indexed token, address indexed to, uint256 amount);
// Errors
error StrategyAllocationPaused(address strategy);
error CounterfeitSettler(address);
error ActionNotSupported();
error ForceDeallocateSwapNotAllowed();
error InvalidAmount(uint256 min, uint256 received);
error InsufficientBalance(uint256 required, uint256 available);
// Functions
/// @dev wrapper function for the customizable _allocate counterpart
function allocate(bytes memory data, uint256 assets, bytes4 selector, address sender) external returns (bytes32[] memory strategyIds, int256 change);
/// @dev wrapper function for the customizable _deallocate counterpart
function deallocate(bytes memory data, uint256 assets, bytes4 selector, address sender) external returns (bytes32[] memory strategyIds, int256 change);
/// @dev alternative withdraw/deallocate route using a 0x quote
//function deallocateDex(bytes memory data, uint256 amount) external returns (bytes32[] memory strategyIds, int256 change);
/// @dev override this function to handle strategies with withdrawal queue NFT
function claimWithdrawalQueue(uint256 positionId) external returns (uint256);
/// @notice withdraw any leftover assets back to the vault
function withdrawToVault() external returns (uint256);
/// @dev override this function to claim all available rewards from the respective
/// protocol of this strategy
function claimRewards(address token, bytes memory quote, uint256 minAmountOut) external returns (uint256);
/// @notice recategorize this strategy to a different risk class
function setRiskClass(RiskClass newClass) external;
function setAdditionalIncentives(bool newValue) external;
/// @notice enter/exit emergency mode for this strategy
function setKillSwitch(bool val) external;
/// @notice get the current snapshotted estimated yield for this strategy.
/// This call does not guarantee the latest up-to-date yield and there might
/// be discrepancies from the respective protocols numbers.
function getEstimatedYield() external view returns (uint256);
// Getter for params
function params()
external
view
returns (
address owner,
string memory name,
string memory protocol,
RiskClass riskClass,
uint256 cap,
uint256 globalCap,
uint256 estimatedYield,
bool additionalIncentives,
uint256 slippageBPS
);
function getCap() external view returns (uint256);
function getGlobalCap() external view returns (uint256);
function realAssets() external view returns (uint256);
function getIdData() external view returns (bytes memory);
function ids() external view returns (bytes32[] memory);
function adapterId() external view returns (bytes32);
function previewAdjustedWithdraw(uint256 amount) external view returns (uint256);
}
src/interfaces/IStrategyClassifier.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @notice Simple interface for DAO-defined percentage-based caps storage (WAD: 1e18 = 100%)
interface IStrategyClassifier {
function getIndividualCap(uint256 strategyId) external view returns (uint256); // WAD percentage of totalAssets
function getGlobalCap(uint8 riskLevel) external view returns (uint256); // WAD percentage of totalAssets
function getStrategyRiskLevel(uint256 strategyId) external view returns (uint8);
event AdminChanged(address indexed admin);
event RiskClassModified(uint256 indexed class, uint256 indexed globalCap, uint256 indexed localCap);
}
src/utils/PermissionedProxy.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
contract PermissionedProxy {
address admin;
mapping (address => bool) public operators;
mapping (bytes4 => bool) public permissionedCalls;
address public pendingAdmin;
constructor(address _admin, address _operator) {
require(_admin != address(0), "zero");
require(_operator != address(0), "zero");
admin = _admin;
operators[_operator] = true;
}
modifier onlyAdmin() {
_onlyAdmin();
_;
}
function _onlyAdmin() internal view {
require(msg.sender == admin, "PD");
}
modifier onlyOperator() {
_onlyOperator();
_;
}
function _onlyOperator() internal view {
require(operators[msg.sender], "PD");
}
event AdminUpdated(address indexed admin);
event OperatorUpdated(address indexed operator);
event AddedPermissionedCall(bytes4 indexed sig);
function transferAdminOwnerShip(address _newAdmin) external onlyAdmin {
pendingAdmin = _newAdmin;
}
function acceptAdminOwnership() external {
require(msg.sender == pendingAdmin, "PD");
admin = pendingAdmin;
pendingAdmin = address(0);
emit AdminUpdated(admin);
}
function setOperator(address _operator, bool value) external onlyAdmin {
require(_operator != address(0), "zero");
operators[_operator] = value;
emit OperatorUpdated(_operator);
}
function setPermissionedCall(bytes4 sig, bool value) external onlyAdmin {
permissionedCalls[sig] = value;
emit AddedPermissionedCall(sig);
}
function proxy(address vault, bytes memory data) external payable onlyOperator {
bytes4 selector;
require(data.length >= 4, "SEL");
assembly {
selector := mload(add(data, 32))
}
require(permissionedCalls[selector], "PD");
(bool success, ) = vault.call{value: msg.value}(data);
require(success, "failed");
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 800,
"details": {
"yul": false
},
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"\"ds-test/=\"../lib/ds-test/src/",
"\"forge-std/=\"lib/forge-std/src/",
"\"@permit2\"/=\"lib/permit2/src/\"/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"chainlink-brownie-contracts/=lib/chainlink-brownie-contracts/",
"ds-test/=lib/solmate/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"permit2/=lib/permit2/",
"solmate/=lib/solmate/src/",
"v2-foundry/=lib/v2-foundry/src/",
"vault-v2/=lib/vault-v2/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.