Перейти к содержимому
Проверенный контрактЧастичноеBUSL-1.1

Roles

Адрес0x31a02f5aefcc93022d04b6b1acb593a4e8fd7948
Баланс

0 ETH

 

Транзакций

0

 

Компилятор

solc 0.8.38

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.38+commit.1835d247
Язык
solidity
Оптимизация
Да, 10 прогонов
Версия EVM
cancun
Через IR
да
Лицензия
BUSL-1.1
Совпадение
Частичноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 436 502
Транзакция создания
0xfe3f30ceda…fb615a54a0
Библиотеки
project/contracts/Roles.sol:ConditionStorer0x1869…173e0cproject/contracts/Roles.sol:WithinRatioChecker0x4f9d…f20ab5project/contracts/Roles.sol:CustomConditionChecker0x81f1…e7e847

45 файлов

project/contracts/Roles.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "./core/Authorization.sol";
import "./core/Membership.sol";
import "./core/RoleTx.sol";
import "./core/Settlement.sol";
import "./core/Setup.sol";

/**
 * @title Zodiac Roles Mod - granular, role-based access control and policy
 *        engine for onchain accounts
 *
 * @author gnosisguild
 *
 */
contract Roles is RolesStorage, Setup, Membership, Authorization, Settlement {
    /// @param _owner Address of the owner
    /// @param _avatar Address of the avatar (e.g. a Gnosis Safe)
    /// @param _target Address of the contract that will call exec function
    constructor(address _owner, address _avatar, address _target) {
        bytes memory initParams = abi.encode(_owner, _avatar, _target);
        setUp(initParams);
    }

    /// @dev Checks whether a module holds an active membership for a role.
    /// @param roleKey Identifier of the role
    /// @param module Address of the module to check
    /// @return True if the module currently has a valid membership for the role
    function isMember(
        bytes32 roleKey,
        address module
    ) external view returns (bool) {
        return _hasActiveMembership(roleKey, module);
    }

    /// @dev Passes a transaction to the modifier using the caller's default role.
    /// @param to Destination address of module transaction
    /// @param value Ether value of module transaction
    /// @param data Data payload of module transaction
    /// @param operation Operation type of module transaction
    /// @notice Can only be called by enabled modules
    function execTransactionFromModule(
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation
    ) public override nonReentrant moduleOnly returns (bool success) {
        return
            _execWithRole(
                to,
                value,
                data,
                operation,
                defaultRoles[sentOrSignedByModule()],
                false
            );
    }

    /// @dev Passes a transaction to the modifier using the caller's default role. Expects return data.
    /// @param to Destination address of module transaction
    /// @param value Ether value of module transaction
    /// @param data Data payload of module transaction
    /// @param operation Operation type of module transaction
    /// @notice Can only be called by enabled modules
    function execTransactionFromModuleReturnData(
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation
    )
        public
        override
        nonReentrant
        moduleOnly
        returns (bool success, bytes memory returnData)
    {
        return
            _execWithRoleReturnData(
                to,
                value,
                data,
                operation,
                defaultRoles[sentOrSignedByModule()],
                false
            );
    }

    /// @dev Passes a transaction to the modifier assuming the specified role.
    /// @param to Destination address of module transaction
    /// @param value Ether value of module transaction
    /// @param data Data payload of module transaction
    /// @param operation Operation type of module transaction
    /// @param roleKey Identifier of the role to assume for this transaction
    /// @param shouldRevert Should the function revert on inner execution returning success false?
    /// @notice Can only be called by enabled modules
    function execTransactionWithRole(
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation,
        bytes32 roleKey,
        bool shouldRevert
    ) public nonReentrant moduleOnly returns (bool success) {
        return _execWithRole(to, value, data, operation, roleKey, shouldRevert);
    }

    /// @dev Relayed variant of execTransactionWithRole. The caller does not
    ///      need to be an enabled module; instead, an enabled module must sign
    ///      the call (EIP-712 over a RoleTx struct).
    /// @param to Destination address of module transaction
    /// @param value Ether value of module transaction
    /// @param data Data payload of module transaction
    /// @param operation Operation type of module transaction
    /// @param roleKey Identifier of the role to assume for this transaction
    /// @param shouldRevert Should the function revert on inner execution returning success false?
    /// @param salt Replay-protection nonce mixed into the signed digest;
    ///        each digest can be consumed only once.
    /// @param signature EIP-712 signature by the module (EOA or ERC-1271)
    function execTransactionWithSignature(
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation,
        bytes32 roleKey,
        bool shouldRevert,
        bytes32 salt,
        bytes calldata signature
    )
        external
        nonReentrant
        moduleOnlySigned(
            RoleTx.hashStruct(
                to,
                value,
                data,
                operation,
                roleKey,
                shouldRevert,
                salt
            ),
            signature
        )
        returns (bool success)
    {
        return _execWithRole(to, value, data, operation, roleKey, shouldRevert);
    }

    /*//////////////////////////////////////////////////////////////
                               INTERNALS
    //////////////////////////////////////////////////////////////*/

    function _execWithRole(
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation,
        bytes32 roleKey,
        bool shouldRevert
    ) private returns (bool success) {
        (address module, uint256 nextMembership) = _authenticate(roleKey);
        Consumption[] memory consumptions = _authorize(
            roleKey,
            to,
            value,
            data,
            operation
        );
        success = IAvatar(target).execTransactionFromModule(
            to,
            value,
            data,
            operation
        );
        if (shouldRevert && !success) {
            revert ModuleTransactionFailed();
        }
        if (success) {
            _persist(module, roleKey, nextMembership, consumptions);
        }
    }

    function _execWithRoleReturnData(
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation,
        bytes32 roleKey,
        bool shouldRevert
    ) private returns (bool success, bytes memory returnData) {
        (address module, uint256 nextMembership) = _authenticate(roleKey);
        Consumption[] memory consumptions = _authorize(
            roleKey,
            to,
            value,
            data,
            operation
        );
        (success, returnData) = IAvatar(target)
            .execTransactionFromModuleReturnData(to, value, data, operation);
        if (shouldRevert && !success) {
            revert ModuleTransactionFailed();
        }
        if (success) {
            _persist(module, roleKey, nextMembership, consumptions);
        }
    }
}

npm/@gnosis-guild/[email protected]/contracts/core/Modifier.sol

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

import {ExecutionTracker} from "../signature/ExecutionTracker.sol";
import {IAvatar} from "../interfaces/IAvatar.sol";
import {Module} from "./Module.sol";
import {SignatureChecker} from "../signature/SignatureChecker.sol";

import "./Operation.sol";

/// @title Modifier Interface - A contract that sits between a Module and an Avatar and enforce some additional logic.
abstract contract Modifier is
  Module,
  ExecutionTracker,
  SignatureChecker,
  IAvatar
{
  address internal constant SENTINEL_MODULES = address(0x1);
  /// Mapping of modules.
  mapping(address => address) internal modules;
  /// Authenticated module for the current moduleOnly call.
  address private transient _authenticatedModule;

  /// `sender` is not an authorized module.
  /// @param sender The address of the sender.
  error NotAuthorized(address sender);

  /// `module` is invalid.
  error InvalidModule(address module);

  /// `pageSize` is invalid.
  error InvalidPageSize();

  /// `module` is already disabled.
  error AlreadyDisabledModule(address module);

  /// `module` is already enabled.
  error AlreadyEnabledModule(address module);

  /// @dev `setModules()` was already called.
  error SetupModulesAlreadyCalled();

  /// @dev A module authentication context is already active.
  error AlreadyAuthenticated();

  /*
    --------------------------------------------------
    You must override both of the following virtual functions,
    execTransactionFromModule() and execTransactionFromModuleReturnData().
    It is recommended that implementations of both functions use the
    parameterless moduleOnly() modifier.
    */

  /// @dev Passes a transaction to the modifier.
  /// @notice Can only be called by enabled modules.
  /// @param to Destination address of module transaction.
  /// @param value Ether value of module transaction.
  /// @param data Data payload of module transaction.
  /// @param operation Operation type of module transaction.
  function execTransactionFromModule(
    address to,
    uint256 value,
    bytes calldata data,
    Operation operation
  ) public virtual returns (bool success);

  /// @dev Passes a transaction to the modifier, expects return data.
  /// @notice Can only be called by enabled modules.
  /// @param to Destination address of module transaction.
  /// @param value Ether value of module transaction.
  /// @param data Data payload of module transaction.
  /// @param operation Operation type of module transaction.
  function execTransactionFromModuleReturnData(
    address to,
    uint256 value,
    bytes calldata data,
    Operation operation
  ) public virtual returns (bool success, bytes memory returnData);

  /// @dev Authenticates a direct call from an enabled module.
  /// @notice Can only be called by enabled modules.
  modifier moduleOnly() {
    if (_authenticatedModule != address(0)) {
      revert AlreadyAuthenticated();
    }

    if (modules[msg.sender] == address(0)) {
      revert NotAuthorized(msg.sender);
    }

    _authenticatedModule = msg.sender;
    _;
    _authenticatedModule = address(0);
  }

  /// @dev Authenticates a relayed call signed by an enabled module using EIP-712.
  ///      The inheriting contract defines the typed message and supplies its struct
  ///      hash. This contract applies its domain separator (chain ID and verifying
  ///      contract) to produce the EIP-712 digest before verification.
  /// @param structHash EIP-712 struct hash (`hashStruct(message)`) supplied by the
  ///        inheriting contract.
  /// @param signature Signature over the EIP-712 digest.
  modifier moduleOnlySigned(bytes32 structHash, bytes calldata signature) {
    if (_authenticatedModule != address(0)) {
      revert AlreadyAuthenticated();
    }

    bytes32 hash = hashTypedData(structHash);
    address signer = signedBy(hash, signature);
    if (signer == address(0) || modules[signer] == address(0)) {
      revert NotAuthorized(msg.sender);
    }

    if (consumed[signer][hash]) {
      revert HashAlreadyConsumed(hash);
    }

    consumed[signer][hash] = true;
    emit HashExecuted(hash);

    _authenticatedModule = signer;
    _;
    _authenticatedModule = address(0);
  }

  /// @dev Returns the module authenticated for the current execution context.
  /// @return The module that directly called or signed the current execution.
  function sentOrSignedByModule() internal view returns (address) {
    return _authenticatedModule;
  }

  /// @dev Disables a module on the modifier.
  /// @notice This can only be called by the owner.
  /// @param prevModule Module that pointed to the module to be removed in the linked list.
  /// @param module Module to be removed.
  function disableModule(
    address prevModule,
    address module
  ) public override onlyOwner {
    if (module == address(0) || module == SENTINEL_MODULES)
      revert InvalidModule(module);
    if (modules[prevModule] != module) revert AlreadyDisabledModule(module);
    modules[prevModule] = modules[module];
    modules[module] = address(0);
    emit DisabledModule(module);
  }

  /// @dev Enables a module that can add transactions to the queue
  /// @param module Address of the module to be enabled
  /// @notice This can only be called by the owner
  function enableModule(address module) public override onlyOwner {
    if (module == address(0) || module == SENTINEL_MODULES)
      revert InvalidModule(module);
    if (modules[module] != address(0)) revert AlreadyEnabledModule(module);
    modules[module] = modules[SENTINEL_MODULES];
    modules[SENTINEL_MODULES] = module;
    emit EnabledModule(module);
  }

  /// @dev Returns if an module is enabled
  /// @return True if the module is enabled
  function isModuleEnabled(
    address _module
  ) public view override returns (bool) {
    return SENTINEL_MODULES != _module && modules[_module] != address(0);
  }

  /// @dev Returns array of modules.
  ///      If all entries fit into a single page, the next pointer will be 0x1.
  ///      If another page is present, next will be the last element of the returned array.
  /// @param start Start of the page. Has to be a module or start pointer (0x1 address)
  /// @param pageSize Maximum number of modules that should be returned. Has to be > 0
  /// @return array Array of modules.
  /// @return next Start of the next page.
  function getModulesPaginated(
    address start,
    uint256 pageSize
  ) external view override returns (address[] memory array, address next) {
    if (start != SENTINEL_MODULES && !isModuleEnabled(start)) {
      revert InvalidModule(start);
    }
    if (pageSize == 0) {
      revert InvalidPageSize();
    }

    // Init array with max page size
    array = new address[](pageSize);

    // Populate return array
    uint256 moduleCount = 0;
    next = modules[start];
    while (
      next != address(0) && next != SENTINEL_MODULES && moduleCount < pageSize
    ) {
      array[moduleCount] = next;
      next = modules[next];
      moduleCount++;
    }

    // Because of the argument validation we can assume that
    // the `currentModule` will always be either a module address
    // or sentinel address (aka the end). If we haven't reached the end
    // inside the loop, we need to set the next pointer to the last element
    // because it skipped over to the next module which is neither included
    // in the current page nor won't be included in the next one
    // if you pass it as a start.
    if (next != SENTINEL_MODULES) {
      next = array[moduleCount - 1];
    }
    // Set correct size of returned array
    // solhint-disable-next-line no-inline-assembly
    assembly {
      mstore(array, moduleCount)
    }
  }

  /// @dev Initializes the modules linked list.
  /// @notice Should be called as part of the `setUp` / initializing function and can only be called once.
  function setupModules() internal {
    if (modules[SENTINEL_MODULES] != address(0))
      revert SetupModulesAlreadyCalled();
    modules[SENTINEL_MODULES] = SENTINEL_MODULES;
  }
}

npm/@gnosis-guild/[email protected]/contracts/core/Module.sol

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

import {FactoryFriendly} from "../factory/FactoryFriendly.sol";
import {Ownable} from "../factory/Ownable.sol";
import {IAvatar} from "../interfaces/IAvatar.sol";
import "./Operation.sol";

/// @title Module Interface - A contract that can pass messages to a Module Manager contract if enabled by that contract.
abstract contract Module is FactoryFriendly, Ownable {
  /// @dev Address that will ultimately execute function calls.
  address public avatar;
  /// @dev Address that this module will pass transactions to.
  address public target;

  /// @dev Emitted each time the avatar is set.
  event AvatarSet(address indexed previousAvatar, address indexed newAvatar);
  /// @dev Emitted each time the Target is set.
  event TargetSet(address indexed previousTarget, address indexed newTarget);

  /// @dev Sets the avatar to a new avatar (`newAvatar`).
  /// @notice Can only be called by the current owner.
  function setAvatar(address _avatar) public onlyOwner {
    address previousAvatar = avatar;
    avatar = _avatar;
    emit AvatarSet(previousAvatar, _avatar);
  }

  /// @dev Sets the target to a new target (`newTarget`).
  /// @notice Can only be called by the current owner.
  function setTarget(address _target) public onlyOwner {
    address previousTarget = target;
    target = _target;
    emit TargetSet(previousTarget, _target);
  }

  /// @dev Passes a transaction to be executed by the avatar.
  /// @notice Can only be called by this contract.
  /// @param to Destination address of module transaction.
  /// @param value Ether value of module transaction.
  /// @param data Data payload of module transaction.
  /// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
  function exec(
    address to,
    uint256 value,
    bytes memory data,
    Operation operation
  ) internal virtual returns (bool success) {
    return
      IAvatar(target).execTransactionFromModule(to, value, data, operation);
  }

  /// @dev Passes a transaction to be executed by the target and returns data.
  /// @notice Can only be called by this contract.
  /// @param to Destination address of module transaction.
  /// @param value Ether value of module transaction.
  /// @param data Data payload of module transaction.
  /// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
  function execAndReturnData(
    address to,
    uint256 value,
    bytes memory data,
    Operation operation
  ) internal virtual returns (bool success, bytes memory returnData) {
    return
      IAvatar(target).execTransactionFromModuleReturnData(
        to,
        value,
        data,
        operation
      );
  }
}

npm/@gnosis-guild/[email protected]/contracts/core/Operation.sol

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

enum Operation {
  Call,
  DelegateCall
}

npm/@gnosis-guild/[email protected]/contracts/factory/FactoryFriendly.sol

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

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

/// @title Zodiac FactoryFriendly - A contract that allows other contracts to be initializable and pass bytes as arguments to define contract state
abstract contract FactoryFriendly is Initializable {
  function setUp(bytes memory initializeParams) public virtual;
}

npm/@gnosis-guild/[email protected]/contracts/factory/Initializable.sol

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

abstract contract Initializable {
  bool private _initialized;

  error AlreadyInitialized();

  modifier initializer() {
    if (_initialized) revert AlreadyInitialized();
    _initialized = true;
    _;
  }
}

npm/@gnosis-guild/[email protected]/contracts/factory/Ownable.sol

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

abstract contract Ownable {
  address public owner;

  event OwnershipTransferred(
    address indexed previousOwner,
    address indexed newOwner
  );

  error OwnableUnauthorizedAccount(address account);

  modifier onlyOwner() {
    if (msg.sender != owner) revert OwnableUnauthorizedAccount(msg.sender);
    _;
  }

  function transferOwnership(address newOwner) public onlyOwner {
    _transferOwnership(newOwner);
  }

  function _transferOwnership(address newOwner) internal {
    address oldOwner = owner;
    owner = newOwner;
    emit OwnershipTransferred(oldOwner, newOwner);
  }
}

npm/@gnosis-guild/[email protected]/contracts/interfaces/IAvatar.sol

// SPDX-License-Identifier: LGPL-3.0-only

/// @title Zodiac Avatar - A contract that manages modules that can execute transactions via this contract.
pragma solidity ^0.8.24;

import "../core/Operation.sol";

interface IAvatar {
  event EnabledModule(address module);
  event DisabledModule(address module);
  event ExecutionFromModuleSuccess(address indexed module);
  event ExecutionFromModuleFailure(address indexed module);

  /// @dev Enables a module on the avatar.
  /// @notice Can only be called by the avatar.
  /// @notice Modules should be stored as a linked list.
  /// @notice Must emit EnabledModule(address module) if successful.
  /// @param module Module to be enabled.
  function enableModule(address module) external;

  /// @dev Disables a module on the avatar.
  /// @notice Can only be called by the avatar.
  /// @notice Must emit DisabledModule(address module) if successful.
  /// @param prevModule Address that pointed to the module to be removed in the linked list
  /// @param module Module to be removed.
  function disableModule(address prevModule, address module) external;

  /// @dev Allows a Module to execute a transaction.
  /// @notice Can only be called by an enabled module.
  /// @notice Must emit ExecutionFromModuleSuccess(address module) if successful.
  /// @notice Must emit ExecutionFromModuleFailure(address module) if unsuccessful.
  /// @param to Destination address of module transaction.
  /// @param value Ether value of module transaction.
  /// @param data Data payload of module transaction.
  /// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
  function execTransactionFromModule(
    address to,
    uint256 value,
    bytes memory data,
    Operation operation
  ) external returns (bool success);

  /// @dev Allows a Module to execute a transaction and return data
  /// @notice Can only be called by an enabled module.
  /// @notice Must emit ExecutionFromModuleSuccess(address module) if successful.
  /// @notice Must emit ExecutionFromModuleFailure(address module) if unsuccessful.
  /// @param to Destination address of module transaction.
  /// @param value Ether value of module transaction.
  /// @param data Data payload of module transaction.
  /// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
  function execTransactionFromModuleReturnData(
    address to,
    uint256 value,
    bytes memory data,
    Operation operation
  ) external returns (bool success, bytes memory returnData);

  /// @dev Returns if an module is enabled
  /// @return True if the module is enabled
  function isModuleEnabled(address module) external view returns (bool);

  /// @dev Returns array of modules.
  /// @param start Start of the page.
  /// @param pageSize Maximum number of modules that should be returned.
  /// @return array Array of modules.
  /// @return next Start of the next page.
  function getModulesPaginated(
    address start,
    uint256 pageSize
  ) external view returns (address[] memory array, address next);
}

npm/@gnosis-guild/[email protected]/contracts/signature/ExecutionTracker.sol

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

/// @title ExecutionTracker - A contract that keeps track of executed and invalidated hashes
contract ExecutionTracker {
  error HashAlreadyConsumed(bytes32);

  event HashExecuted(bytes32);
  event HashInvalidated(bytes32);

  mapping(address => mapping(bytes32 => bool)) public consumed;

  function invalidate(bytes32 hash) external {
    consumed[msg.sender][hash] = true;
    emit HashInvalidated(hash);
  }
}

npm/@gnosis-guild/[email protected]/contracts/signature/IERC1271.sol

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

interface IERC1271 {
  /**
   * @notice EIP1271 method to validate a signature.
   * @param hash Hash of the data signed on the behalf of address(this).
   * @param signature Signature byte array associated with _data.
   *
   * MUST return the bytes4 magic value 0x1626ba7e when function passes.
   * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
   * MUST allow external calls
   */
  function isValidSignature(
    bytes32 hash,
    bytes memory signature
  ) external view returns (bytes4);
}

npm/@gnosis-guild/[email protected]/contracts/signature/SignatureChecker.sol

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

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

/// @title SignatureChecker - Verifies EIP-712 signatures.
/// @dev Supports EOA (ECDSA) and ERC-1271 contract signatures.
abstract contract SignatureChecker {
  /**
   * @dev Computes the EIP-712 digest as
   *      `keccak256(0x1901 ‖ domainSeparator ‖ structHash)`.
   *      This contract derives the domain separator from the current chain ID
   *      and its own address; the inheriting contract defines `structHash`.
   * @param structHash EIP-712 hash of the typed message (`hashStruct(message)`).
   * @return Domain-separated digest to sign or verify.
   */
  function hashTypedData(bytes32 structHash) internal view returns (bytes32) {
    bytes32 domainSeparator = keccak256(
      abi.encode(DOMAIN_SEPARATOR_TYPEHASH, block.chainid, this)
    );
    return
      keccak256(
        abi.encodePacked(
          bytes1(0x19),
          bytes1(0x01),
          domainSeparator,
          structHash
        )
      );
  }

  /**
   * @notice Recovers the signer of an arbitrary EIP-712 digest.
   * @dev Signature layout:
   *      - EOA:     `r || s || v`                 (65 bytes)
   *      - ERC1271: `signer || contractSignature` (signature[0:20] = signer)
   *
   *      A 65-byte signature is checked as an EOA signature first. If recovery
   *      fails, it is then checked as an ERC1271 signature.
   * @param hash The EIP-712 digest that was signed.
   * @param signature Signature using the EOA or ERC-1271 layout above.
   * @return signer The recovered signer, or address(0) when invalid.
   */
  function signedBy(
    bytes32 hash,
    bytes calldata signature
  ) internal view returns (address signer) {
    if (signature.length < 20) {
      return address(0);
    }

    if (signature.length == 65) {
      bytes32 r = bytes32(signature[0:32]);
      bytes32 s = bytes32(signature[32:64]);
      uint8 v = uint8(signature[64]);
      signer = ecrecover(hash, v, r, s);
      // ecrecover fails by returning address(0)
      if (signer != address(0)) {
        return signer;
      }
    }

    signer = address(bytes20(signature));
    return
      _isValidContractSignature(signer, hash, signature[20:])
        ? signer
        : address(0);
  }

  /**
   * @dev Asks the signer contract whether the signature is valid for the hash.
   * @param signer The address of the signer contract.
   * @param hash Hash of the data signed.
   * @param signature The contract signature.
   * @return result Indicates whether the signature is valid.
   */
  function _isValidContractSignature(
    address signer,
    bytes32 hash,
    bytes calldata signature
  ) private view returns (bool result) {
    uint256 size;
    // eslint-disable-line no-inline-assembly
    assembly {
      size := extcodesize(signer)
    }
    if (size == 0) {
      return false;
    }

    (bool success, bytes memory returnData) = signer.staticcall(
      abi.encodeWithSelector(
        IERC1271.isValidSignature.selector,
        hash,
        signature
      )
    );

    return success && bytes4(returnData) == EIP1271_MAGIC_VALUE;
  }

  // keccak256(
  //     "EIP712Domain(uint256 chainId,address verifyingContract)"
  // );
  bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH =
    0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;

  // bytes4(keccak256(
  //     "isValidSignature(bytes32,bytes)"
  // ));
  bytes4 private constant EIP1271_MAGIC_VALUE = 0x1626ba7e;
}

project/contracts/common/AbiLocation.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import {Condition, Encoding} from "../types/Condition.sol";
import {Operator} from "../types/Operator.sol";

/**
 * @title AbiLocation
 * @notice Resolves calldata locations and sizes for ABI-encoded structures.
 *
 * @author gnosisguild
 */
library AbiLocation {
    /**
     * @dev Resolves calldata locations for each child of a block type.
     *      Supports Tuple, Array, and AbiEncoded.
     *
     * @param data      Calldata buffer.
     * @param location  Start of the container block.
     * @param condition Condition defining structure.
     *
     * @return result   Absolute location for each child element.
     * @return overflow True if any location exceeds data bounds.
     */

    function children(
        bytes calldata data,
        uint256 location,
        Condition memory condition
    ) internal pure returns (uint256[] memory result, bool overflow) {
        bool isArray = condition.encoding == Encoding.Array;

        uint256 childCount = condition.children.length;
        if (isArray) {
            /*
             * Arrays prefix their block with an element count word. Read it
             * and advance location to the actual beginning of the block. Treat
             * the rest like a tuple.
             */
            if (location + 32 > data.length) return (result, true);
            assembly {
                childCount := calldataload(add(data.offset, location))
            }
            location += 32;
        }
        result = new uint256[](childCount);

        /*
         * HEAD + TAIL encoding for block types (tuples, arrays):
         *
         * HEAD: Fixed-size region at block start. Each element occupies a
         *       slot here - static children store values inline (possibly
         *       multi-word), dynamic children store a 32-byte offset pointing
         *       into TAIL.
         *
         * TAIL: Variable-size region after HEAD with actual dynamic data,
         *       in declaration order. Offsets are relative to block start.
         */
        uint256 headOffset;
        for (uint256 i; i < childCount; ++i) {
            Condition memory child = condition.children[isArray ? 0 : i];

            if (child.inlined) {
                /* Static elements */
                result[i] = location + headOffset;
                headOffset += child.size;
            } else {
                /* Dynamic elements */
                result[i] = _tailLocation(data, location, headOffset);
                headOffset += 32;
            }

            if (result[i] > data.length) {
                return (result, true);
            }
        }
        return (result, false);
    }

    /**
     * @dev Computes the encoded size of a value at location.
     */
    function size(
        bytes calldata data,
        uint256 location,
        Condition memory condition
    ) internal pure returns (uint256 result) {
        // Every ABI-encoded element occupies at least one word.
        if (location + 32 > data.length) return data.length + 1;

        Encoding encoding = condition.encoding;
        if (encoding == Encoding.Static) {
            return 32;
        }

        /*
         * Always preload the first word - its meaning depends on encoding:
         * - Dynamic: byte length of content
         * - Array: element count
         */
        uint256 word;
        assembly {
            word := calldataload(add(data.offset, location))
        }

        /*
         * A Note on AbiEncoded and this function:
         *
         * AbiEncoded location is patched during ConditionEvaluation
         * so that top-level and nested AbiEncoded nodes are treated
         * uniformly by the evaluator. As a consequence, this function
         * only supports nested AbiEncoded nodes – calling it on a
         * root one would fail. This is fine because the entry point
         * for size is always via EqualTo, and AbiEncoded cannot be
         * paired with that operator.
         */
        if (encoding == Encoding.Dynamic || encoding == Encoding.AbiEncoded) {
            // Dynamic types: length prefix + padded content (ceil32)
            return 32 + ((word + 31) & ~uint256(31));
        }

        uint256 childCount = condition.children.length;
        if (encoding == Encoding.None) {
            /*
             * Logical nodes (And/Or) are transparent. We delegate the size
             * calculation to the first valid (non-empty, non-overflowing)
             * child subtree.
             *
             * This works for both:
             * - Non-Variant: All children share the same type tree.
             * - Variant: Children have different types, but variants are
             *            always Dynamic-encoded, so size is deterministic.
             */
            for (uint256 i; i < childCount; ++i) {
                result = size(data, location, condition.children[i]);
                if (result > 0 && result <= data.length) return result;
            }
            return data.length + 1;
        }

        bool isArray = encoding == Encoding.Array;
        if (isArray) {
            /*
             * Arrays prefix their block with an element count word. Read it
             * and advance location to the actual beginning of the block. Treat
             * the rest like a tuple.
             */
            childCount = word;
            location += 32;
            result = 32;
        }

        /*
         * HEAD + TAIL encoding for block types (tuples, arrays):
         *
         * HEAD: Fixed-size region at block start. Each element occupies a
         *       slot here - static children store values inline (possibly
         *       multi-word), dynamic children store a 32-byte offset pointing
         *       into TAIL.
         *
         * TAIL: Variable-size region after HEAD with actual dynamic data,
         *       in declaration order. Offsets are relative to block start.
         */
        uint256 headOffset;
        for (uint256 i; i < childCount; ++i) {
            Condition memory child = condition.children[isArray ? 0 : i];

            if (child.inlined) {
                /* Static elements */
                result += child.size;
                headOffset += child.size;
            } else {
                /* Dynamic elements */
                result +=
                    32 +
                    size(
                        data,
                        _tailLocation(data, location, headOffset),
                        child
                    );
                headOffset += 32;
            }
        }
    }

    /**
     * @dev Computes the absolute position of a dynamic (non-inline) element.
     *      Reads the relative offset from HEAD and adds it to the block start
     *      to locate the element in the TAIL region.
     *
     * @param data       The calldata being inspected.
     * @param location   Absolute start position of the current ABI block.
     * @param headOffset Byte offset within HEAD where the pointer resides.
     * @return           Absolute position, or data.length + 1 on overflow.
     */
    function _tailLocation(
        bytes calldata data,
        uint256 location,
        uint256 headOffset
    ) private pure returns (uint256) {
        // HEAD overflows buffer
        if (location + headOffset + 32 > data.length) {
            return data.length + 1;
        }

        uint256 tailOffset;
        assembly {
            tailOffset := calldataload(
                add(data.offset, add(location, headOffset))
            )
        }

        // TAIL points backwards (malicious or malformed)
        if (tailOffset <= headOffset) {
            return data.length + 1;
        }

        // TAIL overflows buffer
        if (location + tailOffset + 32 > data.length) {
            return data.length + 1;
        }

        return location + tailOffset;
    }
}

project/contracts/common/AllowanceConsumer.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import {ALLOWANCES_SLOT} from "../core/StorageSlots.sol";
import {Allowance, Consumption} from "../types/Allowance.sol";
import {Status} from "../types/Authorization.sol";

/**
 * @title AllowanceConsumer
 * @notice Loads allowances from storage and tracks their consumption.
 *
 * @dev Owns the running consumption list threaded through permission
 *      evaluation. An entry tracks one allowance key: the balance accrued
 *      when first touched, and the amount consumed since.
 *
 *      The list is immutable. Updates produce a new list via _copyOnWrite,
 *      which copies entry POINTERS (a struct array in memory is an array of
 *      references), so unchanged entries are shared between the old and new
 *      list. Entries must therefore never be mutated in place: _findOrAccrue
 *      returns a newly allocated entry, consume adds the amount to its
 *      consumed total, and _copyOnWrite shallow-copies the list and writes
 *      the updated entry in. This keeps a failed branch's consumption from
 *      leaking into sibling branches sharing the same list.
 *
 * @author gnosisguild
 */
library AllowanceConsumer {
    /**
     * @notice Consumes `amount` from an allowance in the running list.
     * @param consumptions Running consumption list (not mutated)
     * @param allowanceKey The allowance to consume from
     * @param amount Amount to consume, denominated in balance units
     * @return status Ok, or AllowanceExceeded when the amount does not fit
     * @return next Updated list when status is Ok, the input list otherwise
     */
    function consume(
        Consumption[] memory consumptions,
        bytes32 allowanceKey,
        uint256 amount
    ) internal view returns (Status status, Consumption[] memory next) {
        (Consumption memory entry, uint256 index) = _findOrAccrue(
            consumptions,
            allowanceKey
        );

        if (amount > entry.balance - entry.consumed) {
            return (Status.AllowanceExceeded, consumptions);
        }
        // Fits uint128: amount is capped at balance - consumed.
        entry.consumed += uint128(amount);

        return (Status.Ok, _copyOnWrite(consumptions, entry, index));
    }

    /**
     * @notice Loads an allowance from storage and calculates its accrued
     *         balance at `blockTimestamp`.
     */
    function accrue(
        bytes32 allowanceKey,
        uint64 blockTimestamp
    ) internal view returns (uint128 balance, uint64 timestamp) {
        Allowance memory a = _load(allowanceKey);

        // No refill configured.
        if (a.period == 0) return (a.balance, a.timestamp);

        // Nothing accrues when the configured timestamp is current or in the future.
        // This also makes the elapsed-time subtraction below safe.
        if (blockTimestamp <= a.timestamp) return (a.balance, a.timestamp);

        // Calculate full periods elapsed.
        uint64 elapsedIntervals = (blockTimestamp - a.timestamp) / a.period;
        if (elapsedIntervals == 0) return (a.balance, a.timestamp);

        // Timestamp always advances, even when balance is at cap
        timestamp = a.timestamp + elapsedIntervals * a.period;

        // Already at cap, or initial balance was set above maxRefill
        if (a.balance >= a.maxRefill) return (a.balance, timestamp);

        // Add refill for each elapsed period, capping at maxRefill.
        uint256 accruedBalance = uint256(a.balance) +
            uint256(a.refill) *
            elapsedIntervals;
        balance = accruedBalance < a.maxRefill
            ? uint128(accruedBalance)
            : a.maxRefill;
    }

    /**
     * @dev Finds the entry tracking `allowanceKey`, accruing it from storage
     *      when the key is not tracked yet.
     *
     *      Returns a newly allocated Consumption entry, never a reference
     *      into the list: entries are pointer-shared across list copies, so
     *      callers must update the copy and write it back with _copyOnWrite.
     *
     * @return entry Tracked (or newly accrued) entry
     * @return index Position of the entry; equals consumptions.length when new
     */
    function _findOrAccrue(
        Consumption[] memory consumptions,
        bytes32 allowanceKey
    ) private view returns (Consumption memory entry, uint256 index) {
        for (; index < consumptions.length; ++index) {
            if (consumptions[index].allowanceKey == allowanceKey) break;
        }

        if (index < consumptions.length) {
            Consumption memory tracked = consumptions[index];
            return (
                Consumption(
                    allowanceKey,
                    tracked.balance,
                    tracked.consumed,
                    tracked.timestamp
                ),
                index
            );
        }

        (uint128 balance, uint64 timestamp) = accrue(
            allowanceKey,
            uint64(block.timestamp)
        );
        return (Consumption(allowanceKey, balance, 0, timestamp), index);
    }

    /**
     *
     * Storage Layout (2 words, 64 bytes, 512 bits):
     * ┌────────────────────────────────┬────────────────────────────────┐
     * │           maxRefill            │             refill             │
     * │            128 bits            │            128 bits            │
     * ├────────────────┬───────────────┴───────────────┬────────────────┤
     * │   timestamp    │            balance            │     period     │
     * │    64 bits     │           128 bits            │    64 bits     │
     * └────────────────┴───────────────────────────────┴────────────────┘
     *
     */
    function _load(
        bytes32 allowanceKey
    ) private view returns (Allowance memory) {
        uint256 word1;
        uint256 word2;
        assembly {
            mstore(0x00, allowanceKey)
            mstore(0x20, ALLOWANCES_SLOT)
            let slot := keccak256(0x00, 0x40)
            word1 := sload(slot)
            word2 := sload(add(slot, 1))
        }

        return
            Allowance({
                refill: uint128(word1),
                maxRefill: uint128(word1 >> 128),
                period: uint64(word2),
                balance: uint128(word2 >> 64),
                timestamp: uint64(word2 >> 192)
            });
    }

    /**
     * @dev Creates a new list with `entry` written at `index`. When index
     *      equals the list length, the list grows by one.
     *
     *      Shallow: entry pointers are shared with the source list, so
     *      entries must be treated as immutable (see library note).
     */
    function _copyOnWrite(
        Consumption[] memory consumptions,
        Consumption memory entry,
        uint256 index
    ) private pure returns (Consumption[] memory result) {
        uint256 prevLength = consumptions.length;
        uint256 length = prevLength + (index == prevLength ? 1 : 0);

        assembly {
            // Allocate new array
            result := mload(0x40)
            mstore(0x40, add(result, mul(add(length, 1), 0x20)))
            mstore(result, length)

            // Shallow copy previous elements
            let dst := add(result, 0x20)
            let src := add(consumptions, 0x20)
            let size := mul(prevLength, 0x20)
            mcopy(dst, src, size)
        }

        result[index] = entry;
    }
}

project/contracts/common/ImmutableStorage.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

interface ISingletonFactory {
    function deploy(
        bytes memory initCode,
        bytes32 salt
    ) external returns (address);
}

library ImmutableStorage {
    address public constant SINGLETON_FACTORY =
        0xce0042B868300000d44A59004Da54A005ffdcf9f;

    function store(bytes memory buffer) internal returns (address pointer) {
        bytes memory bytecode = _creationBytecode(buffer);
        pointer = _calculateAddress(bytecode);

        uint256 size;
        assembly {
            size := extcodesize(pointer)
        }

        if (size == 0) {
            assert(
                pointer ==
                    ISingletonFactory(SINGLETON_FACTORY).deploy(
                        bytecode,
                        bytes32(0)
                    )
            );
        }
    }

    /**
     * @notice Reads the runtime bytecode stored at a `pointer` contract, skipping the first byte.
     *
     * @param pointer The address of the deployed pointer contract.
     * @return buffer The raw bytecode (minus the prepended 0x00) read from `pointer`.
     */
    function load(address pointer) internal view returns (bytes memory buffer) {
        assembly {
            let size := sub(extcodesize(pointer), 1)
            // free memory point ought to be multiple of 32
            let rounded := and(add(size, 31), not(31))

            // Get free pointer
            buffer := mload(0x40)
            // Store length
            mstore(buffer, size)
            // Update free pointer
            mstore(0x40, add(add(buffer, 0x20), rounded))

            // Copy code starting from offset 0x01 (skip the 0x00 prefix)
            extcodecopy(pointer, add(buffer, 0x20), 0x01, size)
        }
    }

    /**
     * @notice Generates creation bytecode that deploys a contract containing `data` as its runtime bytecode.
     * @dev The generated constructor copies `data` into memory and returns it as the contract's code.
     *      A leading `0x00` byte is prepended so the resulting contract cannot be called.
     *
     * Assembly layout (constructor):
     *
     * ```
     * 0x00    63 <XXXXXX>   PUSH4 code_size         ; push code length (runtime size)
     * 0x01    80             DUP1                   ; duplicate size
     * 0x02    60 0e          PUSH1 0x0e             ; offset of actual code
     * 0x03    60 00          PUSH1 0x00             ; destination offset
     * 0x04    39             CODECOPY               ; copy <code_size> bytes from offset 0x0e
     * 0x05    60 00          PUSH1 0x00             ; return offset
     * 0x06    f3             RETURN                 ; return code as runtime bytecode
     * <CODE>                                        ; runtime code (0x00 + data)
     * ```
     *
     */
    function _creationBytecode(
        bytes memory data
    ) private pure returns (bytes memory) {
        return
            abi.encodePacked(
                hex"63",
                uint32(data.length + 1),
                hex"80_60_0E_60_00_39_60_00_F3",
                // Prepend 0x00 to prevent the deployed contract from being callable
                hex"00",
                data
            );
    }

    function _calculateAddress(
        bytes memory creationBytecode
    ) private pure returns (address) {
        bytes32 hash = keccak256(
            abi.encodePacked(
                bytes1(0xff),
                SINGLETON_FACTORY,
                bytes32(0),
                keccak256(creationBytecode)
            )
        );
        return address(uint160(uint256(hash)));
    }
}

project/contracts/common/PriceLoader.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "../periphery/interfaces/IPricing.sol";
import "../types/Types.sol";

/**
 * @title PriceLoader
 * @notice Library for retrieving exchange rates from IPricing adapters.
 *
 * @dev The adapter returns a price with 18 decimals precision. Applying that
 *      price and any decimal scaling is handled by the caller.
 *
 * @author gnosisguild
 */
library PriceLoader {
    uint256 private constant PRICE_DECIMALS = 18;
    uint256 private constant ONE = 10 ** PRICE_DECIMALS;

    /**
     * @dev Safely invokes pricing adapter via staticcall.
     *
     *  Price Adapter (IPricing.getPrice) Error Scenarios:
     *  | Scenario              | staticcall Result     | Behavior                      | Status                          |
     *  |-----------------------|-----------------------|-------------------------------|---------------------------------|
     *  | No code at address    | (true, "")            | extcodesize == 0              | PricingAdapterNotAContract      |
     *  | Wrong interface       | (false, "")           | staticcall fails              | PricingAdapterReverted          |
     *  | Function reverts      | (false, <error data>) | staticcall fails              | PricingAdapterReverted          |
     *  | Returns wrong type    | (true, <len != 32>)   | returnData.length != 32       | PricingAdapterInvalidResult     |
     *  | Returns zero price    | (true, <32 bytes>)    | price == 0                    | PricingAdapterZeroPrice         |
     *
     */

    function load(
        address adapter,
        bytes memory params
    ) internal view returns (Status, uint256) {
        if (adapter == address(0)) {
            return (Status.Ok, ONE);
        }

        uint256 size;
        assembly {
            size := extcodesize(adapter)
        }
        if (size == 0) {
            return (Status.PricingAdapterNotAContract, 0);
        }

        (bool success, bytes memory returnData) = adapter.staticcall(
            abi.encodeCall(IPricing.getPrice, (params))
        );

        if (!success) {
            return (Status.PricingAdapterReverted, 0);
        }

        if (returnData.length != 32) {
            return (Status.PricingAdapterInvalidResult, 0);
        }

        uint256 price = uint256(bytes32(returnData));
        if (price == 0) {
            return (Status.PricingAdapterZeroPrice, 0);
        }

        return (Status.Ok, price);
    }
}

project/contracts/core/Authorization.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "./evaluate/ConditionEvaluator.sol";
import "./serialize/ConditionLoader.sol";
import "./Storage.sol";

import "../periphery/interfaces/ITransactionUnwrapper.sol";

/**
 * @title   Authorization
 *
 * @notice Authorizes transactions by evaluating role permissions and condition
 *         trees.
 *
 * @dev    The authorization follows three steps:
 *         1. Scope Resolution: Resolves the permission configuration
 *         2. Execution Options: Checks for value transfer and tx operation
 *         3. Payload Validation: Evaluates condition trees against tx data
 *
 *         Transaction bundles are supported via adapter-based unwrapping.
 *
 * @author  gnosisguild
 */
abstract contract Authorization is RolesStorage {
    function _authorize(
        bytes32 roleKey,
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation
    ) internal view returns (Consumption[] memory consumptions) {
        address adapter = unwrappers[_key(to, bytes4(data))];
        if (adapter == address(0)) {
            return
                _transaction(
                    roleKey,
                    data,
                    consumptions,
                    Transaction(to, value, operation)
                );
        }

        /*
         * Transaction Bundle
         */
        try
            ITransactionUnwrapper(adapter).unwrap(to, value, data, operation)
        returns (UnwrappedTransaction[] memory unwrapped) {
            for (uint256 i; i < unwrapped.length; ++i) {
                UnwrappedTransaction memory entry = unwrapped[i];
                consumptions = _transaction(
                    roleKey,
                    data[entry.dataLocation:entry.dataLocation +
                        entry.dataSize],
                    consumptions,
                    Transaction(entry.to, entry.value, entry.operation)
                );
            }
        } catch {
            revert MalformedMultiEntrypoint();
        }
    }

    /// @dev Inspects a transaction and authorizes based on role permissions.
    function _transaction(
        bytes32 roleKey,
        bytes calldata data,
        Consumption[] memory consumptions,
        Transaction memory transaction
    ) private view returns (Consumption[] memory) {
        Role storage role = roles[roleKey];

        if (data.length != 0 && data.length < 4) {
            revert FunctionSignatureTooShort();
        }

        /*
         * Resolve the scopeConfig governing this transaction.
         *
         * Clearance records how the owner scoped the target:
         *   Target:   whole contract allowed - any calldata, even empty
         *   Function: only individually allowed selectors
         *   None:     not scoped - only a global entry can authorize
         *
         * scopeConfig keys pack [20 bytes: address][12 bytes: discriminator]:
         *
         *                   20 bytes   |  8 bytes   | 4 bytes   |
         *   Target entry:   address    |        0xFF..FF        | = any calldata
         *   Function entry: address    |  0x00..00  | selector  |
         *   Global entry:   0x00..00   |  0x00..00  | selector  | = any target
         *
         * A function entry can never collide with a target entry: it always
         * has 8 zero bytes where a target entry has 0xFF.
         */
        Clearance clearance = role.clearance[transaction.to];

        /*
         * Lookup 1 of 2: destination-specific entry.
         * Destination rules take precedence over global rules, so this is
         * consulted first.
         *
         * Clearance.None falls through: only a global entry can authorize.
         */
        uint256 scopeConfig;
        if (clearance == Clearance.Function) {
            scopeConfig = role.scopeConfig[
                bytes32(bytes20(transaction.to)) |
                    (bytes32(bytes4(data)) >> 160)
            ];
        } else if (clearance == Clearance.Target) {
            scopeConfig = role.scopeConfig[
                bytes32(bytes20(transaction.to)) | (~bytes32(0) >> 160)
            ];
        }

        /*
         * Lookup 2 of 2: global entry. Same layout with the address zeroed:
         * selector allowed on any target (write side: allowFunctionGlobally).
         * Requires a selector, so empty-calldata calls never resolve here.
         */
        if (scopeConfig == 0 && data.length != 0) {
            scopeConfig = role.scopeConfig[bytes32(bytes4(data)) >> 160];
        }

        /*
         * scopeConfig == 0 means no permission configured.
         */
        if (scopeConfig == 0) {
            revert TransactionNotAllowed(transaction.to, bytes4(data));
        }

        /*
         * Enforce ExecutionOptions packed in the high bits of scopeConfig.
         * The enum values double as bit flags:
         *
         *   None = 0 (00)   Send = 1 (01)
         *   Both = 3 (11)   DelegateCall = 2 (10)
         *
         *   bit 0 set -> transaction may carry ether
         *   bit 1 set -> transaction may delegatecall
         */
        {
            uint256 options = scopeConfig >> 160;
            // can Send ?
            if (options & 1 == 0 && transaction.value > 0) {
                revert SendNotAllowed(transaction.to);
            }
            // can DelegateCall ?
            if (
                options & 2 == 0 &&
                transaction.operation == Operation.DelegateCall
            ) {
                revert DelegateCallNotAllowed(transaction.to);
            }
        }

        /*
         * Load and Evaluate Condition tree
         */
        (Condition memory condition, uint256 maxPluckCount) = ConditionLoader
            .load(scopeConfig);

        Result memory result = ConditionEvaluator.evaluate(
            data,
            0,
            condition,
            consumptions,
            Context(
                transaction.to,
                transaction.value,
                transaction.operation,
                new bytes32[](maxPluckCount),
                new uint256[](maxPluckCount)
            )
        );

        if (result.status != Status.Ok) {
            revert ConditionViolation(
                result.status,
                result.violatedNodeIndex,
                result.payloadLocation
            );
        }

        return result.consumptions;
    }
}

project/contracts/core/Membership.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "./Storage.sol";

/**
 * @title   Membership
 * @notice  Validates that a module holds an active role membership before
 *          authorizing transactions. Memberships can be time-bound and
 *          usage-limited.
 *
 * @dev     Module authentication is enforced at the public entry points via
 *          `moduleOnly` / `moduleOnlySigned` (defined in `Modifier`). This
 *          function reads `sentOrSignedByModule()` to identify the active
 *          module and verifies its membership for the requested role.
 *          Membership packs timestamps and uses into a single uint256.
 *          See layout below.
 *
 * @author  gnosisguild
 */

abstract contract Membership is RolesStorage {
    uint256 private constant _MEMBERSHIP_NOOP = type(uint256).max;
    uint256 private constant _MEMBERSHIP_REVOKE = 0;

    function _authenticate(
        bytes32 roleKey
    ) internal view returns (address module, uint256 nextMembership) {
        // Never authorize the zero role
        if (roleKey == 0) {
            revert NoMembership();
        }

        module = sentOrSignedByModule();

        uint256 membership = roles[roleKey].members[module];
        if (membership == 0) {
            revert NoMembership();
        }

        /*
         * Membership Layout (256 bits)
         * ┌────────────────┬────────────────┬─────────────────────────────────┐
         * │ startTimestamp │  endTimestamp  │            usesLeft             │
         * │    64 bits     │    64 bits     │            128 bits             │
         * └────────────────┴────────────────┴─────────────────────────────────┘
         *
         * - startTimestamp: Unix timestamp when membership becomes valid
         * - endTimestamp:   Unix timestamp when membership expires
         * - usesLeft:       Remaining uses (type(uint128).max = unlimited)
         */

        if (block.timestamp < uint64(membership >> 192)) {
            revert MembershipNotYetValid();
        }
        if (block.timestamp > uint64(membership >> 128)) {
            revert MembershipExpired();
        }
        if (~membership << 128 == 0) {
            // unlimited uses
            return (module, _MEMBERSHIP_NOOP);
        }

        uint256 usesLeft = (membership << 128) >> 128;

        return (
            module,
            usesLeft <= 1
                ? _MEMBERSHIP_REVOKE
                : ((membership >> 128) << 128) | (usesLeft - 1)
        );
    }

    function _hasActiveMembership(
        bytes32 roleKey,
        address module
    ) internal view returns (bool) {
        if (roleKey == 0) return false;
        uint256 membership = roles[roleKey].members[module];
        if (membership == 0) return false;
        if (block.timestamp < uint64(membership >> 192)) return false;
        if (block.timestamp > uint64(membership >> 128)) return false;
        return true;
    }
}

project/contracts/core/RoleTx.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import {Operation} from "@gnosis-guild/zodiac-core/contracts/core/Operation.sol";

library RoleTx {
    bytes32 internal constant TYPEHASH =
        keccak256(
            "RoleTx(address to,uint256 value,bytes data,uint8 operation,bytes32 roleKey,bool shouldRevert,bytes32 salt)"
        );

    /**
     * @dev Computes the EIP-712 struct hash for a RoleTx message.
     *      This is `hashStruct(message)`, not the final EIP-712 digest;
     *      the domain separator is applied by zodiac-core during authentication.
     * @param to Destination of the transaction.
     * @param value Ether value of the transaction.
     * @param data Transaction calldata.
     * @param operation Transaction operation.
     * @param roleKey Role under which the transaction is authorized.
     * @param shouldRevert Whether a failed inner execution should revert.
     * @param salt Value used to distinguish the signed message for replay protection.
     * @return structHash Hash of the encoded RoleTx message and its type hash.
     */
    function hashStruct(
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation,
        bytes32 roleKey,
        bool shouldRevert,
        bytes32 salt
    ) internal pure returns (bytes32 structHash) {
        return
            keccak256(
                abi.encode(
                    TYPEHASH,
                    to,
                    value,
                    keccak256(data),
                    operation,
                    roleKey,
                    shouldRevert,
                    salt
                )
            );
    }
}

project/contracts/core/Settlement.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "./Storage.sol";

import {Consumption} from "../types/Allowance.sol";

/**
 * @title   Settlement
 * @notice  Persists allowance consumption and membership updates to storage.
 *
 * @dev     Invoked after successful execution. Reentrancy is prevented by the
 *          nonReentrant modifier on execution entry points.
 *
 * @author  gnosisguild
 */
abstract contract Settlement is RolesStorage {
    /**
     * @dev Persists allowance consumption and membership updates after a successful execution.
     *
     * @param sender The address that initiated the transaction
     * @param roleKey The role key used for execution
     * @param nextMembership Packed membership data. uint256.max skips membership update
     * @param consumptions Allowance consumption records to persist
     */
    function _persist(
        address sender,
        bytes32 roleKey,
        uint256 nextMembership,
        Consumption[] memory consumptions
    ) internal {
        uint256 count = consumptions.length;
        for (uint256 i; i < count; ++i) {
            Consumption memory consumption = consumptions[i];

            assert(consumption.consumed <= consumption.balance);

            uint128 updatedBalance = _persistConsumption(consumption);

            emit ConsumeAllowance(
                consumption.allowanceKey,
                consumption.consumed,
                updatedBalance
            );
        }

        // uint256.max == noop
        if (nextMembership == type(uint256).max) return;

        roles[roleKey].members[sender] = nextMembership;
        if (nextMembership != 0) {
            emit UpdateRole(
                roleKey,
                sender,
                uint64(nextMembership >> 192),
                uint64(nextMembership >> 128),
                uint128(nextMembership)
            );
        } else {
            emit RevokeRole(roleKey, sender);
        }
    }

    /// @dev Writes consumption to allowance storage, returns new balance.
    function _persistConsumption(
        Consumption memory consumption
    ) private returns (uint128 updatedBalance) {
        bytes32 allowanceKey = consumption.allowanceKey;
        uint64 _timestamp = consumption.timestamp;
        updatedBalance = consumption.balance - consumption.consumed;

        /*
         * Allowance Storage Layout (2 words):
         * ┌────────────────────────────────┬────────────────────────────────┐
         * │           maxRefill            │             refill             │
         * │            128 bits            │            128 bits            │
         * ├────────────────┬───────────────┴───────────────┬────────────────┤
         * │   timestamp    │            balance            │     period     │
         * │    64 bits     │           128 bits            │    64 bits     │
         * └────────────────┴───────────────────────────────┴────────────────┘
         */
        assembly {
            mstore(0x00, allowanceKey)
            mstore(0x20, allowances.slot)

            let slot := add(keccak256(0x00, 0x40), 1)

            sstore(
                slot,
                or(
                    or(shl(192, _timestamp), shl(64, updatedBalance)),
                    and(sload(slot), 0xffffffffffffffff)
                )
            )
        }
    }
}

project/contracts/core/Setup.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "../common/AllowanceConsumer.sol";
import "./serialize/ConditionStorer.sol";
import "./Storage.sol";

import {Clearance} from "../types/Permission.sol";

/*
 * Permission Model
 *
 * Role
 *  │
 *  ├─ members ───────────────────────► who can use this role
 *  │
 *  ├─ targets (address → Clearance)
 *  │   │
 *  │   ├─ Clearance.None ────────────► no target rule (default) - only a
 *  │   │                               global entry can authorize
 *  │   │
 *  │   ├─ Clearance.Target ──────────► all functions allowed, subject to
 *  │   │                               the target entry below (wildcard)
 *  │   │
 *  │   └─ Clearance.Function ────────► only functions with a function
 *  │                                   entry below are allowed
 *  │
 *  └─ scopeConfig (key → ExecutionOptions + condition tree)
 *      │
 *      │   Key: [20 bytes: address][8 bytes][4 bytes]
 *      │   ├─ Function entry: address  | 0x00..00 | selector  one selector on one address
 *      │   ├─ Target entry:   address  |        0xFF..FF      any calldata on one address
 *      │   └─ Global entry:   0x00..00 | 0x00..00 | selector  one selector on any address
 *      │
 *      ├─ no matching entry ─────────► blocked (TransactionNotAllowed)
 *      │
 *      └─ matching entry ────────────► allowed, subject to ExecutionOptions
 *                                      (send/delegatecall flags) and the
 *                                      condition tree
 *
 * Resolution: the destination-specific entry (function or target, per
 * Clearance) is consulted first - destination rules take precedence over
 * global rules. If no destination-specific entry matches, the global entry
 * applies. A global entry keys on the selector, so calls with empty calldata
 * never resolve globally.
 *
 * Allowances (separate storage, referenced by conditions)
 */

/**
 * @title Setup - Configuration and setup functions for Zodiac Roles Mod.
 *
 * @dev Permission setters come in two flavors:
 *
 *      - Validated (allowTarget, allowFunction, allowFunctionGlobally):
 *        take a ConditionFlat[] tree, then validate (Integrity) and pack it
 *        on-chain. Costs more setup gas, but the stored buffer is guaranteed
 *        well-formed.
 *      - Packed (allowTargetPacked, allowFunctionPacked,
 *        allowFunctionGloballyPacked): take a pre-packed condition buffer
 *        and store it as-is, skipping on-chain validation. An escape hatch
 *        for large condition trees, where packing on-chain can be costly.
 *
 *      To produce a buffer, call the read-only packConditions() off-chain
 *      (eth_call): validation runs offchain, only the storage write is paid.
 *
 * @author  gnosisguild
 */
abstract contract Setup is RolesStorage {
    /*//////////////////////////////////////////////////////////////
                            INITIALIZATION
    //////////////////////////////////////////////////////////////*/

    function setUp(
        bytes memory initParams
    ) public virtual override initializer {
        (address _owner, address _avatar, address _target) = abi.decode(
            initParams,
            (address, address, address)
        );
        _transferOwnership(_owner);
        avatar = _avatar;
        target = _target;

        setupModules();

        emit RolesModSetup(msg.sender, _owner, _avatar, _target, VERSION);
    }

    /*//////////////////////////////////////////////////////////////
                           ROLE MEMBERSHIP
    //////////////////////////////////////////////////////////////*/

    /// @dev Grants a role to a module with optional session parameters.
    /// @param module Module to grant the role to.
    /// @param roleKey Role to grant.
    /// @param startTimestamp Start timestamp (0 = immediately valid).
    /// @param endTimestamp End timestamp (0 = never expires).
    /// @param usesLeft Number of uses (0 = unlimited).
    function grantRole(
        address module,
        bytes32 roleKey,
        uint64 startTimestamp,
        uint64 endTimestamp,
        uint128 usesLeft
    ) public onlyOwner {
        endTimestamp = endTimestamp != 0 ? endTimestamp : type(uint64).max;
        usesLeft = usesLeft != 0 ? usesLeft : type(uint128).max;
        roles[roleKey].members[module] =
            (uint256(startTimestamp) << 192) |
            (uint256(endTimestamp) << 128) |
            uint256(usesLeft);
        if (!isModuleEnabled(module)) {
            enableModule(module);
        }
        emit GrantRole(roleKey, module, startTimestamp, endTimestamp, usesLeft);
    }

    /// @dev Revokes a role from a module.
    /// @param module Module to revoke the role from.
    /// @param roleKey Role to revoke.
    function revokeRole(address module, bytes32 roleKey) public onlyOwner {
        delete roles[roleKey].members[module];
        emit RevokeRole(roleKey, module);
    }

    /// @dev Allows a module to renounce its own role.
    /// @param roleKey Role to renounce.
    function renounceRole(bytes32 roleKey) external {
        delete roles[roleKey].members[msg.sender];
        emit RevokeRole(roleKey, msg.sender);
    }

    /// @dev Batch assigns roles to a module.
    /// @param module Module to assign roles to.
    /// @param roleKeys Roles to assign.
    /// @param memberOf true to grant, false to revoke.
    function assignRoles(
        address module,
        bytes32[] calldata roleKeys,
        bool[] calldata memberOf
    ) external onlyOwner {
        for (uint256 i; i < roleKeys.length; ++i) {
            bytes32 key = roleKeys[i];
            if (memberOf[i]) {
                grantRole(module, key, 0, 0, 0);
            } else {
                revokeRole(module, key);
            }
        }
    }

    /// @dev Sets the default role used for a module if it calls
    ///      execTransactionFromModule() or execTransactionFromModuleReturnData().
    /// @param module Address of the module on which to set default role.
    /// @param roleKey Role to be set as default.
    function setDefaultRole(
        address module,
        bytes32 roleKey
    ) external onlyOwner {
        defaultRoles[module] = roleKey;
        emit SetDefaultRole(module, roleKey);
    }

    /*//////////////////////////////////////////////////////////////
                         TARGET PERMISSIONS
    //////////////////////////////////////////////////////////////*/

    /// @dev Allows transactions to a target address, restricted by a
    ///      target-wide condition: the same condition tree governs every
    ///      call to the target, regardless of selector.
    ///
    ///      Sets Clearance.Target.
    ///
    ///      Conditions are validated and packed on-chain; use
    ///      allowTargetPacked() for a pre-packed buffer.
    /// @param roleKey identifier of the role to be modified.
    /// @param targetAddress Destination address of transaction.
    /// @param conditions Condition tree in flat BFS order. Empty array means
    ///        no payload restrictions (pass-through).
    /// @param options designates if a transaction can send ether and/or delegatecall to target.
    function allowTarget(
        bytes32 roleKey,
        address targetAddress,
        ConditionFlat[] memory conditions,
        ExecutionOptions options
    ) external {
        allowTargetPacked(
            roleKey,
            targetAddress,
            packConditions(conditions),
            options
        );
    }

    /// @dev Allows transactions to a target address using a pre-packed
    ///      condition buffer. Same effect as allowTarget(), but skips
    ///      on-chain validation - see the contract-level note for the tradeoff.
    /// @param roleKey identifier of the role to be modified.
    /// @param targetAddress Destination address of transaction.
    /// @param packedConditions Pre-packed condition buffer. Empty bytes means
    ///        no payload restrictions (a single Pass condition is stored).
    /// @param options designates if a transaction can send ether and/or delegatecall to target.
    function allowTargetPacked(
        bytes32 roleKey,
        address targetAddress,
        bytes memory packedConditions,
        ExecutionOptions options
    ) public onlyOwner {
        _requireNonZeroAddress(targetAddress);
        bytes32 key = bytes32(bytes20(targetAddress)) | (~bytes32(0) >> 160);

        roles[roleKey].clearance[targetAddress] = Clearance.Target;
        roles[roleKey].scopeConfig[key] = ConditionStorer.store(
            _conditionsOrPass(packedConditions),
            options
        );

        emit AllowTarget(roleKey, targetAddress, packedConditions, options);
    }

    /// @dev Designates only specific functions can be called.
    /// @param roleKey identifier of the role to be modified.
    /// @param targetAddress Destination address of transaction.
    function scopeTarget(
        bytes32 roleKey,
        address targetAddress
    ) external onlyOwner {
        _requireNonZeroAddress(targetAddress);
        roles[roleKey].clearance[targetAddress] = Clearance.Function;
        emit ScopeTarget(roleKey, targetAddress);
    }

    /// @dev Removes the target-level rule: resets Clearance to None, so only
    ///      a global entry can still authorize calls to this target.
    /// @param roleKey identifier of the role to be modified.
    /// @param targetAddress Destination address of transaction.
    function revokeTarget(
        bytes32 roleKey,
        address targetAddress
    ) external onlyOwner {
        _requireNonZeroAddress(targetAddress);
        delete roles[roleKey].clearance[targetAddress];
        emit RevokeTarget(roleKey, targetAddress);
    }

    /*//////////////////////////////////////////////////////////////
                        FUNCTION PERMISSIONS
    //////////////////////////////////////////////////////////////*/

    /// @dev Allows a single function on a target address, restricted by
    ///      validated conditions. Writes a function entry, which takes effect
    ///      only while the target is scoped (Clearance.Function, see
    ///      scopeTarget). Conditions are validated and packed on-chain; use
    ///      allowFunctionPacked() for a pre-packed buffer.
    /// @param roleKey identifier of the role to be modified.
    /// @param targetAddress Destination address of transaction.
    /// @param selector 4 byte function selector.
    /// @param conditions Condition tree in flat BFS order. Empty array means
    ///        no payload restrictions (pass-through).
    /// @param options designates if a transaction can send ether and/or delegatecall to target.
    function allowFunction(
        bytes32 roleKey,
        address targetAddress,
        bytes4 selector,
        ConditionFlat[] memory conditions,
        ExecutionOptions options
    ) external {
        allowFunctionPacked(
            roleKey,
            targetAddress,
            selector,
            packConditions(conditions),
            options
        );
    }

    /// @dev Allows a single function on a target address using pre-packed
    ///      conditions. Same effect as allowFunction(), but skips on-chain
    ///      validation - see the contract-level note for the tradeoff.
    /// @param roleKey identifier of the role to be modified.
    /// @param targetAddress Destination address of transaction.
    /// @param selector 4 byte function selector.
    /// @param packedConditions Pre-packed condition buffer. Empty bytes means
    ///        no payload restrictions (a single Pass condition is stored).
    /// @param options designates if a transaction can send ether and/or delegatecall to target.
    function allowFunctionPacked(
        bytes32 roleKey,
        address targetAddress,
        bytes4 selector,
        bytes memory packedConditions,
        ExecutionOptions options
    ) public onlyOwner {
        _requireNonZeroAddress(targetAddress);
        roles[roleKey].scopeConfig[
            _key(targetAddress, selector)
        ] = ConditionStorer.store(_conditionsOrPass(packedConditions), options);

        emit AllowFunction(
            roleKey,
            targetAddress,
            selector,
            packedConditions,
            options
        );
    }

    /// @dev Allows a function selector on all targets, restricted by validated
    ///      conditions. Always enforces no send and no delegatecall
    ///      (ExecutionOptions.None). Consulted only when no destination-
    ///      specific entry matches, and only for calls carrying a selector - calls with
    ///      empty calldata never resolve via a global entry. Conditions are
    ///      validated and packed on-chain; use allowFunctionGloballyPacked()
    ///      for a pre-packed buffer.
    /// @param roleKey identifier of the role to be modified.
    /// @param selector 4 byte function selector.
    /// @param conditions Condition tree in flat BFS order. Empty array means
    ///        no payload restrictions (pass-through).
    function allowFunctionGlobally(
        bytes32 roleKey,
        bytes4 selector,
        ConditionFlat[] memory conditions
    ) external {
        allowFunctionGloballyPacked(
            roleKey,
            selector,
            packConditions(conditions)
        );
    }

    /// @dev Allows a function selector on all targets using pre-packed
    ///      conditions. Same effect as allowFunctionGlobally(), but skips
    ///      on-chain validation - see the contract-level note for the tradeoff.
    /// @param roleKey identifier of the role to be modified.
    /// @param selector 4 byte function selector.
    /// @param packedConditions Pre-packed condition buffer. Empty bytes means
    ///        no payload restrictions (a single Pass condition is stored).
    function allowFunctionGloballyPacked(
        bytes32 roleKey,
        bytes4 selector,
        bytes memory packedConditions
    ) public onlyOwner {
        roles[roleKey].scopeConfig[_key(address(0), selector)] = ConditionStorer
            .store(_conditionsOrPass(packedConditions), ExecutionOptions.None);

        emit AllowFunctionGlobally(roleKey, selector, packedConditions);
    }

    /// @dev Removes a function permission for a target.
    /// @param roleKey identifier of the role to be modified.
    /// @param targetAddress Destination address of transaction.
    /// @param selector 4 byte function selector.
    function revokeFunction(
        bytes32 roleKey,
        address targetAddress,
        bytes4 selector
    ) external onlyOwner {
        _requireNonZeroAddress(targetAddress);
        delete roles[roleKey].scopeConfig[_key(targetAddress, selector)];
        emit RevokeFunction(roleKey, targetAddress, selector);
    }

    /// @dev Removes a globally allowed function permission.
    /// @param roleKey identifier of the role to be modified.
    /// @param selector 4 byte function selector.
    function revokeFunctionGlobally(
        bytes32 roleKey,
        bytes4 selector
    ) external onlyOwner {
        delete roles[roleKey].scopeConfig[_key(address(0), selector)];
        emit RevokeFunctionGlobally(roleKey, selector);
    }

    /*//////////////////////////////////////////////////////////////
                             ALLOWANCES
    //////////////////////////////////////////////////////////////*/

    function setAllowance(
        bytes32 key,
        uint128 balance,
        uint128 maxRefill,
        uint128 refill,
        uint64 period,
        uint64 timestamp
    ) external onlyOwner {
        maxRefill = maxRefill != 0 ? maxRefill : type(uint128).max;
        timestamp = timestamp != 0 ? timestamp : uint64(block.timestamp);

        allowances[key] = Allowance({
            refill: refill,
            maxRefill: maxRefill,
            period: period,
            timestamp: timestamp,
            balance: balance
        });
        emit SetAllowance(key, balance, maxRefill, refill, period, timestamp);
    }

    /// @dev Updates only the refill parameters of an existing allowance, preserving balance and timestamp.
    /// @param key The allowance key.
    /// @param maxRefill Cap at which refilling stops. Pass 0 to set to max uint128.
    /// @param refill Amount added to balance each period.
    /// @param period Refill interval in seconds.
    function updateAllowance(
        bytes32 key,
        uint128 maxRefill,
        uint128 refill,
        uint64 period
    ) external onlyOwner {
        maxRefill = maxRefill != 0 ? maxRefill : type(uint128).max;
        uint64 timestamp = allowances[key].timestamp;
        uint128 balance = allowances[key].balance;

        allowances[key].refill = refill;
        allowances[key].maxRefill = maxRefill;
        allowances[key].period = period;

        emit SetAllowance(key, balance, maxRefill, refill, period, timestamp);
    }

    /// @dev Returns the accrued allowance balance at current block.timestamp.
    /// @param allowanceKey The allowance key.
    /// @return balance The accrued balance.
    /// @return timestamp The timestamp of the last accrual point.
    function accruedAllowance(
        bytes32 allowanceKey
    ) external view returns (uint128 balance, uint64 timestamp) {
        return AllowanceConsumer.accrue(allowanceKey, uint64(block.timestamp));
    }

    /*//////////////////////////////////////////////////////////////
                              ADAPTERS
    //////////////////////////////////////////////////////////////*/

    function setTransactionUnwrapper(
        address to,
        bytes4 selector,
        address adapter
    ) external onlyOwner {
        unwrappers[bytes32(bytes20(to)) | (bytes32(selector) >> 160)] = adapter;
        emit SetUnwrapAdapter(to, selector, adapter);
    }

    /*//////////////////////////////////////////////////////////////
                               HELPERS
    //////////////////////////////////////////////////////////////*/

    /// @dev Read-only entrypoint for packing conditions: permission authors
    ///      can eth_call this to validate and pack, then pass the buffer to
    ///      a *Packed setter. An empty array packs to empty bytes - no
    ///      payload restrictions (pass-through).
    /// @param conditions The conditions to pack, in flat BFS order.
    /// @return buffer The packed condition buffer.
    function packConditions(
        ConditionFlat[] memory conditions
    ) public pure returns (bytes memory buffer) {
        if (conditions.length > 0) {
            buffer = ConditionStorer.pack(conditions);
        }
    }

    /*//////////////////////////////////////////////////////////////
                               INTERNALS
    //////////////////////////////////////////////////////////////*/

    /// @dev If buffer is empty, returns packed single Pass condition;
    ///      otherwise returns the buffer unchanged.
    function _conditionsOrPass(
        bytes memory buffer
    ) private pure returns (bytes memory) {
        if (buffer.length == 0) {
            return ConditionStorer.pack(new ConditionFlat[](1));
        }
        return buffer;
    }

    function _requireNonZeroAddress(address targetAddress) private pure {
        if (targetAddress == address(0)) revert ZeroAddressNotAllowed();
    }
}

project/contracts/core/Storage.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "@gnosis-guild/zodiac-core/contracts/core/Modifier.sol";

import "../types/Types.sol";

/**
 * @title RolesStorage
 * @notice Base contract defining shared storage for Zodiac Roles Mod
 *
 * @author gnosisguild
 *
 */
abstract contract RolesStorage is Modifier, IRolesEvent, IRolesError {
    string public constant VERSION = "3.0.0";

    mapping(bytes32 => Role) internal roles;
    mapping(bytes32 => Allowance) public allowances;
    mapping(bytes32 => address) public unwrappers;
    mapping(address => bytes32) public defaultRoles;

    bool private transient _reentrancyGuard;

    modifier nonReentrant() {
        if (_reentrancyGuard) {
            revert Reentrancy();
        }
        _reentrancyGuard = true;
        _;
        _reentrancyGuard = false;
    }

    function _key(
        address targetAddress,
        bytes4 selector
    ) internal pure returns (bytes32) {
        return bytes32(bytes20(targetAddress)) | (bytes32(selector) >> 160);
    }
}

project/contracts/core/StorageSlots.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

/*
 * StorageSlots — slot indices of `RolesStorage` state variables, exposed for
 * inline-assembly consumers that can't reference the variables directly
 * (i.e. libraries).
 *
 * Storage layout of `Roles` (zodiac-core 4 + RolesStorage):
 *
 *   ┌──────┬─────────────────────────────────────────────────────────┐
 *   │ Slot │ Source                                                  │
 *   ├──────┼─────────────────────────────────────────────────────────┤
 *   │  0   │ Initializable._initialized (bool)         ┐             │
 *   │      │ Ownable.owner              (address)      ┘  packed     │
 *   │  1   │ Module.avatar              (address)                    │
 *   │  2   │ Module.target              (address)                    │
 *   │  3   │ ExecutionTracker.consumed  (mapping)                    │
 *   │  4   │ Modifier.modules           (mapping)                    │
 *   │  5   │ RolesStorage.roles         (mapping)                    │
 *   │  6   │ RolesStorage.allowances    (mapping)                    │
 *   │  7   │ RolesStorage.unwrappers    (mapping)                    │
 *   │  8   │ RolesStorage.defaultRoles  (mapping)                    │
 *   └──────┴─────────────────────────────────────────────────────────┘
 *
 * Transient (TLOAD/TSTORE — not regular storage):
 *   Modifier._authenticatedModule
 *   RolesStorage._reentrancyGuard
 *
 */

uint256 constant AVATAR_SLOT = 1;
uint256 constant ALLOWANCES_SLOT = 6;

project/contracts/core/evaluate/BitmaskChecker.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import {Status} from "../../types/Types.sol";

/**
 * @title BitmaskChecker
 * @notice Validates that selected bits of an operand match an expected pattern.
 *
 * @dev compValue layout (total length = 2 + 2 * N bytes, N >= 1):
 *
 *      ┌────────────────────┬────────────────────┬────────────────────┐
 *      │ shift (16 bits)    │ mask (8N bits)     │ expected (8N bits) │
 *      └────────────────────┴────────────────────┴────────────────────┘
 *
 *      Fields:
 *        - shift     uint16, byte offset into the operand at which the mask
 *                    window starts.
 *        - mask      N bytes; selects which bits of the operand are checked.
 *        - expected  N bytes; the required value of the selected bits.
 *
 *      Operand framing (passed via `inlined` and `size`):
 *        - inlined == true   Operand is a Static value (`size` bytes at
 *                            location; normally 32, or 1-32 after Slice)
 *        - inlined == false  Operand is a Dynamic value; `location` points at
 *                            the length-prefix word, content begins at
 *                            `location + 32` and `shift` indexes into content
 *                            (the prefix is not part of the addressable range)
 *
 *      Bounds: `shift + N` must not exceed the operand's actual byte length
 *      (`size` for Static, the value of the length prefix for Dynamic). The
 *      window is processed in 32-byte chunks; the trailing chunk is rinsed
 *      so unused tail bits cannot contribute to the comparison.
 *
 * @author gnosisguild
 */
library BitmaskChecker {
    function check(
        bytes calldata data,
        uint256 location,
        bytes memory compValue,
        bool inlined,
        uint256 size
    ) internal pure returns (Status) {
        uint256 shift = uint16(bytes2(compValue));
        uint256 n = (compValue.length - 2) / 2;

        /*
         * Resolve the operand's encoded byte length so the compare cannot
         * bleed into trailing zero padding (or, for Dynamic operands sitting
         * mid-buffer, into the next ABI field).
         *   - Static (inlined): `size` bytes inline at `location`. We rely on
         *     the passed `size` because a static node may itself be sliced.
         *   - Dynamic: length prefix at `location`, content at `location + 32`.
         */
        uint256 start = location;
        uint256 encodedLength = size;
        if (inlined == false) {
            if (start + 32 > data.length) {
                return Status.BitmaskOverflow;
            }

            assembly {
                encodedLength := calldataload(add(data.offset, start))
            }

            start += 32;
        }

        // mask window must fit within the declared value length
        if (shift + n > encodedLength) {
            return Status.BitmaskOverflow;
        }

        // declared value length must be physically present in calldata
        if (start + encodedLength > data.length) {
            return Status.CalldataOverflow;
        }

        bytes calldata value = data[start:];

        /*
         * Load actual, expected, and mask in 32-byte chunks. Final chunk
         * gets rinsed if less than 32 bytes remain.
         */
        for (uint256 i; i < n; i += 32) {
            /*
             * compValue memory layout:
             * | 32: length | 2: shift | N: mask | N: expected |
             *                         ^--- 0x22 offset
             */
            bytes32 mask;
            assembly {
                mask := mload(add(add(compValue, 0x22), i))
            }

            bytes32 expected;
            assembly {
                expected := mload(add(add(compValue, 0x22), add(n, i)))
            }

            bytes32 actual;
            assembly {
                actual := calldataload(add(value.offset, add(shift, i)))
            }

            bytes32 rinseMask = _rinseMask(n - i);

            if (expected & rinseMask != actual & mask & rinseMask) {
                return Status.BitmaskNotAllowed;
            }
        }

        return Status.Ok;
    }

    /// @dev Returns a mask with leading 1s for byteCount bytes, rest 0s.
    function _rinseMask(uint256 bytesLeft) private pure returns (bytes32) {
        uint256 bitsToRinse = (bytesLeft > 31 ? 0 : 32 - bytesLeft) * 8;
        return bytes32(type(uint256).max << bitsToRinse);
    }
}

project/contracts/core/evaluate/ConditionEvaluator.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "./BitmaskChecker.sol";
import "./CustomConditionChecker.sol";
import "./WithinAllowanceChecker.sol";
import "./WithinRatioChecker.sol";

import "../../common/AbiLocation.sol";

import "../../types/Types.sol";

/**
 * @title ConditionEvaluator
 * @notice Evaluates condition trees on scoped function calls.
 * @author gnosisguild
 */
library ConditionEvaluator {
    function evaluate(
        bytes calldata data,
        uint256 location,
        Condition memory condition,
        Consumption[] memory consumptions,
        Context memory context
    ) internal view returns (Result memory) {
        Operator operator = condition.operator;

        if (operator < Operator.EqualTo) {
            if (operator == Operator.Pass) {
                return _ok(consumptions);
            } else if (operator == Operator.Matches) {
                location = location > 0 &&
                    condition.encoding == Encoding.AbiEncoded
                    ? location + 32
                    : location;
                return
                    _matches(data, location, condition, consumptions, context);
            } else if (operator == Operator.And) {
                return _and(data, location, condition, consumptions, context);
            } else if (operator == Operator.Or) {
                return _or(data, location, condition, consumptions, context);
            } else if (operator == Operator.Slice) {
                return _slice(data, location, condition, consumptions, context);
            } else if (operator == Operator.Pluck) {
                return _pluck(data, location, condition, consumptions, context);
            } else if (operator == Operator.Empty) {
                return
                    _result(
                        data.length == 0 ? Status.Ok : Status.CalldataNotEmpty,
                        0,
                        condition,
                        consumptions
                    );
            } else if (
                operator == Operator.ArraySome ||
                operator == Operator.ArrayEvery
            ) {
                return
                    _arrayIterator(
                        data,
                        location,
                        condition,
                        consumptions,
                        context
                    );
            } else if (operator == Operator.ArrayTailMatches) {
                return
                    _arrayTailMatches(
                        data,
                        location,
                        condition,
                        consumptions,
                        context
                    );
            } else if (
                operator == Operator.ZipSome || operator == Operator.ZipEvery
            ) {
                return
                    _zipIterator(
                        data,
                        location,
                        condition,
                        consumptions,
                        context
                    );
            }
        } else {
            if (operator <= Operator.SignedIntLessThan) {
                (bytes32 value, bool overflow) = __input(
                    data,
                    location,
                    condition,
                    context
                );

                return
                    _result(
                        overflow
                            ? Status.CalldataOverflow
                            : operator <= Operator.LessThan
                                ? __compare(value, condition)
                                : __compareSigned(value, condition),
                        location,
                        condition,
                        consumptions
                    );
            } else if (operator == Operator.Bitmask) {
                return
                    _result(
                        BitmaskChecker.check(
                            data,
                            location,
                            condition.compValue,
                            condition.inlined,
                            condition.size
                        ),
                        location,
                        condition,
                        consumptions
                    );
            } else if (operator == Operator.WithinAllowance) {
                (bytes32 value, bool overflow) = __input(
                    data,
                    location,
                    condition,
                    context
                );
                if (overflow) {
                    return
                        _violation(
                            Status.CalldataOverflow,
                            location,
                            condition
                        );
                }
                return
                    __allowance(
                        uint256(value),
                        location,
                        condition,
                        consumptions
                    );
            } else if (operator == Operator.CallWithinAllowance) {
                return __allowance(1, location, condition, consumptions);
            } else if (operator == Operator.WithinRatio) {
                return
                    _result(
                        WithinRatioChecker.check(
                            condition.compValue,
                            context.pluckedValues
                        ),
                        location,
                        condition,
                        consumptions
                    );
            } else if (operator == Operator.Custom) {
                uint256 size = condition.size != 0
                    ? condition.size
                    : AbiLocation.size(data, location, condition);
                (
                    Status status,
                    Consumption[] memory nextConsumptions
                ) = CustomConditionChecker.check(
                        condition.compValue,
                        context.to,
                        context.value,
                        data,
                        context.operation,
                        location,
                        size,
                        consumptions,
                        context.pluckedValues
                    );
                return _result(status, location, condition, nextConsumptions);
            }
        }

        revert IRolesError.UnsupportedOperator(condition.index);
    }

    function _matches(
        bytes calldata data,
        uint256 location,
        Condition memory condition,
        Consumption[] memory consumptions,
        Context memory context
    ) private view returns (Result memory result) {
        uint256 length = condition.compValue.length;
        if (length > 0) {
            /*
             * Leading Bytes Validation
             *
             * AbiEncoded + Matches may carry an optional prefix (N <= 32,
             * enforced by Integrity) that must match the first N bytes of
             * calldata at location:
             *
             *   data[location:location + length] == compValue
             *
             * The 2-byte count preceding the prefix in the stored payload is
             * split out by the unpacker into the node's `leadingBytes`, so
             * compValue is exactly the prefix.
             *
             * Both sides are compared on a 32-byte word basis: right-aligned
             * in bytes32, shifting out the trailing 32 - N bytes (shift
             * operands are bits, hence * 8). No slice is allocated.
             */

            // Check bounds before reading leading bytes
            if (location + length > data.length) {
                return _violation(Status.CalldataOverflow, location, condition);
            }

            uint256 shift = (32 - length) * 8;
            bytes32 expected = bytes32(condition.compValue) >> shift;
            bytes32 actual = bytes32(data[location:]) >> shift;

            if (expected != actual) {
                return
                    _violation(
                        Status.LeadingBytesNotAMatch,
                        location,
                        condition
                    );
            }
        }

        // Decode children locations - all children are structural
        (uint256[] memory childLocations, bool overflow) = AbiLocation.children(
            data,
            location + condition.leadingBytes,
            condition
        );

        if (overflow) {
            return _violation(Status.CalldataOverflow, location, condition);
        }

        if (condition.children.length != childLocations.length) {
            return _violation(Status.ParameterNotAMatch, location, condition);
        }

        result.consumptions = consumptions;
        for (uint256 i; i < childLocations.length; ++i) {
            result = evaluate(
                data,
                childLocations[i],
                condition.children[i],
                result.consumptions,
                context
            );
            if (result.status != Status.Ok) {
                return result;
            }
        }
        return result;
    }

    function _and(
        bytes calldata data,
        uint256 location,
        Condition memory condition,
        Consumption[] memory consumptions,
        Context memory context
    ) private view returns (Result memory result) {
        result.consumptions = consumptions;
        for (uint256 i; i < condition.children.length; ++i) {
            result = evaluate(
                data,
                location,
                condition.children[i],
                result.consumptions,
                context
            );
            if (result.status != Status.Ok) {
                return result;
            }
        }
        return result;
    }

    function _or(
        bytes calldata data,
        uint256 location,
        Condition memory condition,
        Consumption[] memory consumptions,
        Context memory context
    ) private view returns (Result memory result) {
        for (uint256 i; i < condition.children.length; ++i) {
            result = evaluate(
                data,
                location,
                condition.children[i],
                consumptions,
                context
            );
            if (result.status == Status.Ok) {
                return result;
            }
        }

        return _violation(Status.OrViolation, location, condition);
    }

    function _arrayIterator(
        bytes calldata data,
        uint256 location,
        Condition memory condition,
        Consumption[] memory consumptions,
        Context memory context
    ) private view returns (Result memory result) {
        bool every = condition.operator == Operator.ArrayEvery;

        (uint256[] memory childLocations, bool overflow) = AbiLocation.children(
            data,
            location,
            condition
        );

        if (overflow) {
            return _violation(Status.CalldataOverflow, location, condition);
        }

        result.consumptions = consumptions;
        for (uint256 i; i < childLocations.length; ++i) {
            result = evaluate(
                data,
                childLocations[i],
                condition.children[0],
                every ? result.consumptions : consumptions,
                context
            );

            if (every) {
                if (result.status != Status.Ok) {
                    result.status = Status.NotEveryArrayElementPasses;
                    return result;
                }
            } else {
                if (result.status == Status.Ok) {
                    return result;
                }
            }
        }

        return
            every
                ? result
                : _violation(Status.NoArrayElementPasses, location, condition);
    }

    function _arrayTailMatches(
        bytes calldata data,
        uint256 location,
        Condition memory condition,
        Consumption[] memory consumptions,
        Context memory context
    ) private view returns (Result memory result) {
        // Decode array element locations
        (uint256[] memory childLocations, bool overflow) = AbiLocation.children(
            data,
            location,
            condition
        );

        if (overflow) {
            return _violation(Status.CalldataOverflow, location, condition);
        }

        uint256 conditionCount = condition.children.length;
        uint256 childCount = childLocations.length;

        if (childCount < conditionCount) {
            return _violation(Status.ParameterNotAMatch, location, condition);
        }

        uint256 tailOffset = childCount - conditionCount;

        result.consumptions = consumptions;
        for (uint256 i; i < conditionCount; ++i) {
            result = evaluate(
                data,
                childLocations[tailOffset + i],
                condition.children[i],
                result.consumptions,
                context
            );

            if (result.status != Status.Ok) {
                return result;
            }
        }
        return result;
    }

    function _zipIterator(
        bytes calldata data,
        uint256 location,
        Condition memory condition,
        Consumption[] memory consumptions,
        Context memory context
    ) private view returns (Result memory result) {
        bool every = condition.operator == Operator.ZipEvery;

        (
            uint256[][] memory locations,
            uint256 length,
            Status status
        ) = _zipLocations(data, condition, context);

        if (status != Status.Ok) {
            return _violation(status, location, condition);
        }

        Condition[] memory fields = condition.children[0].children;

        result.consumptions = consumptions;
        for (uint256 i; i < length; ++i) {
            // For ZipSome, we always start from base consumptions.
            if (!every) result.consumptions = consumptions;

            bool tuplePasses = true;
            for (uint256 f; f < fields.length; ++f) {
                result = evaluate(
                    data,
                    locations[f][i],
                    fields[f],
                    result.consumptions,
                    context
                );
                if (result.status != Status.Ok) {
                    tuplePasses = false;
                    break;
                }
            }

            if (every) {
                if (!tuplePasses) {
                    result.status = Status.NotEveryZippedElementPasses;
                    return result;
                }
            } else {
                if (tuplePasses) {
                    return result;
                }
            }
        }

        return
            every
                ? result
                : _violation(Status.NoZippedElementPasses, location, condition);
    }

    /*
     * Slice computes a new location pointing to a byte-range within the
     * current location, so the child transparently evaluates against that
     * slice.
     *
     * The child will read the slice via __input, which right-aligns values
     * <=32 bytes to match comparison compValue encoding.
     */
    function _slice(
        bytes calldata data,
        uint256 location,
        Condition memory condition,
        Consumption[] memory consumptions,
        Context memory context
    ) private view returns (Result memory result) {
        /*
         * compValue layout (3 bytes):
         *
         *   ┌──────────────────────┬──────────────────────┐
         *   │ shift (16 bits)      │ size (8 bits)        │
         *   └──────────────────────┴──────────────────────┘
         *
         *   shift  byte offset into the operand content at which the window starts
         *   size   number of bytes to extract (right-aligned into a bytes32 word)
         */
        uint256 shift = uint256(uint16(bytes2(condition.compValue)));
        uint256 size = uint256(uint8(condition.compValue[2]));

        /*
         * Integrity guarantees Slice targets either Static or Dynamic values
         * and has one Static child. Normalize both cases to one byte range:
         * - Static starts at `location` and is bounded by `condition.size`.
         * - Dynamic starts after the length word and is bounded by its
         *   declared byte length, not by ABI padding.
         */
        uint256 length = condition.size;
        if (!condition.inlined) {
            if (location + 32 > data.length) {
                return _violation(Status.CalldataOverflow, location, condition);
            }

            assembly {
                length := calldataload(add(data.offset, location))
            }
        }

        if (shift + size > length) {
            return _violation(Status.CalldataOverflow, location, condition);
        }

        Condition memory sliced = condition.children[0];
        sliced.size = size;

        return
            evaluate(
                data,
                location + (condition.inlined ? 0 : 32) + shift,
                sliced,
                consumptions,
                context
            );
    }

    function _pluck(
        bytes calldata data,
        uint256 location,
        Condition memory condition,
        Consumption[] memory consumptions,
        Context memory context
    ) private pure returns (Result memory) {
        (bytes32 pluckedValue, bool overflow) = __input(
            data,
            location,
            condition,
            context
        );
        if (overflow) {
            return _violation(Status.CalldataOverflow, location, condition);
        }

        uint256 index = uint8(condition.compValue[0]);
        context.pluckedLocations[index] = location;
        context.pluckedValues[index] = pluckedValue;

        return _ok(consumptions);
    }

    function __compare(
        bytes32 value,
        Condition memory condition
    ) private pure returns (Status) {
        bytes32 compValue = condition.compValue.length > 32
            ? keccak256(condition.compValue)
            : bytes32(condition.compValue);

        if (condition.operator == Operator.EqualTo) {
            return value == compValue ? Status.Ok : Status.ParameterNotAllowed;
        }
        if (condition.operator == Operator.GreaterThan) {
            return
                value > compValue ? Status.Ok : Status.ParameterLessThanAllowed;
        }
        return
            value < compValue ? Status.Ok : Status.ParameterGreaterThanAllowed;
    }

    function __compareSigned(
        bytes32 rawValue,
        Condition memory condition
    ) private pure returns (Status) {
        int256 value = int256(uint256(rawValue));
        int256 compValue = int256(uint256(bytes32(condition.compValue)));

        if (condition.operator == Operator.SignedIntGreaterThan) {
            return
                value > compValue ? Status.Ok : Status.ParameterLessThanAllowed;
        }
        return
            value < compValue ? Status.Ok : Status.ParameterGreaterThanAllowed;
    }

    function __allowance(
        uint256 value,
        uint256 location,
        Condition memory condition,
        Consumption[] memory consumptions
    ) private view returns (Result memory) {
        (
            Status status,
            Consumption[] memory nextConsumptions
        ) = WithinAllowanceChecker.check(
                consumptions,
                value,
                condition.compValue
            );

        return _result(status, location, condition, nextConsumptions);
    }

    /**
     * @dev Reads a value from calldata or from Transaction.value, right-aligning when needed.
     *      - Encoding.None: returns context.value (ether amount)
     *      - size <= 32: reads from calldata and right-aligns
     *      - size > 32: returns keccak256 hash of the calldata slice
     *
     * @param data      The calldata to read from.
     * @param location  The location in calldata.
     * @param condition The condition with layout info.
     * @param context   The execution context (for ether value).
     * @return result   The value as bytes32, right-aligned or hashed.
     */
    function __input(
        bytes calldata data,
        uint256 location,
        Condition memory condition,
        Context memory context
    ) private pure returns (bytes32 result, bool overflow) {
        /*
         * Integrity rules map Encoding.EtherValue -> Encoding.None during packing.
         * If we encounter Encoding.None here (in a comparison context), it acts as
         * a virtual static parameter representing the transaction value.
         */
        if (condition.encoding == Encoding.None) {
            return (bytes32(context.value), false);
        }

        // Check if condition has size set (e.g., from Slice), otherwise get from decoder
        uint256 size = condition.size != 0
            ? condition.size
            : AbiLocation.size(data, location, condition);

        if (location + size > data.length) {
            return (0, true);
        }

        if (size == 32) {
            assembly {
                result := calldataload(add(data.offset, location))
            }
            return (result, false);
        }

        // align the word for slicing
        if (size < 32) {
            return (
                bytes32(data[location:location + size]) >> ((32 - size) * 8),
                false
            );
        }

        // size > 32
        return (keccak256(data[location:location + size]), false);
    }

    function _ok(
        Consumption[] memory consumptions
    ) private pure returns (Result memory) {
        return
            Result({
                status: Status.Ok,
                violatedNodeIndex: 0,
                payloadLocation: 0,
                consumptions: consumptions
            });
    }

    function _violation(
        Status status,
        uint256 location,
        Condition memory condition
    ) private pure returns (Result memory) {
        Consumption[] memory empty;
        return
            Result({
                status: status,
                violatedNodeIndex: condition.index,
                payloadLocation: location,
                consumptions: empty
            });
    }

    function _result(
        Status status,
        uint256 location,
        Condition memory condition,
        Consumption[] memory consumptions
    ) private pure returns (Result memory) {
        return
            status == Status.Ok
                ? _ok(consumptions)
                : _violation(status, location, condition);
    }

    /**
     * @dev Resolves element locations for arrays being zipped together.
     *
     * @param data      The calldata being evaluated.
     * @param condition The Zip condition (ZipSome / ZipEvery).
     * @param context   Evaluation context with pluckedLocations.
     *
     * @return result One uint256[] per array – element locations in calldata.
     * @return length The common length of all zipped arrays.
     * @return status Status.Ok, or an error
     */
    function _zipLocations(
        bytes calldata data,
        Condition memory condition,
        Context memory context
    )
        private
        pure
        returns (uint256[][] memory result, uint256 length, Status status)
    {
        Condition[] memory fields = condition.children[0].children;
        Condition memory stub;
        stub.encoding = Encoding.Array;
        stub.children = new Condition[](1);

        result = new uint256[][](fields.length);

        for (uint256 f; f < fields.length; ++f) {
            stub.children[0] = fields[f];
            (uint256[] memory locations, bool overflow) = AbiLocation.children(
                data,
                context.pluckedLocations[uint8(condition.compValue[f])],
                stub
            );

            if (overflow) return (result, 0, Status.CalldataOverflow);

            if (f == 0) {
                length = locations.length;
            } else {
                if (length != locations.length) {
                    return (result, 0, Status.ZippedArrayLengthMismatch);
                }
            }

            result[f] = locations;
        }
    }
}

project/contracts/core/evaluate/CustomConditionChecker.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "../../common/AllowanceConsumer.sol";
import "../../periphery/interfaces/ICustomCondition.sol";

import "../../types/Types.sol";

/**
 * @title CustomConditionChecker
 * @notice Validates transactions against external custom condition adapters.
 *
 * @dev Safely invokes ICustomCondition.check via staticcall. A passing adapter
 *      may return allowance consumptions, which are recorded in the running
 *      consumption list via AllowanceConsumer (copy-on-write: the caller's
 *      list is never mutated).
 *
 *   | Scenario              | staticcall Result      | Behavior                      | Status                          |
 *   |-----------------------|------------------------|-------------------------------|---------------------------------|
 *   | No code at address    | (true, "")             | extcodesize == 0              | CustomConditionNotAContract     |
 *   | Wrong interface       | (false, "")            | staticcall fails              | CustomConditionReverted         |
 *   | Function reverts      | (false, <error data>)  | staticcall fails              | CustomConditionReverted         |
 *   | Returns wrong type    | (true, <invalid ABI>)  | Manual validation fails       | CustomConditionInvalidResult    |
 *   | Returns false         | (true, <success>)      | Adapter rejects the condition | CustomConditionViolation        |
 *   | Exceeds allowance     | (true, <consumptions>) | Core rejects consumption      | AllowanceExceeded               |
 *
 * @author gnosisguild
 */
library CustomConditionChecker {
    /**
     * @notice Evaluates a custom condition against an external adapter.
     * @param compValue Packed config: adapter address (20 bytes) + optional extra data
     * @param to Target address of the transaction
     * @param value ETH value of the transaction
     * @param data Calldata of the transaction
     * @param operation Call or DelegateCall
     * @param location Byte offset into calldata
     * @param size Byte size of the payload at location
     * @param consumptions Running allowance consumption list
     * @param pluckedValues Array of previously plucked values
     * @return status Ok if condition passes, error status otherwise
     * @return The updated consumption list when the adapter passes
     */
    function check(
        bytes calldata compValue,
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation,
        uint256 location,
        uint256 size,
        Consumption[] memory consumptions,
        bytes32[] calldata pluckedValues
    ) external view returns (Status, Consumption[] memory) {
        address adapter = address(bytes20(compValue));

        if (adapter.code.length == 0) {
            return (Status.CustomConditionNotAContract, consumptions);
        }

        (bool success, bytes memory result) = adapter.staticcall(
            abi.encodeCall(
                ICustomCondition.check,
                (
                    to,
                    value,
                    data,
                    operation,
                    location,
                    size,
                    compValue[20:],
                    pluckedValues
                )
            )
        );
        if (!success) {
            return (Status.CustomConditionReverted, consumptions);
        }

        (
            Status status,
            AllowanceConsumption[] memory usedConsumptions
        ) = _parseResult(result);
        if (status != Status.Ok) {
            return (status, consumptions);
        }

        return _applyConsumptions(consumptions, usedConsumptions);
    }

    /**
     * @dev Validates and decodes the adapter result, which must be canonical
     *      ABI for (bool success, AllowanceConsumption[] consumptions):
     *
     *        word 0: success (0 or 1)
     *        word 1: offset of the consumptions array (always 0x40)
     *        word 2: array length N, then N {allowanceKey, amount} pairs
     *
     *      Validated by hand because abi.decode reverts on malformed data,
     *      while the adapter's failure must surface as a status.
     *
     * @return status Ok when the adapter passes, error status otherwise
     * @return consumptions Consumptions to apply (empty unless Ok)
     */
    function _parseResult(
        bytes memory result
    )
        private
        pure
        returns (Status status, AllowanceConsumption[] memory consumptions)
    {
        // The header alone is 3 words.
        if (result.length < 96) {
            return (Status.CustomConditionInvalidResult, consumptions);
        }

        // Decoded as uint256: abi.decode of a bool reverts on a dirty word,
        // which must instead surface as an invalid result status.
        (uint256 success, uint256 offset, uint256 count) = abi.decode(
            result,
            (uint256, uint256, uint256)
        );

        // The pairs must fill the tail exactly. Count is bounded before the
        // multiplication so it cannot overflow.
        if (
            success > 1 ||
            offset != 0x40 ||
            count > (result.length - 96) / 64 ||
            result.length != 96 + count * 64
        ) {
            return (Status.CustomConditionInvalidResult, consumptions);
        }

        if (success == 0) {
            return (Status.CustomConditionViolation, consumptions);
        }

        // The layout is canonical, so this decoding cannot fail.
        (, consumptions) = abi.decode(result, (bool, AllowanceConsumption[]));

        return (Status.Ok, consumptions);
    }

    /**
     * @dev Applies each consumption to the running list, in order. The first
     *      failure returns immediately, discarding the adapter's remaining
     *      consumptions.
     */
    function _applyConsumptions(
        Consumption[] memory consumptions,
        AllowanceConsumption[] memory allowanceConsumptions
    ) private view returns (Status, Consumption[] memory) {
        for (uint256 i; i < allowanceConsumptions.length; ++i) {
            Status status;
            (status, consumptions) = AllowanceConsumer.consume(
                consumptions,
                allowanceConsumptions[i].allowanceKey,
                allowanceConsumptions[i].amount
            );
            if (status != Status.Ok) {
                return (status, consumptions);
            }
        }

        return (Status.Ok, consumptions);
    }
}

project/contracts/core/evaluate/WithinAllowanceChecker.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "../../common/AllowanceConsumer.sol";
import "../../common/PriceLoader.sol";
import "../../types/Types.sol";

/**
 * @title WithinAllowanceChecker
 * @notice Validates allowance consumption with optional amount conversion.
 *
 * @dev Checks if a value is within an allowance and consumes it. The input
 *      is converted to balance units (dust rounded up), then consumed via
 *      AllowanceConsumer.
 *
 *      The `consumptions` array is treated as immutable. If consumption occurs,
 *      a new array is allocated and returned (Copy-on-Write).
 *
 * @author gnosisguild
 */
library WithinAllowanceChecker {
    /**
     * CompValue Layout (32, 34, 54, or 54+ bytes):
     * ┌─────────────────────────┬──────────┬──────────┬─────────────────────┬─────────────────────┐
     * │      allowanceKey       │ balance  │  input   │       adapter       │    adapterParams    │
     * │        (bytes32)        │ decimals │ decimals │      (address)      │       (bytes)       │
     * ├─────────────────────────┼──────────┼──────────┼─────────────────────┼─────────────────────┤
     * │         0 - 31          │    32    │    33    │       34 - 53       │        54+          │
     * └─────────────────────────┴──────────┴──────────┴─────────────────────┴─────────────────────┘
     *                           └── optional ─────────┴───── optional ──────┴──── optional ───────┘
     *
     * balanceDecimals: decimals used to track the allowance balance
     * inputDecimals: decimals of the value being checked
     * adapterParams: optional trailing bytes passed to IPricing.getPrice(params)
     */
    function check(
        Consumption[] memory consumptions,
        uint256 value,
        bytes memory compValue
    ) internal view returns (Status status, Consumption[] memory) {
        // 1. Convert the input value to balance units
        (status, value) = _scaleInput(value, compValue);
        if (status != Status.Ok) {
            return (status, consumptions);
        }

        // 2. Consume it from the allowance
        return
            AllowanceConsumer.consume(consumptions, bytes32(compValue), value);
    }

    /**
     * @dev Converts an input value to balance-denominated units: scales up
     *      to the highest decimal precision, applies the price, then scales
     *      back down in a single division that rounds dust up.
     *
     *      Consuming the rounded amount is equivalent to comparing at full
     *      precision: ⌈v/f⌉ > b − c  ⟺  v > (b − c)·f
     */
    function _scaleInput(
        uint256 value,
        bytes memory compValue
    ) private view returns (Status status, uint256) {
        // A 32-byte compValue contains only the allowance key, so the input is
        // already denominated in balance units and needs no conversion.
        if (compValue.length == 32) {
            return (Status.Ok, value);
        }

        (
            uint256 balanceDecimals,
            uint256 inputDecimals,
            uint256 precision
        ) = _unpack(compValue);

        address adapter;
        if (compValue.length > 34) {
            assembly {
                adapter := shr(96, mload(add(compValue, 0x42)))
            }
        }

        bytes memory params;
        if (compValue.length > 54) {
            uint256 length = compValue.length - 54;
            params = new bytes(length);
            assembly {
                // 0x56 = 0x20 (memory length prefix) + 0x36 (byte 54)
                mcopy(add(params, 0x20), add(compValue, 0x56), length)
            }
        }

        uint256 price;
        (status, price) = PriceLoader.load(adapter, params);
        if (status != Status.Ok) {
            return (status, 0);
        }

        return (
            Status.Ok,
            _ceilDiv(
                value * (10 ** (precision - inputDecimals)) * price,
                (10 ** (precision - balanceDecimals)) * 1e18
            )
        );
    }

    function _unpack(
        bytes memory compValue
    )
        private
        pure
        returns (
            uint256 balanceDecimals,
            uint256 inputDecimals,
            uint256 precision
        )
    {
        balanceDecimals = uint8(compValue[32]);
        inputDecimals = uint8(compValue[33]);
        precision = balanceDecimals > inputDecimals
            ? balanceDecimals
            : inputDecimals;
    }

    /// @dev Ceiling division. Returns 0 for 0, otherwise ⌈a / b⌉.
    function _ceilDiv(uint256 a, uint256 b) private pure returns (uint256) {
        if (a == 0) return 0;
        return (a - 1) / b + 1;
    }
}

project/contracts/core/evaluate/WithinRatioChecker.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "../../common/PriceLoader.sol";
import "../../types/Types.sol";

/**
 * @title WithinRatioChecker
 * @notice Validates that a relative amount falls within a ratio range of a
 *         reference amount, with optional price adapter conversion.
 *
 * @dev Bounds are in basis points (10000 = 100%). Both amounts are read from
 *      pluckedValues by index, scaled to shared precision, optionally priced
 *      via adapters, then checked against [minRatio, maxRatio] using exact
 *      cross-multiplied comparisons (no rounding; overflow reverts).
 *
 * @author gnosisguild
 */
library WithinRatioChecker {
    /**
     * @dev Configuration decoded from compValue bytes.
     *
     * Base layout (12 bytes, always present):
     * ┌───────────────────┬───────────────────┬───────────────────┬───────────────────┬────────────┬────────────┐
     * │ referencePluckIdx │ referenceDecimals │ relativePluckIdx  │ relativeDecimals  │  minRatio  │  maxRatio  │
     * │      (uint8)      │      (uint8)      │      (uint8)      │      (uint8)      │  (uint32)  │  (uint32)  │
     * ├───────────────────┼───────────────────┼───────────────────┼───────────────────┼────────────┼────────────┤
     * │         0         │         1         │         2         │         3         │    4–7     │    8–11    │
     * └───────────────────┴───────────────────┴───────────────────┴───────────────────┴────────────┴────────────┘
     *
     * Optionally followed by a ref adapter blob, then a rel adapter blob.
     
     * Adapter blob structure:
     * ┌──────────┬─────────────┬──────────────────────┐
     * │ blobLen  │   adapter   │       params         │
     * │ (uint8)  │  (address)  │ (blobLen - 20) bytes │
     * └──────────┴─────────────┴──────────────────────┘
     *
     * blobLen is the length of the blob excluding the prefix byte itself (0 or >= 20).
     * A blobLen of 0 means no adapter.
     * To include a rel blob without a ref adapter, set ref blobLen to 0.
     * Valid sizes: 12, 13 + refBlobLen, 14 + refBlobLen + relBlobLen
     */
    struct CompValue {
        uint8 referencePluckIndex;
        uint8 referenceDecimals;
        uint8 relativePluckIndex;
        uint8 relativeDecimals;
        uint32 minRatio;
        uint32 maxRatio;
        address referenceAdapter;
        address relativeAdapter;
        bytes referenceParams;
        bytes relativeParams;
    }

    uint256 private constant BPS = 10000;

    /**
     * @notice Checks if ratio of relative to reference amount is within bounds.
     * @param compValue Packed configuration bytes
     * @param pluckedValues Array of values extracted from calldata
     * @return Status Ok if within bounds, error status otherwise
     */
    function check(
        bytes calldata compValue,
        bytes32[] calldata pluckedValues
    ) external view returns (Status) {
        CompValue memory config = _unpack(compValue);
        (
            Status status,
            uint256 referenceAmountUp,
            uint256 relativeAmountUp
        ) = _convert(config, pluckedValues);
        if (status != Status.Ok) {
            return status;
        }

        /*
         * The naive formula looks like:
         *
         *                 relativeAmountUp
         *   ratio (bps) = ───────────────── × 10,000   within [minRatio, maxRatio]
         *                 referenceAmountUp
         *
         * It is equivalent to the following, which does no truncation:
         *
         *   below min ⇔ relativeAmountUp × 10,000 < referenceAmountUp × minRatio
         *   above max ⇔ relativeAmountUp × 10,000 > referenceAmountUp × maxRatio
         *
         * A zero reference needs no special case: nothing is below min, and
         * any nonzero relative amount exceeds a configured max. Checked
         * arithmetic reverts if a multiplication overflows.
         */
        if (
            config.minRatio != 0 &&
            relativeAmountUp * BPS < referenceAmountUp * config.minRatio
        ) {
            return Status.RatioBelowMin;
        }
        if (
            config.maxRatio != 0 &&
            relativeAmountUp * BPS > referenceAmountUp * config.maxRatio
        ) {
            return Status.RatioAboveMax;
        }

        return Status.Ok;
    }

    /**
     * @dev Extracts and converts reference and relative amounts for ratio comparison.
     *
     *      1. Reads raw values from pluckedValues by index
     *      2. Scales both to the higher decimal precision
     *      3. Applies price adapters (if configured)
     *
     * @return status Ok, or the adapter failure status
     * @return referenceAmount Reference amount, scaled up to common precision
     * @return relativeAmount Relative amount, scaled up to common precision
     */
    function _convert(
        CompValue memory config,
        bytes32[] calldata pluckedValues
    )
        private
        view
        returns (Status status, uint256 referenceAmount, uint256 relativeAmount)
    {
        uint256 precision = config.referenceDecimals > config.relativeDecimals
            ? config.referenceDecimals
            : config.relativeDecimals;

        (status, referenceAmount) = _scaleAndPrice(
            uint256(pluckedValues[config.referencePluckIndex]),
            config.referenceDecimals,
            precision,
            config.referenceAdapter,
            config.referenceParams
        );
        if (status != Status.Ok) return (status, 0, 0);

        (status, relativeAmount) = _scaleAndPrice(
            uint256(pluckedValues[config.relativePluckIndex]),
            config.relativeDecimals,
            precision,
            config.relativeAdapter,
            config.relativeParams
        );
        if (status != Status.Ok) return (status, 0, 0);
    }

    /// @dev Returns the scaled value multiplied by the adapter price. The
    ///      price's 10^18 factor is never divided out — it carries on both
    ///      sides and cancels in the ratio comparison.
    function _scaleAndPrice(
        uint256 value,
        uint256 decimals,
        uint256 precision,
        address adapter,
        bytes memory params
    ) private view returns (Status status, uint256 price) {
        (status, price) = PriceLoader.load(adapter, params);
        if (status != Status.Ok) {
            return (status, 0);
        }

        return (Status.Ok, value * (10 ** (precision - decimals)) * price);
    }

    function _unpack(
        bytes calldata compValue
    ) private pure returns (CompValue memory config) {
        bytes32 packed = bytes32(compValue);

        config.referencePluckIndex = uint8(bytes1(packed));
        config.referenceDecimals = uint8(bytes1(packed << 8));
        config.relativePluckIndex = uint8(bytes1(packed << 16));
        config.relativeDecimals = uint8(bytes1(packed << 24));
        config.minRatio = uint32(bytes4(packed << 32));
        config.maxRatio = uint32(bytes4(packed << 64));

        uint256 offset = 12;
        (
            config.referenceAdapter,
            config.referenceParams,
            offset
        ) = _unpackAdapterBlob(compValue, offset);

        (config.relativeAdapter, config.relativeParams, ) = _unpackAdapterBlob(
            compValue,
            offset
        );
    }

    /// @dev Reads an adapter blob at the given offset: blobLen(1) + adapter(20) + params(blobLen - 20).
    ///      blobLen is the total blob length excluding the prefix byte itself.
    ///      Returns the adapter address, params bytes, and the offset after the blob.
    function _unpackAdapterBlob(
        bytes memory buffer,
        uint256 offset
    ) private pure returns (address adapter, bytes memory params, uint256) {
        uint256 blobLen;
        if (offset < buffer.length) {
            blobLen = uint8(buffer[offset]);
            offset += 1;
        }

        if (blobLen >= 20) {
            assembly {
                // 0x20 skips the memory length prefix
                adapter := shr(96, mload(add(add(buffer, 0x20), offset)))
            }
            offset += 20;
        }

        if (blobLen > 20) {
            uint256 length = blobLen - 20;
            params = new bytes(length);
            assembly {
                mcopy(add(params, 0x20), add(add(buffer, 0x20), offset), length)
            }
            offset += length;
        }

        return (adapter, params, offset);
    }
}

project/contracts/core/serialize/ConditionLoader.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "../../common/ImmutableStorage.sol";

import "./ConditionUnpacker.sol";

import "../../types/Types.sol";

/**
 * @title ConditionLoader
 * @notice Loads and unpacks condition trees from immutable storage.
 *
 * @author gnosisguild
 */
library ConditionLoader {
    /**
     * @param scopeConfig Packed scopeSonfig (options << 160 | pointer).
     * @return condition The unpacked condition tree with embedded layout.
     * @return maxPluckIndex Maximum pluck index for pluck bag allocation.
     */
    function load(
        uint256 scopeConfig
    )
        internal
        view
        returns (Condition memory condition, uint256 maxPluckIndex)
    {
        address pointer = address(uint160(scopeConfig));
        bytes memory buffer = ImmutableStorage.load(pointer);
        return ConditionUnpacker.unpack(buffer);
    }
}

project/contracts/core/serialize/ConditionPacker.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "./Topology.sol";

/**
 * @title  ConditionPacker
 * @notice A library that provides packing functions for conditions,
 *         transforming ConditionsFlat[] into a memory-optimized buffer.
 *
 * @dev    This library is NOT gas-sensitive since packing is intended to be
 *         called as a helper function within a view entrypoint.
 *
 * @author gnosisguild
 *
 * ╔════════════════════════════════ BUFFER ═════════════════════════════════╗
 * ║ ┌─────────────────────────────────────────────────────────────────────┐ ║
 * ║ │ HEADER (3 bytes = 24 bits)                                          │ ║
 * ║ ├─────────────────────────────────────────────────────────────────────┤ ║
 * ║ │ • conditionNodeCount     16 bits (bytes 0-1)                        │ ║
 * ║ │ • maxPluckValue           8 bits (byte 2)                           │ ║
 * ║ └─────────────────────────────────────────────────────────────────────┘ ║
 * ║ ┌─────────────────────────────────────────────────────────────────────┐ ║
 * ║ │ NODES (nodeCount × 4 bytes each)                                    │ ║
 * ║ ├─────────────────────────────────────────────────────────────────────┤ ║
 * ║ │ Each node (32 bits = 4 bytes):                                      │ ║
 * ║ │   • encoding              3 bits  [31-29]                           │ ║
 * ║ │   • operator              5 bits  [28-24]                           │ ║
 * ║ │   • childCount           10 bits  [23-14]                           │ ║
 * ║ │   • inlinedSize          13 bits  [13-1]                            │ ║
 * ║ │   • hasCompValue          1 bit   [0]                               │ ║
 * ║ └─────────────────────────────────────────────────────────────────────┘ ║
 * ║ ┌─────────────────────────────────────────────────────────────────────┐ ║
 * ║ │ COMPVALUES (variable length)                                        │ ║
 * ║ ├─────────────────────────────────────────────────────────────────────┤ ║
 * ║ │ For each node with hasCompValue=true (in BFS order):                │ ║
 * ║ │   • length               16 bits  (compValue byte length)           │ ║
 * ║ │   • data                 N bytes  (actual compValue data)           │ ║
 * ║ └─────────────────────────────────────────────────────────────────────┘ ║
 * ╚═════════════════════════════════════════════════════════════════════════╝
 *
 */
library ConditionPacker {
    uint256 private constant HEADER_BYTES = 3;
    uint256 private constant NODE_BYTES = 4;

    function pack(
        ConditionFlat[] memory conditions
    ) internal pure returns (bytes memory buffer) {
        _transform(conditions);

        (uint256 compValuesSize, uint256 maxPluckCount) = _count(conditions);

        uint256 nodeCount = conditions.length;

        buffer = new bytes(
            HEADER_BYTES + nodeCount * NODE_BYTES + compValuesSize
        );

        uint256 header = (nodeCount << 8) | maxPluckCount;
        assembly {
            mstore(add(buffer, 0x20), shl(232, header))
        }

        _packNodes(conditions, buffer);
    }

    function _packNodes(
        ConditionFlat[] memory conditions,
        bytes memory buffer
    ) private pure {
        uint256 offset = HEADER_BYTES;
        uint256 compValueOffset = HEADER_BYTES + conditions.length * NODE_BYTES;

        for (uint256 i; i < conditions.length; ++i) {
            ConditionFlat memory condition = conditions[i];

            Encoding encoding = condition.paramType;
            (, uint256 childCount) = Topology.childBounds(conditions, i);
            uint256 inlinedSize = Topology.isInlined(conditions, i)
                ? Topology.inlinedSize(conditions, i)
                : 0;

            bytes memory compValue = condition.compValue;
            uint256 compValueLength = compValue.length;
            bool hasCompValue = compValueLength > 0;

            /*
             * ┌───────────────────────────────────────────────────────────┐
             * │ packed 32 bits, 4 bytes:                                  │
             * │   • encoding              3 bits  [31-29]                 │
             * │   • operator              5 bits  [28-24]                 │
             * │   • childCount           10 bits  [23-14]                 │
             * │   • inlinedSize          13 bits  [13-1]                  │
             * │   • hasCompValue          1 bit   [0]                     │
             * └───────────────────────────────────────────────────────────┘
             */
            uint256 packed = (uint256(encoding) << 29) |
                (uint256(condition.operator) << 24) |
                (childCount << 14) |
                (inlinedSize << 1) |
                (hasCompValue ? 1 : 0);

            /*
             * The or with mload preserves bytes 4-31 (compValues written in
             * previous iterations) while writing our 4 bytes at positions 0-3.
             */
            assembly {
                let dest := add(add(buffer, 0x20), offset)
                mstore(dest, or(mload(dest), shl(224, packed)))
            }
            offset += NODE_BYTES;

            // Pack compValue writes at tail, no preserving required
            if (hasCompValue) {
                assembly {
                    let dest := add(add(buffer, 0x20), compValueOffset)
                    // write 2 bytes length
                    mstore(dest, shl(240, compValueLength))
                    // copy compValue body
                    mcopy(add(dest, 2), add(compValue, 0x20), compValueLength)
                }
                compValueOffset = compValueOffset + 2 + compValueLength;
            }
        }
    }

    function _count(
        ConditionFlat[] memory conditions
    ) private pure returns (uint256 compValuesSize, uint256 maxPluckCount) {
        for (uint256 i; i < conditions.length; ++i) {
            if (conditions[i].operator == Operator.Pluck) {
                uint8 pluckIndex = uint8(conditions[i].compValue[0]);
                if (pluckIndex + 1 > maxPluckCount) {
                    maxPluckCount = pluckIndex + 1;
                }
            }

            uint256 length = conditions[i].compValue.length;
            if (length > 0) {
                compValuesSize += 2 + length;
            }
        }
    }

    /**
     * @dev Normalizes conditions in-place before packing:
     *      1. AbiEncoded without compValue gets default leadingBytes (0x0004)
     *      2. EqualTo at offset has 32-byte head pointer stripped
     */
    function _transform(ConditionFlat[] memory conditions) private pure {
        for (uint256 i; i < conditions.length; ++i) {
            /*
             * Patch AbiEncoded leadingBytes
             *
             * AbiEncoded nodes without compValue need a default leadingBytes of 4
             * (function selector size). Store as 2-byte big-endian value.
             */
            if (
                conditions[i].paramType == Encoding.AbiEncoded &&
                conditions[i].compValue.length == 0
            ) {
                conditions[i].compValue = hex"0004";
            }

            /*
             * Remove Extraneous Offsets
             *
             * Remove unnecessary offsets from compValue fields. This ensures a
             * consistent API where every `compValue` provided for use in
             * `Operator.EqualTo` is obtained by calling `abi.encode` directly.
             *
             * By removing the leading extraneous offset this makes
             * `abi.encode(...)` output line up with the layout produced by
             * Decoder inspection. Without it, callers would need to patch
             * compValues based on whether the payload is fully inline or at
             * offset.
             */
            if (
                conditions[i].operator == Operator.EqualTo &&
                !Topology.isInlined(conditions, i)
            ) {
                bytes memory compValue = conditions[i].compValue;
                assembly {
                    let newLength := sub(mload(compValue), 32)
                    compValue := add(compValue, 32)
                    mstore(compValue, newLength)
                }
                conditions[i].compValue = compValue;
            }
        }
    }
}

project/contracts/core/serialize/ConditionStorer.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "../../common/ImmutableStorage.sol";

import "./ConditionPacker.sol";
import "./Integrity.sol";

import "../../types/Types.sol";

/**
 * @title ConditionStorer
 * @notice Packs condition trees and stores packed buffers in immutable storage.
 *
 * @author gnosisguild
 */
library ConditionStorer {
    /**
     * @notice Validates and packs a condition tree into bytes.
     *
     * @param conditions The flat condition array in BFS order.
     * @return buffer The packed condition buffer.
     */
    function pack(
        ConditionFlat[] memory conditions
    ) external pure returns (bytes memory buffer) {
        Integrity.enforce(conditions);
        return ConditionPacker.pack(conditions);
    }

    /**
     * @notice Stores a pre-packed condition buffer.
     *
     * @param buffer The packed condition buffer.
     * @param options Execution options (Send, DelegateCall, Both, None).
     * @return scopeConfig Packed scope config (options << 160 | pointer).
     */
    function store(
        bytes memory buffer,
        ExecutionOptions options
    ) external returns (uint256 scopeConfig) {
        address pointer = ImmutableStorage.store(buffer);
        return (uint256(options) << 160) | uint160(pointer);
    }
}

project/contracts/core/serialize/ConditionUnpacker.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import {AVATAR_SLOT} from "../StorageSlots.sol";

import "../../types/Types.sol";

/**
 * @title  ConditionUnpacker
 * @notice A library that provides unpacking functions for reconstructing the
 *         Condition tree from a memory-optimized buffer.
 *
 * @dev    This is performance-critical code. Every transaction execution
 *         begins by loading packed conditions from contract storage
 *         (via extcodecopy) and performing tree unpacking. The implementation
 *         is deliberately low-level to minimize execution overhead.
 *
 * @author gnosisguild
 */
library ConditionUnpacker {
    uint256 private constant HEADER_BYTES = 3;
    uint256 private constant NODE_BYTES = 4;

    function unpack(
        bytes memory buffer
    )
        internal
        view
        returns (Condition memory condition, uint256 maxPluckValue)
    {
        /*
         * ┌───────────────────────────────────────────────────────────────┐
         * │ header 24 bits, 3 bytes:                                      │
         * │   • conditionNodeCount    16 bits  [23-8]                     │
         * │   • maxPluckCount          8 bits  [7-0]                      │
         * └───────────────────────────────────────────────────────────────┘
         */
        uint256 header = uint24(bytes3(buffer));

        Condition[] memory conditions = new Condition[]((header >> 8));

        _unpackConditions(buffer, conditions);

        condition = conditions[0];
        maxPluckValue = header & 0xFF;
    }

    function _unpackConditions(
        bytes memory buffer,
        Condition[] memory conditions
    ) private view {
        uint256 offset;
        uint256 compValueOffset;
        uint256 childConditionPtr;
        assembly {
            offset := add(add(buffer, 0x20), HEADER_BYTES)
            compValueOffset := add(offset, mul(mload(conditions), NODE_BYTES))
            childConditionPtr := add(conditions, 0x40)
        }

        for (uint256 c; c < conditions.length; ++c) {
            /*
             * ┌───────────────────────────────────────────────────────────┐
             * │ packed 32 bits, 4 bytes:                                  │
             * │   • encoding              3 bits  [31-29]                 │
             * │   • operator              5 bits  [28-24]                 │
             * │   • childCount           10 bits  [23-14]                 │
             * │   • inlinedSize          13 bits  [13-1]                  │
             * │   • hasCompValue          1 bit   [0]                     │
             * └───────────────────────────────────────────────────────────┘
             */
            uint256 packed;
            assembly {
                packed := shr(224, mload(offset))
                offset := add(offset, NODE_BYTES)
            }

            Condition memory condition = conditions[c];

            // Extract fields from packed bits
            uint256 encoding = (packed >> 29);
            if (encoding == 6) encoding = 0; // EtherValue -> None
            uint256 childCount = (packed >> 14) & 0x3FF;
            uint256 inlinedSize = (packed >> 1) & 0x1FFF;

            /*
             * Set Condition fields in struct order:
             *   0x00 index
             *   0x20 encoding
             *   0x40 operator
             *   0x60 compValue     (set via assembly below)
             *   0x80 children      (set via assembly below)
             *   0xa0 inlined
             *   0xc0 size
             *   0xe0 leadingBytes  (set when parsing compValue)
             */
            condition.index = c;
            condition.encoding = Encoding(encoding);
            condition.operator = Operator((packed >> 24) & 0x1F);
            condition.inlined = inlinedSize > 0;
            condition.size = inlinedSize;

            // hasCompValue
            if ((packed & 1) != 0) {
                uint256 length;
                assembly {
                    length := shr(240, mload(compValueOffset))
                    compValueOffset := add(compValueOffset, 2)
                }

                // Encoding.AbiEncoded(5): first 2 bytes are leadingBytes
                if (encoding == 5) {
                    uint256 leadingBytes;
                    assembly {
                        leadingBytes := shr(240, mload(compValueOffset))
                        compValueOffset := add(compValueOffset, 2)
                        length := sub(length, 2)
                    }
                    condition.leadingBytes = leadingBytes;
                }

                // parse compValue
                if (length > 0) {
                    assembly {
                        // free mem pointer: load
                        let compValue := mload(0x40)
                        // free mem pointer: advance
                        mstore(0x40, add(add(compValue, 0x20), length))

                        // new buffer: store length
                        mstore(compValue, length)
                        // new buffer: copy body
                        mcopy(add(compValue, 0x20), compValueOffset, length)

                        //condition: point to copied buffer (compValue at offset 0x60)
                        mstore(add(condition, 0x60), compValue)
                        // advance pointer
                        compValueOffset := add(compValueOffset, length)
                    }
                }
            }

            // Parse children
            if (childCount > 0) {
                assembly {
                    let size := mul(childCount, 0x20)
                    // free mem pointer: load
                    let dest := mload(0x40)
                    // free mem pointer: advance
                    mstore(0x40, add(add(dest, 0x20), size))

                    // new array: store length
                    mstore(dest, childCount)
                    // new array: shallow copy body
                    mcopy(add(dest, 0x20), childConditionPtr, size)

                    // condition: point to copied array (children at offset 0x80)
                    mstore(add(condition, 0x80), dest)
                    // advance child pointer
                    childConditionPtr := add(childConditionPtr, size)
                }
            }

            // EqualToAvatar: replace with EqualTo + avatar address
            if (condition.operator == Operator.EqualToAvatar) {
                condition.operator = Operator.EqualTo;
                address avatar;
                assembly {
                    avatar := sload(AVATAR_SLOT)
                }
                condition.compValue = abi.encode(avatar);
            }
        }
    }
}

project/contracts/core/serialize/Integrity.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "./Topology.sol";
import "./TypeTree.sol";

import "../../types/Types.sol";

/**
 * @title Integrity
 * @notice A library that validates input condition integrity
 *
 * @author gnosisguild
 */
library Integrity {
    uint256 private constant MAX_CONDITION_COUNT = type(uint16).max;
    uint256 private constant MAX_CHILD_COUNT = (1 << 10) - 1;
    uint256 private constant MAX_INLINED_SIZE = (1 << 13) - 1;
    uint256 private constant MAX_COMP_VALUE_LENGTH = type(uint16).max;

    function enforce(ConditionFlat[] memory conditions) internal pure {
        if (conditions.length > MAX_CONDITION_COUNT) {
            revert IRolesError.ConditionNodeCountExceedsMax();
        }

        _validateBFS(conditions);

        for (uint256 i = 0; i < conditions.length; ++i) {
            _validatePackedWidths(conditions, i);
            _validateOperator(conditions, i);
            _validateEncoding(conditions, i);
        }

        _validateVariantTypes(conditions);
        _validatePluckZipTypes(conditions);
        _validateUniquePluckDefinitions(conditions);
        _validatePluckAssignments(conditions, 0, 0);
    }

    function _validatePackedWidths(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        if (conditions[index].compValue.length > MAX_COMP_VALUE_LENGTH) {
            revert IRolesError.UnsuitableCompValue(index);
        }

        (, uint256 childCount) = Topology.childBounds(conditions, index);
        if (childCount > MAX_CHILD_COUNT) {
            revert IRolesError.ConditionChildCountExceedsMax(index);
        }

        if (
            Topology.isInlined(conditions, index) &&
            Topology.inlinedSize(conditions, index) > MAX_INLINED_SIZE
        ) {
            revert IRolesError.ConditionInlinedSizeExceedsMax(index);
        }
    }

    function _validateBFS(ConditionFlat[] memory conditions) private pure {
        uint256 length = conditions.length;
        if (length == 0 || conditions[0].parent != 0) {
            revert IRolesError.UnsuitableRootNode();
        }

        for (uint256 i = 1; i < length; ++i) {
            uint256 parent = conditions[i].parent;
            if (parent == i) {
                revert IRolesError.UnsuitableRootNode();
            }
            // Parent must have lower index (no forward references)
            if (parent < conditions[i - 1].parent) {
                revert IRolesError.NotBFS();
            }
            // Parent cannot be higher than self
            if (parent >= i) {
                revert IRolesError.NotBFS();
            }
        }
    }

    function _validateOperator(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        Operator op = conditions[index].operator;

        if (op == Operator.Pass) {
            _checkPass(conditions, index);
        } else if (op == Operator.And || op == Operator.Or) {
            _checkLogic(conditions, index);
        } else if (op == Operator.Empty) {
            _checkEmpty(conditions, index);
        } else if (op == Operator.Matches) {
            _checkMatches(conditions, index);
        } else if (op == Operator.ArraySome || op == Operator.ArrayEvery) {
            _checkArrayIterator(conditions, index);
        } else if (op == Operator.ArrayTailMatches) {
            _checkArrayTail(conditions, index);
        } else if (op == Operator.ZipSome || op == Operator.ZipEvery) {
            _checkZipIterator(conditions, index);
        } else if (op == Operator.Slice) {
            _checkSlice(conditions, index);
        } else if (op == Operator.Pluck) {
            _checkPluck(conditions, index);
        } else if (op == Operator.EqualToAvatar) {
            _checkEqualToAvatar(conditions, index);
        } else if (op == Operator.EqualTo) {
            _checkEqualTo(conditions, index);
        } else if (
            op == Operator.GreaterThan ||
            op == Operator.LessThan ||
            op == Operator.SignedIntGreaterThan ||
            op == Operator.SignedIntLessThan
        ) {
            _checkComparison(conditions, index);
        } else if (op == Operator.Bitmask) {
            _checkBitmask(conditions, index);
        } else if (op == Operator.Custom) {
            _checkCustom(conditions, index);
        } else if (op == Operator.WithinRatio) {
            _checkWithinRatio(conditions, index);
        } else if (op == Operator.WithinAllowance) {
            _checkWithinAllowance(conditions, index);
        } else if (op == Operator.CallWithinAllowance) {
            _checkCallWithinAllowance(conditions, index);
        } else {
            revert IRolesError.UnsupportedOperator(index);
        }
    }

    /**
     * @notice Validates child constraints based on encoding type.
     *
     * @dev Encoding types determine fundamental child rules:
     *      - Leaf types (Static, Dynamic, EtherValue): Cannot have children
     *      - Container types (Tuple, Array): Must have structural children
     *      - None: Operator-dependent (validated elsewhere)
     *
     *      Exception: Slice operator uses Static/Dynamic encoding but requires
     *      exactly one child (validated in _checkSlice).
     */
    function _validateEncoding(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        Encoding encoding = condition.paramType;

        (, uint256 childCount, uint256 sChildCount) = _sChildBounds(
            conditions,
            index
        );

        if (
            (encoding == Encoding.Static ||
                encoding == Encoding.Dynamic ||
                encoding == Encoding.EtherValue) &&
            (condition.operator != Operator.Slice)
        ) {
            // Slice is a special case: uses Static/Dynamic but requires a child
            // Leaf types cannot have children
            if (childCount != 0) {
                revert IRolesError.LeafNodeCannotHaveChildren(index);
            }
        }

        if (
            encoding == Encoding.AbiEncoded ||
            encoding == Encoding.Tuple ||
            encoding == Encoding.Array
        ) {
            // Container types must have structural children for type tree
            if (sChildCount == 0) {
                revert IRolesError.UnsuitableChildCount(index);
            }
        }
    }

    // --- Operator Handlers ---

    function _checkPass(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        // Encoding: Any
        // CompValue: Must be empty
        if (condition.compValue.length != 0) {
            revert IRolesError.UnsuitableCompValue(index);
        }
    }

    function _checkLogic(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        // And/Or
        // ParamType: None
        if (condition.paramType != Encoding.None) {
            revert IRolesError.UnsuitableParameterType(index);
        }
        // CompValue: Empty
        if (condition.compValue.length != 0) {
            revert IRolesError.UnsuitableCompValue(index);
        }
        // Children: Must have children
        (, uint256 childCount) = Topology.childBounds(conditions, index);
        if (childCount == 0) {
            revert IRolesError.UnsuitableChildCount(index);
        }
    }

    function _checkEmpty(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        // ParamType: None
        if (condition.paramType != Encoding.None) {
            revert IRolesError.UnsuitableParameterType(index);
        }
        // CompValue: Empty
        if (condition.compValue.length != 0) {
            revert IRolesError.UnsuitableCompValue(index);
        }
        // Children: None
        (, uint256 childCount) = Topology.childBounds(conditions, index);
        if (childCount != 0) {
            revert IRolesError.LeafNodeCannotHaveChildren(index);
        }
    }

    function _checkMatches(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        Encoding encoding = condition.paramType;
        // ParamType: Tuple, Array, AbiEncoded
        if (
            encoding != Encoding.Tuple &&
            encoding != Encoding.Array &&
            encoding != Encoding.AbiEncoded
        ) {
            revert IRolesError.UnsuitableParameterType(index);
        }

        // CompValue Validation
        if (encoding == Encoding.AbiEncoded) {
            uint16 leadingBytes = condition.compValue.length >= 2
                ? uint16(bytes2(condition.compValue))
                : 0;
            bool valid = condition.compValue.length == 0 ||
                condition.compValue.length == 2 ||
                (condition.compValue.length == 2 + leadingBytes &&
                    leadingBytes <= 32);
            if (!valid) {
                revert IRolesError.UnsuitableCompValue(index);
            }
        } else {
            if (condition.compValue.length != 0) {
                revert IRolesError.UnsuitableCompValue(index);
            }
        }

        // All children must be structural
        (, uint256 childCount, uint256 sChildCount) = _sChildBounds(
            conditions,
            index
        );
        if (sChildCount == 0 || childCount != sChildCount) {
            revert IRolesError.UnsuitableChildCount(index);
        }
    }

    function _checkArrayIterator(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        // ArraySome / ArrayEvery
        // ParamType: Array
        if (condition.paramType != Encoding.Array) {
            revert IRolesError.UnsuitableParameterType(index);
        }
        // CompValue: Empty
        if (condition.compValue.length != 0) {
            revert IRolesError.UnsuitableCompValue(index);
        }
        // Children: Exactly 1 child
        (, uint256 childCount, uint256 sChildCount) = _sChildBounds(
            conditions,
            index
        );
        if (sChildCount != 1 || sChildCount != childCount) {
            revert IRolesError.UnsuitableChildCount(index);
        }
    }

    function _checkArrayTail(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        // ArrayTailMatches
        // ParamType: Array
        if (condition.paramType != Encoding.Array) {
            revert IRolesError.UnsuitableParameterType(index);
        }
        // CompValue: Empty
        if (condition.compValue.length != 0) {
            revert IRolesError.UnsuitableCompValue(index);
        }
        // Children: All children must be structural
        (, uint256 childCount, uint256 sChildCount) = _sChildBounds(
            conditions,
            index
        );
        if (sChildCount == 0 || childCount != sChildCount) {
            revert IRolesError.UnsuitableChildCount(index);
        }
    }

    function _checkZipIterator(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        // ZipSome / ZipEvery
        // ParamType: None
        if (condition.paramType != Encoding.None) {
            revert IRolesError.UnsuitableParameterType(index);
        }
        // CompValue: at least 2 bytes (one per plucked array)
        if (condition.compValue.length < 2) {
            revert IRolesError.UnsuitableCompValue(index);
        }

        // Children: Exactly 1 child
        (
            uint256 childStart,
            uint256 childCount,
            uint256 sChildCount
        ) = _sChildBounds(conditions, index);
        if (sChildCount != 1 || sChildCount != childCount) {
            revert IRolesError.UnsuitableChildCount(index);
        }

        if (conditions[childStart].paramType != Encoding.Tuple) {
            revert IRolesError.UnsuitableChildTypeTree(index);
        }

        /*
         * All children of the Tuple must be structural. TypeTree counts only
         * structural children when matching the field count against compValue,
         * but the evaluator iterates the raw child list - a non-structural
         * child would desync the two and read compValue out of bounds at
         * evaluation time.
         */
        (, uint256 tupleChildCount, uint256 tupleSChildCount) = _sChildBounds(
            conditions,
            childStart
        );
        if (tupleChildCount != tupleSChildCount) {
            revert IRolesError.UnsuitableChildCount(childStart);
        }

        // Child must resolve to a Tuple
        Layout memory layout = TypeTree.resolve(conditions, childStart);
        assert(layout.encoding == Encoding.Tuple);

        // Tuple field count must match compValue length
        if (layout.children.length != condition.compValue.length) {
            revert IRolesError.UnsuitableCompValue(index);
        }

        // Validate pluck references: no duplicates, each must exist and be Array
        uint256 seen;
        for (uint256 k = 0; k < condition.compValue.length; ++k) {
            uint8 pluckIndex = uint8(condition.compValue[k]);
            uint256 mask = 1 << pluckIndex;
            if ((seen & mask) != 0) {
                revert IRolesError.UnsuitableCompValue(index);
            }
            seen |= mask;

            (bool found, uint256 pluckCondition) = _findPluck(
                conditions,
                pluckIndex
            );
            if (
                !found || conditions[pluckCondition].paramType != Encoding.Array
            ) {
                revert IRolesError.UnsuitableCompValue(index);
            }
        }

        // No Pluck allowed in zip descendants
        _validateNoPluckDescendant(conditions, childStart);
    }

    function _checkSlice(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        Encoding encoding = condition.paramType;
        // ParamType: Static / Dynamic
        if (encoding != Encoding.Static && encoding != Encoding.Dynamic) {
            revert IRolesError.UnsuitableParameterType(index);
        }
        // CompValue: 3 bytes
        if (condition.compValue.length != 3) {
            revert IRolesError.UnsuitableCompValue(index);
        }
        uint8 size = uint8(condition.compValue[2]);
        if (size == 0 || size > 32) {
            revert IRolesError.UnsuitableCompValue(index);
        }

        (uint256 childStart, uint256 childCount) = Topology.childBounds(
            conditions,
            index
        );
        // Children: Exactly 1 child
        if (childCount != 1) {
            revert IRolesError.UnsuitableChildCount(index);
        }

        // The child must resolve to Static
        if (conditions[childStart].paramType != Encoding.Static) {
            revert IRolesError.SliceChildNotStatic(index);
        }
    }

    function _checkPluck(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        Encoding encoding = condition.paramType;
        // ParamType: Static / EtherValue / Array
        if (
            encoding != Encoding.Static &&
            encoding != Encoding.EtherValue &&
            encoding != Encoding.Array
        ) {
            revert IRolesError.UnsuitableParameterType(index);
        }
        // CompValue: 1 byte holding the pluck slot index. The packed buffer
        // header stores `maxPluckCount = max(pluckIndex) + 1` in 8 bits, so
        // index 255 would overflow that field on pack. Capped at 254 here.
        if (
            condition.compValue.length != 1 ||
            uint8(condition.compValue[0]) == 255
        ) {
            revert IRolesError.UnsuitableCompValue(index);
        }

        if (encoding == Encoding.Array) {
            /*
             * All children of an Array Pluck must be structural. They only
             * describe the element type and are never evaluated, but the
             * evaluator reads the raw children[0] as the element template
             * for location and size math - a non-structural child is
             * invisible to TypeTree yet breaks that traversal.
             */
            (, uint256 childCount, uint256 sChildCount) = _sChildBounds(
                conditions,
                index
            );
            if (childCount != sChildCount) {
                revert IRolesError.UnsuitableChildCount(index);
            }
        }
    }

    function _checkEqualToAvatar(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        // ParamType: Static
        if (condition.paramType != Encoding.Static) {
            revert IRolesError.UnsuitableParameterType(index);
        }
        // CompValue: Empty
        if (condition.compValue.length != 0) {
            revert IRolesError.UnsuitableCompValue(index);
        }
    }

    function _checkEqualTo(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        Encoding enc = condition.paramType;
        // ParamType: Static, Dynamic, Tuple, Array, EtherValue
        if (enc == Encoding.None || enc == Encoding.AbiEncoded) {
            revert IRolesError.UnsuitableParameterType(index);
        }

        // CompValue check
        bool unsuitable;
        if (enc == Encoding.Static || enc == Encoding.EtherValue) {
            unsuitable = condition.compValue.length != 32;
        }

        if (enc == Encoding.Dynamic) {
            unsuitable =
                condition.compValue.length < 64 ||
                condition.compValue.length > MAX_COMP_VALUE_LENGTH;
        }

        if (enc == Encoding.Tuple || enc == Encoding.Array) {
            uint256 minimumLength = Topology.isInlined(conditions, index)
                ? 32
                : 64;
            unsuitable =
                condition.compValue.length < minimumLength ||
                condition.compValue.length > MAX_COMP_VALUE_LENGTH;
        }

        if (unsuitable) {
            revert IRolesError.UnsuitableCompValue(index);
        }
    }

    function _checkComparison(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        Encoding encoding = condition.paramType;
        // ParamType: WordLike
        if (encoding != Encoding.Static && encoding != Encoding.EtherValue) {
            revert IRolesError.UnsuitableParameterType(index);
        }
        // CompValue: 32 bytes
        if (condition.compValue.length != 32) {
            revert IRolesError.UnsuitableCompValue(index);
        }
    }

    function _checkBitmask(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        Encoding encoding = condition.paramType;
        // ParamType: Static / Dynamic
        if (encoding != Encoding.Static && encoding != Encoding.Dynamic) {
            revert IRolesError.UnsuitableParameterType(index);
        }
        // CompValue: 2 shift + 2N
        if (
            condition.compValue.length < 4 ||
            condition.compValue.length > MAX_COMP_VALUE_LENGTH ||
            (condition.compValue.length - 2) % 2 != 0
        ) {
            revert IRolesError.UnsuitableCompValue(index);
        }
    }

    function _checkCustom(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        if (
            condition.paramType != Encoding.Static &&
            condition.paramType != Encoding.Dynamic &&
            condition.paramType != Encoding.Tuple &&
            condition.paramType != Encoding.Array &&
            condition.paramType != Encoding.EtherValue
        ) {
            revert IRolesError.UnsuitableParameterType(index);
        }
        // CompValue: 20 to 65535 bytes
        if (
            condition.compValue.length < 20 ||
            condition.compValue.length > MAX_COMP_VALUE_LENGTH
        ) {
            revert IRolesError.UnsuitableCompValue(index);
        }
    }

    function _checkWithinRatio(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        // ParamType: None
        if (condition.paramType != Encoding.None) {
            revert IRolesError.UnsuitableParameterType(index);
        }
        // CompValue: 12 base, optionally followed by adapter blobs.
        {
            uint256 len = condition.compValue.length;
            if (len < 12 || len > MAX_COMP_VALUE_LENGTH) {
                revert IRolesError.UnsuitableCompValue(index);
            }
            uint256 offset = 12;
            if (len > offset) {
                offset = _checkAdapterBlob(condition.compValue, offset, index);
            }
            if (len > offset) {
                offset = _checkAdapterBlob(condition.compValue, offset, index);
            }
            if (len != offset) {
                revert IRolesError.UnsuitableCompValue(index);
            }
        }
        if (
            uint8(condition.compValue[1]) > 27 ||
            uint8(condition.compValue[3]) > 27
        ) {
            revert IRolesError.AllowanceDecimalsExceedMax(index);
        }

        for (uint256 offset; offset <= 2; offset += 2) {
            (bool found, uint256 pluckCondition) = _findPluck(
                conditions,
                uint8(condition.compValue[offset])
            );
            if (
                found &&
                conditions[pluckCondition].paramType != Encoding.Static &&
                conditions[pluckCondition].paramType != Encoding.EtherValue
            ) {
                revert IRolesError.WithinRatioTargetNotStatic(index);
            }
        }
        // Check ratio bounds
        uint32 minRatio;
        uint32 maxRatio;
        bytes memory cv = condition.compValue;
        assembly {
            minRatio := shr(224, mload(add(cv, 0x24)))
            maxRatio := shr(224, mload(add(cv, 0x28)))
        }
        if (minRatio == 0 && maxRatio == 0) {
            revert IRolesError.WithinRatioNoRatioProvided(index);
        }
        if (minRatio != 0 && maxRatio != 0 && minRatio > maxRatio) {
            revert IRolesError.WithinRatioMinExceedsMax(index);
        }
        // Children: None
        (, uint256 childCount) = Topology.childBounds(conditions, index);
        if (childCount != 0) {
            revert IRolesError.LeafNodeCannotHaveChildren(index);
        }
    }

    function _checkWithinAllowance(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        Encoding encoding = condition.paramType;
        // ParamType: WordLike
        if (encoding != Encoding.Static && encoding != Encoding.EtherValue) {
            revert IRolesError.UnsuitableParameterType(index);
        }
        // CompValue: 32, 34, or >= 54
        if (
            condition.compValue.length > MAX_COMP_VALUE_LENGTH ||
            (condition.compValue.length != 32 &&
                condition.compValue.length != 34 &&
                condition.compValue.length < 54)
        ) {
            revert IRolesError.UnsuitableCompValue(index);
        }
        if (condition.compValue.length > 32) {
            if (
                uint8(condition.compValue[32]) > 27 ||
                uint8(condition.compValue[33]) > 27
            ) {
                revert IRolesError.AllowanceDecimalsExceedMax(index);
            }
        }
    }

    function _checkCallWithinAllowance(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        ConditionFlat memory condition = conditions[index];
        // ParamType: None
        if (condition.paramType != Encoding.None) {
            revert IRolesError.UnsuitableParameterType(index);
        }
        // CompValue: 32 bytes
        if (condition.compValue.length != 32) {
            revert IRolesError.UnsuitableCompValue(index);
        }
        // Children: None
        (, uint256 childCount) = Topology.childBounds(conditions, index);
        if (childCount != 0) {
            revert IRolesError.LeafNodeCannotHaveChildren(index);
        }
    }

    function _validateVariantTypes(
        ConditionFlat[] memory conditions
    ) private pure {
        for (uint256 i = 0; i < conditions.length; ++i) {
            bool isLogical = conditions[i].operator == Operator.And ||
                conditions[i].operator == Operator.Or;
            bool isArray = conditions[i].paramType == Encoding.Array;
            /*
             * Only Logical or Arrays hold variants
             */
            if (!isLogical && !isArray) continue;

            (uint256 childStart, uint256 childCount) = Topology.childBounds(
                conditions,
                i
            );

            Layout memory prev;
            for (uint256 j = 0; j < childCount; ++j) {
                Layout memory next = TypeTree.resolve(
                    conditions,
                    childStart + j
                );

                if (TypeTree.hash(prev) == 0) prev = next;

                if (TypeTree.hash(next) == 0) continue;

                if (!_isTypeCompatible(prev, next)) {
                    revert IRolesError.UnsuitableChildTypeTree(i);
                }
            }
        }
    }

    function _validatePluckZipTypes(
        ConditionFlat[] memory conditions
    ) private pure {
        for (uint256 i = 0; i < conditions.length; ++i) {
            Operator op = conditions[i].operator;
            if (op != Operator.ZipSome && op != Operator.ZipEvery) continue;

            (uint256 childStart, ) = Topology.childBounds(conditions, i);

            Layout memory tuple = TypeTree.resolve(conditions, childStart);

            for (uint256 j = 0; j < tuple.children.length; ++j) {
                (bool found, uint256 pluckCondition) = _findPluck(
                    conditions,
                    uint8(conditions[i].compValue[j])
                );
                if (!found) {
                    revert IRolesError.UnsuitableCompValue(i);
                }
                Layout memory array = TypeTree.resolve(
                    conditions,
                    pluckCondition
                );

                Layout memory arrayEntry = array.children[0];
                Layout memory tupleField = tuple.children[j];

                if (!_isTypeCompatible(arrayEntry, tupleField)) {
                    revert IRolesError.UnsuitableChildTypeTree(i);
                }
            }
        }
    }

    function _validateUniquePluckDefinitions(
        ConditionFlat[] memory conditions
    ) private pure {
        uint256 defined;
        for (uint256 i; i < conditions.length; ++i) {
            if (conditions[i].operator != Operator.Pluck) continue;

            uint8 pluckIndex = uint8(conditions[i].compValue[0]);
            uint256 mask = 1 << pluckIndex;
            if ((defined & mask) != 0) {
                revert IRolesError.DuplicatePluckIndex(i, pluckIndex);
            }
            defined |= mask;
        }
    }

    /**
     * @notice Walks a subtree and returns the set of Pluck slots guaranteed
     *         to hold a value once that subtree evaluates successfully.
     *         Reverts if an operator reads a slot (WithinRatio, ZipSome,
     *         ZipEvery) that may still be empty at that point.
     *
     * @dev A slot is only "guaranteed" if every evaluation path that leads
     *      to success fills it:
     *      - And/Matches run children in order, so each child sees the slots
     *        filled by its predecessors, and its own additions carry forward.
     *      - Or: any single branch may be the one that succeeded, so only
     *        slots filled by every branch are guaranteed.
     *      - Some succeeds only if at least one element was actually
     *        evaluated, so its child's assignments count.
     *      - Every passes trivially on an empty collection — its child may
     *        never run, so nothing it assigns can be counted on.
     *      Children of Pass, Pluck, comparisons, and Custom only describe
     *      types and are never evaluated, so they are skipped.
     */
    function _validatePluckAssignments(
        ConditionFlat[] memory conditions,
        uint256 index,
        uint256 assigned
    ) private pure returns (uint256) {
        ConditionFlat memory condition = conditions[index];

        if (condition.operator == Operator.Pluck) {
            uint8 pluckIndex = uint8(condition.compValue[0]);
            return assigned | (1 << pluckIndex);
        }

        if (condition.operator == Operator.WithinRatio) {
            uint8 referencePluckIndex = uint8(condition.compValue[0]);
            if ((assigned & (1 << referencePluckIndex)) == 0) {
                revert IRolesError.PluckNotVisitedBeforeRef(
                    index,
                    referencePluckIndex
                );
            }

            uint8 relativePluckIndex = uint8(condition.compValue[2]);
            if ((assigned & (1 << relativePluckIndex)) == 0) {
                revert IRolesError.PluckNotVisitedBeforeRef(
                    index,
                    relativePluckIndex
                );
            }
        }

        if (
            condition.operator == Operator.ZipSome ||
            condition.operator == Operator.ZipEvery
        ) {
            for (uint256 k; k < condition.compValue.length; ++k) {
                uint8 pluckIndex = uint8(condition.compValue[k]);
                if ((assigned & (1 << pluckIndex)) == 0) {
                    revert IRolesError.PluckNotVisitedBeforeRef(
                        index,
                        pluckIndex
                    );
                }
            }
        }

        Operator op = condition.operator;
        (uint256 childStart, uint256 childCount) = Topology.childBounds(
            conditions,
            index
        );

        if (op == Operator.Or) {
            uint256 intersection;
            for (uint256 i; i < childCount; ++i) {
                uint256 branchAssigned = _validatePluckAssignments(
                    conditions,
                    childStart + i,
                    assigned
                );
                intersection = i == 0
                    ? branchAssigned
                    : intersection & branchAssigned;
            }
            return intersection;
        }

        if (op == Operator.ArraySome || op == Operator.ArrayEvery) {
            uint256 childAssigned = _validatePluckAssignments(
                conditions,
                childStart,
                assigned
            );
            return op == Operator.ArraySome ? childAssigned : assigned;
        }

        if (op == Operator.ZipSome || op == Operator.ZipEvery) {
            (uint256 fieldStart, uint256 fieldCount) = Topology.childBounds(
                conditions,
                childStart
            );
            uint256 fieldAssigned = assigned;
            for (uint256 i; i < fieldCount; ++i) {
                fieldAssigned = _validatePluckAssignments(
                    conditions,
                    fieldStart + i,
                    fieldAssigned
                );
            }
            return op == Operator.ZipSome ? fieldAssigned : assigned;
        }

        if (
            op == Operator.And ||
            op == Operator.Matches ||
            op == Operator.ArrayTailMatches
        ) {
            for (uint256 i; i < childCount; ++i) {
                assigned = _validatePluckAssignments(
                    conditions,
                    childStart + i,
                    assigned
                );
            }
            return assigned;
        }

        if (op == Operator.Slice) {
            return _validatePluckAssignments(conditions, childStart, assigned);
        }

        return assigned;
    }

    function _validateNoPluckDescendant(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure {
        if (conditions[index].operator == Operator.Pluck) {
            revert IRolesError.UnsupportedOperator(index);
        }
        (uint256 childStart, uint256 childCount) = Topology.childBounds(
            conditions,
            index
        );
        for (uint256 i = 0; i < childCount; ++i) {
            _validateNoPluckDescendant(conditions, childStart + i);
        }
    }

    /// @dev Validates an adapter blob at the given offset: blobLen(1) + adapter(20) + params(blobLen - 20).
    ///      blobLen must be 0 (no adapter) or >= 20. Returns the offset after the blob.
    function _checkAdapterBlob(
        bytes memory buffer,
        uint256 offset,
        uint256 index
    ) private pure returns (uint256) {
        uint256 blobLen = uint8(buffer[offset]);
        if (blobLen != 0 && blobLen < 20) {
            revert IRolesError.UnsuitableCompValue(index);
        }
        offset += 1 + blobLen;
        if (offset > buffer.length) {
            revert IRolesError.UnsuitableCompValue(index);
        }
        return offset;
    }

    function _sChildBounds(
        ConditionFlat[] memory conditions,
        uint256 index
    )
        private
        pure
        returns (uint256 childStart, uint256 childCount, uint256 sChildCount)
    {
        (childStart, childCount) = Topology.childBounds(conditions, index);
        for (uint256 i; i < childCount; ++i) {
            if (TypeTree.hash(conditions, childStart + i) != 0) {
                ++sChildCount;
            }
        }
    }

    /**
     * @notice Checks if two layouts are type-compatible: either exact type
     *         hash match, or type equivalence (both resolve to Dynamic or
     *         AbiEncoded).
     */
    function _isTypeCompatible(
        Layout memory a,
        Layout memory b
    ) private pure returns (bool) {
        bytes32 hashA = TypeTree.hash(a);
        assert(hashA != 0);

        bytes32 hashB = TypeTree.hash(b);
        assert(hashB != 0);

        if (hashA == hashB) {
            return true;
        }
        return _isDynamicish(a) && _isDynamicish(b);
    }

    /**
     * @notice Finds the conditions index of the Pluck condition with the given
     *         pluck index.
     */
    function _findPluck(
        ConditionFlat[] memory conditions,
        uint8 pluckIndex
    ) private pure returns (bool found, uint256 conditionIndex) {
        for (uint256 i = 0; i < conditions.length; ++i) {
            if (
                conditions[i].operator == Operator.Pluck &&
                uint8(conditions[i].compValue[0]) == pluckIndex
            ) {
                return (true, i);
            }
        }
    }

    function _isDynamicish(Layout memory layout) private pure returns (bool) {
        /*
         * None on a resolved type tree means a Variant placeholder. Such
         * fields equate to Dynamic
         */
        return
            layout.encoding == Encoding.Dynamic ||
            layout.encoding == Encoding.AbiEncoded ||
            layout.encoding == Encoding.None;
    }
}

project/contracts/core/serialize/Topology.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "../../types/Types.sol";

/**
 * @title  Topology
 * @notice Utilities for navigating flat condition tree structure.
 *
 * @author gnosisguild
 */
library Topology {
    /**
     * @notice Gets the bounds and counts of children for a given node
     * @param conditions The flat array of conditions
     * @param index The index of the parent node
     *
     * @return childStart The index of the first child (0 if no children)
     * @return childCount The total number of children
     */
    function childBounds(
        ConditionFlat[] memory conditions,
        uint256 index
    ) internal pure returns (uint256 childStart, uint256 childCount) {
        uint256 len = conditions.length;

        for (uint256 i = index + 1; i < len; ++i) {
            uint256 parent = conditions[i].parent;

            if (parent == index) {
                if (childCount == 0) childStart = i;
                ++childCount;
            } else if (parent > index) {
                break;
            }
        }
    }

    /**
     * @notice Checks if a node is inlined (all descendants are static)
     */
    function isInlined(
        ConditionFlat[] memory conditions,
        uint256 index
    ) internal pure returns (bool) {
        Encoding encoding = conditions[index].paramType;
        if (
            encoding == Encoding.Dynamic ||
            encoding == Encoding.Array ||
            encoding == Encoding.AbiEncoded
        ) {
            return false;
        }

        (uint256 childStart, uint256 childCount) = childBounds(
            conditions,
            index
        );
        for (uint256 i; i < childCount; ++i) {
            if (!isInlined(conditions, childStart + i)) {
                return false;
            }
        }
        return true;
    }

    /**
     * @notice Computes the inlined size (in bytes) for a node.
     *
     * @dev Only invoked on nodes already known to be inlined; the assertion
     *      documents this invariant rather than acting as a runtime guard.
     */
    function inlinedSize(
        ConditionFlat[] memory conditions,
        uint256 index
    ) internal pure returns (uint256 size) {
        assert(isInlined(conditions, index) == true);

        /*
         * Dynamic, Array, and AbiEncoded types are never inlined, so this
         * function is guaranteed to only process Static, Tuple, or None types
         * (enforced by the assertion above).
         */
        Encoding encoding = conditions[index].paramType;

        if (encoding == Encoding.Static) {
            return 32;
        }

        /*
         * Remaining encodings:
         * - Tuple: sum of all children sizes
         * - None: delegates to first structural child
         */
        (uint256 childStart, uint256 childCount) = childBounds(
            conditions,
            index
        );

        for (uint256 i; i < childCount; ++i) {
            uint256 childSize = inlinedSize(conditions, childStart + i);
            /*
             * None nodes are transparent wrappers (And/Or or non-structural).
             * Since inlined nodes can't have variants, all structural children
             * share the same size. Return on first non-zero (structural) child.
             */
            if (encoding == Encoding.None && childSize > 0) return childSize;
            size += childSize;
        }
    }
}

project/contracts/core/serialize/TypeTree.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "../../types/Types.sol";
import "./Topology.sol";

/**
 * @title  TypeTree
 * @notice Extracts type trees from flat conditions for use in decoding.
 *         Variants can appear in logical or array nodes and must be handled.
 *         See inline comments for rules
 *
 * @author gnosisguild
 */
library TypeTree {
    /**
     * @notice Resolves type tree for condition at an index
     */
    function resolve(
        ConditionFlat[] memory conditions,
        uint256 i
    ) internal pure returns (Layout memory layout) {
        bool isLogical = conditions[i].operator == Operator.And ||
            conditions[i].operator == Operator.Or;
        bool isVariant = _isVariant(conditions, i);

        (uint256 childStart, uint256 childCount) = Topology.childBounds(
            conditions,
            i
        );

        if (isLogical && !isVariant) {
            /*
             * Non-variant logical nodes: first structural child defines the type tree
             */
            for (uint256 j; j < childCount; ++j) {
                if (hash(conditions, childStart + j) != 0) {
                    return resolve(conditions, childStart + j);
                }
            }

            /*
             * No structural child was found.
             */
            Layout memory none;
            return none;
        }

        layout.encoding = conditions[i].paramType == Encoding.EtherValue
            ? Encoding.None
            : conditions[i].paramType;

        /*
         * Extract leadingBytes for AbiEncoded from compValue, first 2 bytes
         * Default is 4 (selector size) when compValue is empty
         */
        if (layout.encoding == Encoding.AbiEncoded) {
            bytes memory compValue = conditions[i].compValue;
            layout.leadingBytes = compValue.length >= 2
                ? uint16(bytes2(compValue))
                : 4;
        }

        bool isArray = conditions[i].paramType == Encoding.Array;
        layout.children = new Layout[](childCount);

        uint256 length;
        for (uint256 j; j < layout.children.length; ++j) {
            if (hash(conditions, childStart + j) != bytes32(0)) {
                layout.children[length++] = resolve(conditions, childStart + j);

                /*
                 * For non-variant arrays, the first child serves as a template for
                 * all elements. For all other nodes, traverse all structural children
                 */
                if (isArray && !isVariant) {
                    break;
                }
            }
        }
        assembly {
            // layout.children is at offset 0x20 (second field)
            mstore(mload(add(layout, 0x20)), length)
        }

        layout.inlined = Topology.isInlined(conditions, i);
    }

    /**
     * @notice Computes a unique hash for a type tree structure
     */
    function hash(
        ConditionFlat[] memory conditions,
        uint256 index
    ) internal pure returns (bytes32) {
        return hash(resolve(conditions, index));
    }

    /**
     * @notice Computes a unique hash for a Layout tree
     */
    function hash(Layout memory tree) internal pure returns (bytes32 result) {
        Encoding encoding = tree.encoding == Encoding.EtherValue
            ? Encoding.None
            : tree.encoding;

        if (tree.children.length == 0) {
            return bytes32(uint256(encoding));
        }

        result = bytes32(uint256(encoding));
        for (uint256 i; i < tree.children.length; ++i) {
            bytes32 childHash = hash(tree.children[i]);
            if (childHash != 0) {
                result = keccak256(abi.encodePacked(result, childHash));
            }
        }
    }

    /**
     * @notice Checks if a node is a variant. Ignores non structural subtrees
     */
    function _isVariant(
        ConditionFlat[] memory conditions,
        uint256 index
    ) private pure returns (bool) {
        (uint256 childStart, uint256 childCount) = Topology.childBounds(
            conditions,
            index
        );

        bytes32 prevHash;
        for (uint256 i; i < childCount; ++i) {
            bytes32 nextHash = hash(conditions, childStart + i);

            if (prevHash == 0) prevHash = nextHash;
            if (nextHash == 0) continue;
            else if (prevHash != nextHash) return true;
        }
        return false;
    }
}

project/contracts/periphery/interfaces/ICustomCondition.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "@gnosis-guild/zodiac-core/contracts/core/Operation.sol";

struct AllowanceConsumption {
    bytes32 allowanceKey;
    uint256 amount;
}

interface ICustomCondition {
    function check(
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation,
        uint256 location,
        uint256 size,
        bytes calldata extra,
        bytes32[] calldata pluckedValues
    )
        external
        view
        returns (bool success, AllowanceConsumption[] memory consumptions);
}

project/contracts/periphery/interfaces/IPricing.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

/**
 * @notice Interface for pricing contracts
 * @dev Returns a price with 18 decimals precision
 */
interface IPricing {
    function getPrice(
        bytes calldata params
    ) external view returns (uint256 price);
}

project/contracts/periphery/interfaces/ITransactionUnwrapper.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "@gnosis-guild/zodiac-core/contracts/core/Operation.sol";

struct UnwrappedTransaction {
    Operation operation;
    address to;
    uint256 value;
    // We wanna deal in calldata slices. We return location, let invoker slice
    uint256 dataLocation;
    uint256 dataSize;
}

interface ITransactionUnwrapper {
    function unwrap(
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation
    ) external view returns (UnwrappedTransaction[] memory result);
}

project/contracts/types/Allowance.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

/**
 * @notice Represents an allowance with periodic refilling capability.
 *
 * @dev The struct layout is storage-optimized: fields updated together during
 * accrual (`balance` and `timestamp`) share word2, minimizing SSTORE
 *
 * Storage Layout (2 words, 64 bytes, 512 bits):
 * ┌────────────────────────────────┬────────────────────────────────┐
 * │           maxRefill            │             refill             │
 * │            128 bits            │            128 bits            │
 * ├────────────────┬───────────────┴───────────────┬────────────────┤
 * │   timestamp    │            balance            │     period     │
 * │    64 bits     │           128 bits            │    64 bits     │
 * └────────────────┴───────────────────────────────┴────────────────┘
 *
 * @custom:member refill Amount added to balance each period.
 * @custom:member maxRefill Cap at which refilling stops.
 * @custom:member period Refill interval in seconds. Zero means one-time use.
 * @custom:member balance Current available allowance.
 * @custom:member timestamp Last refill time.
 */
struct Allowance {
    uint128 refill;
    uint128 maxRefill;
    uint64 period;
    uint128 balance;
    uint64 timestamp;
}

struct Consumption {
    bytes32 allowanceKey;
    uint128 balance;
    uint128 consumed;
    uint64 timestamp;
}

project/contracts/types/Authorization.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "@gnosis-guild/zodiac-core/contracts/core/Operation.sol";

import {Consumption} from "./Allowance.sol";

enum Status {
    Ok,
    /// Or conition not met
    OrViolation,
    /// Parameter value is not equal to allowed
    ParameterNotAllowed,
    /// Parameter value less than allowed
    ParameterLessThanAllowed,
    /// Parameter value greater than maximum allowed by role
    ParameterGreaterThanAllowed,
    /// Parameter value does not match
    ParameterNotAMatch,
    /// Array elements do not meet allowed criteria for every element
    NotEveryArrayElementPasses,
    /// Array elements do not meet allowed criteria for at least one element
    NoArrayElementPasses,
    /// Bitmask exceeded value length
    BitmaskOverflow,
    /// Bitmask not an allowed value
    BitmaskNotAllowed,
    CustomConditionViolation,
    CustomConditionNotAContract,
    CustomConditionReverted,
    CustomConditionInvalidResult,
    PricingAdapterNotAContract,
    PricingAdapterReverted,
    PricingAdapterInvalidResult,
    PricingAdapterZeroPrice,
    AllowanceExceeded,
    /// No longer emitted: full-precision comparison reports AllowanceExceeded
    /// instead. Kept to preserve status codes.
    AllowanceValueOverflow,
    CalldataOverflow,
    RatioBelowMin,
    RatioAboveMax,
    /// Calldata is not empty when it should be
    CalldataNotEmpty,
    /// Leading bytes do not match expected value
    LeadingBytesNotAMatch,
    /// Zipped arrays have different lengths
    ZippedArrayLengthMismatch,
    /// No zipped element pair passes
    NoZippedElementPasses,
    /// Not every zipped element pair passes
    NotEveryZippedElementPasses
}

struct Transaction {
    address to;
    uint256 value;
    Operation operation;
}

struct Context {
    address to;
    uint256 value;
    Operation operation;
    bytes32[] pluckedValues;
    uint256[] pluckedLocations;
}

struct Result {
    Status status;
    uint256 violatedNodeIndex;
    uint256 payloadLocation;
    Consumption[] consumptions;
}

project/contracts/types/Condition.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

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

enum Encoding {
    None,
    Static,
    Dynamic,
    Tuple,
    Array,
    AbiEncoded,
    /* EtherValue is a nonstructural, and an alias for None */
    EtherValue
}

struct Condition {
    /// @dev BFS index from unpacking - identifies this node in the flattened tree
    uint256 index;
    Encoding encoding;
    Operator operator;
    bytes compValue;
    Condition[] children;
    /* meta fields */
    bool inlined;
    uint256 size;
    uint256 leadingBytes;
}

// This struct is a flattened version of Condition
// used for ABI encoding a scope config tree
// (ABI does not support recursive types)
struct ConditionFlat {
    uint16 parent;
    Encoding paramType;
    Operator operator;
    bytes compValue;
}

/// @dev Layout is a type tree used for AbiDecoder and EIP712 encoding.
struct Layout {
    Encoding encoding;
    Layout[] children;
    uint256 leadingBytes;
    bool inlined;
}

struct LayoutFlat {
    uint256 parent;
    Encoding encoding;
}

/// @dev Payload is the result of AbiDecoder.inspect() - maps parameter locations.
struct Payload {
    uint256 location;
    uint256 size;
    Payload[] children;
    /* meta flags */
    bool inlined;
    bool variant;
    bool overflow;
}

project/contracts/types/Operator.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

enum Operator {
    // 00:    EMPTY EXPRESSION (default, always passes)
    //          paramType: Static / Dynamic / Tuple / Array / EtherValue
    //          ❓ children (only for paramType: Tuple / Array to describe their structure)
    //          🚫 compValue
    /* 00: */ Pass,
    // ------------------------------------------------------------
    // 01-03: LOGICAL EXPRESSIONS
    //          paramType: None
    //          ✅ children
    //          🚫 compValue
    /* 01: */ And,
    /* 02: */ Or,
    /* 03: */ _Placeholder03,
    // ------------------------------------------------------------
    // 04:    EMPTY CHECK (passes if data.length == 0)
    //          paramType: None
    //          🚫 children
    //          🚫 compValue
    /* 04: */ Empty,
    // ------------------------------------------------------------
    // 05-12: COMPLEX EXPRESSIONS
    //          paramType: AbiEncoded / Tuple / Array,
    //          ✅ children
    //          🚫 compValue (exception AbiEncoded.Matches uses compValue to define leading bytes)
    /* 05: */ Matches,
    /* 06: */ ArraySome,
    /* 07: */ ArrayEvery,
    /* 08: */ ArrayTailMatches,
    /* 09: */ _Placeholder09,
    /* 10: */ ZipSome, // paramType: None, compValue: at least 2 bytes, one per plucked array
    /* 11: */ ZipEvery, // paramType: None, compValue: at least 2 bytes, one per plucked array
    /* 12: */ _Placeholder12,
    // ------------------------------------------------------------
    // 13-14: EXTRACTION EXPRESSIONS
    //          ❓ children (at most one child, must resolve to Static)
    //          ✅ compValue
    /* 13: */ Slice, // paramType: Static / Dynamic, compValue: 3 bytes (2 bytes shift + 1 byte size, 1-32)
    /* 14: */ Pluck, // paramType: Static / EtherValue / Array, compValue: 1 byte (index into pluckedValues, 0-254)
    // ------------------------------------------------------------
    // 15:    SPECIAL COMPARISON (without compValue)
    //          paramType: Static
    //          🚫 children
    //          🚫 compValue
    /* 15: */ EqualToAvatar,
    // ------------------------------------------------------------
    // 16-31: COMPARISON EXPRESSIONS
    //          paramType: Static / Dynamic / Tuple / Array / EtherValue
    //          ❓ children (only for paramType: Tuple / Array to describe their structure)
    //          ✅ compValue
    /* 16: */ EqualTo, // paramType: Static / Dynamic / Tuple / Array / EtherValue
    /* 17: */ GreaterThan, // paramType: Static / EtherValue
    /* 18: */ LessThan, // paramType: Static / EtherValue
    /* 19: */ SignedIntGreaterThan, // paramType: Static / EtherValue
    /* 20: */ SignedIntLessThan, // paramType: Static / EtherValue
    /* 21: */ Bitmask, // paramType: Static / Dynamic
    /* 22: */ Custom, // paramType: Static / Dynamic / Tuple / Array / EtherValue
    /* 23: */ WithinRatio, // paramType: None
    /* 24: */ _Placeholder24,
    /* 25: */ _Placeholder25,
    /* 26: */ _Placeholder26,
    /* 27: */ _Placeholder27,
    /* 28: */ WithinAllowance, // paramType: Static / EtherValue
    /* 29: */ _Placeholder29,
    /* 30: */ CallWithinAllowance, // paramType: None
    /* 31: */ _Placeholder31
}

project/contracts/types/Permission.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

enum Clearance {
    None,
    Target,
    Function
}

enum ExecutionOptions {
    None,
    Send,
    DelegateCall,
    Both
}

struct Role {
    mapping(address => uint256) members;
    mapping(address => Clearance) clearance;
    mapping(bytes32 => uint256) scopeConfig;
}

project/contracts/types/RolesError.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import {Status} from "./Authorization.sol";

/**
 * @title IRolesError - All custom errors emitted by the Roles Mod
 *
 * @author gnosisguild
 */
interface IRolesError {
    /*//////////////////////////////////////////////////////////////
                            EXECUTION ERRORS
    //////////////////////////////////////////////////////////////*/

    /// Sender is allowed to make this call, but the internal transaction failed
    error ModuleTransactionFailed();

    /// Reentrant call detected
    error Reentrancy();

    /*//////////////////////////////////////////////////////////////
                          AUTHORIZATION ERRORS
    //////////////////////////////////////////////////////////////*/

    /// Sender is not a member of the role
    error NoMembership();

    /// Membership is not yet valid (before start timestamp)
    error MembershipNotYetValid();

    /// Membership has expired (after end timestamp)
    error MembershipExpired();

    /// Function signature too short
    error FunctionSignatureTooShort();

    /// Calldata unwrapping failed
    error MalformedMultiEntrypoint();

    /// Authorization check failed with violation information
    error ConditionViolation(
        Status status,
        uint256 violatedNodeIndex,
        uint256 location
    );

    /// No matching permission found for the transaction
    error TransactionNotAllowed(address to, bytes4 selector);

    /// Sending value is not allowed
    error SendNotAllowed(address target);

    /// Delegate call is not allowed
    error DelegateCallNotAllowed(address target);

    /*//////////////////////////////////////////////////////////////
                            DECODING ERRORS
    //////////////////////////////////////////////////////////////*/

    /// Attempted to read beyond calldata bounds
    error CalldataOutOfBounds();

    /*//////////////////////////////////////////////////////////////
                           INTEGRITY ERRORS
    //////////////////////////////////////////////////////////////*/

    /// Root node is invalid or missing
    error UnsuitableRootNode();

    /// Condition tree is not in BFS (breadth-first search) order
    error NotBFS();

    /// Packed condition buffer is malformed (not produced by pack())
    error MalformedConditionBuffer();

    /// Parameter type is unsuitable for the operator at given index
    error UnsuitableParameterType(uint256 index);

    /// Comparison value is unsuitable for the operator at given index
    error UnsuitableCompValue(uint256 index);

    /// Condition count exceeds the packed header's 16-bit field
    error ConditionNodeCountExceedsMax();

    /// Child count exceeds the packed node's 10-bit field
    error ConditionChildCountExceedsMax(uint256 index);

    /// Inlined size exceeds the packed node's 13-bit field
    error ConditionInlinedSizeExceedsMax(uint256 index);

    /// Operator is not supported at given index
    error UnsupportedOperator(uint256 index);

    /// Parent node is unsuitable for the child at given index
    error UnsuitableParent(uint256 index);

    /// Child count is unsuitable for the node at given index
    error UnsuitableChildCount(uint256 index);

    /// Leaf node cannot have children at given index
    error LeafNodeCannotHaveChildren(uint256 index);

    /// Child type tree is unsuitable for the node at given index
    error UnsuitableChildTypeTree(uint256 index);

    /// WithinRatio target must resolve to a Static type
    error WithinRatioTargetNotStatic(uint256 index);

    /// WithinRatio requires at least one ratio (min or max) to be provided
    error WithinRatioNoRatioProvided(uint256 index);

    /// WithinRatio minRatio exceeds maxRatio (range is unsatisfiable)
    error WithinRatioMinExceedsMax(uint256 index);

    /// Allowance decimals exceed maximum of 27
    error AllowanceDecimalsExceedMax(uint256 index);

    /// Slice child must resolve to Static type
    error SliceChildNotStatic(uint256 index);

    /// An operator references a Pluck slot that is not definitely assigned
    error PluckNotVisitedBeforeRef(uint256 index, uint8 pluckIndex);

    /// A Pluck slot is defined more than once in the condition tree
    error DuplicatePluckIndex(uint256 index, uint8 pluckIndex);

    /// address(0) is not allowed
    error ZeroAddressNotAllowed();
}

project/contracts/types/RolesEvent.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import {ExecutionOptions} from "./Permission.sol";

/**
 * @title IRolesEvent - All events emitted by the Roles Mod.
 *
 * @author gnosisguild
 */
interface IRolesEvent {
    /*//////////////////////////////////////////////////////////////
                             SETUP EVENTS
    //////////////////////////////////////////////////////////////*/

    /// Emitted when the Roles Mod is initialized
    event RolesModSetup(
        address indexed initiator,
        address indexed owner,
        address indexed avatar,
        address target,
        string version
    );

    /// Emitted when a role is granted to a module
    event GrantRole(
        bytes32 roleKey,
        address module,
        uint64 start,
        uint64 end,
        uint128 usesLeft
    );

    /// Emitted when a role is revoked from a module
    event RevokeRole(bytes32 roleKey, address module);

    /// Emitted when role membership is updated (e.g., uses consumed)
    event UpdateRole(
        bytes32 roleKey,
        address module,
        uint64 start,
        uint64 end,
        uint128 usesLeft
    );

    /// Emitted when the default role is set for a module
    event SetDefaultRole(address module, bytes32 defaultRoleKey);

    /*//////////////////////////////////////////////////////////////
                           PERMISSION EVENTS
    //////////////////////////////////////////////////////////////*/

    /// Emitted when a target address is allowed for a role
    event AllowTarget(
        bytes32 roleKey,
        address targetAddress,
        bytes conditions,
        ExecutionOptions options
    );

    /// Emitted when a target address is revoked from a role
    event RevokeTarget(bytes32 roleKey, address targetAddress);

    /// Emitted when a target is scoped (function-level permissions enabled)
    event ScopeTarget(bytes32 roleKey, address targetAddress);

    /// Emitted when a function is allowed for a role
    event AllowFunction(
        bytes32 roleKey,
        address targetAddress,
        bytes4 selector,
        bytes conditions,
        ExecutionOptions options
    );

    /// Emitted when a function is allowed globally (applies to all targets)
    event AllowFunctionGlobally(
        bytes32 roleKey,
        bytes4 selector,
        bytes conditions
    );

    /// Emitted when a function is revoked from a role
    event RevokeFunction(
        bytes32 roleKey,
        address targetAddress,
        bytes4 selector
    );

    /// Emitted when a globally allowed function is revoked
    event RevokeFunctionGlobally(bytes32 roleKey, bytes4 selector);

    /// Emitted when an allowance is configured
    event SetAllowance(
        bytes32 allowanceKey,
        uint128 balance,
        uint128 maxRefill,
        uint128 refill,
        uint64 period,
        uint64 timestamp
    );

    /// Emitted when a transaction unwrap adapter is set
    event SetUnwrapAdapter(address to, bytes4 selector, address adapter);

    /*//////////////////////////////////////////////////////////////
                           ALLOWANCE EVENTS
    //////////////////////////////////////////////////////////////*/

    /// Emitted when an allowance is consumed during execution
    event ConsumeAllowance(
        bytes32 allowanceKey,
        uint128 consumed,
        uint128 newBalance
    );
}

project/contracts/types/Types.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 Zodiac Labs GmbH
// Zodiac Roles Modifier v3
// Converts to LGPL-3.0-or-later on 2030-03-01
pragma solidity >=0.8.17 <0.9.0;

import "./Allowance.sol";
import "./Authorization.sol";
import "./Condition.sol";
import "./Operator.sol";
import "./Permission.sol";
import "./RolesError.sol";
import "./RolesEvent.sol";
Настройки компилятораПоказать
{
  "viaIR": true,
  "libraries": {
    "project/contracts/Roles.sol": {
      "ConditionStorer": "0x1869c845280505efae2e272b06d7cfd47f173e0c",
      "WithinRatioChecker": "0x4f9df716f03c70a9fd4f0628063bc88d12f20ab5",
      "CustomConditionChecker": "0x81f1a6511a19cf0640f469caebe2b0f389e7e847"
    }
  },
  "optimizer": {
    "runs": 10,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "project/:@gnosis-guild/zodiac-core/=npm/@gnosis-guild/[email protected]/"
  ]
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.