Skip to content
Verified contractExactBUSL-1.1

ConditionStorer

Address0x1869c845280505efae2e272b06d7cfd47f173e0c
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.38

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.38+commit.1835d247
Language
solidity
Optimization
Yes, 10 runs
EVM version
cancun
Via IR
yes
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,436,394
Creation transaction
0xb4e07b6b37…40147eca57

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);
    }
}

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
}

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/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/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/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";
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 10,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "project/:@gnosis-guild/zodiac-core/=npm/@gnosis-guild/[email protected]/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.