Verified contractExactAGPL-3.0-or-later
MorphoCompounderStrategyFactory
Address0x052d20b0e0b141988bd32772c735085e45f357c1
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 5 runs
- EVM version
- prague
- License
- AGPL-3.0-or-later
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 23,784,110
- Creation transaction
- 0xf24bc9e45c…5e2296127e
21 files
- src/factories/MorphoCompounderStrategyFactory.solmain3.84 KB
- dependencies/@openzeppelin-contracts-5.3.0/contracts/interfaces/IERC1363.sol4.45 KB
- dependencies/@openzeppelin-contracts-5.3.0/contracts/interfaces/IERC165.sol192 B
- dependencies/@openzeppelin-contracts-5.3.0/contracts/interfaces/IERC20.sol181 B
- dependencies/@openzeppelin-contracts-5.3.0/contracts/interfaces/IERC4626.sol12.18 KB
- dependencies/@openzeppelin-contracts-5.3.0/contracts/interfaces/draft-IERC6093.sol6.54 KB
- dependencies/@openzeppelin-contracts-5.3.0/contracts/token/ERC20/ERC20.sol10.88 KB
- dependencies/@openzeppelin-contracts-5.3.0/contracts/token/ERC20/IERC20.sol2.78 KB
- dependencies/@openzeppelin-contracts-5.3.0/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- dependencies/@openzeppelin-contracts-5.3.0/contracts/token/ERC20/extensions/IERC20Permit.sol3.81 KB
- dependencies/@openzeppelin-contracts-5.3.0/contracts/token/ERC20/utils/SafeERC20.sol10.08 KB
- dependencies/@openzeppelin-contracts-5.3.0/contracts/utils/Context.sol963 B
- dependencies/@openzeppelin-contracts-5.3.0/contracts/utils/Create2.sol4.47 KB
- dependencies/@openzeppelin-contracts-5.3.0/contracts/utils/Errors.sol896 B
- dependencies/@openzeppelin-contracts-5.3.0/contracts/utils/introspection/IERC165.sol870 B
- src/core/BaseStrategy.sol22.84 KB
- src/core/interfaces/ITokenizedStrategy.sol11.82 KB
- src/factories/BaseStrategyFactory.sol4.36 KB
- src/strategies/interfaces/IBaseHealthCheck.sol2.03 KB
- src/strategies/periphery/BaseHealthCheck.sol6.65 KB
- src/strategies/yieldDonating/MorphoCompounderStrategy.sol7.02 KB
src/factories/MorphoCompounderStrategyFactory.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity >=0.8.25;
import { Create2 } from "@openzeppelin/contracts/utils/Create2.sol";
import { MorphoCompounderStrategy } from "src/strategies/yieldDonating/MorphoCompounderStrategy.sol";
import { BaseStrategyFactory } from "src/factories/BaseStrategyFactory.sol";
/**
* @title MorphoCompounderStrategyFactory
* @author [Golem Foundation](https://golem.foundation)
* @custom:security-contact [email protected]
* @notice Factory for deploying Morpho Compounder yield donating strategies
* @dev Uses CREATE2 for deterministic deployments; records deployments via BaseStrategyFactory
*
* MORPHO INTEGRATION:
* This factory deploys strategies that deposit into Yearn USDC vaults,
* which in turn deploy into Morpho lending markets for yield generation.
* Morpho is a lending pool optimizer built on top of Compound/Aave.
*/
contract MorphoCompounderStrategyFactory is BaseStrategyFactory {
/// @notice Yearn Strategy USDC vault address (target vault for deposits)
address public constant YS_USDC = 0x074134A2784F4F66b6ceD6f68849382990Ff3215;
/// @notice USDC token address (0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 on Ethereum mainnet)
address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
/// @notice Emitted on successful strategy deployment
/// @param deployer Transaction sender performing deployment
/// @param donationAddress Donation destination address for strategy
/// @param strategyAddress Deployed strategy address
/// @param vaultTokenName Vault token name associated with strategy
event StrategyDeploy(
address indexed deployer,
address indexed donationAddress,
address indexed strategyAddress,
string vaultTokenName
);
/**
* @notice Deploy a new MorphoCompounder strategy
* @dev Deterministic salt derived from all parameters to avoid duplicates
* @param _name Strategy share token name
* @param _management Management address (can update params)
* @param _keeper Keeper address (calls report)
* @param _emergencyAdmin Emergency admin address
* @param _donationAddress Dragon router address (receives profit shares)
* @param _enableBurning True to enable burning shares during loss protection
* @param _tokenizedStrategyAddress TokenizedStrategy implementation address
* @return strategyAddress Deployed MorphoCompounderStrategy address
*/
function createStrategy(
string memory _name,
address _management,
address _keeper,
address _emergencyAdmin,
address _donationAddress,
bool _enableBurning,
address _tokenizedStrategyAddress
) external returns (address) {
bytes32 parameterHash = keccak256(
abi.encode(
YS_USDC,
USDC,
_name,
_management,
_keeper,
_emergencyAdmin,
_donationAddress,
_enableBurning,
_tokenizedStrategyAddress
)
);
bytes memory bytecode = abi.encodePacked(
type(MorphoCompounderStrategy).creationCode,
abi.encode(
YS_USDC,
USDC,
_name,
_management,
_keeper,
_emergencyAdmin,
_donationAddress,
_enableBurning,
_tokenizedStrategyAddress
)
);
address strategyAddress = _deployStrategy(bytecode, parameterHash);
_recordStrategy(_name, _donationAddress, strategyAddress);
emit StrategyDeploy(msg.sender, _donationAddress, strategyAddress, _name);
return strategyAddress;
}
}
dependencies/@openzeppelin-contracts-5.3.0/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
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);
}
dependencies/@openzeppelin-contracts-5.3.0/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
dependencies/@openzeppelin-contracts-5.3.0/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
dependencies/@openzeppelin-contracts-5.3.0/contracts/interfaces/IERC4626.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the 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 Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their 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);
}
dependencies/@openzeppelin-contracts-5.3.0/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
dependencies/@openzeppelin-contracts-5.3.0/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
dependencies/@openzeppelin-contracts-5.3.0/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @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);
}
dependencies/@openzeppelin-contracts-5.3.0/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the 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);
}
dependencies/@openzeppelin-contracts-5.3.0/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
dependencies/@openzeppelin-contracts-5.3.0/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
dependencies/@openzeppelin-contracts-5.3.0/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
dependencies/@openzeppelin-contracts-5.3.0/contracts/utils/Create2.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Create2.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
* `CREATE2` can be used to compute in advance the address where a smart
* contract will be deployed, which allows for interesting new mechanisms known
* as 'counterfactual interactions'.
*
* See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
* information.
*/
library Create2 {
/**
* @dev There's no code to deploy.
*/
error Create2EmptyBytecode();
/**
* @dev Deploys a contract using `CREATE2`. The address where the contract
* will be deployed can be known in advance via {computeAddress}.
*
* The bytecode for a contract can be obtained from Solidity with
* `type(contractName).creationCode`.
*
* Requirements:
*
* - `bytecode` must not be empty.
* - `salt` must have not been used for `bytecode` already.
* - the factory must have a balance of at least `amount`.
* - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
*/
function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
if (bytecode.length == 0) {
revert Create2EmptyBytecode();
}
assembly ("memory-safe") {
addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
// if no address was created, and returndata is not empty, bubble revert
if and(iszero(addr), not(iszero(returndatasize()))) {
let p := mload(0x40)
returndatacopy(p, 0, returndatasize())
revert(p, returndatasize())
}
}
if (addr == address(0)) {
revert Errors.FailedDeployment();
}
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
* `bytecodeHash` or `salt` will result in a new destination address.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
return computeAddress(salt, bytecodeHash, address(this));
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {
assembly ("memory-safe") {
let ptr := mload(0x40) // Get free memory pointer
// | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... |
// |-------------------|---------------------------------------------------------------------------|
// | bytecodeHash | CCCCCCCCCCCCC...CC |
// | salt | BBBBBBBBBBBBB...BB |
// | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA |
// | 0xFF | FF |
// |-------------------|---------------------------------------------------------------------------|
// | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
// | keccak(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |
mstore(add(ptr, 0x40), bytecodeHash)
mstore(add(ptr, 0x20), salt)
mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
mstore8(start, 0xff)
addr := and(keccak256(start, 85), 0xffffffffffffffffffffffffffffffffffffffff)
}
}
}
dependencies/@openzeppelin-contracts-5.3.0/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
dependencies/@openzeppelin-contracts-5.3.0/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @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/core/BaseStrategy.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.25;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
// TokenizedStrategy interface used for internal view delegateCalls.
import { ITokenizedStrategy } from "src/core/interfaces/ITokenizedStrategy.sol";
/**
* @title Octant Base Strategy
* @author [Golem Foundation](https://golem.foundation)
* @custom:security-contact [email protected]
* @notice BaseStrategy implements all of the required functionality to
* seamlessly integrate with the `TokenizedStrategy` implementation contract
* allowing anyone to easily build a fully permissionless ERC-4626 compliant
* Vault by inheriting this contract and overriding three simple functions.
* It utilizes an immutable proxy pattern that allows the BaseStrategy
* to remain simple and small. All standard logic is held within the
* `TokenizedStrategy` and is reused over any n strategies all using the
* `fallback` function to delegatecall the implementation so that strategists
* can only be concerned with writing their strategy specific code.
*
* This contract should be inherited and the three main abstract methods
* `_deployFunds`, `_freeFunds` and `_harvestAndReport` implemented to adapt
* the Strategy to the particular needs it has to generate yield. There are
* other optional methods that can be implemented to further customize
* the strategy if desired.
*
* All default storage for the strategy is controlled and updated by the
* `TokenizedStrategy`. The implementation holds a storage struct that
* contains all needed global variables in a manual storage slot. This
* means strategists can feel free to implement their own custom storage
* variables as they need with no concern of collisions. All global variables
* can be viewed within the Strategy by a simple call using the
* `TokenizedStrategy` variable. IE: TokenizedStrategy.globalVariable();.
*/
abstract contract BaseStrategy {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
error NotSelf();
// ============================================
// MODIFIERS
// ============================================
/**
* @notice Ensures function is called via delegatecall from this contract
* @dev Used on TokenizedStrategy callbacks to verify delegatecall context
* Prevents external calls to internal hook functions
*/
modifier onlySelf() {
_onlySelf();
_;
}
/**
* @notice Restricts function to management address only
* @dev Calls TokenizedStrategy.requireManagement to validate
*/
modifier onlyManagement() {
TokenizedStrategy.requireManagement(msg.sender);
_;
}
/**
* @notice Restricts function to keeper or management
* @dev Calls TokenizedStrategy.requireKeeperOrManagement to validate
* Used for report() and tend() operations
*/
modifier onlyKeepers() {
TokenizedStrategy.requireKeeperOrManagement(msg.sender);
_;
}
/**
* @notice Restricts function to emergencyAdmin or management
* @dev Calls TokenizedStrategy.requireEmergencyAuthorized to validate
* Used for emergency shutdown and withdrawal operations
*/
modifier onlyEmergencyAuthorized() {
TokenizedStrategy.requireEmergencyAuthorized(msg.sender);
_;
}
/**
* @dev Require that the msg.sender is this address.
*/
function _onlySelf() internal view {
if (msg.sender != address(this)) {
revert NotSelf();
}
}
/*//////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/**
* @dev This is the address of the TokenizedStrategy implementation
* contract that will be used by all strategies to handle the
* accounting, logic, storage etc.
*
* Any external calls to the that don't hit one of the functions
* defined in this base or the strategy will end up being forwarded
* through the fallback function, which will delegateCall this address.
*
* This address should be the same for every strategy, never be adjusted
* and always be checked before any integration with the Strategy.
*/
address public immutable TOKENIZED_STRATEGY_ADDRESS;
/// @notice Underlying ERC20 asset the strategy earns yield on
/// @dev Immutable, set during construction. Stored here for gas-efficient access
/// Strategies deposit this asset into yield sources
ERC20 internal immutable asset;
/// @notice Internal interface to TokenizedStrategy implementation
/// @dev Set to address(this) during initialization
///
/// USAGE:
/// Any call to TokenizedStrategy.xxx() will:
/// 1. Call address(this).xxx()
/// 2. Hit the fallback function
/// 3. Delegatecall to TOKENIZED_STRATEGY_ADDRESS
///
/// This pattern allows strategies to access TokenizedStrategy storage
/// as if it were a linked library
ITokenizedStrategy internal immutable TokenizedStrategy;
/**
* @notice Used to initialize the strategy on deployment.
*
* This will set the `TokenizedStrategy` variable for easy
* internal view calls to the implementation. As well as
* initializing the default storage variables based on the
* parameters and using the deployer for the permissioned roles.
*
* @param _asset Address of the underlying asset.
* @param _name Name the strategy will use.
* @param _management Address with management permissions
* @param _keeper Address with keeper permissions
* @param _emergencyAdmin Address with emergency admin permissions
* @param _donationAddress Address that will receive donations for this specific strategy
* @param _enableBurning Whether to enable burning shares from dragon router during loss protection
* @param _tokenizedStrategyAddress Address of the TokenizedStrategy implementation
*/
constructor(
address _asset,
string memory _name,
address _management,
address _keeper,
address _emergencyAdmin,
address _donationAddress,
bool _enableBurning,
address _tokenizedStrategyAddress
) {
asset = ERC20(_asset);
TOKENIZED_STRATEGY_ADDRESS = _tokenizedStrategyAddress;
// Set instance of the implementation for internal use.
TokenizedStrategy = ITokenizedStrategy(address(this));
// Initialize the strategy's storage variables.
_delegateCall(
abi.encodeCall(
ITokenizedStrategy.initialize,
(_asset, _name, _management, _keeper, _emergencyAdmin, _donationAddress, _enableBurning)
)
);
// Store the tokenizedStrategyAddress at the standard implementation
// address storage slot so etherscan picks up the interface. This gets
// stored on initialization and never updated.
assembly {
sstore(
// keccak256('eip1967.proxy.implementation' - 1)
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
_tokenizedStrategyAddress
)
}
}
/*//////////////////////////////////////////////////////////////
NEEDED TO BE OVERRIDDEN BY STRATEGIST
//////////////////////////////////////////////////////////////*/
// ============================================
// REQUIRED OVERRIDES - STRATEGIST MUST IMPLEMENT
// ============================================
/**
* @notice REQUIRED: Deploys assets into the yield source
* @dev Called automatically after deposits/mints to put idle assets to work
*
* WHEN CALLED:
* - After deposit() or mint() completes
* - Via deployFunds() hook from TokenizedStrategy
* - msg.sender == address(this) (via delegatecall)
*
* IMPLEMENTATION GUIDANCE:
* 1. Transfer _amount of asset from this contract to yield source
* 2. Receive yield-bearing tokens (e.g., aTokens, LP tokens)
* 3. Store any necessary state for tracking
* 4. Consider gas costs - don't deploy dust amounts
*
* SECURITY CONSIDERATIONS:
* - PERMISSIONLESS: Can be called by anyone via deposit
* - MEV RISK: May be sandwichable - consider slippage protection
* - VALIDATION: Verify yield source addresses/parameters
* - FAILURE: Revert on critical errors, idle funds stay in strategy
*
* @param _amount Amount of asset to deploy
*/
function _deployFunds(uint256 _amount) internal virtual;
/**
* @notice REQUIRED: Frees assets from the yield source for withdrawal
* @dev Called during withdraw/redeem to liquidate positions and return assets
*
* WHEN CALLED:
* - During withdraw() or redeem() operations
* - Via freeFunds() hook from TokenizedStrategy
* - msg.sender == address(this) (via delegatecall)
* - Idle assets already accounted for (only called if needed)
*
* IMPLEMENTATION GUIDANCE:
* 1. Withdraw _amount from yield source to this contract
* 2. DO NOT rely on asset.balanceOf(this) except for diff accounting
* 3. Any shortfall is counted as loss and passed to withdrawer
* 4. Consider reverting if illiquid rather than realizing losses
*
* LOSS HANDLING:
* - Freed amount < _amount: Shortfall = realized loss for user
* - Loss must be within maxLoss tolerance or withdrawal reverts
* - CAREFUL: Temporary illiquidity ≠ permanent loss
*
* SECURITY CONSIDERATIONS:
* - PERMISSIONLESS: Can be called by anyone via withdraw
* - MEV RISK: May be sandwichable - consider slippage protection
* - ILLIQUIDITY: Revert if withdrawal would realize unfair losses
* - PRECISION: Track actual amounts freed, not estimates
*
* @param _amount Amount of asset needed
*/
function _freeFunds(uint256 _amount) internal virtual;
/**
* @notice REQUIRED: Harvests rewards and reports accurate asset accounting
* @dev Called by report() to update strategy's total assets and realize profits/losses
*
* WHEN CALLED:
* - Via report() by keeper or management
* - Via harvestAndReport() hook from TokenizedStrategy
* - Can be called even after shutdown
*
* CRITICAL RESPONSIBILITIES:
* 1. Harvest all pending rewards from yield source
* 2. Sell/swap rewards to base asset (if applicable)
* 3. Compound rewards back into position (if desired)
* 4. Account for ALL assets: deployed + idle + pending rewards
* 5. Return accurate total (profit/loss calculated from this)
*
* ACCOUNTING RULES:
* - Return value MUST include: deposited assets + idle assets + accrued rewards
* - Return value determines profit/loss since last report
* - Profit = (currentTotal - lastReportedTotal) > 0
* - Loss = (currentTotal - lastReportedTotal) < 0
* - BE PRECISE: All PnL accounting depends on this number
*
* POST-SHUTDOWN BEHAVIOR:
* - Check TokenizedStrategy.isShutdown()
* - If shutdown: Don't redeploy, just harvest and account
* - Allow final report to realize remaining positions
*
* SECURITY CONSIDERATIONS:
* - ORACLE RISK: Prefer actual balances over oracle values
* - MANIPULATION: Ensure returned value reflects real assets
* - PRECISION: Rounding errors accumulate - be conservative
* - TIMING: MEV risk when harvesting - use protected mempools
*
* @return _totalAssets CRITICAL: Accurate total of all strategy assets (deployed + idle)
* @custom:security Return value determines profit/loss - must be manipulation-resistant
*/
function _harvestAndReport() internal virtual returns (uint256 _totalAssets);
/*//////////////////////////////////////////////////////////////
OPTIONAL TO OVERRIDE BY STRATEGIST
//////////////////////////////////////////////////////////////*/
// ============================================
// OPTIONAL OVERRIDES - ADVANCED STRATEGIST FEATURES
// ============================================
/**
* @notice OPTIONAL: Performs maintenance between reports without updating PPS
* @dev Called by tend() between reports for position maintenance
*
* USE CASES:
* - Harvest and compound rewards without full report
* - Deploy idle funds when threshold reached
* - Rebalance positions
* - Update protocol-specific parameters
*
* WHEN TO USE:
* - Strategy has idle funds but depositing is MEV-risky
* - Rewards need compounding more frequently than reports
* - Position requires periodic maintenance
*
* IMPORTANT:
* - Does NOT update strategy PPS (no profit/loss recorded)
* - Only affects internal positions
* - Must also override _tendTrigger() to activate
*
* @param _totalIdle Current idle funds available to deploy
*/
function _tend(uint256 _totalIdle) internal virtual {}
/**
* @notice OPTIONAL: Determines if tend() should be called
* @dev MUST be overridden if _tend() is implemented
*
* @return shouldTend True if tend() should be called by keeper
*/
function _tendTrigger() internal view virtual returns (bool) {
return false;
}
/**
* @notice Returns if tend() should be called by a keeper.
*
* @return shouldTend True if tend() should be called by a keeper.
* @return tendCalldata Calldata for the tend call.
*/
function tendTrigger() external view virtual returns (bool, bytes memory) {
return (
// Return the status of the tend trigger.
_tendTrigger(),
// And the needed calldata either way.
abi.encodeWithSelector(ITokenizedStrategy.tend.selector)
);
}
/**
* @notice Gets the max amount of `asset` that an address can deposit.
* @dev Defaults to an unlimited amount for any address. But can
* be overridden by strategists.
*
* This function will be called before any deposit or mints to enforce
* any limits desired by the strategist. This can be used for either a
* traditional deposit limit or for implementing an allowset etc.
*
* This does not need to take into account any conversion rates
* from shares to assets. But should know that any non max uint256
* amounts may be converted to shares. So it is recommended to keep
* custom amounts low enough as not to cause overflow when multiplied
* by `totalSupply`.
*
* The address that is depositing into the strategy can be used by overrides to enforce custom limits.
* @return Available amount owner can deposit
*/
function availableDepositLimit(address /* _owner */) public view virtual returns (uint256) {
return type(uint256).max;
}
/**
* @notice Gets the max amount of `asset` that can be withdrawn.
* @dev Defaults to an unlimited amount for any address. But can
* be overridden by strategists.
*
* This function will be called before any withdraw or redeem to enforce
* any limits desired by the strategist. This can be used for illiquid
* or sandwichable strategies. It should never be lower than `totalIdle`.
*
* This does not need to take into account the `_owner`'s share balance
* or conversion rates from shares to assets.
*
* The address that is withdrawing from the strategy can be used by overrides to enforce custom limits.
* @return Available amount that can be withdrawn
*/
function availableWithdrawLimit(address /* _owner */) public view virtual returns (uint256) {
return type(uint256).max;
}
/**
* @notice OPTIONAL: Manually withdraws funds after shutdown
* @dev Allows management to recover funds from yield source post-shutdown
*
* WHEN CALLED:
* - Only after strategy is shutdown
* - Via emergencyWithdraw() by management or emergencyAdmin
*
* IMPORTANT:
* - Does NOT realize profit/loss (need separate report() for that)
* - _amount may exceed currently deployed amount
* - In _harvestAndReport(), check isShutdown() to avoid redeploying
*
* @param _amount Amount of asset to attempt to free
*/
function _emergencyWithdraw(uint256 _amount) internal virtual {}
/*//////////////////////////////////////////////////////////////
TokenizedStrategy HOOKS
//////////////////////////////////////////////////////////////*/
/**
* @notice Can deploy up to '_amount' of 'asset' in yield source.
* @dev Callback for the TokenizedStrategy to call during a {deposit}
* or {mint} to tell the strategy it can deploy funds.
*
* Since this can only be called after a {deposit} or {mint}
* delegateCall to the TokenizedStrategy msg.sender == address(this).
*
* Unless an allowset is implemented this will be entirely permissionless
* and thus can be sandwiched or otherwise manipulated.
*
* @param _amount Amount of asset strategy can deploy
*/
function deployFunds(uint256 _amount) external virtual onlySelf {
_deployFunds(_amount);
}
/**
* @notice Should attempt to free the '_amount' of 'asset'.
* @dev Callback for the TokenizedStrategy to call during a withdraw
* or redeem to free the needed funds to service the withdraw.
*
* This can only be called after a 'withdraw' or 'redeem' delegateCall
* to the TokenizedStrategy so msg.sender == address(this).
*
* @param _amount Amount of asset strategy should attempt to free up
*/
function freeFunds(uint256 _amount) external virtual onlySelf {
_freeFunds(_amount);
}
/**
* @notice Returns the accurate amount of all funds currently
* held by the Strategy.
* @dev Callback for the TokenizedStrategy to call during a report to
* get an accurate accounting of assets the strategy controls.
*
* This can only be called after a report() delegateCall to the
* TokenizedStrategy so msg.sender == address(this).
*
* @return A trusted and accurate account for the total amount
* of 'asset' the strategy currently holds including idle funds
*/
function harvestAndReport() external virtual onlySelf returns (uint256) {
return _harvestAndReport();
}
/**
* @notice Will call the internal '_tend' when a keeper tends the strategy.
* @dev Callback for the TokenizedStrategy to initiate a _tend call in the strategy.
*
* This can only be called after a tend() delegateCall to the TokenizedStrategy
* so msg.sender == address(this).
*
* We name the function `tendThis` so that `tend` calls are forwarded to
* the TokenizedStrategy.
*
* @param _totalIdle Amount of current idle funds available to be deployed during the tend
*/
function tendThis(uint256 _totalIdle) external virtual onlySelf {
_tend(_totalIdle);
}
/**
* @notice Will call the internal '_emergencyWithdraw' function.
* @dev Callback for the TokenizedStrategy during an emergency withdraw.
*
* This can only be called after a emergencyWithdraw() delegateCall to
* the TokenizedStrategy so msg.sender == address(this).
*
* We name the function `shutdownWithdraw` so that `emergencyWithdraw`
* calls are forwarded to the TokenizedStrategy.
*
* @param _amount Amount of asset to attempt to free
*/
function shutdownWithdraw(uint256 _amount) external virtual onlySelf {
_emergencyWithdraw(_amount);
}
/**
* @dev Function used to delegate call the TokenizedStrategy with
* certain `_calldata` and return any return values.
*
* This is used to setup the initial storage of the strategy, and
* can be used by strategist to forward any other call to the
* TokenizedStrategy implementation.
*
* @param _calldata ABI encoded calldata to use in delegatecall
* @return returndata Return value if call was successful in bytes
*/
function _delegateCall(bytes memory _calldata) internal returns (bytes memory returndata) {
// Delegate call the tokenized strategy with provided calldata.
(bool success, bytes memory result) = TOKENIZED_STRATEGY_ADDRESS.delegatecall(_calldata);
// If the call reverted. Return the error.
if (!success) {
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
// Return the result.
return result;
}
/**
* @dev Execute a function on the TokenizedStrategy and return any value.
*
* This fallback function will be executed when any of the standard functions
* defined in the TokenizedStrategy are called since they wont be defined in
* this contract.
*
* It will delegatecall the TokenizedStrategy implementation with the exact
* calldata and return any relevant values.
*
*/
fallback() external {
// load our target address
address _tokenizedStrategyAddress = TOKENIZED_STRATEGY_ADDRESS;
// Execute external function using delegatecall and return any value.
assembly {
// Copy function selector and any arguments.
calldatacopy(0, 0, calldatasize())
// Execute function delegatecall.
let result := delegatecall(gas(), _tokenizedStrategyAddress, 0, calldatasize(), 0, 0)
// Get any return value
returndatacopy(0, 0, returndatasize())
// Return any return value or error back to the caller
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
}
src/core/interfaces/ITokenizedStrategy.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
/**
* @title Yearn V3 Tokenized Strategy Interface
* @author yearn.finance; port maintained by [Golem Foundation](https://golem.foundation)
* @custom:security-contact [email protected]
* @custom:ported-from https://github.com/yearn/tokenized-strategy/blob/master/src/interfaces/ITokenizedStrategy.sol
* @notice Interface that implements the 4626 standard and the implementation functions
* for the TokenizedStrategy contract.
*/
interface ITokenizedStrategy is IERC4626, IERC20Permit {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when a strategy is shutdown.
*/
event StrategyShutdown();
/**
* @notice Emitted on the initialization of any new `strategy` that uses `asset`
* with this specific `apiVersion`.
*/
event NewTokenizedStrategy(address indexed strategy, address indexed asset, string apiVersion);
/**
* @notice Emitted when the strategy reports `profit` or `loss`.
*/
event Reported(uint256 profit, uint256 loss);
/**
* @notice Emitted when the 'keeper' address is updated to 'newKeeper'.
*/
event UpdateKeeper(address indexed newKeeper);
/**
* @notice Emitted when the 'management' address is updated to 'newManagement'.
*/
event UpdateManagement(address indexed newManagement);
/**
* @notice Emitted when the 'emergencyAdmin' address is updated to 'newEmergencyAdmin'.
*/
event UpdateEmergencyAdmin(address indexed newEmergencyAdmin);
/**
* @notice Emitted when the 'pendingManagement' address is updated to 'newPendingManagement'.
*/
event UpdatePendingManagement(address indexed newPendingManagement);
/**
* @notice Emitted when the dragon router address is updated.
*/
event UpdateDragonRouter(address indexed newDragonRouter);
/**
* @notice Emitted when a pending dragon router change is initiated
* @param newDragonRouter Proposed dragon router address
* @param effectiveTimestamp Timestamp when change can be finalized
*/
event PendingDragonRouterChange(address indexed newDragonRouter, uint256 effectiveTimestamp);
/*//////////////////////////////////////////////////////////////
INITIALIZATION
//////////////////////////////////////////////////////////////*/
/**
* @notice Used to initialize storage for a newly deployed strategy
* @param _asset Underlying asset address
* @param _name Strategy name
* @param _management Management address
* @param _keeper Keeper address
* @param _emergencyAdmin Emergency admin address
* @param _dragonRouter Dragon router address (receives minted shares from yield)
* @param _enableBurning True to enable burning shares during loss protection
*/
function initialize(
address _asset,
string memory _name,
address _management,
address _keeper,
address _emergencyAdmin,
address _dragonRouter,
bool _enableBurning
) external;
/*//////////////////////////////////////////////////////////////
NON-STANDARD 4626 OPTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Withdraws assets from owner's shares and sends underlying tokens to receiver
* @dev This includes an added parameter to allow for losses
* @param assets Amount of underlying to withdraw
* @param receiver Address to receive assets
* @param owner Address whose shares are burnt
* @param maxLoss Maximum acceptable loss in basis points (1 bps = 0.01%)
* @return shares Actual amount of shares burnt
*/
function withdraw(uint256 assets, address receiver, address owner, uint256 maxLoss) external returns (uint256);
/**
* @notice Redeems exactly shares from owner and sends underlying tokens to receiver
* @dev This includes an added parameter to allow for losses
* @param shares Amount of shares burnt
* @param receiver Address to receive assets
* @param owner Address whose shares are burnt
* @param maxLoss Maximum acceptable loss in basis points (1 bps = 0.01%)
* @return Actual amount of underlying withdrawn
*/
function redeem(uint256 shares, address receiver, address owner, uint256 maxLoss) external returns (uint256);
/**
* @notice Variable maxLoss is ignored
* @dev Accepts a maxLoss variable in order to match the multi strategy vaults ABI
* @param owner Address to check maximum withdrawal for
* @return Maximum withdrawable amount
*/
function maxWithdraw(address owner, uint256 /*maxLoss*/) external view returns (uint256);
/**
* @notice Variable maxLoss is ignored
* @dev Accepts a maxLoss variable in order to match the multi strategy vaults ABI
* @param owner Address to check maximum redemption for
* @return Maximum redeemable shares
*/
function maxRedeem(address owner, uint256 /*maxLoss*/) external view returns (uint256);
/*//////////////////////////////////////////////////////////////
MODIFIER HELPERS
//////////////////////////////////////////////////////////////*/
/**
* @notice Require a caller is `management`.
* @param _sender Original msg.sender
*/
function requireManagement(address _sender) external view;
/**
* @notice Require a caller is the `keeper` or `management`.
* @param _sender Original msg.sender
*/
function requireKeeperOrManagement(address _sender) external view;
/**
* @notice Require a caller is the `management` or `emergencyAdmin`.
* @param _sender Original msg.sender
*/
function requireEmergencyAuthorized(address _sender) external view;
/*//////////////////////////////////////////////////////////////
KEEPERS FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice For a 'keeper' to 'tend' the strategy if a custom
* tendTrigger() is implemented.
*/
function tend() external;
/**
* @notice Function for keepers to harvest and record all profits/losses since last report.
* @dev Keepers should consider MEV-protected submission. Specialized implementations may
* mint shares to the donation destination (dragon router) on profit, and apply
* loss-protection via dragon burning (if enabled). The return values are denominated
* in the underlying `asset`.
* @return _profit Gain since last report, in `asset` units.
* @return _loss Loss since last report, in `asset` units.
*/
function report() external returns (uint256 _profit, uint256 _loss);
/*//////////////////////////////////////////////////////////////
GETTERS
//////////////////////////////////////////////////////////////*/
/**
* @notice Get the API version for this TokenizedStrategy.
* @return API version for this TokenizedStrategy
*/
function apiVersion() external view returns (string memory);
/**
* @notice Get the price per share.
* @return Price per share
*/
function pricePerShare() external view returns (uint256);
/**
* @notice Get the current address that controls the strategy.
* @return Address of management
*/
function management() external view returns (address);
/**
* @notice Get the current pending management address if any.
* @return Address of pendingManagement
*/
function pendingManagement() external view returns (address);
/**
* @notice Get the current address that can call tend and report.
* @return Address of the keeper
*/
function keeper() external view returns (address);
/**
* @notice Get the current address that can shutdown and emergency withdraw.
* @return Address of the emergencyAdmin
*/
function emergencyAdmin() external view returns (address);
/**
* @notice Get the current dragon router address that will receive minted shares.
* @return Address of dragonRouter
*/
function dragonRouter() external view returns (address);
/**
* @notice Get the pending dragon router address if any.
* @return Address of the pending dragon router
*/
function pendingDragonRouter() external view returns (address);
/**
* @notice Get the timestamp when dragon router change was initiated.
* @return Timestamp of the dragon router change initiation
*/
function dragonRouterChangeTimestamp() external view returns (uint256);
/**
* @notice The timestamp of the last time protocol fees were charged.
* @return Last report timestamp in seconds
*/
function lastReport() external view returns (uint256);
/**
* @notice To check if the strategy has been shutdown.
* @return Whether or not the strategy is shutdown.
*/
function isShutdown() external view returns (bool);
/*//////////////////////////////////////////////////////////////
SETTERS
//////////////////////////////////////////////////////////////*/
/**
* @notice Step one of two to set a new address to be in charge of the strategy.
* @param _management New address to set `pendingManagement` to.
*/
function setPendingManagement(address _management) external;
/**
* @notice Step two of two to set a new 'management' of the strategy.
*/
function acceptManagement() external;
/**
* @notice Sets a new address to be in charge of tend and reports.
* @param _keeper New address to set `keeper` to.
*/
function setKeeper(address _keeper) external;
/**
* @notice Sets a new address to be able to shutdown the strategy.
* @param _emergencyAdmin New address to set `emergencyAdmin` to.
*/
function setEmergencyAdmin(address _emergencyAdmin) external;
/**
* @notice Initiates a change to a new donation destination (dragon router) with cooldown.
* @dev Emits PendingDragonRouterChange(new, effectiveTimestamp) and starts a mandatory
* cooldown before finalization. Users can exit during the cooldown if they disagree.
* @param _dragonRouter New address to set as pending `dragonRouter`.
*/
function setDragonRouter(address _dragonRouter) external;
/**
* @notice Finalizes the dragon router change after the cooldown period.
* @dev Requires cooldown to have elapsed and pending router to be set.
*/
function finalizeDragonRouterChange() external;
/**
* @notice Cancels a pending dragon router change.
* @dev Resets pending router and timestamp, emitting PendingDragonRouterChange(address(0), 0).
*/
function cancelDragonRouterChange() external;
/**
* @notice Updates the name for the strategy.
* @param _newName New strategy name
*/
function setName(string calldata _newName) external;
/**
* @notice Used to shutdown the strategy preventing any further deposits.
*/
function shutdownStrategy() external;
/**
* @notice To manually withdraw funds from the yield source after a
* strategy has been shutdown.
* @param _amount Amount of asset to withdraw
*/
function emergencyWithdraw(uint256 _amount) external;
}
src/factories/BaseStrategyFactory.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity >=0.8.25;
import { Create2 } from "@openzeppelin/contracts/utils/Create2.sol";
/**
* @title BaseStrategyFactory
* @author [Golem Foundation](https://golem.foundation)
* @custom:security-contact [email protected]
* @notice Base contract for strategy factories with deterministic deployment
* @dev Uses CREATE2 with parameter-based hashing to prevent duplicate deployments
*
* Security Considerations:
* - Strategy parameters are hashed to create a unique salt
* - Same parameters always result in the same deployment address
* - Duplicate strategy deployments are automatically prevented
* - Addresses are deterministic and predictable based on parameters
*/
abstract contract BaseStrategyFactory {
/**
* @dev Struct to store information about a strategy
* @param deployerAddress Deployer who created the strategy
* @param timestamp Timestamp when the strategy was created (seconds)
* @param vaultTokenName Name of the vault token associated with the strategy
* @param donationAddress Address where donations from the strategy will be sent
*/
struct StrategyInfo {
address deployerAddress;
uint256 timestamp;
string vaultTokenName;
address donationAddress;
}
/// @dev Mapping from deployer address to their deployed strategies
/// Used for tracking deployed strategies
mapping(address => StrategyInfo[]) public strategies;
// Custom errors
error StrategyAlreadyExists(address existingStrategy);
// Note: Child factories should declare and emit their own `StrategyDeploy` event for compatibility.
/**
* @notice Predict deployment address using strategy parameter hash
* @dev Combines parameter hash with deployer address for deterministic deployment
* @param _parameterHash Hash of all strategy parameters
* @param deployer Deployer address
* @param bytecode Deployment bytecode (including constructor args)
* @return Predicted contract address
*/
function predictStrategyAddress(
bytes32 _parameterHash,
address deployer,
bytes memory bytecode
) external view returns (address) {
bytes32 finalSalt = keccak256(abi.encodePacked(_parameterHash, deployer));
return Create2.computeAddress(finalSalt, keccak256(bytecode));
}
/**
* @dev Internal function to deploy strategy using CREATE2
* @param bytecode Deployment bytecode including constructor args
* @param _parameterHash Hash of all strategy parameters for deterministic deployment
* @return strategyAddress Deployed strategy address
*/
function _deployStrategy(bytes memory bytecode, bytes32 _parameterHash) internal returns (address strategyAddress) {
bytes32 finalSalt = keccak256(abi.encodePacked(_parameterHash, msg.sender));
// Check if strategy would be deployed to an existing address
address predictedAddress = Create2.computeAddress(finalSalt, keccak256(bytecode));
if (predictedAddress.code.length > 0) {
revert StrategyAlreadyExists(predictedAddress);
}
strategyAddress = Create2.deploy(0, finalSalt, bytecode);
}
/**
* @dev Internal function to record strategy deployment
* @param _name Strategy name
* @param _donationAddress Donation address
* @param _strategyAddress Deployed strategy address
*/
function _recordStrategy(string memory _name, address _donationAddress, address _strategyAddress) internal {
// Silence unused parameter warning
_strategyAddress;
StrategyInfo memory strategyInfo = StrategyInfo({
deployerAddress: msg.sender,
timestamp: block.timestamp,
vaultTokenName: _name,
donationAddress: _donationAddress
});
strategies[msg.sender].push(strategyInfo);
}
/**
* @notice Returns all strategies deployed by a specific address
* @dev Get all strategies deployed by a specific address
* @param deployer Deployer address
* @return Array of StrategyInfo for all strategies deployed by the address
*/
function getStrategiesByDeployer(address deployer) external view returns (StrategyInfo[] memory) {
return strategies[deployer];
}
}
src/strategies/interfaces/IBaseHealthCheck.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.25;
/**
* @title IBaseHealthCheck Interface
* @author Yearn.finance; adapted by [Golem Foundation](https://golem.foundation)
* @custom:security-contact [email protected]
* @notice Interface for health checking strategy profit/loss reporting
* @custom:origin https://github.com/yearn/tokenized-strategy-periphery/blob/master/src/HealthCheck/BaseHealthCheck.sol
*/
interface IBaseHealthCheck {
/*//////////////////////////////////////////////////////////////
VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Returns whether the health check is currently enabled
* @return True if health check is enabled
*/
function doHealthCheck() external view returns (bool);
/**
* @notice Returns the profit limit ratio
* @return Profit limit ratio in basis points
*/
function profitLimitRatio() external view returns (uint256);
/**
* @notice Returns the loss limit ratio
* @return Loss limit ratio in basis points
*/
function lossLimitRatio() external view returns (uint256);
/*//////////////////////////////////////////////////////////////
MUTATIVE FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Set the profit limit ratio
* @param _newProfitLimitRatio New profit limit ratio in basis points
*/
function setProfitLimitRatio(uint256 _newProfitLimitRatio) external;
/**
* @notice Set the loss limit ratio
* @param _newLossLimitRatio New loss limit ratio in basis points
*/
function setLossLimitRatio(uint256 _newLossLimitRatio) external;
/**
* @notice Enable or disable health check
* @dev If disabled, next report will re-enable it
* @param _doHealthCheck Whether health check should be performed
*/
function setDoHealthCheck(bool _doHealthCheck) external;
}
src/strategies/periphery/BaseHealthCheck.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import { BaseStrategy } from "src/core/BaseStrategy.sol";
import { IBaseHealthCheck } from "src/strategies/interfaces/IBaseHealthCheck.sol";
/**
* @title Base Health Check
* @author [Golem Foundation](https://golem.foundation)
* @custom:security-contact [email protected]
* @notice This contract is based on Yearn's BaseHealthCheck from
* https://github.com/yearn/tokenized-strategy-periphery/blob/master/src/Bases/HealthCheck/BaseHealthCheck.sol
*
* This contract can be inherited by any strategy wishing to implement a health check during
* the `report` function in order to prevent any unexpected behavior from being permanently
* recorded as well as the `checkHealth` modifier.
*
* A strategist simply needs to inherit this contract. Set
* the limit ratios to the desired amounts and then
* override `_harvestAndReport()` just as they otherwise
* would. If the profit or loss that would be recorded is
* outside the acceptable bounds the tx will revert.
*
* The healthcheck does not prevent a strategy from reporting
* losses, but rather can make sure manual intervention is
* needed before reporting an unexpected loss or profit.
*/
abstract contract BaseHealthCheck is BaseStrategy, IBaseHealthCheck {
// Can be used to determine if a healthcheck should be called.
// Defaults to true;
bool public doHealthCheck = true;
uint256 internal constant MAX_BPS = 10_000;
// Default profit limit to 100%.
uint16 private _profitLimitRatio = uint16(MAX_BPS);
// Defaults loss limit to 0.
uint16 private _lossLimitRatio;
/// @notice Emitted when the health check flag is updated
event HealthCheckUpdated(bool doHealthCheck);
/// @notice Emitted when the profit limit ratio is updated
event ProfitLimitRatioUpdated(uint256 newProfitLimitRatio);
/// @notice Emitted when the loss limit ratio is updated
event LossLimitRatioUpdated(uint256 newLossLimitRatio);
constructor(
address _asset,
string memory _name,
address _management,
address _keeper,
address _emergencyAdmin,
address _donationAddress,
bool _enableBurning,
address _tokenizedStrategyAddress
)
BaseStrategy(
_asset,
_name,
_management,
_keeper,
_emergencyAdmin,
_donationAddress,
_enableBurning,
_tokenizedStrategyAddress
)
{}
/**
* @notice Returns the current profit limit ratio.
* @dev Use a getter function to keep the variable private.
* @return profitLimitRatio Current profit limit ratio in basis points
*/
function profitLimitRatio() public view returns (uint256) {
return _profitLimitRatio;
}
/**
* @notice Returns the current loss limit ratio.
* @dev Use a getter function to keep the variable private.
* @return lossLimitRatio Current loss limit ratio in basis points
*/
function lossLimitRatio() public view returns (uint256) {
return _lossLimitRatio;
}
/**
* @notice Set the `profitLimitRatio`.
* @dev Denominated in basis points. I.E. 1_000 == 10%.
* @param _newProfitLimitRatio New profit limit ratio in basis points
*/
function setProfitLimitRatio(uint256 _newProfitLimitRatio) external onlyManagement {
_setProfitLimitRatio(_newProfitLimitRatio);
}
/**
* @dev Internally set the profit limit ratio. Denominated
* in basis points. I.E. 1_000 == 10%.
* @param _newProfitLimitRatio New profit limit ratio in basis points
*/
function _setProfitLimitRatio(uint256 _newProfitLimitRatio) internal {
require(_newProfitLimitRatio > 0, "!zero profit");
require(_newProfitLimitRatio <= type(uint16).max, "!too high");
_profitLimitRatio = uint16(_newProfitLimitRatio);
emit ProfitLimitRatioUpdated(_newProfitLimitRatio);
}
/**
* @notice Set the `lossLimitRatio`.
* @dev Denominated in basis points. I.E. 1_000 == 10%.
* @param _newLossLimitRatio New loss limit ratio in basis points
*/
function setLossLimitRatio(uint256 _newLossLimitRatio) external onlyManagement {
_setLossLimitRatio(_newLossLimitRatio);
}
/**
* @dev Internally set the loss limit ratio. Denominated
* in basis points. I.E. 1_000 == 10%.
* @param _newLossLimitRatio New loss limit ratio in basis points
*/
function _setLossLimitRatio(uint256 _newLossLimitRatio) internal {
require(_newLossLimitRatio < MAX_BPS, "!loss limit");
_lossLimitRatio = uint16(_newLossLimitRatio);
emit LossLimitRatioUpdated(_newLossLimitRatio);
}
/**
* @notice Turns the healthcheck on and off.
* @dev If turned off the next report will auto turn it back on.
* @param _doHealthCheck Bool if healthCheck should be done.
*/
function setDoHealthCheck(bool _doHealthCheck) public onlyManagement {
doHealthCheck = _doHealthCheck;
emit HealthCheckUpdated(_doHealthCheck);
}
/**
* @notice OVerrides the default {harvestAndReport} to include a healthcheck.
* @return _totalAssets New totalAssets post report.
*/
function harvestAndReport() external override onlySelf returns (uint256 _totalAssets) {
// Let the strategy report.
_totalAssets = _harvestAndReport();
// Run the healthcheck on the amount returned.
_executeHealthCheck(_totalAssets);
}
/**
* @dev To be called during a report to make sure the profit
* or loss being recorded is within the acceptable bound.
*
* @param _newTotalAssets Amount that will be reported in asset base units
*/
function _executeHealthCheck(uint256 _newTotalAssets) internal virtual {
if (!doHealthCheck) {
doHealthCheck = true;
return;
}
// Get the current total assets from the implementation.
uint256 currentTotalAssets = TokenizedStrategy.totalAssets();
if (_newTotalAssets > currentTotalAssets) {
require(
((_newTotalAssets - currentTotalAssets) <= (currentTotalAssets * uint256(_profitLimitRatio)) / MAX_BPS),
"healthCheck"
);
} else if (currentTotalAssets > _newTotalAssets) {
require(
(currentTotalAssets - _newTotalAssets <= ((currentTotalAssets * uint256(_lossLimitRatio)) / MAX_BPS)),
"healthCheck"
);
}
}
}
src/strategies/yieldDonating/MorphoCompounderStrategy.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import { BaseHealthCheck } from "src/strategies/periphery/BaseHealthCheck.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/interfaces/IERC20.sol";
import { ITokenizedStrategy } from "src/core/interfaces/ITokenizedStrategy.sol";
/**
* @title MorphoCompounderStrategy
* @author [Golem Foundation](https://golem.foundation)
* @custom:security-contact [email protected]
* @notice Yield-donating strategy that compounds rewards from a Morpho vault
* @dev Deposits assets into a Morpho compounder vault (e.g., Morpho Steakhouse) to earn yield
*
* YIELD FLOW:
* 1. Deposits assets into Morpho compounder vault
* 2. Vault compounds yield automatically via Morpho markets
* 3. On report, profit is minted as shares to donation address
*
* META-VAULT INFLATION ISSUE:
* - When compounderVault is a meta-vault (e.g., Morpho → SteakHouse),
* maxDeposit chains through multiple vaults
* - If underlying vaults have duplicate markets in supply queues,
* maxDeposit may overstate actual capacity
* - This can cause deposits to temporarily revert but is not a critical issue
*
* LOSS HANDLING:
* - Accepts 100% loss on withdrawals to prevent revert cascades
* - MultistrategyVault enforces actual loss limits via updateDebt
*
* @custom:security Morpho vault convertToAssets must be manipulation-resistant
*/
contract MorphoCompounderStrategy is BaseHealthCheck {
using SafeERC20 for IERC20;
/// @notice Address of the Morpho compounder vault this strategy deposits into
/// @dev Must implement ITokenizedStrategy and use the same asset as this strategy
address public immutable compounderVault;
/**
* @notice Initializes the Morpho compounder strategy
* @dev Validates asset matches Morpho vault's asset and approves max allowance
* @param _compounderVault Address of the Morpho compounder vault to deposit into
* @param _asset Address of the underlying asset (must match compounder vault's asset)
* @param _name Strategy display name (e.g., "Octant Morpho USDC Strategy")
* @param _management Address with management permissions
* @param _keeper Address authorized to call report() and tend()
* @param _emergencyAdmin Address authorized for emergency shutdown
* @param _donationAddress Address receiving minted profit shares
* @param _enableBurning True to enable loss protection via share burning
* @param _tokenizedStrategyAddress Address of TokenizedStrategy implementation contract
*/
constructor(
address _compounderVault,
address _asset,
string memory _name,
address _management,
address _keeper,
address _emergencyAdmin,
address _donationAddress,
bool _enableBurning,
address _tokenizedStrategyAddress
)
BaseHealthCheck(
_asset,
_name,
_management,
_keeper,
_emergencyAdmin,
_donationAddress,
_enableBurning,
_tokenizedStrategyAddress
)
{
// make sure asset is Morpho's asset
require(ITokenizedStrategy(_compounderVault).asset() == _asset, "Asset mismatch with compounder vault");
IERC20(_asset).forceApprove(_compounderVault, type(uint256).max);
compounderVault = _compounderVault;
}
/**
* @notice Returns maximum additional assets that can be deposited
* @dev Queries compounder vault's maxDeposit and subtracts idle balance
*
* META-VAULT INFLATION:
* When compounderVault is Morpho Steakhouse or similar meta-vault,
* maxDeposit may be inflated if underlying SteakHouse USDC has duplicate
* markets in its supplyQueue. Deposits may temporarily revert.
*
* @return limit Maximum additional deposit amount in asset base units
*/
function availableDepositLimit(address /*_owner*/) public view override returns (uint256) {
// NOTE: When compounderVault points to certain vaults (like Morpho Steakhouse USDC Compounder),
// the maxDeposit value may be inflated due to duplicate markets in underlying vault's supplyQueue.
// This is because maxDeposit chains through: this strategy → Morpho Steakhouse → SteakHouse USDC,
// and SteakHouse USDC's maxDeposit may overstate capacity when duplicate markets exist.
uint256 vaultLimit = ITokenizedStrategy(compounderVault).maxDeposit(address(this));
uint256 idleBalance = IERC20(asset).balanceOf(address(this));
return vaultLimit > idleBalance ? vaultLimit - idleBalance : 0;
}
/**
* @notice Returns maximum assets withdrawable without expected loss
* @dev Sums idle balance and compounder vault's maxWithdraw
* @return limit Maximum withdrawal amount in asset base units
*/
function availableWithdrawLimit(address /*_owner*/) public view override returns (uint256) {
return IERC20(asset).balanceOf(address(this)) + ITokenizedStrategy(compounderVault).maxWithdraw(address(this));
}
/**
* @dev Deposits idle assets into Morpho compounder vault
* @param _amount Amount of assets to deploy in asset base units
*/
function _deployFunds(uint256 _amount) internal override {
ITokenizedStrategy(compounderVault).deposit(_amount, address(this));
}
/**
* @dev Withdraws assets from Morpho compounder vault
* @param _amount Amount of assets to withdraw in asset base units
* @custom:security maxLoss set to 100% (10_000 BPS) to prevent revert cascades
* MultistrategyVault enforces actual loss limits via updateDebt
*/
function _freeFunds(uint256 _amount) internal override {
ITokenizedStrategy(compounderVault).withdraw(_amount, address(this), address(this), 10_000);
}
/**
* @dev Emergency withdrawal after strategy shutdown
* @param _amount Amount of assets to withdraw in asset base units
*/
function _emergencyWithdraw(uint256 _amount) internal override {
_freeFunds(_amount);
}
/**
* @dev Reports current total assets under management
* @return _totalAssets Sum of compounder vault value and idle assets in asset base units
*/
function _harvestAndReport() internal view override returns (uint256 _totalAssets) {
// Get strategy's share balance in the compounder vault
uint256 shares = ITokenizedStrategy(compounderVault).balanceOf(address(this));
uint256 vaultAssets = ITokenizedStrategy(compounderVault).convertToAssets(shares);
// Include idle funds as per BaseStrategy specification
uint256 idleAssets = IERC20(asset).balanceOf(address(this));
_totalAssets = vaultAssets + idleAssets;
return _totalAssets;
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 5,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@gnosis.pm/safe-contracts/=dependencies/safe-global-safe-smart-account-1.4.1-3/",
"@openzeppelin/contracts-upgradeable/=dependencies/@openzeppelin-contracts-upgradeable-5.3.0/contracts/",
"@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.3.0/contracts/",
"@tokenized-strategy-periphery/=dependencies/tokenized-strategy-periphery-3.0.2/src/",
"abdk-libraries-solidity/=dependencies/abdk-libraries-solidity-3.2/",
"erc4626-tests/=dependencies/erc4626-tests-0.0.0/",
"forge-std/=dependencies/forge-std-1.9.7/src/",
"hats-protocol/=dependencies/hats-protocol-1.0/src/",
"kontrol-cheatcodes/=dependencies/kontrol-cheatcodes-v0.0.1/",
"lib/ERC1155/=dependencies/hats-protocol-1.0/lib/ERC1155/",
"solady-test/=dependencies/solady-0.1.21/test/",
"solady/=dependencies/solady-0.1.21/src/",
"solbase/=dependencies/solbase-0.0.0/src/",
"solmate/=dependencies/solmate-6.8.0/",
"staker/=dependencies/staker-1.0.1/src/",
"surl/=dependencies/surl-0.0.0/src/",
"tokenized-strategy/=dependencies/tokenized-strategy-3.0.4/",
"zodiac/=dependencies/gnosisguild-zodiac-4.1.1/contracts/",
"@openzeppelin-contracts-5.3.0/=dependencies/@openzeppelin-contracts-5.3.0/",
"@openzeppelin-contracts-upgradeable-5.3.0/=dependencies/@openzeppelin-contracts-upgradeable-5.3.0/",
"@tokenized-strategy/=dependencies/tokenized-strategy-periphery-3.0.2/lib/tokenized-strategy/src/",
"@yearn-vaults/=dependencies/tokenized-strategy-periphery-3.0.2/lib/yearn-vaults-v3/contracts/",
"ERC1155/=dependencies/hats-protocol-1.0/lib/ERC1155/",
"abdk-libraries-solidity-3.2/=dependencies/abdk-libraries-solidity-3.2/",
"ds-test/=dependencies/tokenized-strategy-periphery-3.0.2/lib/forge-std/lib/ds-test/src/",
"erc4626-tests-0.0.0/=dependencies/erc4626-tests-0.0.0/",
"forge-std-1.9.7/=dependencies/forge-std-1.9.7/src/",
"gnosisguild-zodiac-4.1.1/=dependencies/gnosisguild-zodiac-4.1.1/contracts/",
"hats-protocol-1.0/=dependencies/hats-protocol-1.0/src/",
"kontrol-cheatcodes-v0.0.1/=dependencies/kontrol-cheatcodes-v0.0.1/",
"safe-global-safe-smart-account-1.4.1-3/=dependencies/safe-global-safe-smart-account-1.4.1-3/",
"solady-0.1.21/=dependencies/solady-0.1.21/src/",
"solbase-0.0.0/=dependencies/solbase-0.0.0/src/",
"solidity-stringutils/=dependencies/surl-0.0.0/lib/solidity-stringutils/src/",
"solmate-6.8.0/=dependencies/solmate-6.8.0/src/",
"staker-1.0.1/=dependencies/staker-1.0.1/src/",
"staker-test/=dependencies/staker-1.0.1/test/",
"surl-0.0.0/=dependencies/surl-0.0.0/src/",
"tokenized-strategy-3.0.4/=dependencies/tokenized-strategy-3.0.4/src/",
"tokenized-strategy-periphery-3.0.2/=dependencies/tokenized-strategy-periphery-3.0.2/src/",
"utils/=dependencies/hats-protocol-1.0/lib/utils/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.