Проверенный контрактЧастичноеApache-2.0
AaveV4WithdrawHook
Адрес0x8a45dfd418bd64f8e42cb396dae1565e36ad0bdb
- Баланс
0 ETH
- Транзакций
0
- Компилятор
solc 0.8.30
- Тот же код
ещё 1 контракт
Подробности
- Компилятор
- solc 0.8.30+commit.73712a01
- Язык
- solidity
- Оптимизация
- Да, 200 прогонов
- Версия EVM
- prague
- Лицензия
- Apache-2.0
- Совпадение
- Частичноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 26 121 239
- Транзакция создания
- 0x87d322f7e5…5ee97b60b5
16 файлов
- src/hooks/loan/aave-v4/AaveV4WithdrawHook.solглавный4,46 КБ
- lib/modulekit/src/accounts/common/interfaces/IERC7579Account.sol5,01 КБ
- lib/modulekit/src/accounts/common/lib/ModeLib.sol5,98 КБ
- lib/modulekit/src/accounts/erc7579/lib/ExecutionLib.sol3,14 КБ
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 Б
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2,78 КБ
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 Б
- src/hooks/BaseHook.sol18,75 КБ
- src/hooks/loan/BaseLoanHook.sol4,09 КБ
- src/hooks/loan/aave-v4/BaseAaveV4LoanHook.sol20,14 КБ
- src/interfaces/ISuperHook.sol16,83 КБ
- src/libraries/AaveV4ReserveKey.sol12,22 КБ
- src/libraries/HookDataDecoder.sol530 Б
- src/libraries/HookSubTypes.sol1,99 КБ
- src/vendor/BytesLib.sol19,29 КБ
- src/vendor/aave-v4/IAaveV4Spoke.sol9,64 КБ
src/hooks/loan/aave-v4/AaveV4WithdrawHook.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
// external
import { Execution } from "modulekit/accounts/erc7579/lib/ExecutionLib.sol";
import { IAaveV4Spoke } from "../../../vendor/aave-v4/IAaveV4Spoke.sol";
// Superform
import { BaseHook } from "../../BaseHook.sol";
import { BaseAaveV4LoanHook } from "./BaseAaveV4LoanHook.sol";
import { HookSubTypes } from "../../../libraries/HookSubTypes.sol";
import { ISuperHookResult, ISuperHookInspector } from "../../../interfaces/ISuperHook.sol";
/// @title AaveV4WithdrawHook
/// @author Superform Labs
/// @dev data has the following structure (standard 52-byte strategy header + hook-specific):
/// @notice bytes32 yieldSourceOracleId = data.extractYieldSourceOracleId(); // Superform Aave V4 YS oracle id
/// @notice address yieldSource = data.extractYieldSource(); // AaveV4ReserveKey(spoke, supplyReserveId)
/// @notice address loanToken = BytesLib.toAddress(data, 52);
/// @notice address collateralToken = BytesLib.toAddress(data, 72);
/// @notice address spoke = BytesLib.toAddress(data, 92);
/// @notice uint256 supplyReserveId = BytesLib.toUint256(data, 112);
/// @notice uint256 borrowReserveId = BytesLib.toUint256(data, 144);
/// @notice uint256 amount = BytesLib.toUint256(data, 176);
/// @notice bool usePrevHookAmount = _decodeBool(data, 208);
contract AaveV4WithdrawHook is BaseAaveV4LoanHook {
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor() BaseAaveV4LoanHook(HookSubTypes.LOAN_REPAY) { }
/// @notice Human-readable name for UI display
function name() external pure override returns (string memory) {
return "Aave V4 Withdraw";
}
/// @notice One-sentence description of what this hook does
function description() external pure override returns (string memory) {
return "Withdraws assets from an Aave V4 lending pool";
}
/*//////////////////////////////////////////////////////////////
VIEW METHODS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc BaseHook
function _buildHookExecutions(
address prevHook,
address account,
bytes calldata data
)
internal
view
override
returns (Execution[] memory executions)
{
WithdrawHookLocalVars memory vars = _decodeWithdrawHookData(data);
_requireCollateralPosition(vars.spoke, vars.supplyReserveId, account);
if (vars.usePrevHookAmount) {
vars.amount = ISuperHookResult(prevHook).getOutAmount(account);
}
if (vars.amount == 0) revert AMOUNT_NOT_VALID();
executions = new Execution[](1);
executions[0] = Execution({
target: vars.spoke,
value: 0,
callData: abi.encodeCall(IAaveV4Spoke.withdraw, (vars.supplyReserveId, vars.amount, account))
});
}
/// @inheritdoc ISuperHookInspector
function inspect(bytes calldata data) external pure override returns (bytes memory) {
WithdrawHookLocalVars memory vars = _decodeWithdrawHookData(data);
return _inspectAaveV4(
vars.reserveKey,
vars.spoke,
vars.loanToken,
vars.collateralToken,
vars.supplyReserveId,
vars.borrowReserveId
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL METHODS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc BaseHook
function _preExecute(address, address account, bytes calldata data) internal override {
// Re-run the strict decode (header key pin) on the execution path, like the V2 hooks
WithdrawHookLocalVars memory vars = _decodeWithdrawHookData(data);
_requireCollateralPosition(vars.spoke, vars.supplyReserveId, account);
_setOutAmount(getCollateralTokenBalance(account, data), account);
}
/// @inheritdoc BaseHook
function _postExecute(address, address account, bytes calldata data) internal override {
_setOutAmount(getCollateralTokenBalance(account, data) - getOutAmount(account), account);
_setOutToken(getCollateralTokenAddress(data), account);
}
}
lib/modulekit/src/accounts/common/interfaces/IERC7579Account.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.23 <0.9.0;
/* solhint-disable no-unused-import */
// Types
import { CallType, ExecType, ModeCode } from "../lib/ModeLib.sol";
// Structs
struct Execution {
address target;
uint256 value;
bytes callData;
}
interface IERC7579Account {
event ModuleInstalled(uint256 moduleTypeId, address module);
event ModuleUninstalled(uint256 moduleTypeId, address module);
/**
* @dev Executes a transaction on behalf of the account.
* This function is intended to be called by ERC-4337 EntryPoint.sol
* @dev Ensure adequate authorization control: i.e. onlyEntryPointOrSelf
*
* @dev MSA MUST implement this function signature.
* If a mode is requested that is not supported by the Account, it MUST revert
* @param mode The encoded execution mode of the transaction. See ModeLib.sol for details
* @param executionCalldata The encoded execution call data
*/
function execute(ModeCode mode, bytes calldata executionCalldata) external payable;
/**
* @dev Executes a transaction on behalf of the account.
* This function is intended to be called by Executor Modules
* @dev Ensure adequate authorization control: i.e. onlyExecutorModule
*
* @dev MSA MUST implement this function signature.
* If a mode is requested that is not supported by the Account, it MUST revert
* @param mode The encoded execution mode of the transaction. See ModeLib.sol for details
* @param executionCalldata The encoded execution call data
*/
function executeFromExecutor(
ModeCode mode,
bytes calldata executionCalldata
)
external
payable
returns (bytes[] memory returnData);
/**
* @dev ERC-1271 isValidSignature
* This function is intended to be used to validate a smart account signature
* and may forward the call to a validator module
*
* @param hash The hash of the data that is signed
* @param data The data that is signed
*/
function isValidSignature(bytes32 hash, bytes calldata data) external view returns (bytes4);
/**
* @dev installs a Module of a certain type on the smart account
* @dev Implement Authorization control of your chosing
* @param moduleTypeId the module type ID according the ERC-7579 spec
* @param module the module address
* @param initData arbitrary data that may be required on the module during `onInstall`
* initialization.
*/
function installModule(
uint256 moduleTypeId,
address module,
bytes calldata initData
)
external
payable;
/**
* @dev uninstalls a Module of a certain type on the smart account
* @dev Implement Authorization control of your chosing
* @param moduleTypeId the module type ID according the ERC-7579 spec
* @param module the module address
* @param deInitData arbitrary data that may be required on the module during `onUninstall`
* de-initialization.
*/
function uninstallModule(
uint256 moduleTypeId,
address module,
bytes calldata deInitData
)
external
payable;
/**
* Function to check if the account supports a certain CallType or ExecType (see ModeLib.sol)
* @param encodedMode the encoded mode
*/
function supportsExecutionMode(ModeCode encodedMode) external view returns (bool);
/**
* Function to check if the account supports installation of a certain module type Id
* @param moduleTypeId the module type ID according the ERC-7579 spec
*/
function supportsModule(uint256 moduleTypeId) external view returns (bool);
/**
* Function to check if the account has a certain module installed
* @param moduleTypeId the module type ID according the ERC-7579 spec
* Note: keep in mind that some contracts can be multiple module types at the same time. It
* thus may be necessary to query multiple module types
* @param module the module address
* @param additionalContext additional context data that the smart account may interpret to
* identifiy conditions under which the module is installed.
* usually this is not necessary, but for some special hooks that
* are stored in mappings, this param might be needed
*/
function isModuleInstalled(
uint256 moduleTypeId,
address module,
bytes calldata additionalContext
)
external
view
returns (bool);
/**
* @dev Returns the account id of the smart account
* @return accountImplementationId the account id of the smart account
* the accountId should be structured like so:
* "vendorname.accountname.semver"
*/
function accountId() external view returns (string memory accountImplementationId);
}
lib/modulekit/src/accounts/common/lib/ModeLib.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0 <0.9.0;
/**
* @title ModeLib
* @author rhinestone | zeroknots.eth, Konrad Kopp (@kopy-kat)
* To allow smart accounts to be very simple, but allow for more complex execution, A custom mode
* encoding is used.
* Function Signature of execute function:
* function execute(ModeCode mode, bytes calldata executionCalldata) external payable;
* This allows for a single bytes32 to be used to encode the execution mode, calltype, execType and
* context.
* NOTE: Simple Account implementations only have to scope for the most significant byte. Account that
* implement
* more complex execution modes may use the entire bytes32.
*
* |--------------------------------------------------------------------|
* | CALLTYPE | EXECTYPE | UNUSED | ModeSelector | ModePayload |
* |--------------------------------------------------------------------|
* | 1 byte | 1 byte | 4 bytes | 4 bytes | 22 bytes |
* |--------------------------------------------------------------------|
*
* CALLTYPE: 1 byte
* CallType is used to determine how the executeCalldata paramter of the execute function has to be
* decoded.
* It can be either single, batch or delegatecall. In the future different calls could be added.
* CALLTYPE can be used by a validation module to determine how to decode <userOp.callData[36:]>.
*
* EXECTYPE: 1 byte
* ExecType is used to determine how the account should handle the execution.
* It can indicate if the execution should revert on failure or continue execution.
* In the future more execution modes may be added.
* Default Behavior (EXECTYPE = 0x00) is to revert on a single failed execution. If one execution in
* a batch fails, the entire batch is reverted
*
* UNUSED: 4 bytes
* Unused bytes are reserved for future use.
*
* ModeSelector: bytes4
* The "optional" mode selector can be used by account vendors, to implement custom behavior in
* their accounts.
* the way a ModeSelector is to be calculated is bytes4(keccak256("vendorname.featurename"))
* this is to prevent collisions between different vendors, while allowing innovation and the
* development of new features without coordination between ERC-7579 implementing accounts
*
* ModePayload: 22 bytes
* Mode payload is used to pass additional data to the smart account execution, this may be
* interpreted depending on the ModeSelector
*
* ExecutionCallData: n bytes
* single, delegatecall or batch exec abi.encoded as bytes
*/
// Custom type for improved developer experience
type ModeCode is bytes32;
type CallType is bytes1;
type ExecType is bytes1;
type ModeSelector is bytes4;
type ModePayload is bytes22;
// Default CallType
CallType constant CALLTYPE_SINGLE = CallType.wrap(0x00);
// Batched CallType
CallType constant CALLTYPE_BATCH = CallType.wrap(0x01);
CallType constant CALLTYPE_STATIC = CallType.wrap(0xFE);
// @dev Implementing delegatecall is OPTIONAL!
// implement delegatecall with extreme care.
CallType constant CALLTYPE_DELEGATECALL = CallType.wrap(0xFF);
// @dev default behavior is to revert on failure
// To allow very simple accounts to use mode encoding, the default behavior is to revert on failure
// Since this is value 0x00, no additional encoding is required for simple accounts
ExecType constant EXECTYPE_DEFAULT = ExecType.wrap(0x00);
// @dev account may elect to change execution behavior. For example "try exec" / "allow fail"
ExecType constant EXECTYPE_TRY = ExecType.wrap(0x01);
ModeSelector constant MODE_DEFAULT = ModeSelector.wrap(bytes4(0x00000000));
// Example declaration of a custom mode selector
ModeSelector constant MODE_OFFSET = ModeSelector.wrap(bytes4(keccak256("default.mode.offset")));
/**
* @dev ModeLib is a helper library to encode/decode ModeCodes
*/
library ModeLib {
function decode(ModeCode mode)
internal
pure
returns (
CallType _calltype,
ExecType _execType,
ModeSelector _modeSelector,
ModePayload _modePayload
)
{
// solhint-disable-next-line no-inline-assembly
assembly {
_calltype := mode
_execType := shl(8, mode)
_modeSelector := shl(48, mode)
_modePayload := shl(80, mode)
}
}
function encode(
CallType callType,
ExecType execType,
ModeSelector mode,
ModePayload payload
)
internal
pure
returns (ModeCode)
{
return ModeCode.wrap(
bytes32(
abi.encodePacked(callType, execType, bytes4(0), ModeSelector.unwrap(mode), payload)
)
);
}
function encodeSimpleBatch() internal pure returns (ModeCode mode) {
mode = encode(CALLTYPE_BATCH, EXECTYPE_DEFAULT, MODE_DEFAULT, ModePayload.wrap(0x00));
}
function encodeSimpleSingle() internal pure returns (ModeCode mode) {
mode = encode(CALLTYPE_SINGLE, EXECTYPE_DEFAULT, MODE_DEFAULT, ModePayload.wrap(0x00));
}
function getCallType(ModeCode mode) internal pure returns (CallType calltype) {
// solhint-disable-next-line no-inline-assembly
assembly {
calltype := mode
}
}
}
using { eqModeSelector as == } for ModeSelector global;
using { eqCallType as == } for CallType global;
using { neqCallType as != } for CallType global;
using { eqExecType as == } for ExecType global;
function eqCallType(CallType a, CallType b) pure returns (bool) {
return CallType.unwrap(a) == CallType.unwrap(b);
}
function neqCallType(CallType a, CallType b) pure returns (bool) {
return CallType.unwrap(a) == CallType.unwrap(b);
}
function eqExecType(ExecType a, ExecType b) pure returns (bool) {
return ExecType.unwrap(a) == ExecType.unwrap(b);
}
function eqModeSelector(ModeSelector a, ModeSelector b) pure returns (bool) {
return ModeSelector.unwrap(a) == ModeSelector.unwrap(b);
}
lib/modulekit/src/accounts/erc7579/lib/ExecutionLib.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.23 <0.9.0;
// Types
import { Execution } from "../../common/interfaces/IERC7579Account.sol";
/**
* Helper Library for decoding Execution calldata
* malloc for memory allocation is bad for gas. use this assembly instead
*/
library ExecutionLib {
error ERC7579DecodingError();
/**
* @notice Decode a batch of `Execution` executionBatch from a `bytes` calldata.
* @dev code is copied from solady's LibERC7579.sol
* https://github.com/Vectorized/solady/blob/740812cedc9a1fc11e17cb3d4569744367dedf19/src/accounts/LibERC7579.sol#L146
* Credits to Vectorized and the Solady Team
*/
function decodeBatch(bytes calldata executionCalldata)
internal
pure
returns (Execution[] calldata executionBatch)
{
/// @solidity memory-safe-assembly
assembly {
let u := calldataload(executionCalldata.offset)
let s := add(executionCalldata.offset, u)
let e := sub(add(executionCalldata.offset, executionCalldata.length), 0x20)
executionBatch.offset := add(s, 0x20)
executionBatch.length := calldataload(s)
if or(shr(64, u), gt(add(s, shl(5, executionBatch.length)), e)) {
mstore(0x00, 0xba597e7e) // `DecodingError()`.
revert(0x1c, 0x04)
}
if executionBatch.length {
// Perform bounds checks on the decoded `executionBatch`.
// Loop runs out-of-gas if `executionBatch.length` is big enough to cause overflows.
for { let i := executionBatch.length } 1 { } {
i := sub(i, 1)
let p := calldataload(add(executionBatch.offset, shl(5, i)))
let c := add(executionBatch.offset, p)
let q := calldataload(add(c, 0x40))
let o := add(c, q)
// forgefmt: disable-next-item
if or(shr(64, or(calldataload(o), or(p, q))),
or(gt(add(c, 0x40), e), gt(add(o, calldataload(o)), e))) {
mstore(0x00, 0xba597e7e) // `DecodingError()`.
revert(0x1c, 0x04)
}
if iszero(i) { break }
}
}
}
}
function encodeBatch(Execution[] memory executions)
internal
pure
returns (bytes memory callData)
{
callData = abi.encode(executions);
}
function decodeSingle(bytes calldata executionCalldata)
internal
pure
returns (address target, uint256 value, bytes calldata callData)
{
target = address(bytes20(executionCalldata[0:20]));
value = uint256(bytes32(executionCalldata[20:52]));
callData = executionCalldata[52:];
}
function encodeSingle(
address target,
uint256 value,
bytes memory callData
)
internal
pure
returns (bytes memory userOpCalldata)
{
userOpCalldata = abi.encodePacked(target, value, callData);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
src/hooks/BaseHook.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
// External
import { Execution } from "modulekit/accounts/erc7579/lib/ExecutionLib.sol";
import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
// Superform
import { HookDataDecoder } from "../libraries/HookDataDecoder.sol";
import {
ISuperHook,
ISuperHookSetter,
ISuperHookResult,
ISuperHookInspector,
ISuperHookInflowOutflow,
ISuperHookOutflow
} from "../interfaces/ISuperHook.sol";
/// @title BaseHook
/// @author Superform Labs
/// @notice Base implementation for all hooks in the Superform system
/// @dev Provides core security validation and execution flow management for hooks
/// All specialized hooks should inherit from this base contract
/// Implements the ISuperHook interface defined lifecycle methods
/// Uses a transient storage pattern for stateful execution context
abstract contract BaseHook is ISuperHook, ISuperHookSetter, ISuperHookResult, ISuperHookInspector, IERC165 {
using HookDataDecoder for bytes;
/*//////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice The number of shares used by this hook's operation
/// @dev Used for accounting and tracking consumption of position shares
uint256 public transient usedShares;
/// @notice The special token address (if any) associated with this hook's operation
/// @dev May be used to track token addresses for various operations
address public transient spToken;
/// @notice The primary asset address this hook operates on
/// @dev Typically the base token or asset being processed
address public transient asset;
/// @notice Execution nonce for creating unique contexts
uint256 public transient executionNonce;
/// @notice Last execution context caller
address public transient lastCaller;
// Storage offsets for different state variables
uint256 private constant OUT_AMOUNT_OFFSET = 1;
uint256 private constant PRE_EXECUTE_MUTEX_OFFSET = 2;
uint256 private constant POST_EXECUTE_MUTEX_OFFSET = 3;
uint256 private constant OUT_TOKEN_OFFSET = 4;
/*//////////////////////////////////////////////////////////////
ENUMS
//////////////////////////////////////////////////////////////*/
/// @notice Declares how a hook handles its output (outAmount + outToken) relative to the previous hook
/// @dev TRANSFORM: Hook converts input to output (balance-diff pattern). Default.
/// PASSTHROUGH: Hook performs a side-effect only, auto-forwards prev hook's output.
/// SOURCE: Hook creates output from external state, ignores prev hook. Reserved for future use.
enum PipeMode {
TRANSFORM,
PASSTHROUGH,
SOURCE
}
/// @notice Base storage key for hook execution state
bytes32 private constant HOOK_EXECUTION_STORAGE = keccak256("hook.execution.state");
/// @notice Storage key for account context mapping
bytes32 private constant ACCOUNT_CONTEXT_STORAGE = keccak256("hook.account.context");
/// @notice The specific subtype identifier for this hook
/// @dev Used to identify specialized hook types beyond the basic HookType enum
bytes32 public immutable SUB_TYPE;
/// @notice The type of hook (NONACCOUNTING, INFLOW, OUTFLOW)
/// @dev Determines how the hook impacts accounting in the system
ISuperHook.HookType public hookType;
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when a caller attempts to execute hook methods without proper authorization
/// @dev Used by security validation to prevent unauthorized hook execution
error NOT_AUTHORIZED();
/// @notice Thrown when an amount parameter is invalid (e.g., zero or overflow)
/// @dev Used in validation checks for asset amounts and share values
error AMOUNT_NOT_VALID();
/// @notice Thrown when an address parameter is invalid (e.g., zero address)
/// @dev Used in validation checks for tokens, accounts, and other addresses
error ADDRESS_NOT_VALID();
/// @notice Thrown when a caller is not authorized to execute hook methods
/// @dev Used by security validation to prevent unauthorized hook execution
error UNAUTHORIZED_CALLER();
/// @notice Thrown when preExecute is called more than once
/// @dev Used to prevent reentrancy attacks and ensure proper execution flow
error PRE_EXECUTE_ALREADY_CALLED();
/// @notice Thrown when postExecute is called more than once
/// @dev Used to prevent reentrancy attacks and ensure proper execution flow
error POST_EXECUTE_ALREADY_CALLED();
/// @notice Thrown when a hook execution is incomplete
/// @dev Used to prevent incomplete hook execution
error INCOMPLETE_HOOK_EXECUTION();
/// @notice Thrown when trying to set outAmount after preExecute or postExecute
/// @dev Used to prevent setting outAmount after preExecute or postExecute
error CANNOT_SET_OUT_AMOUNT();
/// @notice Thrown when the amounts array length doesn't match the expected count
/// @dev Used by replaceCalldataAmounts to validate input
error INVALID_AMOUNTS_LENGTH();
/// @notice Initializes the hook with its type and subtype
/// @dev Sets immutable parameters that define the hook's behavior
/// @param hookType_ The type classification for this hook (NONACCOUNTING, INFLOW, OUTFLOW)
/// @param subType_ The specific subtype identifier for specialized hook functionality
constructor(ISuperHook.HookType hookType_, bytes32 subType_) {
hookType = hookType_;
SUB_TYPE = subType_;
}
modifier onlyLastCaller() {
if (msg.sender != lastCaller) revert UNAUTHORIZED_CALLER();
_;
}
/*//////////////////////////////////////////////////////////////
EXECUTION SECURITY
//////////////////////////////////////////////////////////////*/
/// @inheritdoc ISuperHook
function setExecutionContext(address caller) external {
_createExecutionContext(caller);
lastCaller = msg.sender;
}
/// @dev Standard build pattern - MUST include preExecute first, postExecute last
/// @inheritdoc ISuperHook
function build(
address prevHook,
address account,
bytes calldata hookData
)
external
view
virtual
returns (Execution[] memory executions)
{
// Get hook-specific executions
Execution[] memory hookExecutions = _buildHookExecutions(prevHook, account, hookData);
// Always include pre + hook + post
executions = new Execution[](hookExecutions.length + 2);
// FIRST: preExecute
executions[0] = Execution({
target: address(this),
value: 0,
callData: abi.encodeCall(this.preExecute, (prevHook, account, hookData))
});
// MIDDLE: hook-specific operations
for (uint256 i = 0; i < hookExecutions.length; i++) {
executions[i + 1] = hookExecutions[i];
}
// LAST: postExecute
executions[executions.length - 1] = Execution({
target: address(this),
value: 0,
callData: abi.encodeCall(this.postExecute, (prevHook, account, hookData))
});
}
/// @inheritdoc ISuperHook
function preExecute(address prevHook, address account, bytes calldata data) external {
if (msg.sender != account) revert UNAUTHORIZED_CALLER();
uint256 context = _getCurrentExecutionContext(account);
if (_getPreExecuteMutex(context)) revert PRE_EXECUTE_ALREADY_CALLED();
_setPreExecuteMutex(context, true);
_preExecute(prevHook, account, data);
}
/// @inheritdoc ISuperHook
function postExecute(address prevHook, address account, bytes calldata data) external {
if (msg.sender != account) revert UNAUTHORIZED_CALLER();
uint256 context = _getCurrentExecutionContext(account);
if (_getPostExecuteMutex(context)) revert POST_EXECUTE_ALREADY_CALLED();
_setPostExecuteMutex(context, true);
_postExecute(prevHook, account, data);
}
/// @inheritdoc ISuperHookSetter
function setOutAmount(uint256 _outAmount, address caller) external {
uint256 context = _getCurrentExecutionContext(caller);
if (_getPreExecuteMutex(context) || _getPostExecuteMutex(context)) {
revert CANNOT_SET_OUT_AMOUNT();
}
bytes32 key = _makeKey(context, OUT_AMOUNT_OFFSET);
assembly ("memory-safe") {
tstore(key, _outAmount)
}
}
function getOutAmount(address caller) public view returns (uint256) {
return _getOutAmount(_getCurrentExecutionContext(caller));
}
function getOutToken(address caller) public view returns (address) {
return _getOutToken(_getCurrentExecutionContext(caller));
}
/// @inheritdoc ISuperHook
function resetExecutionState(address caller) external onlyLastCaller {
uint256 context = _getCurrentExecutionContext(caller);
if (!_getPreExecuteMutex(context) || !_getPostExecuteMutex(context)) {
revert INCOMPLETE_HOOK_EXECUTION();
}
_clearExecutionState(context);
}
/*//////////////////////////////////////////////////////////////
VIEW METHODS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc ISuperHook
function subtype() external view returns (bytes32) {
return SUB_TYPE;
}
/// @inheritdoc ISuperHookInspector
function inspect(bytes calldata) external view virtual returns (bytes memory) { }
/// @inheritdoc IERC165
/// @dev Hooks that implement ISuperHookInflowOutflow/ISuperHookOutflow override
/// _supportsSizingInterface() to return true, which enables three-state detection:
/// S1: supportsInterface(ISuperHookInflowOutflow) == true → hook has sizing interface
/// S2: same as S1 but amountRoles(data).length == 0 → authoritatively sizeless
/// S3: supportsInterface(ISuperHookInflowOutflow) == false → legacy, no sizing interface
function supportsInterface(bytes4 interfaceId) external view virtual override returns (bool) {
if (
interfaceId == type(ISuperHookInflowOutflow).interfaceId
|| interfaceId == type(ISuperHookOutflow).interfaceId
) {
return _supportsSizingInterface();
}
return interfaceId == type(IERC165).interfaceId || interfaceId == type(ISuperHook).interfaceId
|| interfaceId == type(ISuperHookResult).interfaceId
|| interfaceId == type(ISuperHookInspector).interfaceId;
}
/// @dev Override to return true in hooks that implement ISuperHookInflowOutflow/ISuperHookOutflow
function _supportsSizingInterface() internal pure virtual returns (bool) {
return false;
}
/*//////////////////////////////////////////////////////////////
INTERNAL METHODS
//////////////////////////////////////////////////////////////*/
/// @notice Internal implementation of build
/// @dev Abstract function to be implemented by derived hooks
/// Called during build to generate hook-specific execution sequences
/// @param prevHook The previous hook in the chain, or address(0) if first hook
/// @param account The account that operations will be performed for
/// @param data Hook-specific parameters and configuration data
/// @return executions Array of execution objects containing target, value, and callData
function _buildHookExecutions(
address prevHook,
address account,
bytes calldata data
)
internal
view
virtual
returns (Execution[] memory executions);
/// @notice Internal implementation of preExecute
/// @dev Default behavior for PASSTHROUGH hooks: auto-forward prevHook's outAmount + outToken.
/// TRANSFORM and SOURCE hooks override this entirely.
/// @param prevHook The previous hook in the chain, or address(0) if first hook
/// @param account The account that operations will be performed for
function _preExecute(address prevHook, address account, bytes calldata) internal virtual {
if (_pipeMode() == PipeMode.PASSTHROUGH && prevHook != address(0)) {
_setOutAmount(ISuperHookResult(prevHook).getOutAmount(account), account);
_setOutToken(ISuperHookResult(prevHook).getOutToken(account), account);
}
}
/// @notice Internal implementation of postExecute
/// @dev Abstract function to be implemented by derived hooks
/// Called after execution to finalize the hook's state and set output values
/// Typically calculates final results and sets outAmount, usedShares, etc.
/// May perform additional validations on execution results
/// @param prevHook The previous hook in the chain, or address(0) if first hook
/// @param account The account operations were performed for
/// @param data Hook-specific parameters and configuration data
function _postExecute(address prevHook, address account, bytes calldata data) internal virtual { }
/// @notice Decodes a boolean value from a byte array at the specified offset
/// @dev Helper function for extracting boolean values from packed data
/// Used when parsing hook-specific data parameters
/// @param data The byte array containing the encoded data
/// @param offset The position in the array to read from
/// @return The decoded boolean value (true if byte is non-zero)
function _decodeBool(bytes memory data, uint256 offset) internal pure returns (bool) {
return data[offset] != 0;
}
/// @notice Replaces an amount value within a byte array at the specified offset
/// @dev Used to modify hook calldata for amount adjustments without full re-encoding
/// Particularly useful for modifying amounts in multi-hook execution chains
/// Directly modifies the bytes in-place for gas efficiency
/// @param data The original byte array containing encoded calldata
/// @param amount The new amount value to insert
/// @param offset The position in the array where the amount starts
/// @return The modified byte array with the replaced amount
function _replaceCalldataAmount(
bytes memory data,
uint256 amount,
uint256 offset
)
internal
pure
returns (bytes memory)
{
bytes memory newAmountEncoded = abi.encodePacked(amount);
for (uint256 i; i < 32; ++i) {
data[offset + i] = newAmountEncoded[i];
}
return data;
}
/// @notice Declares the pipe semantics for this hook
/// @dev Override to return PASSTHROUGH for side-effect-only hooks.
/// Default: TRANSFORM. Inlined by the compiler (pure virtual).
function _pipeMode() internal pure virtual returns (PipeMode) {
return PipeMode.TRANSFORM;
}
/// @notice Sets the output token address for this hook execution
/// @param token The output token address
/// @param caller The caller address for context identification
function _setOutToken(address token, address caller) internal {
uint256 context = _getCurrentExecutionContext(caller);
bytes32 key = _makeKey(context, OUT_TOKEN_OFFSET);
assembly ("memory-safe") {
tstore(key, token)
}
}
function _makeAccountContextKey(address account) private pure returns (bytes32) {
return keccak256(abi.encodePacked(ACCOUNT_CONTEXT_STORAGE, account));
}
function _createExecutionContext(address caller) private returns (uint256) {
// Always increment nonce for new execution context
executionNonce++;
bytes32 key = _makeAccountContextKey(caller);
// Store this context for the current caller
uint256 currentNonce = executionNonce; // Load into local variable for assembly
assembly ("memory-safe") {
tstore(key, currentNonce)
}
return executionNonce;
}
function _getCurrentExecutionContext(address caller) private view returns (uint256 context) {
bytes32 key = _makeAccountContextKey(caller);
assembly ("memory-safe") {
context := tload(key)
}
}
function _makeKey(uint256 context, uint256 offset) private pure returns (bytes32) {
return keccak256(abi.encodePacked(HOOK_EXECUTION_STORAGE, context, offset));
}
function _getOutAmount(uint256 context) private view returns (uint256 value) {
bytes32 key = _makeKey(context, OUT_AMOUNT_OFFSET);
assembly ("memory-safe") {
value := tload(key)
}
}
function _getOutToken(uint256 context) private view returns (address value) {
bytes32 key = _makeKey(context, OUT_TOKEN_OFFSET);
assembly ("memory-safe") {
value := tload(key)
}
}
function _setOutAmount(uint256 value, address caller) internal {
uint256 context = _getCurrentExecutionContext(caller);
bytes32 key = _makeKey(context, OUT_AMOUNT_OFFSET);
assembly ("memory-safe") {
tstore(key, value)
}
}
function _getPreExecuteMutex(uint256 context) private view returns (bool value) {
bytes32 key = _makeKey(context, PRE_EXECUTE_MUTEX_OFFSET);
assembly ("memory-safe") {
value := tload(key)
}
}
function _setPreExecuteMutex(uint256 context, bool value) private {
bytes32 key = _makeKey(context, PRE_EXECUTE_MUTEX_OFFSET);
assembly ("memory-safe") {
tstore(key, value)
}
}
function _getPostExecuteMutex(uint256 context) private view returns (bool value) {
bytes32 key = _makeKey(context, POST_EXECUTE_MUTEX_OFFSET);
assembly ("memory-safe") {
value := tload(key)
}
}
function _setPostExecuteMutex(uint256 context, bool value) private {
bytes32 key = _makeKey(context, POST_EXECUTE_MUTEX_OFFSET);
assembly ("memory-safe") {
tstore(key, value)
}
}
function _clearExecutionState(uint256 context) private {
_setPreExecuteMutex(context, false);
_setPostExecuteMutex(context, false);
}
}
src/hooks/loan/BaseLoanHook.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
// external
import { BytesLib } from "../../vendor/BytesLib.sol";
import { IERC20 } from "@openzeppelin/contracts/interfaces/IERC20.sol";
// Superform
import { BaseHook } from "../BaseHook.sol";
import {
ISuperHookLoans,
ISuperHookContextAware,
ISuperHookInflowOutflow,
ISuperHookOutflow
} from "../../interfaces/ISuperHook.sol";
import { HookDataDecoder } from "../../libraries/HookDataDecoder.sol";
/// @title BaseLoanHook
/// @author Superform Labs
abstract contract BaseLoanHook is BaseHook, ISuperHookLoans, ISuperHookInflowOutflow, ISuperHookOutflow {
using HookDataDecoder for bytes;
uint256 internal constant AMOUNT_POSITION = 132;
uint256 internal constant USE_PREV_HOOK_AMOUNT_POSITION = 196;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(bytes32 hookSubtype_) BaseHook(HookType.NONACCOUNTING, hookSubtype_) { }
/*//////////////////////////////////////////////////////////////
EXTERNAL METHODS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc ISuperHookContextAware
function decodeUsePrevHookAmount(bytes memory data) external pure virtual returns (bool) {
return _decodeBool(data, USE_PREV_HOOK_AMOUNT_POSITION);
}
/// @inheritdoc ISuperHookInflowOutflow
function decodeAmounts(bytes memory data) external pure virtual override returns (uint256[] memory amounts) {
amounts = new uint256[](1);
amounts[0] = _decodeAmount(data);
}
/// @inheritdoc ISuperHookInflowOutflow
function amountRoles(bytes memory)
external
pure
virtual
override
returns (ISuperHookInflowOutflow.AmountMeta[] memory meta)
{
meta = new ISuperHookInflowOutflow.AmountMeta[](1);
meta[0] = ISuperHookInflowOutflow.AmountMeta(ISuperHookInflowOutflow.Direction.IN, ISuperHookInflowOutflow.Denomination.TOKEN);
}
/// @inheritdoc ISuperHookOutflow
function replaceCalldataAmounts(
bytes memory data,
uint256[] memory amounts
)
external
pure
virtual
override
returns (bytes memory)
{
if (amounts.length != 1) revert INVALID_AMOUNTS_LENGTH();
return _replaceCalldataAmount(data, amounts[0], AMOUNT_POSITION);
}
/*//////////////////////////////////////////////////////////////
PUBLIC METHODS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc ISuperHookLoans
function getLoanTokenAddress(bytes memory data) public pure returns (address) {
return BytesLib.toAddress(data, 52);
}
/// @inheritdoc ISuperHookLoans
function getCollateralTokenAddress(bytes memory data) public pure returns (address) {
return BytesLib.toAddress(data, 72);
}
/// @inheritdoc ISuperHookLoans
function getCollateralTokenBalance(address account, bytes memory data) public view returns (uint256) {
address collateralToken = BytesLib.toAddress(data, 72);
return IERC20(collateralToken).balanceOf(account);
}
/// @inheritdoc ISuperHookLoans
function getLoanTokenBalance(address account, bytes memory data) public view returns (uint256) {
address loanToken = BytesLib.toAddress(data, 52);
return IERC20(loanToken).balanceOf(account);
}
/// @dev BaseLoanHook implements ISuperHookInflowOutflow + ISuperHookOutflow
function _supportsSizingInterface() internal pure override returns (bool) {
return true;
}
/*//////////////////////////////////////////////////////////////
INTERNAL METHODS
//////////////////////////////////////////////////////////////*/
function _decodeAmount(bytes memory data) internal pure returns (uint256) {
return BytesLib.toUint256(data, AMOUNT_POSITION);
}
}
src/hooks/loan/aave-v4/BaseAaveV4LoanHook.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
// external
import { BytesLib } from "../../../vendor/BytesLib.sol";
import { IAaveV4Spoke } from "../../../vendor/aave-v4/IAaveV4Spoke.sol";
// Superform
import { BaseLoanHook } from "../BaseLoanHook.sol";
import { HookDataDecoder } from "../../../libraries/HookDataDecoder.sol";
import { AaveV4ReserveKey } from "../../../libraries/AaveV4ReserveKey.sol";
import { ISuperHookInflowOutflow, ISuperHookOutflow } from "../../../interfaces/ISuperHook.sol";
/// @title BaseAaveV4LoanHook
/// @author Superform Labs
/// @notice Base abstract hook for Aave V4 Hub-and-Spoke lending protocol integrations
/// @dev All Aave V4 hooks inherit from this contract. Unlike Morpho hooks, the Spoke address
/// comes from calldata rather than the constructor, enabling a single hook deployment to
/// work with any Aave V4 Spoke (Core, e-Mode, Isolation, RWA, Vault Spokes).
/// HEADER IDENTITY (SUP-21143): `yieldSource` (offset 32) MUST equal
/// `AaveV4ReserveKey.computeReserveKey(spoke, primaryReserveId)` (supply reserve for Supply /
/// Withdraw / SupplyAndBorrow / RepayAndWithdraw, borrow reserve for Borrow / Repay); every decoder
/// pins it (`AaveV4ReserveKey.RESERVE_KEY_MISMATCH`, on build(), preExecute() and inspect()) and every
/// `inspect()` packs it first; a zero oracle id is refused (ORACLE_ID_NOT_VALID). Flag-setting supplies refuse
/// an idle position (RESERVE_HAS_IDLE_POSITION) and withdraw legs refuse an un-flagged one
/// (RESERVE_NOT_COLLATERAL). The Spoke (offset 92) stays the only call target. `yieldSourceOracleId` (offset 0)
/// is identity only (LOAN is NONACCOUNTING).
/// SIZING APIs ARE TRANSFORMATION-ONLY (V1): `decodeAmounts` / `replaceCalldataAmounts` /
/// `decodeUsePrevHookAmount` read or rewrite the amount word(s) and do not run the header decoder
/// (unlike the V2 hooks, whose sizing views run the strict decoder). A template that sizes here has NOT
/// passed identity validation — it must also pass inspect() / build(). The V1 decoders keep their
/// inherited minimum-length and nonzero-byte-is-true boolean rules; V2 is exact-length / canonical-bool.
/// V1 hooks are not used for new roots; their bytecode changed with this bind (accepted).
/// SECURITY INVARIANT: onBehalfOf is always hardcoded to `account` — never arbitrary.
abstract contract BaseAaveV4LoanHook is BaseLoanHook {
using HookDataDecoder for bytes;
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice Aave V4 data layout byte offsets
uint256 internal constant LOAN_TOKEN_OFFSET = 52;
uint256 internal constant COLLATERAL_TOKEN_OFFSET = 72;
uint256 internal constant SPOKE_OFFSET = 92;
uint256 internal constant SUPPLY_RESERVE_ID_OFFSET = 112;
uint256 internal constant BORROW_RESERVE_ID_OFFSET = 144;
uint256 internal constant AAVE_V4_AMOUNT_OFFSET = 176;
uint256 internal constant AAVE_V4_USE_PREV_HOOK_AMOUNT_POSITION = 208;
/// @dev Byte 209 is used by TWO DIFFERENT data layouts (never both at once):
/// - SupplyAndBorrow: uint256 borrowAmount starts at 209 (no isFullRepayment field)
/// - RepayAndWithdraw: bool isFullRepayment at 209, then uint256 withdrawAmount at 210
uint256 internal constant IS_FULL_REPAYMENT_OFFSET = 209;
uint256 internal constant BORROW_AMOUNT_OFFSET = 209;
uint256 internal constant WITHDRAW_AMOUNT_OFFSET = 210;
/// @notice Minimum data lengths for validation
uint256 internal constant SUPPLY_MIN_DATA_LENGTH = 209;
uint256 internal constant WITHDRAW_MIN_DATA_LENGTH = 209;
uint256 internal constant BORROW_MIN_DATA_LENGTH = 209;
uint256 internal constant REPAY_MIN_DATA_LENGTH = 210;
uint256 internal constant SUPPLY_AND_BORROW_MIN_DATA_LENGTH = 241;
uint256 internal constant REPAY_AND_WITHDRAW_MIN_DATA_LENGTH = 242;
/*//////////////////////////////////////////////////////////////
STRUCTS
//////////////////////////////////////////////////////////////*/
struct SupplyHookLocalVars {
address reserveKey;
address loanToken;
address collateralToken;
address spoke;
uint256 supplyReserveId;
uint256 borrowReserveId; // identity only
uint256 amount;
bool usePrevHookAmount;
}
struct WithdrawHookLocalVars {
address reserveKey;
address loanToken;
address collateralToken;
address spoke;
uint256 supplyReserveId;
uint256 borrowReserveId; // identity only
uint256 amount;
bool usePrevHookAmount;
}
struct BorrowHookLocalVars {
address reserveKey;
address loanToken;
address collateralToken;
address spoke;
uint256 supplyReserveId; // identity only
uint256 borrowReserveId;
uint256 amount;
bool usePrevHookAmount;
}
struct RepayHookLocalVars {
address reserveKey;
address loanToken;
address collateralToken;
address spoke;
uint256 supplyReserveId; // identity only
uint256 borrowReserveId;
uint256 amount;
bool usePrevHookAmount;
bool isFullRepayment;
}
struct SupplyAndBorrowHookLocalVars {
address reserveKey;
address loanToken;
address collateralToken;
address spoke;
uint256 supplyReserveId;
uint256 borrowReserveId;
uint256 amount;
bool usePrevHookAmount;
uint256 borrowAmount;
}
struct RepayAndWithdrawHookLocalVars {
address reserveKey;
address loanToken;
address collateralToken;
address spoke;
uint256 supplyReserveId;
uint256 borrowReserveId;
uint256 amount;
bool usePrevHookAmount;
bool isFullRepayment;
uint256 withdrawAmount;
}
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when hook calldata is shorter than the required minimum
error INVALID_DATA_LENGTH();
/// @notice Thrown when a supply that would flag the reserve as collateral targets a reserve already carrying an
/// un-flagged (idle MONEY_MARKET, ledger-tracked) position
error RESERVE_HAS_IDLE_POSITION();
/// @notice Thrown when the header `yieldSourceOracleId` (offset 0) is zero
error ORACLE_ID_NOT_VALID();
/// @notice Thrown when a withdraw leg (Withdraw, RepayAndWithdraw) targets a reserve that is not enabled as
/// collateral for the account — an un-flagged position is the idle MONEY_MARKET side's (ledger-tracked)
error RESERVE_NOT_COLLATERAL();
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice No constructor args — Spoke address comes from calldata
/// @param hookSubtype_ Hook subtype identifier (LOAN or LOAN_REPAY)
constructor(bytes32 hookSubtype_) BaseLoanHook(hookSubtype_) { }
/*//////////////////////////////////////////////////////////////
EXTERNAL METHODS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc BaseLoanHook
/// @dev Overrides parent to use Aave V4 offset (156) instead of Morpho offset (144)
function decodeUsePrevHookAmount(bytes memory data) external pure override returns (bool) {
return _decodeBool(data, AAVE_V4_USE_PREV_HOOK_AMOUNT_POSITION);
}
/// @inheritdoc ISuperHookInflowOutflow
/// @dev Transformation-only: reads the amount word, does not authenticate the header (inspect / build do)
function decodeAmounts(bytes memory data) external pure virtual override returns (uint256[] memory amounts) {
amounts = new uint256[](1);
amounts[0] = BytesLib.toUint256(data, AAVE_V4_AMOUNT_OFFSET);
}
/// @inheritdoc ISuperHookInflowOutflow
function amountRoles(bytes memory)
external
pure
virtual
override
returns (ISuperHookInflowOutflow.AmountMeta[] memory meta)
{
meta = new ISuperHookInflowOutflow.AmountMeta[](1);
meta[0] = ISuperHookInflowOutflow.AmountMeta(ISuperHookInflowOutflow.Direction.IN, ISuperHookInflowOutflow.Denomination.TOKEN);
}
/// @inheritdoc ISuperHookOutflow
/// @dev Transformation-only: rewrites the amount word and returns the rest of the payload — header included —
/// untouched and unchecked; a mis-keyed template still fails at inspect / build
function replaceCalldataAmounts(
bytes memory data,
uint256[] memory amounts
)
external
pure
virtual
override
returns (bytes memory)
{
if (amounts.length != 1) revert INVALID_AMOUNTS_LENGTH();
return _replaceCalldataAmount(data, amounts[0], AAVE_V4_AMOUNT_OFFSET);
}
/*//////////////////////////////////////////////////////////////
INTERNAL METHODS
//////////////////////////////////////////////////////////////*/
/// @dev Mode guard for the V1 flag-setting supplies (Supply, SupplyAndBorrow): a supplied position that is NOT
/// flagged as collateral belongs to the idle MONEY_MARKET side (ledger-tracked) and is refused
/// (RESERVE_HAS_IDLE_POSITION) on build() and preExecute(); a fresh or already-flagged reserve passes.
/// @param spoke The calldata Spoke
/// @param supplyReserveId The reserve the supply targets
/// @param account The executing smart account
function _requireNoIdlePosition(address spoke, uint256 supplyReserveId, address account) internal view {
(bool flagged,) = IAaveV4Spoke(spoke).getUserReserveStatus(supplyReserveId, account);
if (!flagged && IAaveV4Spoke(spoke).getUserSuppliedAssets(supplyReserveId, account) != 0) {
revert RESERVE_HAS_IDLE_POSITION();
}
}
/// @dev Gate for the V1 withdraw legs (Withdraw, RepayAndWithdraw), on build() and preExecute(): the account must
/// hold a position on the supply reserve (empty → AMOUNT_NOT_VALID) and it must be flagged as collateral
/// (RESERVE_NOT_COLLATERAL otherwise) — a V1 withdraw can never pay an idle, ledger-tracked position out.
/// @param spoke The calldata Spoke
/// @param supplyReserveId The reserve the withdraw targets
/// @param account The executing smart account
/// @return supplied The account's live supplied assets on the supply reserve
function _requireCollateralPosition(address spoke, uint256 supplyReserveId, address account)
internal
view
returns (uint256 supplied)
{
supplied = IAaveV4Spoke(spoke).getUserSuppliedAssets(supplyReserveId, account);
if (supplied == 0) revert AMOUNT_NOT_VALID();
(bool flagged,) = IAaveV4Spoke(spoke).getUserReserveStatus(supplyReserveId, account);
if (!flagged) revert RESERVE_NOT_COLLATERAL();
}
/// @dev Inspector payload shared by every V1 hook, same 144-byte shape as the V2 family: reserve key
/// FIRST, then spoke, loan token, collateral token and both reserve ids
function _inspectAaveV4(
address reserveKey,
address spoke,
address loanToken,
address collateralToken,
uint256 supplyReserveId,
uint256 borrowReserveId
)
internal
pure
returns (bytes memory)
{
return abi.encodePacked(reserveKey, spoke, loanToken, collateralToken, supplyReserveId, borrowReserveId);
}
/// @dev Decodes supply hook data
function _decodeSupplyHookData(bytes memory data) internal pure returns (SupplyHookLocalVars memory vars) {
if (data.length < SUPPLY_MIN_DATA_LENGTH) revert INVALID_DATA_LENGTH();
if (data.extractYieldSourceOracleId() == bytes32(0)) revert ORACLE_ID_NOT_VALID();
vars.reserveKey = data.extractYieldSource();
vars.loanToken = BytesLib.toAddress(data, LOAN_TOKEN_OFFSET);
vars.collateralToken = BytesLib.toAddress(data, COLLATERAL_TOKEN_OFFSET);
vars.spoke = BytesLib.toAddress(data, SPOKE_OFFSET);
if (
vars.reserveKey == address(0) || vars.loanToken == address(0) || vars.collateralToken == address(0)
|| vars.spoke == address(0)
) {
revert ADDRESS_NOT_VALID();
}
vars.supplyReserveId = BytesLib.toUint256(data, SUPPLY_RESERVE_ID_OFFSET);
vars.borrowReserveId = BytesLib.toUint256(data, BORROW_RESERVE_ID_OFFSET);
vars.amount = BytesLib.toUint256(data, AAVE_V4_AMOUNT_OFFSET);
vars.usePrevHookAmount = _decodeBool(data, AAVE_V4_USE_PREV_HOOK_AMOUNT_POSITION);
AaveV4ReserveKey.requireHeaderKey(vars.reserveKey, vars.spoke, vars.supplyReserveId);
}
/// @dev Decodes withdraw hook data (same layout as supply)
function _decodeWithdrawHookData(bytes memory data) internal pure returns (WithdrawHookLocalVars memory vars) {
if (data.length < WITHDRAW_MIN_DATA_LENGTH) revert INVALID_DATA_LENGTH();
if (data.extractYieldSourceOracleId() == bytes32(0)) revert ORACLE_ID_NOT_VALID();
vars.reserveKey = data.extractYieldSource();
vars.loanToken = BytesLib.toAddress(data, LOAN_TOKEN_OFFSET);
vars.collateralToken = BytesLib.toAddress(data, COLLATERAL_TOKEN_OFFSET);
vars.spoke = BytesLib.toAddress(data, SPOKE_OFFSET);
if (
vars.reserveKey == address(0) || vars.loanToken == address(0) || vars.collateralToken == address(0)
|| vars.spoke == address(0)
) {
revert ADDRESS_NOT_VALID();
}
vars.supplyReserveId = BytesLib.toUint256(data, SUPPLY_RESERVE_ID_OFFSET);
vars.borrowReserveId = BytesLib.toUint256(data, BORROW_RESERVE_ID_OFFSET);
vars.amount = BytesLib.toUint256(data, AAVE_V4_AMOUNT_OFFSET);
vars.usePrevHookAmount = _decodeBool(data, AAVE_V4_USE_PREV_HOOK_AMOUNT_POSITION);
AaveV4ReserveKey.requireHeaderKey(vars.reserveKey, vars.spoke, vars.supplyReserveId);
}
/// @dev Decodes borrow hook data — uses borrowReserveId (not supplyReserveId)
function _decodeBorrowHookData(bytes memory data) internal pure returns (BorrowHookLocalVars memory vars) {
if (data.length < BORROW_MIN_DATA_LENGTH) revert INVALID_DATA_LENGTH();
if (data.extractYieldSourceOracleId() == bytes32(0)) revert ORACLE_ID_NOT_VALID();
vars.reserveKey = data.extractYieldSource();
vars.loanToken = BytesLib.toAddress(data, LOAN_TOKEN_OFFSET);
vars.collateralToken = BytesLib.toAddress(data, COLLATERAL_TOKEN_OFFSET);
vars.spoke = BytesLib.toAddress(data, SPOKE_OFFSET);
if (
vars.reserveKey == address(0) || vars.loanToken == address(0) || vars.collateralToken == address(0)
|| vars.spoke == address(0)
) {
revert ADDRESS_NOT_VALID();
}
vars.supplyReserveId = BytesLib.toUint256(data, SUPPLY_RESERVE_ID_OFFSET);
vars.borrowReserveId = BytesLib.toUint256(data, BORROW_RESERVE_ID_OFFSET);
vars.amount = BytesLib.toUint256(data, AAVE_V4_AMOUNT_OFFSET);
vars.usePrevHookAmount = _decodeBool(data, AAVE_V4_USE_PREV_HOOK_AMOUNT_POSITION);
AaveV4ReserveKey.requireHeaderKey(vars.reserveKey, vars.spoke, vars.borrowReserveId);
}
/// @dev Decodes repay hook data — uses borrowReserveId + isFullRepayment
function _decodeRepayHookData(bytes memory data) internal pure returns (RepayHookLocalVars memory vars) {
if (data.length < REPAY_MIN_DATA_LENGTH) revert INVALID_DATA_LENGTH();
if (data.extractYieldSourceOracleId() == bytes32(0)) revert ORACLE_ID_NOT_VALID();
vars.reserveKey = data.extractYieldSource();
vars.loanToken = BytesLib.toAddress(data, LOAN_TOKEN_OFFSET);
vars.collateralToken = BytesLib.toAddress(data, COLLATERAL_TOKEN_OFFSET);
vars.spoke = BytesLib.toAddress(data, SPOKE_OFFSET);
if (
vars.reserveKey == address(0) || vars.loanToken == address(0) || vars.collateralToken == address(0)
|| vars.spoke == address(0)
) {
revert ADDRESS_NOT_VALID();
}
vars.supplyReserveId = BytesLib.toUint256(data, SUPPLY_RESERVE_ID_OFFSET);
vars.borrowReserveId = BytesLib.toUint256(data, BORROW_RESERVE_ID_OFFSET);
vars.amount = BytesLib.toUint256(data, AAVE_V4_AMOUNT_OFFSET);
vars.usePrevHookAmount = _decodeBool(data, AAVE_V4_USE_PREV_HOOK_AMOUNT_POSITION);
vars.isFullRepayment = _decodeBool(data, IS_FULL_REPAYMENT_OFFSET);
AaveV4ReserveKey.requireHeaderKey(vars.reserveKey, vars.spoke, vars.borrowReserveId);
}
/// @dev Decodes supply-and-borrow hook data — uses BOTH reserveIds + borrowAmount at position 157
function _decodeSupplyAndBorrowHookData(bytes memory data)
internal
pure
returns (SupplyAndBorrowHookLocalVars memory vars)
{
if (data.length < SUPPLY_AND_BORROW_MIN_DATA_LENGTH) revert INVALID_DATA_LENGTH();
if (data.extractYieldSourceOracleId() == bytes32(0)) revert ORACLE_ID_NOT_VALID();
vars.reserveKey = data.extractYieldSource();
vars.loanToken = BytesLib.toAddress(data, LOAN_TOKEN_OFFSET);
vars.collateralToken = BytesLib.toAddress(data, COLLATERAL_TOKEN_OFFSET);
vars.spoke = BytesLib.toAddress(data, SPOKE_OFFSET);
if (
vars.reserveKey == address(0) || vars.loanToken == address(0) || vars.collateralToken == address(0)
|| vars.spoke == address(0)
) {
revert ADDRESS_NOT_VALID();
}
vars.supplyReserveId = BytesLib.toUint256(data, SUPPLY_RESERVE_ID_OFFSET);
vars.borrowReserveId = BytesLib.toUint256(data, BORROW_RESERVE_ID_OFFSET);
vars.amount = BytesLib.toUint256(data, AAVE_V4_AMOUNT_OFFSET);
vars.usePrevHookAmount = _decodeBool(data, AAVE_V4_USE_PREV_HOOK_AMOUNT_POSITION);
vars.borrowAmount = BytesLib.toUint256(data, BORROW_AMOUNT_OFFSET);
AaveV4ReserveKey.requireHeaderKey(vars.reserveKey, vars.spoke, vars.supplyReserveId);
}
/// @dev Decodes repay-and-withdraw hook data — uses BOTH reserveIds + isFullRepayment + withdrawAmount
function _decodeRepayAndWithdrawHookData(bytes memory data)
internal
pure
returns (RepayAndWithdrawHookLocalVars memory vars)
{
if (data.length < REPAY_AND_WITHDRAW_MIN_DATA_LENGTH) revert INVALID_DATA_LENGTH();
if (data.extractYieldSourceOracleId() == bytes32(0)) revert ORACLE_ID_NOT_VALID();
vars.reserveKey = data.extractYieldSource();
vars.loanToken = BytesLib.toAddress(data, LOAN_TOKEN_OFFSET);
vars.collateralToken = BytesLib.toAddress(data, COLLATERAL_TOKEN_OFFSET);
vars.spoke = BytesLib.toAddress(data, SPOKE_OFFSET);
if (
vars.reserveKey == address(0) || vars.loanToken == address(0) || vars.collateralToken == address(0)
|| vars.spoke == address(0)
) {
revert ADDRESS_NOT_VALID();
}
vars.supplyReserveId = BytesLib.toUint256(data, SUPPLY_RESERVE_ID_OFFSET);
vars.borrowReserveId = BytesLib.toUint256(data, BORROW_RESERVE_ID_OFFSET);
vars.amount = BytesLib.toUint256(data, AAVE_V4_AMOUNT_OFFSET);
vars.usePrevHookAmount = _decodeBool(data, AAVE_V4_USE_PREV_HOOK_AMOUNT_POSITION);
vars.isFullRepayment = _decodeBool(data, IS_FULL_REPAYMENT_OFFSET);
vars.withdrawAmount = BytesLib.toUint256(data, WITHDRAW_AMOUNT_OFFSET);
AaveV4ReserveKey.requireHeaderKey(vars.reserveKey, vars.spoke, vars.supplyReserveId);
}
}
src/interfaces/ISuperHook.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
// external
import { Execution } from "modulekit/accounts/erc7579/lib/ExecutionLib.sol";
/**
* @title SuperHook System
* @author Superform Labs
* @notice The hook system provides a modular and composable way to execute operations on assets
* @dev The hook system architecture consists of several interfaces that work together:
* - ISuperHook: The base interface all hooks implement, with lifecycle methods
* - ISuperHookResult: Provides execution results and output information
* - Specialized interfaces (ISuperHookOutflow, ISuperHookLoans, etc.) for specific behaviors
*
* Hooks are executed in sequence, where each hook can access the results from previous hooks.
* The three main types of hooks are:
* - NONACCOUNTING: Utility hooks that don't update the accounting system
* - INFLOW: Hooks that process deposits or additions to positions
* - OUTFLOW: Hooks that process withdrawals or reductions to positions
*/
interface ISuperLockableHook {
/// @notice The vault bank address used to lock SuperPositions
/// @dev Only relevant for cross-chain operations where positions are locked
/// @return The vault bank address, or address(0) if not applicable
function vaultBank() external view returns (address);
/// @notice The destination chain ID for cross-chain operations
/// @dev Used to identify the target chain for cross-chain position transfers
/// @return The destination chain ID, or 0 if not a cross-chain operation
function dstChainId() external view returns (uint256);
}
interface ISuperHookSetter {
/// @notice Sets the output amount for the hook
/// @dev Used for updating `outAmount` when fees were deducted
/// @param outAmount The amount of tokens processed by the hook
/// @param caller The caller address for context identification
function setOutAmount(uint256 outAmount, address caller) external;
}
/// @title ISuperHookInspector
/// @author Superform Labs
/// @notice Interface for the SuperHookInspector contract that manages hook inspection
interface ISuperHookInspector {
/// @notice Inspect the hook
/// @param data The hook data to inspect
/// @return argsEncoded The arguments of the hook encoded
function inspect(bytes calldata data) external view returns (bytes memory argsEncoded);
}
/// @title ISuperHookResult
/// @author Superform Labs
/// @notice Interface that exposes the result of a hook execution
/// @dev All hooks must implement this interface to provide standardized access to execution results.
/// These results are used by subsequent hooks in the execution chain and by the executor.
interface ISuperHookResult {
/*//////////////////////////////////////////////////////////////
VIEW METHODS
//////////////////////////////////////////////////////////////*/
/// @notice The type of hook
/// @dev Used to determine how accounting should process this hook's results
/// @return The hook type (NONACCOUNTING, INFLOW, or OUTFLOW)
function hookType() external view returns (ISuperHook.HookType);
/// @notice The SuperPosition (SP) token associated with this hook
/// @dev For vault hooks, this would be the tokenized position representing shares
/// @return The address of the SP token, or address(0) if not applicable
function spToken() external view returns (address);
/// @notice The underlying asset token being processed
/// @dev For most hooks, this is the actual token being deposited or withdrawn
/// @return The address of the asset token, or address(0) for native assets
function asset() external view returns (address);
/// @notice The amount of tokens processed by the hook in a given caller context, subject to fees after update
/// @dev This is the primary output value used by subsequent hooks
/// @param caller The caller address for context identification
/// @return The amount of tokens (assets or shares) processed
function getOutAmount(address caller) external view returns (uint256);
/// @notice The output token address produced by the hook in a given caller context
/// @dev Used by subsequent hooks to determine what token the previous hook produced
/// PASSTHROUGH hooks auto-forward the previous hook's outToken
/// TRANSFORM hooks set this to their specific output token
/// @param caller The caller address for context identification
/// @return The address of the output token, or address(0) if not set
function getOutToken(address caller) external view returns (address);
}
/// @title ISuperHookContextAware
/// @author Superform Labs
/// @notice Interface for hooks that can use previous hook results in their execution
/// @dev Enables contextual awareness and data flow between hooks in a chain
interface ISuperHookContextAware {
/// @notice Determines if this hook should use the amount from the previous hook
/// @dev Used to create hook chains where output from one hook becomes input to the next
/// @param data The hook-specific data containing configuration
/// @return True if the hook should use the previous hook's output amount
function decodeUsePrevHookAmount(bytes memory data) external pure returns (bool);
}
/// @title ISuperHookInflowOutflow
/// @author Superform Labs
/// @notice Interface for hooks that handle both inflows and outflows
/// @dev Provides standardized amount extraction for both deposit and withdrawal operations
interface ISuperHookInflowOutflow {
/// @notice Direction of an amount slot
/// @dev IN = primary amount the OMS sizes (intent amount)
/// OUT = secondary derived amount (e.g. borrow amount in supply-and-borrow)
enum Direction {
IN,
OUT
}
/// @notice Denomination of an amount slot
/// @dev TOKEN = raw ERC-20 amount (swaps, bridges, transfers, loan operations)
/// ASSETS = underlying asset amount (vault deposits, ERC-4626/7540 withdraw)
/// SHARES = vault share amount (vault redeems, ERC-4626/7540 requestRedeem)
enum Denomination {
TOKEN,
ASSETS,
SHARES
}
/// @notice Per-slot metadata: direction + denomination
/// @dev Aligned 1:1 with the array from decodeAmounts.
/// A slot belongs in decodeAmounts/amountRoles iff the OMS can rewrite it
/// at execution time without invalidating any commitment (signature or proof)
/// embedded in the same data.
struct AmountMeta {
Direction dir;
Denomination denom;
}
/// @notice Extracts all amounts from the hook's calldata
/// @dev Used to determine the quantity of assets or shares being processed
/// @param data The hook-specific calldata
/// @return amounts Array of amounts (length 1 for single-amount hooks, 2+ for compound hooks)
function decodeAmounts(bytes memory data) external pure returns (uint256[] memory amounts);
/// @notice Returns per-slot metadata (direction + denomination) for each amount
/// @dev Must return an array of the same length as decodeAmounts(data).
/// Enables the OMS to know which slots to size (IN vs OUT) and in what
/// denomination (TOKEN vs ASSETS vs SHARES).
/// Takes data so variable-count hooks can return the correct number of slots.
/// @param data The hook-specific calldata (same as passed to decodeAmounts)
/// @return meta Array of AmountMeta structs aligned index-by-index with decodeAmounts
function amountRoles(bytes memory data) external pure returns (AmountMeta[] memory meta);
}
/// @title ISuperHookOutflow
/// @author Superform Labs
/// @notice Interface for hooks that specifically handle outflows (withdrawals)
/// @dev Provides additional functionality needed only for outflow operations
interface ISuperHookOutflow {
/// @notice Replace amounts in the calldata
/// @param data The data to replace amounts in
/// @param amounts The amounts to replace (must match length from decodeAmounts)
/// @return The data with replaced amounts
function replaceCalldataAmounts(
bytes memory data,
uint256[] memory amounts
)
external
pure
returns (bytes memory);
}
/// @title ISuperHookResultOutflow
/// @author Superform Labs
/// @notice Extended result interface for outflow hook operations
/// @dev Extends the base result interface with outflow-specific information
interface ISuperHookResultOutflow is ISuperHookResult {
/// @notice The amount of shares consumed during outflow processing
/// @dev Used for cost basis calculation in the accounting system
/// @return The amount of shares consumed from the user's position
function usedShares() external view returns (uint256);
}
/// @title ISuperHookLoans
/// @author Superform Labs
/// @notice Interface for hooks that interact with lending protocols
/// @dev Extends context awareness to enable loan operations within hook chains
interface ISuperHookLoans is ISuperHookContextAware {
/// @notice Gets the address of the token being borrowed
/// @dev Used to identify which asset is being borrowed from the lending protocol
/// @param data The hook-specific data containing loan information
/// @return The address of the borrowed token
function getLoanTokenAddress(bytes memory data) external pure returns (address);
/// @notice Gets the address of the token used as collateral
/// @dev Used to identify which asset is being used to secure the loan
/// @param data The hook-specific data containing collateral information
/// @return The address of the collateral token
function getCollateralTokenAddress(bytes memory data) external view returns (address);
/// @notice Gets the account's current ERC-20 wallet balance of the loan token
/// @dev Returns the plain wallet balance (not the outstanding debt on the lending protocol).
/// Hooks snapshot this before execution and measure the post-execution delta to report
/// actual loan tokens received (borrow) or spent (repay).
/// @param account The account to check the wallet balance for
/// @param data The hook-specific data containing the loan token address
/// @return The account's wallet balance of the loan token
function getLoanTokenBalance(address account, bytes memory data) external view returns (uint256);
/// @notice Gets the account's current ERC-20 wallet balance of the collateral token
/// @dev Returns the plain wallet balance (not the collateral posted on the lending protocol).
/// Hooks snapshot this before execution and measure the post-execution delta to report
/// actual collateral tokens spent (supply) or received (withdraw).
/// @param account The account to check the wallet balance for
/// @param data The hook-specific data containing the collateral token address
/// @return The account's wallet balance of the collateral token
function getCollateralTokenBalance(address account, bytes memory data) external view returns (uint256);
}
/// @title ISuperHookAsyncCancelations
/// @author Superform Labs
/// @notice Interface for hooks that can cancel asynchronous operations
/// @dev Used to handle cancellation of pending operations that haven't completed
interface ISuperHookAsyncCancelations {
/// @notice Types of cancellations that can be performed
/// @dev Distinguishes between different operation types that can be canceled
enum CancelationType {
NONE, // Not a cancelation hook
INFLOW, // Cancels a pending deposit operation
OUTFLOW // Cancels a pending withdrawal operation
}
/// @notice Identifies the type of async operation this hook can cancel
/// @dev Used to verify the hook is appropriate for the operation being canceled
/// @return asyncType The type of cancellation this hook performs
function isAsyncCancelHook() external pure returns (CancelationType asyncType);
}
/// @title ISuperHook
/// @author Superform Labs
/// @notice The core hook interface that all hooks must implement
/// @dev Defines the lifecycle methods and execution flow for the hook system
/// Hooks are executed in sequence with results passed between them
interface ISuperHook {
/*//////////////////////////////////////////////////////////////
ENUMS
//////////////////////////////////////////////////////////////*/
/// @notice Defines the possible types of hooks in the system
/// @dev Used to determine how the hook affects accounting and what operations it performs
enum HookType {
NONACCOUNTING, // Hook doesn't affect accounting (e.g., a swap or bridge)
INFLOW, // Hook processes deposits or positions being added
OUTFLOW // Hook processes withdrawals or positions being removed
}
/*//////////////////////////////////////////////////////////////
VIEW METHODS
//////////////////////////////////////////////////////////////*/
/// @notice Builds the execution array for the hook operation
/// @dev This is the core method where hooks define their on-chain interactions
/// The returned executions are a sequence of contract calls to perform
/// No state changes should occur in this method
/// @param prevHook The address of the previous hook in the chain, or address(0) if first
/// @param account The account to perform executions for (usually an ERC7579 account)
/// @param data The hook-specific parameters and configuration data
/// @return executions Array of Execution structs defining calls to make
function build(
address prevHook,
address account,
bytes calldata data
)
external
view
returns (Execution[] memory executions);
/*//////////////////////////////////////////////////////////////
PUBLIC METHODS
//////////////////////////////////////////////////////////////*/
/// @notice Prepares the hook for execution
/// @dev Called before the main execution, used to validate inputs and set execution context
/// This method may perform state changes to set up the hook's execution state
/// @param prevHook The address of the previous hook in the chain, or address(0) if first
/// @param account The account to perform operations for
/// @param data The hook-specific parameters and configuration data
function preExecute(address prevHook, address account, bytes memory data) external;
/// @notice Finalizes the hook after execution
/// @dev Called after the main execution, used to update hook state and calculate results
/// Sets output values (outAmount, usedShares, etc.) for subsequent hooks
/// @param prevHook The address of the previous hook in the chain, or address(0) if first
/// @param account The account operations were performed for
/// @param data The hook-specific parameters and configuration data
function postExecute(address prevHook, address account, bytes memory data) external;
/// @notice Human-readable name for UI display
/// @return The hook's friendly name
function name() external pure returns (string memory);
/// @notice One-sentence description of what this hook does
/// @return A human-readable description for UI display
function description() external pure returns (string memory);
/// @notice Returns the specific subtype identification for this hook
/// @dev Used to categorize hooks beyond the basic HookType
/// For example, a hook might be of type INFLOW but subtype VAULT_DEPOSIT
/// @return A bytes32 identifier for the specific hook functionality
function subtype() external view returns (bytes32);
/// @notice Resets hook mutexes
/// @param caller The caller address for context identification
function resetExecutionState(address caller) external;
/// @notice Sets the caller address that initiated the execution
/// @dev Used for security validation between preExecute and postExecute calls
/// @param caller The caller address for context identification
function setExecutionContext(address caller) external;
/// @notice Returns the execution nonce for the current execution context
/// @dev Used to ensure unique execution contexts and prevent replay attacks
/// @return The execution nonce
function executionNonce() external view returns (uint256);
/// @notice Returns the last caller registered by `setExecutionContext`
/// @return The last caller address
function lastCaller() external view returns (address);
}
src/libraries/AaveV4ReserveKey.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
/// @title AaveV4ReserveKey
/// @author Superform Labs
/// @notice Every Aave V4 key derivation, in one place. Aave V4 has TWO key namespaces with disjoint consumers:
/// 1. ACCOUNTING / NAV — one key per reserve LEG: `computeReserveKey` (SUPPLY) and `computeDebtKey`
/// (DEBT). Consumed by `AaveV4ReserveOracle`, `AaveV4ReserveRegistryV2._reserves`, and SuperLedger
/// via the idle INFLOW / OUTFLOW pair. These are oracle-resolvable and can be ledger keys.
/// 2. INTENT / IDENTITY — one key per market PAIR: `computeMarketKey(spoke, supplyReserveId,
/// borrowReserveId)` (SUP-21239). Consumed by the header `yieldSource` of the V2 LOAN hooks, and
/// hence by merkle leaves, vault whitelists and off-chain indexing. The V2 LOAN hooks are
/// NONACCOUNTING, so the executor never reads their header and a market key is never a ledger
/// key for them. `AaveV4ReserveOracle` DOES resolve a market key (SUP-21255), but
/// one-directionally and to one thing only: its COLLATERAL (supply) leg, so the sideless
/// `IYieldSourceOracle` surface still returns one number in one asset. Debt is never reachable
/// through a market key, the legs are never netted, and portfolio valuation belongs in the
/// batched `getOwnerSnapshot`, which de-duplicates legs across the whole requested set.
/// @dev Single definition: `AaveV4ReserveRegistryV2.computeReserveKey` / `.computeMarketKey` (the `public pure`
/// ones off-chain indexers call), the idle `BaseAaveV4MoneyMarketHook` decoder and both LOAN bases all
/// delegate here. The literal formulas are what off-chain consumers derive; each is pinned independently
/// of this library against the written-out expression — the reserve formula by
/// `testFuzz_ReserveKey_MatchesLiteralFormula` (LOAN unit suites) and
/// `test/unit/accounting/oracles/AaveV4Oracles.t.sol`, the market formula by
/// `testFuzz_MarketKey_MatchesLiteralFormula` and
/// `AaveV4ReserveKeyDerivation.testFuzz_ComputeMarketKey_MatchesLiteralFormula`.
/// Collision surface: forging a key equal to a specific registered reserve's or market's is a 160-bit
/// second preimage (~2^160 keccak evaluations; 2^160 / N against N registered entries) — the 2^80
/// birthday figure does not apply because the target is fixed. A collision could only block a second
/// registration in the registry; hooks never call or approve the key (the Spoke in calldata is the sole
/// call target), so it is identity only.
/// Cross-namespace collision: the three derivations take 2-, 3- and 4-word preimages, but differing
/// preimage LENGTH is structural separation and NOT a proof — keccak256 is not injective across lengths
/// and all three truncate to 160 bits. The domain constants are what make the separation intentional and
/// auditable. On-chain a cross-namespace collision is harmless anyway: the two namespaces live in
/// separate registry mappings with disjoint consumers.
library AaveV4ReserveKey {
/// @notice Thrown when a hook's header yield source (offset 32) is not the reserve key of the op's primary
/// reserve on the calldata Spoke
error RESERVE_KEY_MISMATCH();
/// @notice Thrown when a V2 LOAN hook's header yield source (offset 32) is not the market key of the
/// (spoke, supplyReserveId, borrowReserveId) triple the body acts on
error MARKET_KEY_MISMATCH();
/// @notice Domain separator mixed into the DEBT key preimage
/// @dev FROZEN. This literal MUST NOT change once any registry is seeded with debt keys: it is baked
/// into every debt key ever derived, so editing it silently repoints every registered debt leg
/// while leaving every test that pins it passing. It names `AaveV4ReserveRegistryV2` because that
/// is the contract whose key space it defines (V1 has no debt leg);
/// `AaveV4ReserveRegistryV2.DEBT_KEY_DOMAIN` re-exports this value, and
/// `AaveV4ReserveOracleDispatch.t.sol` pins the two equal.
bytes32 internal constant DEBT_KEY_DOMAIN = keccak256("AaveV4ReserveRegistryV2.DEBT");
/// @notice Domain separator mixed into the MARKET key preimage
/// @dev FROZEN once any market key is signed into a merkle root: it is baked into every market key ever
/// derived, so editing it silently repoints every registered market and every signed intent that
/// names one, while leaving every test that pins it passing.
/// Named after THIS LIBRARY, not after a registry — deliberately unlike its `DEBT_KEY_DOMAIN`
/// sibling, which baked a registry VERSION into a frozen constant and can never be corrected. Do
/// NOT "align" `DEBT_KEY_DOMAIN` to this convention: that literal is frozen and already baked into
/// live debt keys.
bytes32 internal constant MARKET_KEY_DOMAIN = keccak256("AaveV4ReserveKey.MARKET");
/// @notice Lower 20 bytes of keccak256(abi.encode(spoke, reserveId, DEBT_KEY_DOMAIN))
/// @dev The DEBT counterpart to `computeReserveKey`. Lives here, beside the supply derivation, so Aave
/// V4 key derivation has exactly ONE home — the reason this library exists. Being `internal` and
/// unused by the hooks, it is dead-code-eliminated from their creation code: verified by
/// `AaveV4LoanBytecodeUnchanged.t.sol`, which pins all 14 deployed hooks' freshly compiled
/// creation code against their locked artifacts and still passes with this present.
/// A future accounting-typed debt hook needs this derivation; it must call this and never
/// re-implement the hash.
/// @param spoke The Aave V4 spoke address
/// @param reserveId The reserve identifier within the spoke
/// @return The pseudo-address debt key
function computeDebtKey(address spoke, uint256 reserveId) internal pure returns (address) {
return address(uint160(uint256(keccak256(abi.encode(spoke, reserveId, DEBT_KEY_DOMAIN)))));
}
/// @notice Lower 20 bytes of keccak256(abi.encode(spoke, reserveId))
/// @param spoke The Aave V4 spoke address
/// @param reserveId The reserve identifier within the spoke
/// @return The pseudo-address reserve key
function computeReserveKey(address spoke, uint256 reserveId) internal pure returns (address) {
return address(uint160(uint256(keccak256(abi.encode(spoke, reserveId)))));
}
/// @notice Lower 20 bytes of keccak256(abi.encode(spoke, supplyReserveId, borrowReserveId, MARKET_KEY_DOMAIN))
/// @dev The INTENT-namespace derivation (SUP-21239): one key per Aave V4 market pair, so one economic
/// market is one yield source in merkle leaves, whitelists and the UI instead of two unrelated
/// reserve keys. Aave V4 has no market object on-chain (positions are reserve-granular), so a market
/// is a Superform curation decision: this key names one, `AaveV4ReserveRegistryV2.registerMarket`
/// records its bindings, and nothing on-chain enumerates markets.
/// ORDER IS SIGNIFICANT and MUST NOT be sorted: the legs are asymmetric — "equity collateral, borrow
/// USDC" and "USDC collateral, borrow equity" are different strategies with different risk, so
/// `computeMarketKey(s, a, b) != computeMarketKey(s, b, a)` and that asymmetry is pinned by test.
/// Tokens are NOT in the preimage: `loanToken` / `collateralToken` are a function of
/// `(spoke, reserveId)` and are already bound per call by the hooks' `_validateReserves` and at
/// registration by the registry, so including them would create a second source of truth and let two
/// keys name one market.
/// Being `internal` and unused by the V1 LOAN six, it is dead-code-eliminated from THEIR creation
/// code — `AaveV4LoanBytecodeUnchanged.t.sol` pins that empirically. The idle pair DOES reach it
/// since SUP-21263, through `requireHeaderIsMarketKey` in `_requireTargetIsMarketLeg` — in
/// `BaseAaveV4MoneyMarketHook`, so both idle leaves link it in. They do NOT reach
/// `computeReserveKey`: the chaining token is `_idleChainToken`, derived in the base from the
/// (market, leg) pair, because a reserve key is market-blind.
/// @param spoke The Aave V4 spoke address
/// @param supplyReserveId The collateral (supply) reserve identifier within the spoke
/// @param borrowReserveId The loan (borrow) reserve identifier within the spoke
/// @return The pseudo-address market key
function computeMarketKey(
address spoke,
uint256 supplyReserveId,
uint256 borrowReserveId
)
internal
pure
returns (address)
{
return
address(uint160(uint256(keccak256(abi.encode(spoke, supplyReserveId, borrowReserveId, MARKET_KEY_DOMAIN)))));
}
/// @notice Header pin shared by the V1 LOAN six and the idle pair: the header yield source must equal the
/// reserve key of the op's primary reserve on the calldata Spoke, so a crafted header can never name
/// a different reserve than the one the body acts on. Pure — safe inside pure decoders (build,
/// preExecute, inspect, sizing).
/// @param headerKey The header yield source (offset 32)
/// @param spoke The calldata Spoke
/// @param reserveId The op's primary reserve id
function requireHeaderKey(address headerKey, address spoke, uint256 reserveId) internal pure {
if (headerKey != computeReserveKey(spoke, reserveId)) revert RESERVE_KEY_MISMATCH();
}
/// @notice Header pin for the V2 LOAN hooks (SUP-21239): the header yield source must equal the market key of
/// the (Spoke, supply reserve, borrow reserve) triple the body acts on, so a crafted header can never
/// name a different market — nor either leg's reserve key — than the one the body acts on. Pure, so
/// build, preExecute, inspect and — for the V2 LOAN hooks only — decodeAmounts and
/// replaceCalldataAmounts all fail closed. The idle pair deliberately leaves its three sizing
/// views length-and-bool-only (they are transformation APIs a bundler calls before
/// authentication); its resize window at offsets 124-155 is disjoint from every identity field,
/// so a resize can never turn a mis-keyed payload into a well-keyed one.
/// FOR THE IDLE PAIR the key is additionally a SuperLedger key and an oracle argument, and the
/// oracle resolves it to the market's SUPPLY leg. CAUTION, CHANGED BY SUP-21263: that leg is no
/// longer necessarily the reserve the op moved. The idle body now carries one `targetReserveId`
/// which may be EITHER leg, so when it is the BORROW leg the oracle's scalar read describes the
/// collateral reserve instead. Nothing in this library can detect that — membership is a registry
/// read in the hook. See SECURITY.md §16 and `BaseAaveV4MoneyMarketHook`'s contract docblock.
/// @dev Replaces the per-hook `_primaryReserveId` selection the reserve-key pin needed: the market key is a
/// function of the WHOLE body, so there is no leg left to choose and the "override picked the wrong leg"
/// bug class is closed by construction rather than by convention.
/// @param headerKey The header yield source (offset 32)
/// @param spoke The calldata Spoke
/// @param supplyReserveId The body's collateral (supply) reserve id
/// @param borrowReserveId The body's loan (borrow) reserve id
function requireHeaderIsMarketKey(
address headerKey,
address spoke,
uint256 supplyReserveId,
uint256 borrowReserveId
)
internal
pure
{
if (headerKey != computeMarketKey(spoke, supplyReserveId, borrowReserveId)) revert MARKET_KEY_MISMATCH();
}
}
src/libraries/HookDataDecoder.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
import { BytesLib } from "../vendor/BytesLib.sol";
/// @title HookDataDecoder
/// @author Superform Labs
/// @notice Library for decoding hook data
library HookDataDecoder {
function extractYieldSourceOracleId(bytes memory data) internal pure returns (bytes32) {
return bytes32(BytesLib.slice(data, 0, 32));
}
function extractYieldSource(bytes memory data) internal pure returns (address) {
return BytesLib.toAddress(data, 32);
}
}
src/libraries/HookSubTypes.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
/// @title HookSubTypes
/// @author Superform Labs
/// @notice Library for hook subtypes
library HookSubTypes {
bytes32 public constant BRIDGE = keccak256(bytes("Bridge"));
bytes32 public constant CANCEL_DEPOSIT = keccak256(bytes("CancelDeposit"));
bytes32 public constant CANCEL_DEPOSIT_REQUEST = keccak256(bytes("CancelDepositRequest"));
bytes32 public constant CANCEL_REDEEM = keccak256(bytes("CancelRedeem"));
bytes32 public constant CANCEL_REDEEM_REQUEST = keccak256(bytes("CancelRedeemRequest"));
bytes32 public constant CLAIM = keccak256(bytes("Claim"));
bytes32 public constant CLAIM_CANCEL_DEPOSIT_REQUEST = keccak256(bytes("ClaimCancelDepositRequest"));
bytes32 public constant CLAIM_CANCEL_REDEEM_REQUEST = keccak256(bytes("ClaimCancelRedeemRequest"));
bytes32 public constant COOLDOWN = keccak256(bytes("Cooldown"));
bytes32 public constant ETHENA = keccak256(bytes("Ethena"));
bytes32 public constant ERC4626 = keccak256(bytes("ERC4626"));
bytes32 public constant ERC5115 = keccak256(bytes("ERC5115"));
bytes32 public constant ERC7540 = keccak256(bytes("ERC7540"));
bytes32 public constant HYPERCORE = keccak256(bytes("HyperCore"));
bytes32 public constant LOAN = keccak256(bytes("Loan"));
bytes32 public constant LOAN_REPAY = keccak256(bytes("LoanRepay"));
bytes32 public constant MISC = keccak256(bytes("Misc"));
bytes32 public constant STAKE = keccak256(bytes("Stake"));
bytes32 public constant SWAP = keccak256(bytes("Swap"));
bytes32 public constant TOKEN = keccak256(bytes("Token"));
bytes32 public constant UNSTAKE = keccak256(bytes("Unstake"));
bytes32 public constant PTYT = keccak256(bytes("PTYT"));
bytes32 public constant VAULT_BANK = keccak256(bytes("VaultBank"));
function getHookSubType(string memory hookSubtype) internal pure returns (bytes32) {
return keccak256(bytes(hookSubtype));
}
}
src/vendor/BytesLib.sol
// SPDX-License-Identifier: Unlicense
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity 0.8.30;
library BytesLib {
function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {
bytes memory tempBytes;
assembly ("memory-safe") {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for { let cc := add(_postBytes, 0x20) } lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} { mstore(mc, mload(cc)) }
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(
0x40,
and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
)
)
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly ("memory-safe") {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes.slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes.slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes.slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} { sstore(sc, mload(mc)) }
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes.slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} { sstore(sc, mload(mc)) }
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory) {
// We're using the unchecked block below because otherwise execution ends
// with the native overflow error code.
unchecked {
require(_length + 31 >= _length, "slice_overflow");
}
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly ("memory-safe") {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} { mstore(mc, mload(cc)) }
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly ("memory-safe") {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
require(_bytes.length >= _start + 1, "toUint8_outOfBounds");
uint8 tempUint;
assembly ("memory-safe") {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
uint16 tempUint;
assembly ("memory-safe") {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
uint32 tempUint;
assembly ("memory-safe") {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
uint64 tempUint;
assembly ("memory-safe") {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
uint96 tempUint;
assembly ("memory-safe") {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
uint128 tempUint;
assembly ("memory-safe") {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
uint256 tempUint;
assembly ("memory-safe") {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
bytes32 tempBytes32;
assembly ("memory-safe") {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success = true;
assembly ("memory-safe") {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for { let cc := add(_postBytes, 0x20) }
// the next line is the loop condition:
// while(uint256(mc < end) + cb == 2)
eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {
bool success = true;
assembly ("memory-safe") {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes.slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint256(mc < end) + cb == 2)
for { } eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
}
src/vendor/aave-v4/IAaveV4Spoke.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.30;
/// @title IAaveV4Spoke
/// @notice Minimal interface for Aave V4 Spoke contracts
/// @dev Only includes the functions needed by Superform hooks.
/// The actual Aave V4 Spoke is BUSL-licensed; this minimal interface avoids license conflict.
/// Spoke functions are protected by onlyPositionManager(onBehalfOf), but self-calls
/// (msg.sender == onBehalfOf) are allowed without registration.
/// Return-value semantics follow the canonical ISpoke interface: every money function
/// returns (shares, assets) — the share amount first, then the underlying asset amount.
interface IAaveV4Spoke {
/// @notice Number of listed reserves, including paused or frozen reserves.
/// @return Number of sequential reserve identifiers starting at zero.
function getReserveCount() external view returns (uint256);
/// @notice Reserve level data (canonical ISpoke.Reserve)
/// @dev `hub` is declared as `address` (canonically `IHubBase`) and `flags` as `uint8`
/// (canonically the wrapped user-defined value type `ReserveFlags`); both encodings are
/// ABI-identical for decoding purposes.
/// @param underlying The address of the underlying asset
/// @param hub The address of the associated Hub
/// @param assetId The identifier of the asset in the Hub
/// @param decimals The number of decimals of the underlying asset
/// @param collateralRisk The risk associated with a collateral asset, expressed in BPS
/// @param flags The packed boolean flags of the reserve (a wrapped uint8)
/// @param dynamicConfigKey The key of the last reserve dynamic config
struct Reserve {
address underlying;
address hub;
uint16 assetId;
uint8 decimals;
uint24 collateralRisk;
uint8 flags;
uint32 dynamicConfigKey;
}
/// @notice Supply assets to a reserve
/// @dev The Spoke pulls the underlying asset from the caller, so prior token approval is required
/// @param reserveId The reserve identifier within this Spoke
/// @param amount The amount of underlying asset to supply
/// @param onBehalfOf The address that will receive the supply position
/// @return shares The amount of shares supplied
/// @return assets The amount of assets supplied
function supply(uint256 reserveId, uint256 amount, address onBehalfOf) external returns (uint256, uint256);
/// @notice Withdraw assets from a reserve
/// @dev Providing an amount greater than the maximum withdrawable value (e.g. type(uint256).max)
/// signals a full withdrawal
/// @param reserveId The reserve identifier within this Spoke
/// @param amount The amount of underlying asset to withdraw
/// @param onBehalfOf The address that owns the supply position
/// @return shares The amount of shares withdrawn
/// @return assets The amount of assets withdrawn
function withdraw(uint256 reserveId, uint256 amount, address onBehalfOf) external returns (uint256, uint256);
/// @notice Borrow assets from a reserve
/// @param reserveId The reserve identifier within this Spoke
/// @param amount The amount of underlying asset to borrow
/// @param onBehalfOf The address that will receive the borrowed assets and incur the debt
/// @return shares The amount of shares borrowed
/// @return assets The amount of assets borrowed
function borrow(uint256 reserveId, uint256 amount, address onBehalfOf) external returns (uint256, uint256);
/// @notice Repay borrowed assets to a reserve
/// @dev The Spoke pulls the underlying asset from the caller, so prior approval is required.
/// An amount greater than the outstanding debt (e.g. type(uint256).max) signals a full
/// repayment.
/// @param reserveId The reserve identifier within this Spoke
/// @param amount The amount of underlying asset to repay
/// @param onBehalfOf The address whose debt will be repaid
/// @return shares The amount of shares repaid
/// @return assets The amount of assets repaid
function repay(uint256 reserveId, uint256 amount, address onBehalfOf) external returns (uint256, uint256);
/// @notice Enable or disable a supplied reserve as collateral
/// @dev Must be called after supply to enable borrowing against the position.
/// Aave V4 does NOT auto-enable collateral on supply (unlike V3).
/// Protected by onlyPositionManager(onBehalfOf), but self-calls are allowed.
/// @param reserveId The reserve identifier within this Spoke
/// @param useAsCollateral True to enable, false to disable
/// @param onBehalfOf The address whose collateral setting is being changed
function setUsingAsCollateral(uint256 reserveId, bool useAsCollateral, address onBehalfOf) external;
/// @notice Returns whether a reserve is flagged as collateral and/or borrowed for a user
/// @dev The collateral flag is per (user, reserve), not per deposit; it is toggled only through
/// setUsingAsCollateral (self-call or an approved position manager). Verified against the live
/// Spoke implementation: `(false, false)` for a plain idle supply, `(true, false)` for a
/// pledged reserve, `(false, true)` for a reserve with drawn debt.
/// @param reserveId The identifier of the reserve
/// @param user The address of the user
/// @return isUsingAsCollateral True when the reserve backs the user's borrows
/// @return isBorrowing True when the user has debt on the reserve
function getUserReserveStatus(uint256 reserveId, address user) external view returns (bool, bool);
/// @notice Returns the reserve data for a given reserve identifier
/// @dev Reverts if the reserve is not listed
/// @param reserveId The identifier of the reserve
/// @return The reserve data (see Reserve)
function getReserve(uint256 reserveId) external view returns (Reserve memory);
/// @notice Returns the debt of a specific user for a given reserve
/// @dev The total debt of the user is the sum of drawn debt and premium debt
/// @param reserveId The identifier of the reserve
/// @param user The address of the user
/// @return drawnDebt The amount of drawn debt
/// @return premiumDebt The amount of premium debt
function getUserDebt(uint256 reserveId, address user) external view returns (uint256, uint256);
/// @notice Returns the amount of assets supplied by a specific user for a given reserve
/// @param reserveId The identifier of the reserve
/// @param user The address of the user
/// @return The amount of assets supplied by the user
function getUserSuppliedAssets(uint256 reserveId, address user) external view returns (uint256);
/// @notice Returns the reserve-level aggregate debt for a given reserve
/// @dev The total reserve debt is the sum of drawn debt and premium debt (the totalBorrows
/// analog used by the Superform debt oracle's getTVL)
/// @param reserveId The identifier of the reserve
/// @return drawnDebt The aggregate amount of drawn debt
/// @return premiumDebt The aggregate amount of premium debt
function getReserveDebt(uint256 reserveId) external view returns (uint256, uint256);
/// @notice Returns the reserve-level aggregate supplied assets for a given reserve
/// @param reserveId The identifier of the reserve
/// @return The total amount of assets supplied to the reserve
function getReserveSuppliedAssets(uint256 reserveId) external view returns (uint256);
/// @notice Account-wide risk snapshot of `user` on this Spoke (upstream `ISpoke.UserAccountData`, field order
/// verified against the Ethereum Main Spoke implementation behind `0x94e7A5dCbE816e498b89aB752661904E2F56c485`)
/// @dev FIELD ORDER IS A PINNED, UNCHECKED ABI ASSUMPTION. `getUserAccountData` is decoded positionally, so
/// `healthFactor` must stay at word index 2. The read has no runtime scale/plausibility check, so a Spoke
/// implementation upgrade that REORDERS this struct would be silently mis-decoded: shifting the read onto
/// `totalCollateralValue`/`totalDebtValueRay` (RAY-scaled, ~1e27+) returns an implausibly large value that
/// satisfies any WAD `minHealthFactor`, so the health guard would FAIL OPEN. The only backstop is the
/// mainnet-fork test (`test/integration/AaveV4V2HooksFork.t.sol`, pinned to the address above): re-verify
/// the field order against the live Spoke before adopting a new Spoke implementation.
/// @dev Health is per ACCOUNT per SPOKE (cross-reserve), never per market. `healthFactor` is WAD-scaled: the
/// Spoke's `HEALTH_FACTOR_LIQUIDATION_THRESHOLD` is 1e18 and `type(uint256).max` means no debt. It is
/// evaluated with the account's STORED dynamic-config keys; `borrow` and a flagged `withdraw` refresh the
/// keys of all flagged reserves first, `supply` / `setUsingAsCollateral` do not.
struct UserAccountData {
uint256 riskPremium;
uint256 avgCollateralFactor;
uint256 healthFactor;
uint256 totalCollateralValue;
uint256 totalDebtValueRay;
uint256 activeCollateralCount;
uint256 borrowCount;
}
/// @notice Returns the account-wide risk data of `user` on this Spoke
/// @param user The account
/// @return The account data (see `UserAccountData`)
function getUserAccountData(address user) external view returns (UserAccountData memory);
}
Настройки компилятораПоказать
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"excessivelySafeCall/=lib/ExcessivelySafeCall/src/",
"modulekit/=lib/modulekit/src/",
"@prb/math/=lib/modulekit/node_modules/@prb/math/src/",
"@solady/=lib/solady/",
"@account-abstraction/=lib/modulekit/node_modules/account-abstraction/contracts/",
"@ERC4337/=lib/modulekit/node_modules/@ERC4337/",
"@pigeon/=lib/pigeon/src/",
"@surl/=lib/surl/src/",
"@stringutils/=lib/solidity-stringutils/src/",
"@pendle/=lib/pendle-core-v2-public/contracts/",
"@safe/=lib/safe-smart-account/contracts/",
"@safe7579/=lib/safe7579/src/",
"@nexus/=lib/nexus/contracts/",
"sentinellist/=lib/nexus/node_modules/sentinellist/src/",
"solady/=lib/nexus/node_modules/solady/src/",
"solarray/=lib/nexus/node_modules/solarray/src/",
"account-abstraction/=lib/modulekit/node_modules/@ERC4337/account-abstraction/contracts/",
"account-abstraction-v0.6/=lib/modulekit/node_modules/@ERC4337/account-abstraction-v0.6/contracts/",
"excessively-safe-call/=lib/ExcessivelySafeCall/src/",
"composability/=lib/nexus/node_modules/@biconomy/composability/contracts/",
"erc7739Validator/=lib/nexus/node_modules/erc7739-validator-base/src/",
"test/mock_fiattoken/=lib/evm-gateway-contracts/test/mock_fiattoken/",
"@rhinestone/erc4337-validation/=lib/modulekit/node_modules/@rhinestone/erc4337-validation/",
"erc4337-validation/=lib/modulekit/node_modules/@rhinestone/erc4337-validation/src/",
"forge-std/=lib/modulekit/node_modules/forge-std/src/",
"rhinestone/checknsignatures/=lib/checknsignatures/",
"evm-gateway/=lib/evm-gateway-contracts/src/",
"lib/evm-gateway-contracts:src/=lib/evm-gateway-contracts/src/",
"lib/evm-gateway-contracts:src/=lib/evm-gateway-contracts/src/",
"lib/evm-gateway-contracts:test/=lib/evm-gateway-contracts/test/",
"lib/evm-gateway-contracts:test/=lib/evm-gateway-contracts/test/",
"v4-core/=lib/v4-core/src/",
"lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/account-abstraction/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/account-abstraction/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/account-abstraction/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/account-abstraction/node_modules/@openzeppelin/contracts/",
"lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/account-abstraction/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/account-abstraction/node_modules/@openzeppelin/contracts/",
"lib/nexus/node_modules/@rhinestone/safe7579/node_modules/account-abstraction/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/node_modules/@rhinestone/safe7579/node_modules/account-abstraction/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/node_modules/@rhinestone/safe7579/node_modules/account-abstraction/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/account-abstraction/node_modules/@openzeppelin/contracts/",
"lib/nexus/node_modules/@rhinestone/safe7579/node_modules/account-abstraction/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/account-abstraction/node_modules/@openzeppelin/contracts/",
"lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/:@openzeppelin/=lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/node_modules/@openzeppelin/contracts/",
"lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/:@openzeppelin/=lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/node_modules/@openzeppelin/contracts/",
"lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/:hardhat-deploy/=lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/node_modules/hardhat-deploy/",
"lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/:hardhat-deploy/=lib/nexus/node_modules/@ERC4337/account-abstraction-v0.6/node_modules/hardhat-deploy/",
"lib/nexus/node_modules/@ERC4337/account-abstraction/:hardhat-deploy/=lib/nexus/node_modules/@ERC4337/account-abstraction/node_modules/hardhat-deploy/",
"lib/nexus/node_modules/@ERC4337/account-abstraction/:hardhat-deploy/=lib/nexus/node_modules/@ERC4337/account-abstraction/node_modules/hardhat-deploy/",
"lib/nexus/node_modules/@rhinestone/erc4337-validation/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/node_modules/@rhinestone/erc4337-validation/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/node_modules/@rhinestone/erc4337-validation/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/@openzeppelin/contracts/",
"lib/nexus/node_modules/@rhinestone/erc4337-validation/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/@openzeppelin/contracts/",
"lib/nexus/node_modules/@rhinestone/erc4337-validation/:hardhat-deploy/=lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/hardhat-deploy/",
"lib/nexus/node_modules/@rhinestone/erc4337-validation/:hardhat-deploy/=lib/nexus/node_modules/@rhinestone/erc4337-validation/node_modules/hardhat-deploy/",
"lib/nexus/node_modules/@rhinestone/registry/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/node_modules/@rhinestone/registry/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/node_modules/@rhinestone/registry/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/registry/node_modules/@openzeppelin/contracts/",
"lib/nexus/node_modules/@rhinestone/registry/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/registry/node_modules/@openzeppelin/contracts/",
"lib/nexus/node_modules/@rhinestone/safe7579/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/node_modules/@rhinestone/safe7579/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/node_modules/@rhinestone/safe7579/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/@openzeppelin/contracts/",
"lib/nexus/node_modules/@rhinestone/safe7579/:@openzeppelin/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/@openzeppelin/contracts/",
"lib/nexus/node_modules/@rhinestone/safe7579/:@rhinestone/erc4337-validation/=lib/modulekit/node_modules/@rhinestone/erc4337-validation/",
"lib/nexus/node_modules/@rhinestone/safe7579/:@rhinestone/erc4337-validation/=lib/modulekit/node_modules/@rhinestone/erc4337-validation/",
"lib/nexus/node_modules/@rhinestone/safe7579/:@rhinestone/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/@rhinestone/erc4337-validation/src/",
"lib/nexus/node_modules/@rhinestone/safe7579/:@rhinestone/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/@rhinestone/erc4337-validation/src/",
"lib/nexus/node_modules/@rhinestone/safe7579/:hardhat-deploy/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/hardhat-deploy/",
"lib/nexus/node_modules/@rhinestone/safe7579/:hardhat-deploy/=lib/nexus/node_modules/@rhinestone/safe7579/node_modules/hardhat-deploy/",
"lib/evm-gateway-contracts/lib/memview-sol/:ds-test/=lib/evm-gateway-contracts/lib/memview-sol/lib/ds-test/src/",
"lib/evm-gateway-contracts/lib/memview-sol/:ds-test/=lib/evm-gateway-contracts/lib/memview-sol/lib/ds-test/src/",
"lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
"lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
"lib/evm-gateway-contracts/lib/openzeppelin-contracts/:erc4626-tests/=lib/evm-gateway-contracts/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/evm-gateway-contracts/lib/openzeppelin-contracts/:erc4626-tests/=lib/evm-gateway-contracts/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/evm-gateway-contracts/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/evm-gateway-contracts/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"lib/evm-gateway-contracts/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/evm-gateway-contracts/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"lib/nexus/node_modules/account-abstraction-v0.6/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/node_modules/account-abstraction-v0.6/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/node_modules/account-abstraction-v0.6/:@openzeppelin/=lib/nexus/node_modules/account-abstraction-v0.6/node_modules/@openzeppelin/contracts/",
"lib/nexus/node_modules/account-abstraction-v0.6/:@openzeppelin/=lib/nexus/node_modules/account-abstraction-v0.6/node_modules/@openzeppelin/contracts/",
"lib/nexus/node_modules/account-abstraction-v0.6/:hardhat-deploy/=lib/nexus/node_modules/account-abstraction-v0.6/node_modules/hardhat-deploy/",
"lib/nexus/node_modules/account-abstraction-v0.6/:hardhat-deploy/=lib/nexus/node_modules/account-abstraction-v0.6/node_modules/hardhat-deploy/",
"lib/nexus/node_modules/account-abstraction/:hardhat-deploy/=lib/nexus/node_modules/account-abstraction/node_modules/hardhat-deploy/",
"lib/nexus/node_modules/account-abstraction/:hardhat-deploy/=lib/nexus/node_modules/account-abstraction/node_modules/hardhat-deploy/",
"lib/nexus/node_modules/erc7579/:hardhat-deploy/=lib/nexus/node_modules/erc7579/node_modules/hardhat-deploy/",
"lib/nexus/node_modules/erc7579/:hardhat-deploy/=lib/nexus/node_modules/erc7579/node_modules/hardhat-deploy/",
"lib/pigeon/lib/openzeppelin-contracts/:erc4626-tests/=lib/pigeon/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/pigeon/lib/openzeppelin-contracts/:erc4626-tests/=lib/pigeon/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/pigeon/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/pigeon/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"lib/pigeon/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/pigeon/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"lib/surl/lib/forge-std/:ds-test/=lib/surl/lib/forge-std/lib/ds-test/src/",
"lib/surl/lib/forge-std/:ds-test/=lib/surl/lib/forge-std/lib/ds-test/src/",
"lib/surl/lib/solidity-stringutils/:ds-test/=lib/surl/lib/solidity-stringutils/lib/ds-test/src/",
"lib/surl/lib/solidity-stringutils/:ds-test/=lib/surl/lib/solidity-stringutils/lib/ds-test/src/",
"lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/ExcessivelySafeCall/:ds-test/=lib/ExcessivelySafeCall/lib/ds-test/src/",
"lib/ExcessivelySafeCall/:ds-test/=lib/ExcessivelySafeCall/lib/ds-test/src/",
"lib/evm-gateway-contracts/:openzeppelin-contracts/=lib/evm-gateway-contracts/lib/openzeppelin-contracts/",
"lib/evm-gateway-contracts/:openzeppelin-contracts/=lib/evm-gateway-contracts/lib/openzeppelin-contracts/",
"lib/modulekit/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/modulekit/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/modulekit/:@openzeppelin/=lib/modulekit/node_modules/@openzeppelin/",
"lib/modulekit/:@openzeppelin/=lib/modulekit/node_modules/@openzeppelin/",
"lib/modulekit/:@gnosis.pm/safe-contracts/=lib/modulekit/node_modules/@gnosis.pm/safe-contracts/",
"lib/modulekit/:@gnosis.pm/safe-contracts/=lib/modulekit/node_modules/@gnosis.pm/safe-contracts/",
"lib/modulekit/:@prb/math/=lib/modulekit/node_modules/@prb/math/src/",
"lib/modulekit/:@prb/math/=lib/modulekit/node_modules/@prb/math/src/",
"lib/modulekit/:@prb/=lib/modulekit/node_modules/@prb/math/src/",
"lib/modulekit/:@prb/=lib/modulekit/node_modules/@prb/math/src/",
"lib/modulekit/:@rhinestone/sentinellist/=lib/modulekit/node_modules/@rhinestone/sentinellist/",
"lib/modulekit/:@rhinestone/sentinellist/=lib/modulekit/node_modules/@rhinestone/sentinellist/",
"lib/modulekit/:ds-test/=lib/modulekit/node_modules/ds-test/src/",
"lib/modulekit/:ds-test/=lib/modulekit/node_modules/ds-test/src/",
"lib/modulekit/:hardhat-deploy/=lib/modulekit/node_modules/hardhat-deploy/",
"lib/modulekit/:hardhat-deploy/=lib/modulekit/node_modules/hardhat-deploy/",
"lib/modulekit/:hardhat/=lib/modulekit/node_modules/hardhat/",
"lib/modulekit/:hardhat/=lib/modulekit/node_modules/hardhat/",
"lib/nexus/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/nexus/:@openzeppelin/=lib/nexus/node_modules/@openzeppelin/",
"lib/nexus/:@openzeppelin/=lib/nexus/node_modules/@openzeppelin/",
"lib/nexus/:@gnosis.pm/safe-contracts/=lib/nexus/node_modules/@gnosis.pm/safe-contracts/",
"lib/nexus/:@gnosis.pm/safe-contracts/=lib/nexus/node_modules/@gnosis.pm/safe-contracts/",
"lib/nexus/:@prb/math/=lib/modulekit/node_modules/@prb/math/src/",
"lib/nexus/:@prb/math/=lib/modulekit/node_modules/@prb/math/src/",
"lib/nexus/:@prb/=lib/nexus/node_modules/@prb/math/src/",
"lib/nexus/:@prb/=lib/nexus/node_modules/@prb/math/src/",
"lib/nexus/:@rhinestone/checknsignatures/=lib/nexus/node_modules/@rhinestone/checknsignatures/",
"lib/nexus/:@rhinestone/checknsignatures/=lib/nexus/node_modules/@rhinestone/checknsignatures/",
"lib/nexus/:@rhinestone/module-bases/=lib/nexus/node_modules/@rhinestone/module-bases/",
"lib/nexus/:@rhinestone/module-bases/=lib/nexus/node_modules/@rhinestone/module-bases/",
"lib/nexus/:@rhinestone/modulekit/=lib/nexus/node_modules/@rhinestone/modulekit/",
"lib/nexus/:@rhinestone/modulekit/=lib/nexus/node_modules/@rhinestone/modulekit/",
"lib/nexus/:@rhinestone/registry/=lib/nexus/node_modules/@rhinestone/registry/",
"lib/nexus/:@rhinestone/registry/=lib/nexus/node_modules/@rhinestone/registry/",
"lib/nexus/:@rhinestone/safe7579/=lib/nexus/node_modules/@rhinestone/safe7579/",
"lib/nexus/:@rhinestone/safe7579/=lib/nexus/node_modules/@rhinestone/safe7579/",
"lib/nexus/:@rhinestone/sentinellist/=lib/nexus/node_modules/@rhinestone/sentinellist/",
"lib/nexus/:@rhinestone/sentinellist/=lib/nexus/node_modules/@rhinestone/sentinellist/",
"lib/nexus/:@safe-global/safe-contracts/=lib/nexus/node_modules/@safe-global/safe-contracts/",
"lib/nexus/:@safe-global/safe-contracts/=lib/nexus/node_modules/@safe-global/safe-contracts/",
"lib/nexus/:ds-test/=lib/nexus/node_modules/ds-test/src/",
"lib/nexus/:ds-test/=lib/nexus/node_modules/ds-test/src/",
"lib/nexus/:erc7579/=lib/nexus/node_modules/erc7579/",
"lib/nexus/:erc7579/=lib/nexus/node_modules/erc7579/",
"lib/nexus/:hardhat-deploy/=lib/nexus/node_modules/hardhat-deploy/",
"lib/nexus/:hardhat-deploy/=lib/nexus/node_modules/hardhat-deploy/",
"lib/nexus/:hardhat/=lib/nexus/node_modules/hardhat/",
"lib/nexus/:hardhat/=lib/nexus/node_modules/hardhat/",
"lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"lib/pigeon/:openzeppelin-contracts/=lib/pigeon/lib/openzeppelin-contracts/",
"lib/pigeon/:openzeppelin-contracts/=lib/pigeon/lib/openzeppelin-contracts/",
"lib/safe7579/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/safe7579/:@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/safe7579/:@openzeppelin/=lib/safe7579/node_modules/@openzeppelin/",
"lib/safe7579/:@openzeppelin/=lib/safe7579/node_modules/@openzeppelin/",
"lib/safe7579/:@gnosis.pm/safe-contracts/=lib/safe7579/node_modules/@gnosis.pm/safe-contracts/",
"lib/safe7579/:@gnosis.pm/safe-contracts/=lib/safe7579/node_modules/@gnosis.pm/safe-contracts/",
"lib/safe7579/:@rhinestone/.ignored_checknsignatures/=lib/safe7579/node_modules/@rhinestone/.ignored_checknsignatures/",
"lib/safe7579/:@rhinestone/.ignored_checknsignatures/=lib/safe7579/node_modules/@rhinestone/.ignored_checknsignatures/",
"lib/safe7579/:@rhinestone/.ignored_erc4337-validation/=lib/safe7579/node_modules/@rhinestone/.ignored_erc4337-validation/",
"lib/safe7579/:@rhinestone/.ignored_erc4337-validation/=lib/safe7579/node_modules/@rhinestone/.ignored_erc4337-validation/",
"lib/safe7579/:@rhinestone/.ignored_module-bases/=lib/safe7579/node_modules/@rhinestone/.ignored_module-bases/",
"lib/safe7579/:@rhinestone/.ignored_module-bases/=lib/safe7579/node_modules/@rhinestone/.ignored_module-bases/",
"lib/safe7579/:@rhinestone/.ignored_sentinellist/=lib/safe7579/node_modules/@rhinestone/.ignored_sentinellist/",
"lib/safe7579/:@rhinestone/.ignored_sentinellist/=lib/safe7579/node_modules/@rhinestone/.ignored_sentinellist/",
"lib/safe7579/:@rhinestone/checknsignatures/=lib/safe7579/node_modules/@rhinestone/checknsignatures/",
"lib/safe7579/:@rhinestone/checknsignatures/=lib/safe7579/node_modules/@rhinestone/checknsignatures/",
"lib/safe7579/:@rhinestone/module-bases/=lib/safe7579/node_modules/@rhinestone/module-bases/",
"lib/safe7579/:@rhinestone/module-bases/=lib/safe7579/node_modules/@rhinestone/module-bases/",
"lib/safe7579/:@rhinestone/sentinellist/=lib/safe7579/node_modules/@rhinestone/sentinellist/",
"lib/safe7579/:@rhinestone/sentinellist/=lib/safe7579/node_modules/@rhinestone/sentinellist/",
"lib/safe7579/:@safe-global/.ignored_safe-contracts/=lib/safe7579/node_modules/@safe-global/.ignored_safe-contracts/",
"lib/safe7579/:@safe-global/.ignored_safe-contracts/=lib/safe7579/node_modules/@safe-global/.ignored_safe-contracts/",
"lib/safe7579/:@safe-global/safe-contracts/=lib/safe7579/node_modules/@safe-global/safe-contracts/",
"lib/safe7579/:@safe-global/safe-contracts/=lib/safe7579/node_modules/@safe-global/safe-contracts/",
"lib/safe7579/:ds-test/=lib/safe7579/node_modules/ds-test/src/",
"lib/safe7579/:ds-test/=lib/safe7579/node_modules/ds-test/src/",
"lib/safe7579/:erc7579/=lib/safe7579/node_modules/erc7579/src/",
"lib/safe7579/:erc7579/=lib/safe7579/node_modules/erc7579/src/",
"lib/safe7579/:hardhat-deploy/=lib/safe7579/node_modules/hardhat-deploy/",
"lib/safe7579/:hardhat-deploy/=lib/safe7579/node_modules/hardhat-deploy/",
"lib/safe7579/:hardhat/=lib/safe7579/node_modules/hardhat/",
"lib/safe7579/:hardhat/=lib/safe7579/node_modules/hardhat/",
"lib/solidity-stringutils/:ds-test/=lib/solidity-stringutils/lib/ds-test/src/",
"lib/solidity-stringutils/:ds-test/=lib/solidity-stringutils/lib/ds-test/src/",
"lib/surl/:solidity-stringutils/=lib/surl/lib/solidity-stringutils/src/",
"lib/surl/:solidity-stringutils/=lib/surl/lib/solidity-stringutils/src/",
"lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
"lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
"lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"@biconomy/=lib/nexus/node_modules/@biconomy/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"@erc7579/=lib/nexus/node_modules/@erc7579/enumerablemap4337/src/",
"@gnosis.pm/=lib/modulekit/node_modules/@gnosis.pm/",
"@memview-sol/=lib/evm-gateway-contracts/lib/memview-sol/contracts/",
"@openzeppelin/=lib/modulekit/node_modules/@openzeppelin/",
"@prb/=lib/modulekit/node_modules/@prb/math/src/",
"@rhinestone/=lib/safe7579/node_modules/@rhinestone/",
"@safe-global/=lib/nexus/node_modules/@safe-global/",
"@zerodev/=lib/nexus/node_modules/@zerodev/kernel/src/",
"ExcessivelySafeCall/=lib/ExcessivelySafeCall/src/",
"checknsignatures/=lib/checknsignatures/src/",
"ds-test/=lib/ExcessivelySafeCall/lib/ds-test/src/",
"enumerableset4337/=lib/nexus/node_modules/erc7739-validator-base/node_modules/@erc7579/enumerablemap4337/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"erc7579/=lib/safe7579/node_modules/erc7579/src/",
"erc7739-validator-base/=lib/nexus/node_modules/erc7739-validator-base/src/",
"eth-gas-reporter/=lib/nexus/node_modules/eth-gas-reporter/",
"evm-gateway-contracts/=lib/evm-gateway-contracts/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"hardhat-deploy/=lib/modulekit/node_modules/hardhat-deploy/",
"hardhat/=lib/modulekit/node_modules/hardhat/",
"kernel/=lib/nexus/node_modules/erc7739-validator-base/node_modules/@zerodev/kernel/src/",
"memview-sol/=lib/evm-gateway-contracts/lib/memview-sol/contracts/",
"module-bases/=lib/safe7579/node_modules/@rhinestone/module-bases/src/",
"nexus/=lib/nexus/",
"openzeppelin-contracts-upgradeable/=lib/evm-gateway-contracts/lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"pendle-core-v2-public/=lib/pendle-core-v2-public/contracts/",
"pigeon/=lib/pigeon/src/",
"prep/=lib/nexus/node_modules/prep/src/",
"safe-smart-account/=lib/safe-smart-account/",
"safe7579/=lib/safe7579/",
"solidity-stringutils/=lib/solidity-stringutils/",
"solmate/=lib/v4-core/lib/solmate/",
"surl/=lib/surl/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.