Skip to content
Verified contractPartialUNLICENSED

SwapModule

Address0x875afe759edc811f0d15adcbbe3315dface7b197
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
UNLICENSED
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,159,290
Creation transaction
0x937db374b6…ac42b75178

src/modules/SwapModule.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2026 Truss Labs
pragma solidity 0.8.28;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {IExecutionModule} from "src/interfaces/IExecutionModule.sol";
import {ModuleBase} from "src/modules/ModuleBase.sol";
import {Errors} from "src/types/Errors.sol";
import {ModuleTypes} from "src/types/ModuleTypes.sol";

/// @title SwapModule
/// @author Truss Labs
/// @notice Swaps a pair through any router. The route declares which spenders it needs; the module grants those
///         allowances once, runs the calls, revokes them, and approves both legs back to the owner. No price check
///         of its own; the owner's is the check.
/// @dev The module grants the input's allowance itself, at the input the owner handed over, because that is what
///      lets a holder's unwind be sized when it runs rather than when it was written. Every other allowance a route
///      needs is declared the same way, and all of them are revoked when the calls are done. The module ends holding
///      neither leg and its owner measures what arrived, so whatever else a route does with a token answers to that
///      measurement.
contract SwapModule is ModuleBase {
    using SafeERC20 for IERC20;

    /// @notice One allowance a route needs: `spender` may take `token` from this module while the route runs. The
    ///         input is granted at exactly the handed-over amount; anything else at whatever the route brings in.
    struct Approval {
        address token;
        address spender;
    }

    /// @inheritdoc IExecutionModule
    /// @dev `moduleData` is `abi.encode(Approval[])`, or empty for a route that needs none.
    function execute(
        Intent calldata intent,
        address[] calldata targets,
        bytes[] calldata calls,
        bytes calldata moduleData
    ) external override onlyOwner nonReentrant {
        SingleInOutIntent memory pair = _singleInOutIntent(intent);
        require(targets.length == calls.length, IExecutionModule.TargetsCallsMismatch(targets.length, calls.length));
        Approval[] memory approvals = moduleData.length == 0 ? new Approval[](0) : abi.decode(moduleData, (Approval[]));
        for (uint256 i = 0; i < approvals.length; i++) {
            _requireCallableTarget(approvals[i].spender);
            uint256 allowed = approvals[i].token == pair.input.asset ? pair.input.amount : type(uint256).max;
            IERC20(approvals[i].token).forceApprove(approvals[i].spender, allowed);
        }
        for (uint256 i = 0; i < targets.length; i++) {
            _requireCallableTarget(targets[i]);
            (bool ok, bytes memory returned) = targets[i].call(calls[i]);
            if (!ok) {
                // Bubble the venue's own reason so an operator can read why the route failed.
                assembly ("memory-safe") {
                    revert(add(returned, 32), mload(returned))
                }
            }
        }
        for (uint256 i = 0; i < approvals.length; i++) {
            IERC20(approvals[i].token).forceApprove(approvals[i].spender, 0);
        }
        IERC20(pair.assetOut).forceApprove(msg.sender, IERC20(pair.assetOut).balanceOf(address(this)));
        IERC20(pair.input.asset).forceApprove(msg.sender, IERC20(pair.input.asset).balanceOf(address(this)));
    }

    /// @inheritdoc IExecutionModule
    function moduleType() external pure virtual override returns (bytes32) {
        return ModuleTypes.SWAP;
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /// @dev Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
    function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
        bytes4 selector = IERC20Metadata.decimals.selector;
        assembly ("memory-safe") {
            mstore(0x00, selector)
            success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
            success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
            decimals := mul(success, mload(0x00))
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
     * return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
     * value: the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
     * the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param spender The spender of the tokens
     * @param value The amount of token to approve
     * @param bubble Behavior switch if the approve call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuardTransient.sol)

pragma solidity ^0.8.24;

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

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 *
 * _Available since v5.1._
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuardTransient {
    using TransientSlot for *;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().asBoolean().tstore(true);
    }

    function _nonReentrantAfter() private {
        _reentrancyGuardStorageSlot().asBoolean().tstore(false);
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _reentrancyGuardStorageSlot().asBoolean().tload();
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represents a slot holding an address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

src/interfaces/IExecutionModule.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2026 Truss Labs
pragma solidity ^0.8.28;

import {InputLeg} from "src/types/InputLeg.sol";

/// @title IExecutionModule
/// @author Truss Labs
/// @notice The shape every execution module implements. A module is owned by exactly one sub-account and holds
///         nothing between calls; its owner measures every outcome itself.
interface IExecutionModule {
    /// @notice Complete caller-authorized asset sets and a tolerance over their aggregate measured values.
    struct Intent {
        /// @dev Each amount is a maximum input quantity; the sub-account resolves Constants.ALL before execution.
        InputLeg[] inputs;
        address[] outputs;
        uint16 toleranceBps;
    }

    /// @notice The caller is not the module's owner.
    /// @custom:selector 0x333886de
    error CallerNotModuleOwner(address caller);

    /// @notice A module may not call a system address.
    /// @custom:selector 0xef8f0bb6
    error ProtectedTarget(address target);

    /// @notice Targets and calls differ in length.
    /// @custom:selector 0x16397d18
    error TargetsCallsMismatch(uint256 targets, uint256 calls);

    /// @notice A balance a route left in the module was sent home to the owning sub-account.
    event Swept(address indexed token, uint256 amount);

    /// @notice Getter for the module family.
    /// @return moduleType The module family; a policy governs only modules of its own family.
    function moduleType() external pure returns (bytes32);

    /// @notice Sends everything the module holds of `token` to the sub-account that owns it. Permissionless, since
    ///          the destination is fixed.
    /// @param token The token to send home.
    function sweep(address token) external;

    /// @notice Getter for the sub-account that owns this instance.
    /// @return owner The sub-account that owns this instance, set at initialization.
    function owner() external view returns (address);

    /// @notice Whether `intent` only unwraps a position the owner already holds into `output`, so that crediting
    ///         `output` adds no exposure the owner did not already have.
    /// @param intent An execution the owner runs through this module.
    /// @param output One of the intent's outputs.
    /// @return unwraps True only when all of `output` the execution pays comes out of the input position.
    function unwraps(Intent calldata intent, address output) external view returns (bool);

    /// @notice Runs the execution for the owning sub-account, which is the only permitted caller. `targets` and
    ///          `calls` are the venue calls the owner has already screened; `moduleData` is this module's own payload,
    ///          opaque to the owner. Returns nothing: the owner measures what moved from its own balances, so a module
    ///          has no claim to make about it.
    /// @dev The owner checks only what holds for every module: one or two inputs, one or two outputs, and no zero,
    ///      repeated or shared asset across them. Everything else about `intent` is the module's to check:
    ///      how many inputs and outputs it takes, which assets they may be, and how they relate. A module must revert
    ///      on any intent it was not built for, because the owner books every declared leg and applies the tolerance
    ///      to their summed value, not to each leg.
    /// @param intent What the execution means to do.
    /// @param targets Addresses the module calls.
    /// @param calls Calldata for each target, in the same order.
    /// @param moduleData Payload only the module decodes.
    function execute(
        Intent calldata intent,
        address[] calldata targets,
        bytes[] calldata calls,
        bytes calldata moduleData
    ) external;
}

src/interfaces/IMulticall.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2026 Truss Labs
pragma solidity ^0.8.28;

/// @title IMulticall
/// @author Truss Labs
/// @notice Runs several calls against the implementing contract in one transaction, delegating to itself so each
///         inner call is authorized against the original caller. The first revert aborts the whole batch.
interface IMulticall {
    /// @notice Runs `data` in order; reverts with the first inner revert.
    /// @param data Execution payload in the shape the implementation decodes.
    /// @return results Each call's return data, in order.
    function multicall(bytes[] calldata data) external returns (bytes[] memory results);
}

src/interfaces/INavOracle.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2026 Truss Labs
pragma solidity ^0.8.28;

/// @title INavOracle
/// @author Truss Labs
/// @notice Sums sub-account positions through the price oracle and returns NAV in the vault's underlying at its
///         decimals, through exactly one underlying/USD conversion. Never reverts on feed content.
interface INavOracle {
    /// @notice A NAV figure with its freshness.
    struct Nav {
        /// @dev In underlying units at underlying decimals.
        uint256 assets;
        /// @dev The OR of every input's staleness.
        bool isStale;
    }

    /// @notice The address is not a sub-account of the vault.
    /// @custom:selector 0x0c31c9d4
    error NotASubAccount(address subAccount);

    /// @notice Getter for the vault this oracle serves.
    /// @return vault The vault this oracle serves.
    function vault() external view returns (address);

    /// @notice Getter for the price oracle it routes through.
    /// @return priceOracle The price oracle it routes through.
    function priceOracle() external view returns (address);

    /// @notice Getter for the underlying this oracle converts into.
    /// @return underlying The underlying this oracle converts into; the vault checks the match when it binds.
    function underlying() external view returns (address);

    /// @notice Returns accounted idle plus every sub-account's total NAV.
    /// @return vaultNav Accounted idle plus every sub-account's total NAV, in units of the underlying.
    function vaultNav() external view returns (Nav memory);

    /// @notice Returns one sub-account's total NAV.
    /// @param subAccount Address of the sub-account.
    /// @return subAccountNav One sub-account's total NAV, in units of the underlying.
    function subAccountNav(address subAccount) external view returns (Nav memory);

    /// @notice Converts `usdWad`, USD at 18 decimals, to the underlying.
    /// @param usdWad Amount in USD at 18 decimals.
    /// @return amount The amount in units of the underlying.
    /// @return isStale Whether the underlying's price could not be read.
    function usdWadToUnderlying(uint256 usdWad) external view returns (uint256 amount, bool isStale);
}

src/interfaces/ISubAccount.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2026 Truss Labs
pragma solidity ^0.8.28;

import {IMulticall} from "src/interfaces/IMulticall.sol";
import {INavOracle} from "src/interfaces/INavOracle.sol";
import {IVaultBound} from "src/interfaces/IVaultBound.sol";

/// @title ISubAccount
/// @author Truss Labs
/// @notice The custody and lifecycle surface shared by every vault compartment.
interface ISubAccount is IVaultBound, IMulticall {
    /// @notice Whether the account's NAV is derived from on-chain positions or supplied by attestation.
    enum ValuationMode {
        Derived,
        Attested
    }

    /// @notice Underlying was deposited into the account.
    event Deposited(uint256 amount);
    /// @notice The account's operational pause was changed.
    event PauseSet(bool paused);
    /// @notice Underlying was returned to the vault.
    event Returned(uint256 amount);
    /// @notice The policy controlling allocations into the account was changed.
    event SubAccountAllocationPolicySet(address indexed policy);

    /// @notice The account holds less available underlying than the vault requested.
    /// @custom:selector 0xb520f771
    error InsufficientUnderlying(uint256 requested, uint256 available);
    /// @notice The operation is unavailable while the account is paused.
    /// @custom:selector 0x096a3f2a
    error SubAccountPaused();

    /// @notice Pulls underlying from the vault and records the deposit.
    /// @param amount Amount of underlying to pull.
    /// @param extraArgs Flavor-specific deposit data.
    function deposit(uint256 amount, bytes calldata extraArgs) external;

    /// @notice Returns available underlying to the owning vault.
    /// @param amount Amount to return, or `type(uint256).max` for all available underlying.
    function returnAssetsToVault(uint256 amount) external;

    /// @notice Pauses the operator's execution and the vault's deposits into the account. Returning assets stays
    ///         available, and so does a holder's unwind on an account that offers one.
    function pause() external;

    /// @notice Resumes the operator's execution and the vault's deposits into the account.
    function unpause() external;

    /// @notice Sets the policy consulted before the vault allocates underlying to this account.
    /// @param policy Address of the allocation policy, or zero to remove it.
    function setSubAccountAllocationPolicy(address policy) external;

    /// @notice Returns the underlying that can be sent back without an unwind.
    /// @return available Amount currently available, in units of the underlying.
    function availableUnderlying() external view returns (uint256);

    /// @notice Returns how the account's NAV is established.
    /// @return mode Derived for tracked accounts or Attested for attested accounts.
    function valuationMode() external view returns (ValuationMode);

    /// @notice Returns the account's NAV and staleness status.
    /// @return accountNav NAV in units of the vault underlying and whether it is stale.
    function nav() external view returns (INavOracle.Nav memory);

    /// @notice Returns whether the account satisfies its flavor-specific removal conditions.
    /// @return removable Whether the vault may finalize removal of the account.
    function canRemove() external view returns (bool);

    /// @notice Returns the policy consulted before deposits into this account.
    /// @return policy Address of the allocation policy, or zero when none is bound.
    function subAccountAllocationPolicy() external view returns (address);

    /// @notice Returns whether the operator's execution and the vault's deposits into the account are paused.
    /// @return isPaused Whether the account is paused.
    function paused() external view returns (bool);
}

src/interfaces/ITrackedSubAccount.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2026 Truss Labs
pragma solidity ^0.8.28;

import {IExecutionModule} from "src/interfaces/IExecutionModule.sol";
import {ISubAccount} from "src/interfaces/ISubAccount.sol";

/// @title ITrackedSubAccount
/// @author Truss Labs
/// @notice A compartment whose NAV is derived from registered ERC-20 quantities and on-chain prices.
interface ITrackedSubAccount is ISubAccount {
    /// @notice A module execution completed and its measured movement was recorded. `holderInitiated` marks a step of
    ///         a forced-exit unwind; of one unwind's steps only the first moves the book.
    event Executed(
        address indexed module,
        address indexed assetIn,
        address indexed assetOut,
        uint256 amountIn,
        uint256 amountOut,
        bool holderInitiated
    );
    /// @notice A secondary execution asset moved. Primary amounts are in `Executed`; quantities are token units.
    event ExecutionAssetMovement(
        address indexed module, address indexed asset, uint256 spent, uint256 received, bool holderInitiated
    );
    /// @notice A module and its policy were installed.
    event ModuleAdded(address indexed module, address indexed policy);
    /// @notice A module was removed.
    event ModuleRemoved(address indexed module);
    /// @notice An unprotected token balance was rescued.
    event TokensRescued(address indexed asset, address indexed to, uint256 amount);

    /// @notice The execution attempted to increase an asset the registry does not admit.
    /// @custom:selector 0x4ff83916
    error AssetNotIncreasable(address asset);
    /// @custom:selector 0xb9f91cff
    error AssetNotValued(address asset);
    /// @custom:selector 0x467dcf9f
    error InsufficientTracked(address asset, uint256 requested, uint256 tracked);
    /// @custom:selector 0xcae25e0e
    error InsufficientUntracked(address asset, uint256 requested, uint256 untracked);
    /// @notice Execution consumed more of an input than its declared maximum.
    /// @custom:selector 0x7f9b245f
    error ExecutionSpendExceedsInput(address asset, uint256 amount, uint256 spent);
    /// @custom:selector 0x5c426a42
    error ModuleAlreadyInstalled(address module);
    /// @custom:selector 0x8e3b8e1a
    error ModuleHoldsResidue(address module, address asset, uint256 amount);
    /// @custom:selector 0x026d9639
    error ModuleNotInstalled(address module);
    /// @custom:selector 0xdb464741
    error ModuleOwnerMismatch(address module, address owner);
    /// @custom:selector 0xd4dbf0ef
    error PolicyTypeMismatch(address module, address policy);
    /// @notice An input asset also appears in the declared output set.
    /// @custom:selector 0x29cb2ab5
    error SameAsset(address asset);
    /// @custom:selector 0xeef3d3cc
    error PositionBlocksRemoval(address module, address asset);
    /// @notice An unwind ended holding proceeds other than the underlying that no later step spent.
    /// @custom:selector 0x35008291
    error UnwindLeavesProceeds(address asset, uint256 amount);
    /// @custom:selector 0x12a50112
    error UnwindMustProduceUnderlying(address assetOut);
    /// @notice An unwind step took more of its input from this account than it handed the module.
    /// @custom:selector 0x94c6bfc5
    error UnwindSpendExceedsInput(uint256 amountIn, uint256 spent);
    /// @custom:selector 0x85b9a5fe
    error UnwindSpendMismatch(uint256 heldBefore, uint256 heldAfter);
    /// @notice A step may spend only what is available to it: the sized booked quantity for the first step,
    ///         remaining proceeds from earlier steps for each later one.
    /// @custom:selector 0x75039496
    error UnwindStepExceedsAvailable(uint256 amount, uint256 available);
    /// @notice A step after the first must spend an asset produced by an earlier step.
    /// @custom:selector 0x32b07f8e
    error UnwindStepInputMismatch(address produced, address input);
    /// @notice An unwind names at least one step, and a module, an input leg and a payload for each.
    /// @custom:selector 0x73350d41
    error UnwindStepsMismatch(uint256 modules, uint256 inputs, uint256 data);

    /// @notice Executes an installed module and updates tracked asset quantities from measured balance changes.
    /// @param module Address of the installed module.
    /// @param intent Complete input maxima and output assets, with an aggregate value tolerance.
    /// @param data Module-specific execution data.
    /// @param policyData Data supplied to the installed module policy.
    /// @return amountOut Measured primary output quantity; secondary quantities are in ExecutionAssetMovement.
    function executeModule(
        address module,
        IExecutionModule.Intent calldata intent,
        bytes calldata data,
        bytes calldata policyData
    ) external returns (uint256 amountOut);

    /// @notice Installs a module and the policy that governs it.
    /// @param module Address of the module, owned by this account.
    /// @param policy Address of a policy compatible with the module family.
    function addModule(address module, address policy) external;

    /// @notice Removes an installed module once the account tracks nothing but the underlying. The same module may be
    ///         added again later.
    /// @param module Address of the installed module.
    function removeModule(address module) external;

    /// @notice Sends an unprotected token balance out of the account.
    /// @param asset Token to rescue.
    /// @param to Recipient of the rescued tokens.
    /// @param amount Quantity to send, at most `untracked(asset)`.
    function rescueTokens(address asset, address to, uint256 amount) external;

    /// @notice Returns every asset the account's NAV values, with the quantity the account tracks of each.
    /// @return assets Addresses of the valued assets.
    /// @return quantities The tracked quantity of each, in that asset's units.
    function positions() external view returns (address[] memory assets, uint256[] memory quantities);

    /// @notice Returns the quantity of an asset the account tracks.
    /// @param asset Address of the asset.
    /// @return quantity Tracked quantity in the asset's own units.
    function trackedQuantity(address asset) external view returns (uint256);

    /// @notice Returns the account's balance of an asset above what it tracks.
    /// @param asset Address of the asset.
    /// @return quantity Untracked quantity in the asset's own units.
    function untracked(address asset) external view returns (uint256);

    /// @notice Returns whether a module is installed on the account.
    /// @param module Address of the module.
    /// @return installed Whether the module is installed.
    function isModuleInstalled(address module) external view returns (bool);

    /// @notice Returns the policy bound to an installed module.
    /// @param module Address of the module.
    /// @return policy Address of the module's policy, or zero when not installed.
    function modulePolicy(address module) external view returns (address);

    /// @notice Returns all installed modules.
    /// @return installedModules Installed module addresses, in no particular order.
    function modules() external view returns (address[] memory);

    /// @notice Returns whether arbitrary approvals or rescues must not target an address.
    /// @param target Address to check.
    /// @return protectedAddress Whether the address is protected by the account.
    function isProtectedAddress(address target) external view returns (bool);

    /// @notice Returns the registry defining which assets the account may hold and value.
    /// @return registry Address of the asset registry.
    function assetRegistry() external view returns (address);

    /// @notice Returns the price oracle used to value tracked assets.
    /// @return oracle Address of the price oracle.
    function priceOracle() external view returns (address);

    /// @notice Returns the vault-level NAV oracle that values this account.
    /// @return oracle Address of the NAV oracle.
    function navOracle() external view returns (address);
}

src/interfaces/IVaultBound.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2026 Truss Labs
pragma solidity ^0.8.28;

/// @title IVaultBound
/// @author Truss Labs
/// @notice A contract that serves exactly one vault.
interface IVaultBound {
    /// @notice Getter for the vault this contract serves.
    /// @return vault The vault this contract serves.
    function vault() external view returns (address);
}

src/modules/ModuleBase.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2026 Truss Labs
pragma solidity 0.8.28;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";

import {IExecutionModule} from "src/interfaces/IExecutionModule.sol";
import {ITrackedSubAccount} from "src/interfaces/ITrackedSubAccount.sol";

import {Constants} from "src/types/Constants.sol";
import {Errors} from "src/types/Errors.sol";
import {InputLeg} from "src/types/InputLeg.sol";

/// @title ModuleBase
/// @author Truss Labs
/// @notice What every execution module shares: an owner fixed at initialization, so a clone serves one sub-account
///         for life; the owner-only entry; and the owner's denylist, checked on every venue call.
/// @dev Holds nothing at rest: whatever it receives is approved back to the owner, which checks nothing was left.
abstract contract ModuleBase is ReentrancyGuardTransient, IExecutionModule {
    using SafeERC20 for IERC20;

    /// @dev The one input and one output of a pair-only module's execution.
    struct SingleInOutIntent {
        InputLeg input;
        address assetOut;
        uint16 toleranceBps;
    }

    /// @dev The sub-account this instance serves. Zero until initialized; no setter exists after that.
    address private _owner;

    /// @notice Restricts a function to the owning sub-account.
    modifier onlyOwner() {
        require(msg.sender == _owner, IExecutionModule.CallerNotModuleOwner(msg.sender));
        _;
    }

    /// @notice Sets the owning sub-account. A second call reverts.
    function initialize(address owner_) external {
        _initialize(owner_);
    }

    /// @notice Sends everything this module holds of `token` to the owning sub-account, where it lands untracked
    ///          and the admin can rescue it. Permissionless: the destination is fixed, and a free-form route can
    ///          leave an intermediate token here that nothing else reaches, outside every NAV read until it comes
    ///          back. Refused inside an execution, so it cannot move an input a route is in the middle of spending.
    /// @param token The token to send home.
    function sweep(address token) external override nonReentrant {
        uint256 held = IERC20(token).balanceOf(address(this));
        if (held == 0) {
            return;
        }
        IERC20(token).safeTransfer(_owner, held);
        emit Swept(token, held);
    }

    /// @inheritdoc IExecutionModule
    /// @dev No execution unwraps a position unless a module names which of its own do.
    function unwraps(Intent calldata, address) external view virtual override returns (bool) {
        return false;
    }

    /// @inheritdoc IExecutionModule
    function owner() public view override returns (address) {
        return _owner;
    }

    /// @dev Binds the owning sub-account, once.
    function _initialize(address owner_) internal {
        require(_owner == Constants.ZERO_ADDRESS, Errors.AlreadyInitialized());
        require(owner_ != Constants.ZERO_ADDRESS, Errors.ZeroAddress());
        _owner = owner_;
    }

    /// @dev A venue call may not target this module, its owner, or any address the owner protects. The check screens
    ///      this module's own calls: a contract it calls can reach those addresses itself, so what bounds a route is
    ///      the owner's measurement of the outcome and each address's own access control.
    function _requireCallableTarget(address target) internal view {
        require(target != address(this) && target != _owner, IExecutionModule.ProtectedTarget(target));
        require(!ITrackedSubAccount(_owner).isProtectedAddress(target), IExecutionModule.ProtectedTarget(target));
    }

    /// @return singleIntent The intent's only input and output, after enforcing this module's single-pair shape.
    function _singleInOutIntent(Intent calldata intent) internal pure returns (SingleInOutIntent memory singleIntent) {
        require(intent.inputs.length == 1 && intent.outputs.length == 1, Errors.InvalidExecutionAssets());
        return SingleInOutIntent(intent.inputs[0], intent.outputs[0], intent.toleranceBps);
    }
}

src/types/Constants.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2026 Truss Labs
pragma solidity 0.8.28;

/// @title Constants
/// @author Truss Labs
/// @notice The numeric constants more than one contract shares. A constant that only one contract's arithmetic
///         needs stays with that contract.
library Constants {
    /// @dev The zero address: "none" wherever an address is optional, and never a valid party.
    address internal constant ZERO_ADDRESS = address(0);
    /// @dev Basis points in one whole: the denominator of every bps-denominated rate, fee, cap and tolerance.
    uint256 internal constant MAX_BPS = 10_000;
    /// @dev One unit in 18-decimal fixed point: the scale of every USD value and share price.
    uint256 internal constant WAD = 1e18;
    /// @dev The decimals of WAD.
    uint8 internal constant WAD_DECIMALS = 18;
    /// @dev The vault's share decimals, whatever the underlying's.
    uint8 internal constant SHARE_DECIMALS = 18;
    /// @dev The year the management rate is quoted per.
    uint256 internal constant YEAR = 365 days;
    /// @dev "Everything": an amount a sub-account resolves to its whole tracked balance when the call runs, so an
    ///      operator batching dependent calls need not know a figure that a venue or a pool moves before execution.
    uint256 internal constant ALL = type(uint256).max;
}

src/types/Errors.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2026 Truss Labs
pragma solidity ^0.8.28;

/// @title Errors
/// @author Truss Labs
/// @notice The errors more than one contract raises: initialization, binding, the shared levers and meters, and the
///         one contract without an interface. An error one contract's interface owns is declared there.
library Errors {
    /// @notice The contract was already initialized.
    /// @custom:selector 0x0dc149f0
    error AlreadyInitialized();

    /// @notice A basis-point figure above 100%.
    /// @custom:selector 0xcb5271e1
    error BpsAboveMax(uint256 bps);

    /// @notice An unlimited bucket has no refill rate to change.
    /// @custom:selector 0x64634d01
    error BucketUnlimited();

    /// @notice The caller is not a live sub-account of the vault.
    /// @custom:selector 0xcf2c82d0
    error CallerNotSubAccount(address caller);

    /// @notice The caller is not the vault.
    /// @custom:selector 0x8edca129
    error CallerNotVault(address caller);

    /// @notice The cap would exceed its immutable ceiling.
    /// @custom:selector 0xf64ec131
    error CapAboveCeiling(uint256 cap, uint256 ceiling);

    /// @notice Too little gas was left to fund a bounded external read; retry with more rather than read the failure
    ///         as an answer.
    /// @custom:selector 0x24b593d9
    error InsufficientGasForExternalCall();

    /// @notice The declared asset sets are empty, exceed the leg bound, contain zero addresses or duplicate assets.
    /// @custom:selector 0xc66639c3
    error InvalidExecutionAssets();

    /// @notice A lend execution names its venue in the intent and takes no targets.
    /// @custom:selector 0xc3abdf85
    error LendTakesNoTargets(uint256 count);

    /// @notice Two arrays that must pair up do not.
    /// @custom:selector 0xff633a38
    error LengthMismatch();

    /// @notice A liquidity quantity does not fit in 128 bits.
    /// @custom:selector 0xb03425ae
    error LiquidityOverflow();

    /// @notice A lower lever was given a value at or above the current one.
    /// @custom:selector 0xefc9caba
    error NotALower(uint256 current, uint256 proposed);

    /// @notice A raise lever was given a value at or below the current one.
    /// @custom:selector 0xb0f35f5a
    error NotARaise(uint256 current, uint256 proposed);

    /// @notice The caller is not the owner.
    /// @custom:selector 0x245aecd3
    error NotOwner(address caller);

    /// @notice An execution's output value fell short of its input value by more than the tolerance.
    /// @custom:selector 0xd2cc684d
    error OutcomeBelowTolerance(uint256 valueInUsdWad, uint256 valueOutUsdWad, uint256 toleranceBps);

    /// @notice A policy answers to another authority than the contract binding it.
    /// @custom:selector 0x43b6f4ec
    error PolicyAuthorityMismatch(address policy, address authority);

    /// @notice A policy names a different vault than the one binding it.
    /// @custom:selector 0x1e04721c
    error PolicyVaultMismatch(address policy, address boundVault);

    /// @notice The operation exceeds the bucket's available capacity.
    /// @custom:selector 0x40df7ba9
    error RateLimited(uint256 amount, uint256 available);

    /// @notice A price the operation needs is stale.
    /// @custom:selector 0x605b9eb9
    error StaleValuation(address asset);

    /// @notice The sub-account is not in the Active state.
    /// @custom:selector 0xd6077d1b
    error SubAccountNotActive(address subAccount);

    /// @notice The per-call tolerance exceeds the governed ceiling.
    /// @custom:selector 0x472bb045
    error ToleranceAboveMax(uint256 toleranceBps, uint256 maxBps);

    /// @notice The policy payload carries a tag the policy does not define.
    /// @custom:selector 0xa3c0b4ca
    error UnknownPolicyData();

    /// @notice A bucket can only become unlimited while its refill rate is zero.
    /// @custom:selector 0xcd262ca9
    error UnlimitedNeedsZeroRefill();

    /// @notice A required address is zero.
    /// @custom:selector 0xd92e233d
    error ZeroAddress();

    /// @notice A value that must be non-zero was zero; `name` says which.
    /// @custom:selector 0x46c82ad0
    error ZeroValue(string name);
}

src/types/InputLeg.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2026 Truss Labs
pragma solidity ^0.8.28;

/// @title InputLeg
/// @author Truss Labs
/// @notice An asset and raw token quantity, shared by execution inputs and holder-unwind accounting.
struct InputLeg {
    address asset;
    uint256 amount;
}

src/types/ModuleTypes.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2026 Truss Labs
pragma solidity ^0.8.28;

/// @title ModuleTypes
/// @author Truss Labs
/// @notice The module families a policy and a module must agree on before they can be bound together.
library ModuleTypes {
    /// @notice Arbitrary-call swaps through any router.
    bytes32 internal constant SWAP = keccak256("swap");

    /// @notice Supply to and withdraw from ERC-4626 venues.
    bytes32 internal constant LEND_ERC4626 = keccak256("lend.erc4626");

    /// @notice Supply to and redeem from concentrated-liquidity positions, including supporting swaps.
    bytes32 internal constant CONCENTRATED_LP = keccak256("lp.concentrated");
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "src/=src/",
    "test/=test/",
    "script/=script/",
    "erc4626-tests/=lib/erc4626-tests/",
    "crytic-properties/=lib/crytic-properties/contracts/",
    "ds-test/=lib/crytic-properties/lib/forge-std/lib/ds-test/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "properties/=lib/crytic-properties/contracts/",
    "solmate/=lib/crytic-properties/lib/solmate/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.