Skip to content
Verified contractPartialLGPL-3.0-only

BoundModuleGuard

Address0x092a58c845b30c790a2abe63ba49e9fcec63ba4d
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.35

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 200 runs
EVM version
osaka
Via IR
yes
License
LGPL-3.0-only
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,377,086
Creation transaction
0x6c6a73c492…e1089ca928

src/core/BoundModuleGuard.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {Enum, StrategyModule} from "./StrategyModule.sol";
import {StrategyRegistry} from "./StrategyRegistry.sol";
import {IERC20Minimal} from "../interfaces/tokens/IERC20Minimal.sol";

/// @title IERC165
/// @notice Minimal ERC-165 interface used by Safe 1.5 when installing a module guard.
interface IERC165 {
    /// @notice Whether this contract implements `interfaceId`.
    /// @param interfaceId ERC-165 interface identifier to query.
    /// @return supported True when `interfaceId` is supported.
    function supportsInterface(bytes4 interfaceId) external view returns (bool supported);
}

/// @title IModuleGuard
/// @notice Safe 1.5 module-guard hook interface.
/// @dev Safe-only pre/post hooks are applied to each module transaction, not to
///      an entire multi-step engine plan as one balance comparison.
interface IModuleGuard is IERC165 {
    /// @notice Validate and snapshot a module transaction before execution.
    /// @param to Target of the module transaction.
    /// @param value Native value sent by the module transaction.
    /// @param data Calldata sent by the module transaction.
    /// @param operation Safe operation type.
    /// @param module Enabled Safe module initiating the transaction.
    /// @return moduleTxHash Unique key passed back to the post-execution hook.
    function checkModuleTransaction(
        address to,
        uint256 value,
        bytes calldata data,
        Enum.Operation operation,
        address module
    ) external returns (bytes32 moduleTxHash);

    /// @notice Validate tracked reserves after a module transaction executes.
    /// @param txHash Key returned by the matching pre-execution hook.
    /// @param success Whether the target call succeeded.
    function checkAfterModuleExecution(bytes32 txHash, bool success) external;
}

/// @title IModuleGuardSafe
/// @notice Minimal Safe surface used by the module guard.
interface IModuleGuardSafe {
    /// @notice Whether `module` is currently enabled on the Safe.
    /// @param module Address to inspect.
    /// @return enabled True when the address is an enabled Safe module.
    function isModuleEnabled(address module) external view returns (bool enabled);
}

/// @title IReserveToken
/// @notice Minimal token balance surface used for reserve snapshots.
interface IReserveToken {
    /// @notice Return `account`'s token balance.
    /// @param account Account whose balance is read.
    /// @return balance Current token balance.
    function balanceOf(address account) external view returns (uint256 balance);
}

/// @title BoundModuleGuard
/// @notice Immutable Safe 1.5 module guard enforcing Bound control-plane isolation
///         and non-decreasing balances for configured reserve assets.
/// @dev One guard instance serves exactly one Safe. The hooks deliberately apply
///      to every enabled module, not only the Bound StrategyModule.
///      Track only assets legitimate module actions never consume. This is not a
///      portfolio-value check or permanent reserve floor: later external transfers
///      under an allowance do not pass through these module hooks.
contract BoundModuleGuard is IModuleGuard {
    // ─── Errors ──────────────────────────────────────────────────────────

    error BoundModuleGuard_ZeroAddress();
    error BoundModuleGuard_ModuleSafeMismatch(address safe, address moduleSafe);
    error BoundModuleGuard_RegistrySafeMismatch(address safe, address registrySafe);
    error BoundModuleGuard_ModuleRegistryMismatch(address moduleRegistry, address registry);
    error BoundModuleGuard_DuplicateTrackedAsset(address asset);
    error BoundModuleGuard_AllowanceLengthMismatch(uint256 tokenCount, uint256 spenderCount);
    error BoundModuleGuard_ZeroSpender();
    error BoundModuleGuard_NativeAllowanceToken();
    error BoundModuleGuard_AllowanceTokenNotTracked(address token);
    error BoundModuleGuard_DuplicateAllowancePair(address token, address spender);
    error BoundModuleGuard_OnlySafe(address caller);
    error BoundModuleGuard_OperationNotCall(Enum.Operation operation);
    error BoundModuleGuard_ForbiddenTarget(address target);
    error BoundModuleGuard_MalformedApproveCalldata(uint256 length);
    error BoundModuleGuard_SpenderNotAllowed(address token, address spender);
    error BoundModuleGuard_ApprovalSelectorForbidden(address token, bytes4 selector);
    error BoundModuleGuard_Permit2SelectorForbidden(address target, bytes4 selector);
    error BoundModuleGuard_UnknownSnapshot(bytes32 key);
    error BoundModuleGuard_ReserveDecreased(address asset, uint256 balanceBefore, uint256 balanceAfter);

    // ─── Events ──────────────────────────────────────────────────────────

    event SnapshotCreated(bytes32 indexed key, address indexed module);
    event SnapshotConsumed(bytes32 indexed key, bool success);

    // ─── Constants ───────────────────────────────────────────────────────

    /// @notice Safe module-guard hook interface ID, excluding inherited ERC-165.
    bytes4 public constant MODULE_GUARD_INTERFACE_ID = type(IModuleGuard).interfaceId;
    /// @notice Standard ERC-165 interface ID.
    bytes4 public constant ERC165_INTERFACE_ID = type(IERC165).interfaceId;

    bytes4 private constant APPROVE_SELECTOR = IERC20Minimal.approve.selector;
    bytes4 private constant PERMIT2_APPROVE_SELECTOR = 0x87517c45;
    bytes4 private constant PERMIT2_PERMIT_SELECTOR = 0x2b67b570;
    bytes4 private constant PERMIT2_BATCH_PERMIT_SELECTOR = 0x2a2d80d1;

    // ─── Immutable configuration ─────────────────────────────────────────

    /// @notice Safe protected by this guard.
    address public immutable SAFE;

    /// @notice Bound StrategyModule associated with `SAFE`.
    StrategyModule public immutable STRATEGY_MODULE;

    /// @notice StrategyRegistry associated with `STRATEGY_MODULE` and `SAFE`.
    StrategyRegistry public immutable REGISTRY;

    address[] private _trackedAssets;
    /// @notice Whether an asset is protected against decreases during module calls.
    mapping(address asset => bool tracked) public isTrackedAsset;

    struct AllowancePair {
        address token;
        address spender;
    }

    AllowancePair[] private _allowancePairs;
    /// @notice Whether nonzero tracked-token approvals may name a spender; no amount cap is applied.
    mapping(address token => mapping(address spender => bool allowed)) public isAllowedSpender;
    mapping(address token => address[] spenders) private _allowedSpenders;

    // ─── Snapshot state ──────────────────────────────────────────────────

    uint256 private _nextSnapshotNonce = 1;
    mapping(bytes32 key => bool exists) private _snapshotExists;
    mapping(bytes32 key => mapping(address asset => uint256 balance)) private _snapshotBalances;

    // ─── Constructor ─────────────────────────────────────────────────────

    /// @notice Configure one immutable module guard for one Safe.
    /// @param safe Safe multisig protected by the guard.
    /// @param strategyModule Bound StrategyModule associated with `safe`.
    /// @param registry StrategyRegistry associated with `strategyModule`.
    /// @param trackedAssets_ Reserve assets whose balances may never decrease;
    ///        use address(0) to track the native asset.
    /// @param allowanceTokens Tracked ERC-20 for each allowed spender pair.
    /// @param allowedSpenders Spender for each corresponding allowance token.
    constructor(
        address safe,
        address strategyModule,
        address registry,
        address[] memory trackedAssets_,
        address[] memory allowanceTokens,
        address[] memory allowedSpenders
    ) {
        if (safe == address(0) || strategyModule == address(0) || registry == address(0)) {
            revert BoundModuleGuard_ZeroAddress();
        }

        address moduleSafe = StrategyModule(strategyModule).SAFE();
        if (moduleSafe != safe) revert BoundModuleGuard_ModuleSafeMismatch(safe, moduleSafe);

        address registrySafe = StrategyRegistry(registry).SAFE();
        if (registrySafe != safe) revert BoundModuleGuard_RegistrySafeMismatch(safe, registrySafe);

        address moduleRegistry = address(StrategyModule(strategyModule).REGISTRY());
        if (moduleRegistry != registry) {
            revert BoundModuleGuard_ModuleRegistryMismatch(moduleRegistry, registry);
        }

        SAFE = safe;
        STRATEGY_MODULE = StrategyModule(strategyModule);
        REGISTRY = StrategyRegistry(registry);

        uint256 assetCount = trackedAssets_.length;
        for (uint256 i; i < assetCount; ++i) {
            address asset = trackedAssets_[i];
            if (isTrackedAsset[asset]) revert BoundModuleGuard_DuplicateTrackedAsset(asset);
            isTrackedAsset[asset] = true;
            _trackedAssets.push(asset);
        }

        uint256 pairCount = allowanceTokens.length;
        if (pairCount != allowedSpenders.length) {
            revert BoundModuleGuard_AllowanceLengthMismatch(pairCount, allowedSpenders.length);
        }
        for (uint256 i; i < pairCount; ++i) {
            address token = allowanceTokens[i];
            address spender = allowedSpenders[i];
            if (spender == address(0)) revert BoundModuleGuard_ZeroSpender();
            if (token == address(0)) revert BoundModuleGuard_NativeAllowanceToken();
            if (!isTrackedAsset[token]) revert BoundModuleGuard_AllowanceTokenNotTracked(token);
            if (isAllowedSpender[token][spender]) {
                revert BoundModuleGuard_DuplicateAllowancePair(token, spender);
            }

            isAllowedSpender[token][spender] = true;
            _allowedSpenders[token].push(spender);
            _allowancePairs.push(AllowancePair({token: token, spender: spender}));
        }
    }

    // ─── ERC-165 ─────────────────────────────────────────────────────────

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) external pure returns (bool supported) {
        return interfaceId == MODULE_GUARD_INTERFACE_ID || interfaceId == ERC165_INTERFACE_ID;
    }

    // ─── Configuration views ─────────────────────────────────────────────

    /// @notice Return the number of configured tracked assets.
    /// @return count Number of tracked assets.
    function trackedAssetCount() external view returns (uint256 count) {
        return _trackedAssets.length;
    }

    /// @notice Return one tracked asset by constructor-order index.
    /// @param index Index into the tracked asset enumeration.
    /// @return asset Tracked asset address; address(0) denotes native value.
    function trackedAssetAt(uint256 index) external view returns (address asset) {
        return _trackedAssets[index];
    }

    /// @notice Return every configured tracked asset.
    /// @return assets Tracked assets in constructor order.
    function getTrackedAssets() external view returns (address[] memory assets) {
        return _trackedAssets;
    }

    /// @notice Return the number of configured token/spender pairs.
    /// @return count Number of allowance pairs.
    function allowancePairCount() external view returns (uint256 count) {
        return _allowancePairs.length;
    }

    /// @notice Return one configured allowance pair by constructor-order index.
    /// @param index Index into the allowance pair enumeration.
    /// @return token Tracked ERC-20 address.
    /// @return spender Allowed spender address.
    function allowancePairAt(uint256 index) external view returns (address token, address spender) {
        AllowancePair storage pair = _allowancePairs[index];
        return (pair.token, pair.spender);
    }

    /// @notice Return all configured spenders for one token.
    /// @param token Tracked ERC-20 address.
    /// @return spenders Allowed spenders in constructor order.
    function getAllowedSpenders(address token) external view returns (address[] memory spenders) {
        return _allowedSpenders[token];
    }

    // ─── Safe 1.5 hooks ──────────────────────────────────────────────────

    /// @inheritdoc IModuleGuard
    function checkModuleTransaction(address to, uint256, bytes calldata data, Enum.Operation operation, address module)
        external
        returns (bytes32 moduleTxHash)
    {
        _requireSafe();
        if (operation != Enum.Operation.Call) revert BoundModuleGuard_OperationNotCall(operation);
        if (
            to == SAFE || to == address(this) || to == address(STRATEGY_MODULE) || to == address(REGISTRY)
                || REGISTRY.strategyEpoch(to) != 0 || IModuleGuardSafe(SAFE).isModuleEnabled(to)
        ) {
            revert BoundModuleGuard_ForbiddenTarget(to);
        }

        bytes4 selector = _selector(data);
        if (
            selector == PERMIT2_APPROVE_SELECTOR || selector == PERMIT2_PERMIT_SELECTOR
                || selector == PERMIT2_BATCH_PERMIT_SELECTOR
        ) {
            revert BoundModuleGuard_Permit2SelectorForbidden(to, selector);
        }
        if (to != address(0) && isTrackedAsset[to]) _checkTrackedTokenCall(to, data, selector);

        moduleTxHash = bytes32(_nextSnapshotNonce++);
        _snapshotExists[moduleTxHash] = true;

        uint256 assetCount = _trackedAssets.length;
        for (uint256 i; i < assetCount; ++i) {
            address asset = _trackedAssets[i];
            _snapshotBalances[moduleTxHash][asset] = _balanceOf(asset);
        }

        emit SnapshotCreated(moduleTxHash, module);
    }

    /// @inheritdoc IModuleGuard
    function checkAfterModuleExecution(bytes32 txHash, bool success) external {
        _requireSafe();
        if (!_snapshotExists[txHash]) revert BoundModuleGuard_UnknownSnapshot(txHash);
        delete _snapshotExists[txHash];

        uint256 assetCount = _trackedAssets.length;
        for (uint256 i; i < assetCount; ++i) {
            address asset = _trackedAssets[i];
            uint256 balanceBefore = _snapshotBalances[txHash][asset];
            delete _snapshotBalances[txHash][asset];
            uint256 balanceAfter = _balanceOf(asset);
            if (balanceAfter < balanceBefore) {
                revert BoundModuleGuard_ReserveDecreased(asset, balanceBefore, balanceAfter);
            }
        }

        emit SnapshotConsumed(txHash, success);
    }

    // ─── Internals ───────────────────────────────────────────────────────

    function _requireSafe() private view {
        if (msg.sender != SAFE) revert BoundModuleGuard_OnlySafe(msg.sender);
    }

    // Tracked reserves are intentionally enumerated to snapshot each configured balance.
    // slither-disable-start calls-loop
    function _balanceOf(address asset) private view returns (uint256 balance) {
        if (asset == address(0)) return SAFE.balance;
        return IReserveToken(asset).balanceOf(SAFE);
    }
    // slither-disable-end calls-loop

    function _selector(bytes calldata data) private pure returns (bytes4 selector) {
        if (data.length < 4) return bytes4(0);
        assembly ("memory-safe") {
            selector := calldataload(data.offset)
        }
    }

    function _checkTrackedTokenCall(address token, bytes calldata data, bytes4 selector) private view {
        if (selector != APPROVE_SELECTOR) {
            revert BoundModuleGuard_ApprovalSelectorForbidden(token, selector);
        }
        if (data.length != 68) revert BoundModuleGuard_MalformedApproveCalldata(data.length);

        uint256 spenderWord;
        uint256 amount;
        assembly ("memory-safe") {
            spenderWord := calldataload(add(data.offset, 4))
            amount := calldataload(add(data.offset, 36))
        }
        if (spenderWord >> 160 != 0) revert BoundModuleGuard_MalformedApproveCalldata(data.length);
        // Safe because the preceding check rejects any nonzero upper 96 bits.
        // forge-lint: disable-next-line(unsafe-typecast)
        address spender = address(uint160(spenderWord));
        if (amount != 0 && !isAllowedSpender[token][spender]) {
            revert BoundModuleGuard_SpenderNotAllowed(token, spender);
        }
    }
}

src/core/StrategyModule.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {IPolicyEngine} from "../interfaces/core/IPolicyEngine.sol";
import {IStrategy} from "../interfaces/core/IStrategy.sol";
import {StrategyRegistry} from "./StrategyRegistry.sol";

/// @title Enum
/// @notice Safe operation values: Call = 0, DelegateCall = 1.
/// @dev    Inlined to avoid vendoring the entire Safe contracts repo for a
///         single two-value enum. Enums encode as `uint8`, so this is
///         ABI-identical to Safe's own `Enum.Operation` on the module call path.
abstract contract Enum {
    enum Operation {
        Call,
        DelegateCall
    }
}

/// @title ISafe
/// @notice ABI-compatible subset of Safe's module execution interface.
/// @dev Module calls bypass the owner-transaction guard. Safe 1.5 can invoke a
///      separately installed module guard around each forwarded transaction.
interface ISafe {
    /// @notice Execute a transaction from an enabled Safe module.
    /// @dev The Safe authenticates the calling module and applies its module guard.
    /// @param to Target address.
    /// @param value Native asset amount in wei.
    /// @param data Target calldata.
    /// @param operation Call or delegatecall; Bound forwarding always uses Call.
    /// @return success Whether the target execution succeeded.
    function execTransactionFromModule(address to, uint256 value, bytes memory data, Enum.Operation operation)
        external
        returns (bool success);

    /// @notice Execute a module transaction and return the target's response.
    /// @dev Applies the same module authorization and installed module guard.
    /// @param to Target address.
    /// @param value Native asset amount in wei.
    /// @param data Target calldata.
    /// @param operation Call or delegatecall; Bound forwarding always uses Call.
    /// @return success Whether the target execution succeeded.
    /// @return returnData Target return or revert data.
    function execTransactionFromModuleReturnData(address to, uint256 value, bytes memory data, Enum.Operation operation)
        external
        returns (bool success, bytes memory returnData);

    /// @notice Check whether an address is enabled as a Safe module.
    /// @param module Address to inspect.
    /// @return True when the address is enabled.
    function isModuleEnabled(address module) external view returns (bool);
}

/// @title  StrategyModule
/// @notice Core Bound Safe Module. This router directs execution
///         payloads to the correct registered strategy.
///
/// @dev    This contract is enabled as a Safe Module via `enableModule()`.
///         It is the only contract that calls `execTransactionFromModule` on the
///         Safe. Individual strategies call back into this router to forward
///         their validated transactions to the Safe.
///
///         SECURITY: The StrategyModule itself holds no funds and has no
///         fallback/receive. It authenticates execution and isolates forwarding;
///         engines enforce their typed policies and execution postconditions.
///
///         Safe module calls bypass ITransactionGuard. A separately installed
///         Safe 1.5 module guard does run. This router does not require a specific
///         installed guard; deployment and keeper checks enforce that prerequisite.
contract StrategyModule {
    // ─── Errors ──────────────────────────────────────────────────────────

    error StrategyModule_StrategyNotRegistered(address strategy);
    error StrategyModule_OnlySafe(address caller);
    error StrategyModule_ExecutorNotAuthorized(address caller, address strategy);
    error StrategyModule_OnlyActiveStrategy(address caller, address activeStrategy);
    error StrategyModule_ExecutionFailed(address to, bytes data);
    error StrategyModule_ForbiddenTarget(address to);
    error StrategyModule_RegistrySafeMismatch(address safe, address registrySafe);
    error StrategyModule_ReentrantExecution(address activeStrategy);
    error StrategyModule_ZeroAddress();
    error StrategyModule_PolicyIdentityMismatch();

    // ─── Events ──────────────────────────────────────────────────────────

    event StrategyExecuted(address indexed strategy, address indexed safe, bytes32 dataHash);
    event SafeForwarded(
        address indexed strategy, address indexed to, uint256 value, Enum.Operation operation, bytes32 dataHash
    );
    event ExecutorSet(address indexed executor, bool allowed);
    event StrategyPermissionlessSet(address indexed strategy, bool allowed);

    // ─── State ───────────────────────────────────────────────────────────

    /// @notice The Safe multisig vault this router serves.
    address public immutable SAFE;

    /// @notice The StrategyRegistry that whitelists authorized strategies.
    StrategyRegistry public immutable REGISTRY;

    /// @notice Executors authorized across all registered engines and enabled policies.
    mapping(address executor => bool allowed) public isExecutor;

    /// @dev Registered strategies that may be executed by any caller.
    mapping(address strategy => bool allowed) private _isPermissionlessStrategy;

    /// @notice Registry epoch at which permissionless execution was enabled.
    mapping(address strategy => uint256 epoch) public permissionlessStrategyEpoch;

    /// @dev The strategy currently executing through `execute()`.
    address private _activeStrategy;

    /// @dev An active engine may request cleanup, which runs after it returns.
    bool private _autoRemovalRequested;

    // ─── Constructor ─────────────────────────────────────────────────────

    /// @notice Bind the router to one Safe and its matching registry.
    /// @param safe  The Safe multisig address.
    /// @param registry The StrategyRegistry address.
    constructor(address safe, address registry) {
        if (safe == address(0) || registry == address(0)) revert StrategyModule_ZeroAddress();
        address registrySafe = StrategyRegistry(registry).SAFE();
        if (registrySafe != safe) revert StrategyModule_RegistrySafeMismatch(safe, registrySafe);
        SAFE = safe;
        REGISTRY = StrategyRegistry(registry);
    }

    // ─── Modifiers ───────────────────────────────────────────────────────

    modifier onlySafe() {
        if (msg.sender != SAFE) revert StrategyModule_OnlySafe(msg.sender);
        _;
    }

    // ─── Admin ───────────────────────────────────────────────────────────

    /// @notice Add or remove an authorized executor.
    /// @dev Safe-caller only; approval is router-wide, with no per-engine scope or expiry.
    /// @param executor The keeper/executor address to configure.
    /// @param allowed  Whether `executor` may call `execute()`.
    function setExecutor(address executor, bool allowed) external onlySafe {
        if (executor == address(0)) revert StrategyModule_ZeroAddress();

        isExecutor[executor] = allowed;

        emit ExecutorSet(executor, allowed);
    }

    /// @notice Allow or disallow permissionless execution for a registered strategy.
    /// @dev Safe-caller only. Approval covers the engine's entire action surface,
    ///      including cancellation. Use it only when every allowed action/state
    ///      satisfies the project's permissionless execution criteria.
    /// @param strategy The registered strategy to configure.
    /// @param allowed  Whether any caller may execute `strategy`.
    function setStrategyPermissionless(address strategy, bool allowed) external onlySafe {
        if (strategy == address(0)) revert StrategyModule_ZeroAddress();
        if (allowed && !REGISTRY.isRegistered(strategy)) {
            revert StrategyModule_StrategyNotRegistered(strategy);
        }

        _isPermissionlessStrategy[strategy] = allowed;
        permissionlessStrategyEpoch[strategy] = allowed ? REGISTRY.strategyEpoch(strategy) : 0;

        emit StrategyPermissionlessSet(strategy, allowed);
    }

    /// @notice Whether `strategy` currently has valid permissionless execution.
    /// @dev Permissionless approval is bound to the registry lifecycle epoch, so
    ///      removing and re-registering a strategy invalidates the old approval.
    /// @param strategy The strategy to query.
    /// @return allowed True if anyone may currently execute `strategy`.
    function isPermissionlessStrategy(address strategy) public view returns (bool allowed) {
        return _isPermissionlessStrategy[strategy]
            && permissionlessStrategyEpoch[strategy] == REGISTRY.strategyEpoch(strategy);
    }

    // ─── External ────────────────────────────────────────────────────────

    /// @notice Advisory plan validation forwarded to a registered strategy.
    /// @dev Checks registration and delegates the engine's advisory subset. It
    ///      does not check executor authorization, Safe module enablement or the
    ///      installed guard. External reads and malformed plans may revert.
    /// @param strategy Address of the IStrategy to query.
    /// @param data ABI-encoded payload to pass to the strategy.
    /// @return executable True when registration and engine advisory checks pass.
    /// @return reason `bytes4(0)` when executable; otherwise an error selector.
    function canExecute(address strategy, bytes calldata data) external view returns (bool executable, bytes4 reason) {
        if (!REGISTRY.isRegistered(strategy)) {
            return (false, StrategyModule_StrategyNotRegistered.selector);
        }
        return IStrategy(strategy).canExecute(SAFE, data);
    }

    /// @notice Advisory validation bound to an exact policy identity and selected plan policy.
    /// @dev Malformed plans and failed engine reads may revert. Does not check executor authority.
    /// @param strategy Registered policy engine.
    /// @param policyId Policy selected by the plan.
    /// @param expectedRevision Reviewed monotonic revision.
    /// @param expectedHash Hash of the complete reviewed typed policy.
    /// @param data Original engine-specific typed plan.
    /// @return executable Whether identity and engine advisory checks pass.
    /// @return reason First failed check, or zero.
    function canExecutePolicy(
        address strategy,
        bytes32 policyId,
        uint256 expectedRevision,
        bytes32 expectedHash,
        bytes calldata data
    ) external view returns (bool executable, bytes4 reason) {
        if (!REGISTRY.isRegistered(strategy)) {
            return (false, StrategyModule_StrategyNotRegistered.selector);
        }
        if (!_policyIdentityMatches(strategy, policyId, expectedRevision, expectedHash, data)) {
            return (false, StrategyModule_PolicyIdentityMismatch.selector);
        }
        return IStrategy(strategy).canExecute(SAFE, data);
    }

    /// @notice Execute only the exact reviewed policy revision and complete policy hash.
    /// @dev Preserves the engine's typed plan ABI. Unlike execute, this binds configuration at inclusion time.
    /// @param strategy Registered policy engine.
    /// @param policyId Policy selected by the plan.
    /// @param expectedRevision Reviewed monotonic revision.
    /// @param expectedHash Hash of the complete reviewed typed policy.
    /// @param data Original engine-specific typed plan.
    function executePolicy(
        address strategy,
        bytes32 policyId,
        uint256 expectedRevision,
        bytes32 expectedHash,
        bytes calldata data
    ) external {
        _authorizeExecution(strategy);
        if (!_policyIdentityMatches(strategy, policyId, expectedRevision, expectedHash, data)) {
            revert StrategyModule_PolicyIdentityMismatch();
        }
        _execute(strategy, data);
    }

    function _policyIdentityMatches(
        address strategy,
        bytes32 policyId,
        uint256 expectedRevision,
        bytes32 expectedHash,
        bytes calldata data
    ) private view returns (bool) {
        IPolicyEngine engine = IPolicyEngine(strategy);
        return expectedRevision != 0 && engine.policyConfigured(policyId) && engine.executionPolicyId(data) == policyId
            && engine.policyRevision(policyId) == expectedRevision && engine.policyHash(policyId) == expectedHash;
    }

    /// @notice Execute a strategy against the vault. Called by a Safe-approved
    ///         executor, the Safe itself, or anyone for an explicitly
    ///         permissionless strategy. The strategy's onchain invariants
    ///         determine whether the transaction proceeds or reverts. This compatibility
    ///         path does not bind a policy revision; reviewed automation uses executePolicy.
    /// @dev Holds the active-engine mutex until execution completes. Simulate
    ///      from the intended caller to include module and Safe guard checks.
    /// @param  strategy  Address of the IStrategy to execute.
    /// @param  data      ABI-encoded payload to pass to the strategy.
    function execute(address strategy, bytes calldata data) external {
        _authorizeExecution(strategy);
        _execute(strategy, data);
    }

    function _authorizeExecution(address strategy) private view {
        if (!REGISTRY.isRegistered(strategy)) {
            revert StrategyModule_StrategyNotRegistered(strategy);
        }
        if (msg.sender != SAFE && !isExecutor[msg.sender] && !isPermissionlessStrategy(strategy)) {
            revert StrategyModule_ExecutorNotAuthorized(msg.sender, strategy);
        }
        if (_activeStrategy != address(0)) {
            revert StrategyModule_ReentrantExecution(_activeStrategy);
        }
    }

    function _execute(address strategy, bytes calldata data) private {
        _activeStrategy = strategy;
        // slither-disable-start reentrancy-no-eth
        // Mutex, not a bug: the write below RELEASES the lock acquired above; a
        // reentrant execute() reverts on the _activeStrategy check while the call runs.
        IStrategy(strategy).execute(SAFE, data);
        _activeStrategy = address(0);
        // slither-disable-end reentrancy-no-eth

        if (_autoRemovalRequested) {
            _autoRemovalRequested = false;
            REGISTRY.removeCompleted(strategy);
        }

        // Emitted after the guarded strategy call completes successfully.
        // slither-disable-next-line reentrancy-events
        emit StrategyExecuted(strategy, SAFE, keccak256(data));
    }

    /// @notice Request atomic removal after the active engine finishes execution.
    /// @dev Only the currently executing engine may request this. The registry
    ///      requires current Safe preauthorization and no unfinished policies.
    ///      Cleanup runs after forwarding is closed; any failure reverts the plan.
    function requestAutoRemoval() external {
        address strategy = _activeStrategy;
        if (msg.sender != strategy || strategy == address(0)) {
            revert StrategyModule_OnlyActiveStrategy(msg.sender, strategy);
        }
        _autoRemovalRequested = true;
    }

    /// @notice Forward a typed protocol call from the currently executing engine.
    /// @dev    Only the strategy currently executing through `execute()` may
    ///         forward. The operation is hardcoded to Call; delegatecall is never
    ///         exposed to strategies. Control-plane targets are blocked so a
    ///         strategy cannot make the Safe call itself, the registry, or this
    ///         module's Safe-admin functions, current or historical engines, or enabled modules.
    ///         The engine validates admission before forwarding and postconditions
    ///         after protocol execution; any revert rolls back the whole transaction.
    /// @param  to        Target contract to call (e.g. Uniswap Router).
    /// @param  value     ETH value to send.
    /// @param  data      Calldata for the target.
    function forwardToSafe(address to, uint256 value, bytes calldata data) external {
        address strategy = _validateForward(to);

        bool success = ISafe(SAFE).execTransactionFromModule(to, value, data, Enum.Operation.Call);
        if (!success) {
            revert StrategyModule_ExecutionFailed(to, data);
        }

        // Emitted only after the Safe confirms the forwarded call succeeded.
        // slither-disable-next-line reentrancy-events
        emit SafeForwarded(strategy, to, value, Enum.Operation.Call, keccak256(data));
    }

    /// @notice Forward a typed protocol call and return the target response.
    /// @dev Uses the native Safe return-data execution path with the same active
    ///      engine, Call-only, control-plane isolation and failure checks as
    ///      `forwardToSafe`. Engines must validate returned values and postconditions.
    /// @param to Target contract to call.
    /// @param value ETH value to send in wei.
    /// @param data Calldata for the target.
    /// @return returnData Target response bytes after a successful Safe execution.
    function forwardToSafeWithReturnData(address to, uint256 value, bytes calldata data)
        external
        returns (bytes memory returnData)
    {
        address strategy = _validateForward(to);
        bool success;
        (success, returnData) = ISafe(SAFE).execTransactionFromModuleReturnData(to, value, data, Enum.Operation.Call);
        if (!success) revert StrategyModule_ExecutionFailed(to, data);
        emit SafeForwarded(strategy, to, value, Enum.Operation.Call, keccak256(data));
    }

    function _validateForward(address to) private view returns (address strategy) {
        strategy = _activeStrategy;
        if (msg.sender != strategy || strategy == address(0)) {
            revert StrategyModule_OnlyActiveStrategy(msg.sender, strategy);
        }
        if (
            to == SAFE || to == address(REGISTRY) || to == address(this) || REGISTRY.strategyEpoch(to) != 0
                || ISafe(SAFE).isModuleEnabled(to)
        ) revert StrategyModule_ForbiddenTarget(to);
    }
}

src/core/StrategyRegistry.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title IAutoRemovalEngine
/// @notice Policy lifecycle surface used for Safe-preauthorized engine removal.
interface IAutoRemovalEngine {
    /// @notice Return the engine's immutable Bound module.
    /// @return module Engine execution chokepoint.
    function MODULE() external view returns (address module);

    /// @notice Count configured policies that have not permanently retired.
    /// @return count Unfinished policies, including disabled policies.
    function unfinishedPolicyCount() external view returns (uint256 count);
}

/// @title IAutoRemovalModule
/// @notice Module identity checks for narrow completion-removal authorization.
interface IAutoRemovalModule {
    /// @notice Return the Safe served by the module.
    /// @return safe Immutable Safe address.
    function SAFE() external view returns (address safe);

    /// @notice Return the module's strategy registry.
    /// @return registry Immutable registry address.
    function REGISTRY() external view returns (address registry);
}

/// @title  StrategyRegistry
/// @notice Strategy whitelist for Bound. Maintains which strategies
///         are authorized to execute against the vault. Only registered
///         strategies can be invoked by the StrategyModule.
///
/// @dev    The Safe adds and removes strategies and may preauthorize automatic
///         removal after every engine policy has retired. That narrow permission
///         is bound to the engine's module and current registration epoch.
///         The caller check authenticates the Safe address, not its signature
///         provenance. Owner-quorum control requires the reviewed module setup
///         and installed module guard. Registration is a bytecode authorization
///         decision; this registry does not verify the engine ABI or module binding.
contract StrategyRegistry {
    // ─── Errors ──────────────────────────────────────────────────────────

    error StrategyRegistry_OnlySafe(address caller);
    error StrategyRegistry_AlreadyRegistered(address strategy);
    error StrategyRegistry_NotRegistered(address strategy);
    error StrategyRegistry_NotContract(address strategy);
    error StrategyRegistry_ZeroAddress();
    error StrategyRegistry_InvalidAutoRemovalModule(address strategy, address module);
    error StrategyRegistry_AutoRemovalNotAuthorized(address caller, address strategy);
    error StrategyRegistry_StrategyUnfinished(address strategy, uint256 count);

    // ─── Events ──────────────────────────────────────────────────────────

    event StrategyRegistered(address indexed strategy);
    event StrategyRemoved(address indexed strategy);
    event StrategyAutoRemovalSet(address indexed strategy, address indexed module, bool allowed, uint256 epoch);
    event StrategyAutoRemoved(address indexed strategy, address indexed module, uint256 epoch);

    // ─── State ───────────────────────────────────────────────────────────

    /// @notice The Safe multisig that owns this registry.
    address public immutable SAFE;

    /// @notice Mapping of strategy address → registered status.
    mapping(address => bool) public isRegistered;

    /// @notice Array of all currently registered strategies.
    address[] public strategies;

    /// @notice Index of each strategy in the `strategies` array (1-indexed for
    ///         zero-check; actual index = value - 1).
    mapping(address => uint256) internal _strategyIndex;

    /// @notice Monotonic lifecycle version for each strategy address.
    mapping(address strategy => uint256 epoch) public strategyEpoch;

    /// @notice Module authorized by the Safe to remove a completed engine.
    mapping(address strategy => address module) public strategyAutoRemovalModule;

    /// @notice Registration epoch to which an automatic-removal approval belongs.
    mapping(address strategy => uint256 epoch) public strategyAutoRemovalEpoch;

    // ─── Constructor ─────────────────────────────────────────────────────

    /// @notice Bind the registry to one immutable Safe.
    /// @param safe The Safe multisig address that governs this registry.
    constructor(address safe) {
        if (safe == address(0)) revert StrategyRegistry_ZeroAddress();
        SAFE = safe;
    }

    // ─── Modifiers ───────────────────────────────────────────────────────

    modifier onlySafe() {
        if (msg.sender != SAFE) revert StrategyRegistry_OnlySafe(msg.sender);
        _;
    }

    // ─── Admin ───────────────────────────────────────────────────────────

    /// @notice Register a new strategy with the registry.
    /// @dev Safe-caller only. Requires deployed code and advances the lifecycle epoch.
    /// @param strategy Address of the IStrategy contract to whitelist.
    function register(address strategy) external onlySafe {
        if (strategy == address(0)) revert StrategyRegistry_ZeroAddress();
        if (strategy.code.length == 0) revert StrategyRegistry_NotContract(strategy);
        if (isRegistered[strategy]) revert StrategyRegistry_AlreadyRegistered(strategy);

        strategyEpoch[strategy]++;
        isRegistered[strategy] = true;
        strategies.push(strategy);
        _strategyIndex[strategy] = strategies.length; // 1-indexed

        emit StrategyRegistered(strategy);
    }

    /// @notice Remove a strategy from the registry.
    /// @dev Safe-caller only. Invalidates permissionless approval and reorders
    ///      enumeration. Existing external orders must be retired before removal.
    /// @param strategy Address of the IStrategy contract to remove.
    function remove(address strategy) external onlySafe {
        if (!isRegistered[strategy]) revert StrategyRegistry_NotRegistered(strategy);

        _remove(strategy);
    }

    /// @notice Preauthorize or revoke removal after all engine policies retire.
    /// @dev Safe-only. Approval covers only the current registration epoch and
    ///      the engine's Bound module; it never authorizes registration or updates.
    /// @param strategy Registered policy engine whose completion is trusted.
    /// @param allowed Whether its module may remove it after completion.
    function setStrategyAutoRemoval(address strategy, bool allowed) external onlySafe {
        address module = address(0);
        uint256 epoch = 0;
        if (allowed) {
            if (!isRegistered[strategy]) revert StrategyRegistry_NotRegistered(strategy);
            module = IAutoRemovalEngine(strategy).MODULE();
            if (
                module.code.length == 0 || IAutoRemovalModule(module).SAFE() != SAFE
                    || IAutoRemovalModule(module).REGISTRY() != address(this)
            ) revert StrategyRegistry_InvalidAutoRemovalModule(strategy, module);
            epoch = strategyEpoch[strategy];
        }
        strategyAutoRemovalModule[strategy] = module;
        strategyAutoRemovalEpoch[strategy] = epoch;
        emit StrategyAutoRemovalSet(strategy, module, allowed, epoch);
    }

    /// @notice Whether automatic removal is approved for this registration.
    /// @param strategy Policy engine to inspect.
    /// @return allowed True when registered with a current module-bound approval.
    function isStrategyAutoRemovalEnabled(address strategy) public view returns (bool allowed) {
        return isRegistered[strategy] && strategyAutoRemovalModule[strategy] != address(0)
            && strategyAutoRemovalEpoch[strategy] == strategyEpoch[strategy];
    }

    /// @notice Remove a completed engine through its Safe-approved module.
    /// @dev The module invokes this only after a successful engine execution has
    ///      returned and forwarding is closed. A failed cleanup reverts execution.
    ///      Disabled but unretired policies still count as unfinished.
    /// @param strategy Engine whose policies have all retired.
    function removeCompleted(address strategy) external {
        if (!isStrategyAutoRemovalEnabled(strategy) || msg.sender != strategyAutoRemovalModule[strategy]) {
            revert StrategyRegistry_AutoRemovalNotAuthorized(msg.sender, strategy);
        }
        uint256 unfinished = IAutoRemovalEngine(strategy).unfinishedPolicyCount();
        if (unfinished != 0) revert StrategyRegistry_StrategyUnfinished(strategy, unfinished);
        _remove(strategy);
        emit StrategyAutoRemoved(strategy, msg.sender, strategyEpoch[strategy]);
    }

    function _remove(address strategy) private {
        isRegistered[strategy] = false;
        strategyEpoch[strategy]++;

        // Swap-and-pop from the strategies array
        uint256 idx = _strategyIndex[strategy] - 1;
        uint256 lastIdx = strategies.length - 1;

        if (idx != lastIdx) {
            address lastStrategy = strategies[lastIdx];
            strategies[idx] = lastStrategy;
            _strategyIndex[lastStrategy] = idx + 1;
        }

        strategies.pop();
        delete _strategyIndex[strategy];

        emit StrategyRemoved(strategy);
    }

    // ─── Views ───────────────────────────────────────────────────────────

    /// @notice Return all currently registered strategies.
    /// @return Registered strategy addresses; order can change on removal.
    function getStrategies() external view returns (address[] memory) {
        return strategies;
    }

    /// @notice Return the number of registered strategies.
    /// @return Number of currently registered addresses.
    function count() external view returns (uint256) {
        return strategies.length;
    }
}

src/interfaces/core/IPolicyEngine.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {IStrategy} from "./IStrategy.sol";

/// @title  IPolicyEngine
/// @notice Shared interface for Bound strategy engines with Safe-owned policies.
/// @dev    Concrete engines add typed policy records and typed execution plans.
///         This interface exposes only the common lifecycle and state surface
///         inherited from `BaseStrategyEngine`.
interface IPolicyEngine is IStrategy {
    /// @notice Resolve the policy selected by an engine-specific typed plan.
    /// @param data ABI-encoded typed plan; malformed input may revert.
    /// @return policyId Selected Safe-owned policy.
    function executionPolicyId(bytes calldata data) external view returns (bytes32 policyId);

    /// @notice Monotonic add/update and executable-configuration revision.
    /// @param policyId Safe-owned policy.
    /// @return revision Current revision, or zero for an unconfigured policy.
    function policyRevision(bytes32 policyId) external view returns (uint256 revision);

    /// @notice Hash of the complete ABI-encoded typed policy.
    /// @param policyId Safe-owned policy.
    /// @return digest Current hash, or zero for an unconfigured policy.
    function policyHash(bytes32 policyId) external view returns (bytes32 digest);

    /// @notice Read the stored execution and budget buckets for a policy id.
    /// @dev Execution projects epoch rollover and charges the current plus the
    ///      full previous bucket. This conservatively bounds a trailing window
    ///      and can charge activity for up to one extra epoch. This getter does
    ///      not project rollover. Amount units are defined by the concrete engine;
    ///      policy counters do not segregate the Safe's assets or protocol account.
    /// @param policyId Safe-owned policy id.
    /// @return lastExecution Last successful execution timestamp, or zero.
    /// @return epochStart Current budget epoch start timestamp.
    /// @return epochNotionalUsed Notional booked in the current stored bucket.
    /// @return prevEpochNotionalUsed Notional used in the previous bucket.
    /// @return epochLossUsed Realized loss booked in the current stored bucket, if supported.
    /// @return prevEpochLossUsed Realized loss booked in the previous bucket.
    function policyState(bytes32 policyId)
        external
        view
        returns (
            uint256 lastExecution,
            uint256 epochStart,
            uint256 epochNotionalUsed,
            uint256 prevEpochNotionalUsed,
            uint256 epochLossUsed,
            uint256 prevEpochLossUsed
        );

    /// @notice Whether a policy id has been added.
    /// @param policyId Safe-owned policy id.
    /// @return configured True when the engine has policy config for `policyId`.
    function policyConfigured(bytes32 policyId) external view returns (bool configured);

    /// @notice Whether the Safe has enabled a configured policy id.
    /// @dev Enabled status alone does not establish that a plan can execute.
    /// @param policyId Safe-owned policy id.
    /// @return enabled True when the Safe has enabled execution for `policyId`.
    function policyEnabled(bytes32 policyId) external view returns (bool enabled);

    /// @notice Enable an existing policy id.
    /// @dev Only the Safe served by the engine's immutable module may call this.
    /// @param policyId Safe-owned policy id to enable.
    function enablePolicy(bytes32 policyId) external;
}

src/interfaces/core/IStrategy.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title  IStrategy
/// @notice Interface that all Bound strategy contracts must implement.
///         Each strategy represents a single automated execution — a targeted,
///         invariant-guarded execution against a specific DeFi protocol.
///
/// @dev    Strategies are registered in the StrategyRegistry and invoked by the
///         StrategyModule. Keepers produce typed execution plans off-chain; strategy
///         contracts validate those plans onchain before forwarding any Safe call.
interface IStrategy {
    /// @notice Evaluate the engine's advisory checks for a keeper plan.
    /// @dev Checks vary by engine and exclude caller authorization, installed
    ///      Safe guards and final execution postconditions. Malformed calldata
    ///      or failing external reads may revert. Simulate the complete module
    ///      transaction from the intended executor before submitting it.
    /// @param safe The Safe multisig vault.
    /// @param plan ABI-encoded strategy-specific execution plan.
    /// @return executable True when the implemented advisory checks pass.
    /// @return reason `bytes4(0)` when executable; otherwise the selector for the
    ///         first validation error the strategy can identify off-chain.
    function canExecute(address safe, bytes calldata plan) external view returns (bool executable, bytes4 reason);

    /// @notice Execute a typed plan against the configured protocol.
    /// @dev Bound engines restrict this entry point to their immutable module.
    ///      Validate admission conditions before moving custody, then enforce
    ///      postconditions after the typed protocol calls. Any failed check
    ///      reverts the entire transaction, including preceding protocol accrual.
    /// @param safe The address of the Safe multisig vault.
    /// @param plan ABI-encoded strategy-specific execution plan.
    function execute(address safe, bytes calldata plan) external;
}

src/interfaces/tokens/IERC20Minimal.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title IERC20Minimal
/// @notice ERC-20 balance and allowance methods used by Bound.
/// @dev Minimal subset, not a complete ERC-20 interface. Amounts use raw token units.
///      Safe forwarding checks call success rather than decoding approval return data;
///      Bound's forwarding helpers require zero residual allowance after approval cleanup.
interface IERC20Minimal {
    /// @notice Sets the caller's allowance for a spender.
    /// @dev Replaces the existing allowance; token-specific approval restrictions may apply.
    /// @param spender Account that receives allowance.
    /// @param amount Allowance in raw token units.
    /// @return success True when the token reports approval success.
    function approve(address spender, uint256 amount) external returns (bool);

    /// @notice Read token allowance.
    /// @dev Reports authorization, not the owner's available balance.
    /// @param owner Token owner.
    /// @param spender Allowance spender.
    /// @return amount Current allowance in raw token units.
    function allowance(address owner, address spender) external view returns (uint256);

    /// @notice Read token balance.
    /// @dev The value follows the token's own accounting, including any rebasing behavior.
    /// @param account Token holder.
    /// @return amount Current balance in raw token units.
    function balanceOf(address account) external view returns (uint256);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "viaSSACFG": false,
  "evmVersion": "osaka",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ],
  "experimental": false
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.