{"version":3,"file":"main-B3KR99eP.mjs","names":["coerced: PermissionCoerced","and","avatar: ConditionFunction<string>","matches","conditions: (Condition | undefined)[]","scoping","abiType","and","calldataMatches: CalldataMatches","conditionFunction: ConditionFunction<any>","expectedLength: number","type: ParamType","avatarIsOwnerOfErc721: ConditionFunction<BigNumberish>","allow","result: ConditionFlat[]","condition","matches","and","child","hingeIndex: number | null","id","invariant","result: Condition","prunedChildren: Condition[]","id","condition","conditionId","shallowEquals","id","child","invariant","match","permissions","invariant","isTargetAllowed","isTargetScoped","right","left","lf","target"],"sources":["../src/main/types.ts","../src/main/chains.ts","../src/main/abiEncode.ts","../src/main/target/authoring/c/allowance.ts","../src/main/permission/coercePermission.ts","../src/main/condition/conditionIntegrity.ts","../src/main/target/authoring/c/helpers/parameterType.ts","../src/main/target/authoring/c/helpers/describeStructure.ts","../src/main/target/authoring/c/branching.ts","../src/main/target/authoring/c/comparison.ts","../src/main/target/authoring/c/matches.ts","../src/main/target/authoring/c/array.ts","../src/main/target/authoring/c/custom.ts","../src/main/target/authoring/c/pass.ts","../src/main/target/authoring/c/index.ts","../src/main/target/authoring/forAll.ts","../src/main/target/integrity.ts","../src/main/condition/flattenCondition.ts","../src/main/condition/conditionId.ts","../src/main/condition/typeTree.ts","../src/main/condition/normalize/padToMatchTypeTree.ts","../src/main/condition/normalize/pushDownOr.ts","../src/main/condition/normalize/index.ts","../src/main/condition/subtractCondition.ts","../src/main/permission/executionFlagsToOptions.ts","../src/main/permission/id.ts","../src/main/permission/mergePermissions.ts","../src/main/groupBy.ts","../src/main/permission/processPermissions.ts","../src/main/permission/reconstructPermissions.ts","../src/main/target/subtractFunction.ts","../src/main/target/subtractTarget.ts","../src/main/target/targetIncludes.ts","../src/main/permission/validatePresets.ts","../src/main/abi.ts","../src/main/keys.ts","../src/main/postRole.ts","../src/main/licensing.ts"],"sourcesContent":["import { chains } from \"./chains\"\n\nexport type ChainId = keyof typeof chains\n\nexport enum ExecutionOptions {\n  None = 0,\n  Send = 1,\n  DelegateCall = 2,\n  Both = 3,\n}\n\nexport enum Clearance {\n  None = 0,\n  Target = 1,\n  Function = 2,\n}\n\nexport enum ParameterType {\n  None = 0,\n  Static = 1,\n  Dynamic = 2,\n  Tuple = 3,\n  Array = 4,\n  Calldata = 5,\n  AbiEncoded = 6,\n}\n\nexport enum Operator {\n  // 00:    EMPTY EXPRESSION (default, always passes)\n  //          paramType: Static / Dynamic / Tuple / Array\n  //          ❓ children (only for paramType: Tuple / Array to describe their structure)\n  //          🚫 compValue\n  Pass = 0,\n  // ------------------------------------------------------------\n  // 01-04: LOGICAL EXPRESSIONS\n  //          paramType: None\n  //          ✅ children\n  //          🚫 compValue\n  And = 1,\n  Or = 2,\n  // ------------------------------------------------------------\n  // 05-14: COMPLEX EXPRESSIONS\n  //          paramType: Calldata / AbiEncoded / Tuple / Array,\n  //          ✅ children\n  //          🚫 compValue\n  Matches = 5,\n  ArrayEvery = 7,\n  // ------------------------------------------------------------\n  // 15:    SPECIAL COMPARISON (without compValue)\n  //          paramType: Static\n  //          🚫 children\n  //          🚫 compValue\n  EqualToAvatar = 15,\n  // ------------------------------------------------------------\n  // 16-31: COMPARISON EXPRESSIONS\n  //          paramType: Static / Dynamic / Tuple / Array\n  //          🚫 children\n  //          ✅ compValue\n  EqualTo = 16, // paramType: Static / Dynamic / Tuple / Array\n  GreaterThan = 17, // paramType: Static\n  LessThan = 18, // paramType: Static\n  SignedIntGreaterThan = 19, // paramType: Static\n  SignedIntLessThan = 20, // paramType: Static\n  Bitmask = 21, // paramType: Static / Dynamic\n  Custom = 22, // paramType: Static / Dynamic / Tuple / Array\n  WithinAllowance = 28, // paramType: Static\n  EtherWithinAllowance = 29, // paramType: None\n  CallWithinAllowance = 30, // paramType: None\n}\n\nexport enum Status {\n  Ok,\n  /** Role not allowed to delegate call to target address */\n  DelegateCallNotAllowed,\n  /** Role not allowed to call target address */\n  TargetAddressNotAllowed,\n  /** Role not allowed to call this function on target address */\n  FunctionNotAllowed,\n  /** Role not allowed to send to target address */\n  SendNotAllowed,\n  /** Or condition not met */\n  OrViolation,\n  /** Nor condition not met */\n  NorViolation,\n  /** Parameter value is not equal to allowed */\n  ParameterNotAllowed,\n  /** Parameter value less than allowed */\n  ParameterLessThanAllowed,\n  /** Parameter value greater than maximum allowed by role */\n  ParameterGreaterThanAllowed,\n  /** Parameter value does not match */\n  ParameterNotAMatch,\n  /** Array elements do not meet allowed criteria for every element */\n  NotEveryArrayElementPasses,\n  /** Array elements do not meet allowed criteria for at least one element */\n  NoArrayElementPasses,\n  /** Parameter value not a subset of allowed */\n  ParameterNotSubsetOfAllowed,\n  /** Bitmask exceeded value length */\n  BitmaskOverflow,\n  /** Bitmask not an allowed value */\n  BitmaskNotAllowed,\n  CustomConditionViolation,\n  AllowanceExceeded,\n  CallAllowanceExceeded,\n  EtherAllowanceExceeded,\n}\n\nexport interface Role {\n  key: `0x${string}`\n  members: `0x${string}`[]\n  targets: Target[]\n  annotations: Annotation[]\n  lastUpdate: number\n}\n\nexport interface Target {\n  address: `0x${string}`\n  clearance: Clearance\n  executionOptions: ExecutionOptions\n  functions: Function[]\n}\n\nexport interface Function {\n  selector: `0x${string}`\n  executionOptions: ExecutionOptions\n  wildcarded: boolean\n  condition?: Condition\n}\n\nexport interface Condition {\n  paramType: ParameterType\n  operator: Operator\n  compValue?: `0x${string}`\n  children?: readonly Condition[]\n}\n\nexport interface Allowance {\n  key: `0x${string}`\n  refill: bigint\n  maxRefill: bigint\n  period: bigint\n  balance: bigint\n  timestamp: bigint\n}\n\nexport interface Annotation {\n  /** The URI serves as ID for the annotation. An http get request will be made to fetch the targeted permissions. */\n  uri: string\n  /** The OpenAPI schema that describes the API endpoint at uri. */\n  schema: string\n}\n\nexport interface RolesModifier {\n  address: `0x${string}`\n  owner: `0x${string}`\n  avatar: `0x${string}`\n  target: `0x${string}`\n  roles: Role[]\n  allowances: Allowance[]\n  multiSendAddresses: `0x${string}`[]\n}\n","export const chains = {\n  [1]: {\n    name: \"mainnet\",\n    prefix: \"eth\",\n  },\n  [10]: {\n    name: \"optimism\",\n    prefix: \"oeth\",\n  },\n  [100]: {\n    name: \"gnosis\",\n    prefix: \"gno\",\n  },\n  [1101]: {\n    name: \"zkevm\",\n    prefix: \"zkevm\",\n  },\n  [11155111]: {\n    name: \"sepolia\",\n    prefix: \"sep\",\n  },\n  [137]: {\n    name: \"polygon\",\n    prefix: \"matic\",\n  },\n  [146]: {\n    name: \"sonic\",\n    prefix: \"sonic\",\n  },\n  [42161]: {\n    name: \"arbitrumOne\",\n    prefix: \"arb1\",\n  },\n  [42220]: {\n    name: \"celo\",\n    prefix: \"celo\",\n  },\n  [43114]: {\n    name: \"avalanche\",\n    prefix: \"avax\",\n  },\n  [56]: {\n    name: \"bsc\",\n    prefix: \"bnb\",\n  },\n  [130]: {\n    name: \"unichain\",\n    prefix: \"unichain\",\n  },\n  [480]: {\n    name: \"worldchain\",\n    prefix: \"worldchain\",\n  },\n  [5000]: {\n    name: \"mantle\",\n    prefix: \"mantle\",\n  },\n  [57073]: {\n    name: \"ink\",\n    prefix: \"ink\",\n  },\n  [60808]: {\n    name: \"bob\",\n    prefix: \"bob\",\n  },\n  [747474]: {\n    name: \"katana\",\n    prefix: \"katana\",\n  },\n  [80094]: {\n    name: \"berachain\",\n    prefix: \"berachain\",\n  },\n  [8453]: {\n    name: \"base\",\n    prefix: \"base\",\n  },\n  [84532]: {\n    name: \"baseSepolia\",\n    prefix: \"basesep\",\n  },\n  [999]: {\n    name: \"hyperevm\",\n    prefix: \"hyperevm\",\n  },\n  [14]: {\n    name: \"flare\",\n    prefix: \"flr\",\n  },\n  [534352]: {\n    name: \"scroll\",\n    prefix: \"scr\",\n  },\n  [9745]: {\n    name: \"plasma\",\n    prefix: \"plasma\",\n  },\n  [4326]: {\n    name: \"megaeth\",\n    prefix: \"megaeth\",\n  },\n} as const\n","import { AbiCoder, ParamType } from \"ethers\"\n\nexport const abiEncode = (\n  types: readonly (string | ParamType)[],\n  values: readonly any[]\n): `0x${string}` =>\n  AbiCoder.defaultAbiCoder().encode(types, values) as `0x${string}`\n","import { BigNumberish, ParamType } from \"ethers\"\nimport { Operator, ParameterType } from \"../../../types\"\n\nimport { abiEncode } from \"../../../abiEncode\"\n\nimport { ConditionFunction } from \"../types\"\n\nexport const withinAllowance =\n  (allowanceKey: `0x${string}`): ConditionFunction<BigNumberish> =>\n  (abiType: ParamType) => {\n    const type = ParamType.from(abiType)\n    if (!type.type.startsWith(\"uint\")) {\n      throw new Error(\"`withinAllowance` is only supported for uint params\")\n    }\n    return {\n      paramType: ParameterType.Static,\n      operator: Operator.WithinAllowance,\n      compValue: abiEncode([\"bytes32\"], [allowanceKey]),\n    }\n  }\n","import { ethers, ParamType } from \"ethers\"\n\nimport {\n  Permission,\n  PermissionCoerced,\n  FunctionPermission,\n  FunctionPermissionCoerced,\n  TargetPermission,\n} from \"./types\"\n\nconst sighash = (signature: string) => {\n  const fragment = ethers.FunctionFragment.from(signature)\n  const selector = ethers.id(fragment.format()).slice(0, 10)\n  return selector\n}\n\nexport const coercePermission = <P extends Permission>(\n  permission: P\n): P extends FunctionPermission\n  ? FunctionPermissionCoerced\n  : TargetPermission => {\n  const selector = () => {\n    if (\"selector\" in permission) {\n      return { selector: permission.selector.toLowerCase() as `0x${string}` }\n    }\n\n    if (\"signature\" in permission) {\n      return { selector: sighash(permission.signature) as `0x${string}` }\n    }\n\n    return {}\n  }\n\n  const condition = () => {\n    if (\n      \"condition\" in permission &&\n      typeof permission.condition === \"function\"\n    ) {\n      return { condition: permission.condition(ParamType.from(\"bytes\")) }\n    }\n\n    if (\"condition\" in permission) {\n      return { condition: permission.condition }\n    }\n\n    return {}\n  }\n\n  const coerced: PermissionCoerced = {\n    targetAddress: permission.targetAddress.toLowerCase() as `0x${string}`,\n    ...selector(),\n    ...condition(),\n    send: Boolean(permission.send),\n    delegatecall: Boolean(permission.delegatecall),\n  }\n  return coerced as any\n}\n","import { Condition, Operator, ParameterType } from \"../types\"\n\nexport const checkRootConditionIntegrity = (condition: Condition): void => {\n  const rootType = checkConsistentChildrenTypes(condition)\n  if (rootType !== ParameterType.Calldata) {\n    throw new Error(\n      `Root param type must be \\`Calldata\\`, got \\`${ParameterType[rootType]}\\``\n    )\n  }\n  checkConditionIntegrityRecursive(condition)\n}\n\nexport const checkConditionIntegrity = (condition: Condition): void => {\n  checkConsistentChildrenTypes(condition)\n  checkConditionIntegrityRecursive(condition)\n}\n\n/**\n * Validates that logical condition children have consistent types.\n * Since the children conditions address the very same value it does not make sense for them to declare incompatible param types.\n * */\nconst checkConsistentChildrenTypes = (condition: Condition): ParameterType => {\n  if (condition.paramType !== ParameterType.None) {\n    return condition.paramType\n  }\n\n  const [first, ...rest] = condition.children || []\n  const expectedType = first\n    ? checkConsistentChildrenTypes(first)\n    : ParameterType.None\n\n  rest.forEach((child) => {\n    const childType = checkConsistentChildrenTypes(child)\n    checkParameterTypeCompatibility(expectedType, childType)\n  })\n\n  return expectedType\n}\n\nexport const checkParameterTypeCompatibility = (\n  left: ParameterType,\n  right: ParameterType\n): void => {\n  if (right === ParameterType.None) return\n\n  if (right === left) return\n\n  if (\n    right === ParameterType.Dynamic &&\n    (left === ParameterType.Calldata || left === ParameterType.AbiEncoded)\n  ) {\n    return\n  }\n\n  if (\n    (right === ParameterType.Calldata || right === ParameterType.AbiEncoded) &&\n    left === ParameterType.Dynamic\n  ) {\n    throw new Error(\n      `Mixed children types: \\`${ParameterType[right]}\\` must appear before \\`${ParameterType[left]}\\``\n    )\n  }\n\n  throw new Error(\n    `Inconsistent children types (\\`${ParameterType[left]}\\` and \\`${ParameterType[right]}\\`)`\n  )\n}\n\nconst checkConditionIntegrityRecursive = (condition: Condition): void => {\n  condition.children?.forEach(checkConditionIntegrityRecursive)\n\n  checkParamTypeIntegrity(condition)\n  checkCompValueIntegrity(condition)\n  checkChildrenIntegrity(condition)\n  banDeprecatedCondition(condition)\n}\n\nconst checkParamTypeIntegrity = (condition: Condition): void => {\n  const COMPATIBLE_TYPES = {\n    [Operator.Pass]: [\n      ParameterType.Static,\n      ParameterType.Dynamic,\n      ParameterType.Tuple,\n      ParameterType.Array,\n      ParameterType.Calldata,\n      ParameterType.AbiEncoded,\n    ],\n\n    [Operator.And]: [ParameterType.None],\n    [Operator.Or]: [ParameterType.None],\n\n    [Operator.Matches]: [\n      ParameterType.Calldata,\n      ParameterType.AbiEncoded,\n      ParameterType.Tuple,\n      ParameterType.Array,\n    ],\n\n    [Operator.ArrayEvery]: [ParameterType.Array],\n\n    [Operator.EqualToAvatar]: [ParameterType.Static],\n    [Operator.EqualTo]: [\n      ParameterType.Static,\n      ParameterType.Dynamic,\n      ParameterType.Tuple,\n      ParameterType.Array,\n    ],\n\n    [Operator.GreaterThan]: [ParameterType.Static],\n    [Operator.LessThan]: [ParameterType.Static],\n    [Operator.SignedIntGreaterThan]: [ParameterType.Static],\n    [Operator.SignedIntLessThan]: [ParameterType.Static],\n\n    [Operator.Bitmask]: [ParameterType.Static, ParameterType.Dynamic],\n\n    [Operator.Custom]: [\n      ParameterType.Static,\n      ParameterType.Dynamic,\n      ParameterType.Tuple,\n      ParameterType.Array,\n    ],\n\n    [Operator.WithinAllowance]: [ParameterType.Static],\n\n    [Operator.EtherWithinAllowance]: [ParameterType.None],\n    [Operator.CallWithinAllowance]: [ParameterType.None],\n  }\n  const compatibleTypes = COMPATIBLE_TYPES[condition.operator]\n\n  if (!compatibleTypes.includes(condition.paramType)) {\n    throw new Error(\n      `\\`${\n        Operator[condition.operator]\n      }\\` condition not supported for paramType \\`${\n        ParameterType[condition.paramType]\n      }\\``\n    )\n  }\n}\n\nconst checkCompValueIntegrity = (condition: Condition): void => {\n  if (condition.operator >= Operator.EqualTo && !condition.compValue) {\n    throw new Error(\n      `\\`${Operator[condition.operator]}\\` condition must have a compValue`\n    )\n  }\n\n  if (condition.operator < Operator.EqualTo && condition.compValue) {\n    throw new Error(\n      `\\`${Operator[condition.operator]}\\` condition cannot have a compValue`\n    )\n  }\n}\n\nconst checkChildrenIntegrity = (condition: Condition): void => {\n  if (\n    condition.paramType === ParameterType.Tuple ||\n    condition.paramType === ParameterType.Array\n  ) {\n    if (!condition.children || condition.children.length === 0) {\n      throw new Error(\n        `Condition on \\`${\n          ParameterType[condition.paramType]\n        }\\` params must have children to describe the type structure, found violation in \\`${\n          Operator[condition.operator]\n        }\\` condition`\n      )\n    }\n  }\n\n  if (condition.operator === Operator.ArrayEvery) {\n    if (condition.children?.length !== 1) {\n      throw new Error(\n        `\\`${\n          Operator[condition.operator]\n        }\\` conditions must have exactly one child`\n      )\n    }\n  }\n\n  if (condition.operator === Operator.Matches) {\n    if (!condition.children || condition.children.length === 0) {\n      throw new Error(\n        `\\`${Operator[condition.operator]}\\` conditions must have children`\n      )\n    }\n  }\n\n  if (\n    condition.operator >= Operator.EqualToAvatar &&\n    condition.operator !== Operator.Custom && // TODO Does this make sense? Can Custom have children?\n    condition.paramType !== ParameterType.Calldata &&\n    condition.paramType !== ParameterType.AbiEncoded &&\n    condition.paramType !== ParameterType.Tuple &&\n    condition.paramType !== ParameterType.Array\n  ) {\n    if (condition.children && condition.children?.length > 0) {\n      throw new Error(\n        `\\`${Operator[condition.operator]}\\` condition on \\`${\n          ParameterType[condition.paramType]\n        }\\` type param must not have children`\n      )\n    }\n  }\n\n  if (\n    condition.operator === Operator.And ||\n    condition.operator === Operator.Or\n  ) {\n    if (!condition.children || condition.children.length === 0) {\n      throw new Error(\n        `\\`${Operator[condition.operator]}\\` condition must have children`\n      )\n    }\n  }\n}\n\nconst DEPRECATED_OPERATORS = [\n  3, // Nor\n  6, // ArraySome\n  8, // ArraySubset\n]\n\nconst banDeprecatedCondition = (condition: Condition): void => {\n  if (DEPRECATED_OPERATORS.includes(condition.operator)) {\n    throw new Error(`Condition operator ${condition.operator} is deprecated`)\n  }\n}\n","import { ParamType } from \"ethers\"\nimport { ParameterType } from \"../../../../types\"\n\nexport const parameterType = (type: ParamType): ParameterType => {\n  switch (type.baseType) {\n    case \"tuple\":\n      return ParameterType.Tuple\n    case \"array\":\n      return ParameterType.Array\n    case \"string\":\n    case \"bytes\":\n      return ParameterType.Dynamic\n    default:\n      return ParameterType.Static\n  }\n}\n","import { ParamType } from \"ethers\"\nimport { Condition, Operator } from \"../../../../types\"\n\nimport { parameterType } from \"./parameterType\"\n\n/**\n * Given an ABI param type, generates a tree of Pass nodes that matches the structure of the type\n */\nexport const describeStructure = (type: ParamType): Condition => {\n  const children = type.arrayChildren\n    ? [type.arrayChildren]\n    : (type.components as ParamType[] | undefined) // ethers typings are wrong\n\n  return {\n    paramType: parameterType(type),\n    operator: Operator.Pass,\n    children:\n      children && children.length > 0\n        ? children.map(describeStructure)\n        : undefined,\n  }\n}\n","import { ParamType } from \"ethers\"\nimport { Condition, Operator, ParameterType } from \"../../../types\"\n\nimport { mapScoping } from \"./matches\"\n\nimport { ConditionFunction, Scoping } from \"../types\"\n\ntype ScopingBranches<T> = [Scoping<T>, Scoping<T>, ...Scoping<T>[]]\n\n/**\n * Passes if any of the branch conditions are true.\n * @param branches conditions to be evaluated\n */\nexport const or =\n  <Branches extends ScopingBranches<T>, T>(\n    ...branches: Branches\n  ): ConditionFunction<T> =>\n  (abiType: ParamType) => ({\n    paramType: ParameterType.None,\n    operator: Operator.Or,\n    children: branches.map((branch) => {\n      if (branch === undefined) {\n        throw new Error(\"or() branch condition must not be undefined\")\n      }\n      return mapScoping(branch, abiType) as Condition // cast is safe because of earlier branch check\n    }),\n  })\n\n/**\n * Passes if all of the branch conditions are true.\n * @param branches conditions to be evaluated\n */\nexport const and =\n  <Branches extends ScopingBranches<T>, T>(\n    ...branches: Branches\n  ): ConditionFunction<T> =>\n  (abiType: ParamType) => ({\n    paramType: ParameterType.None,\n    operator: Operator.And,\n    children: branches.map((branch) => {\n      if (branch === undefined) {\n        throw new Error(\"and() branch condition must not be undefined\")\n      }\n      return mapScoping(branch, abiType) as Condition // cast is safe because of earlier branch check\n    }),\n  })\n","import {\n  BigNumberish,\n  BytesLike,\n  concat,\n  getBytes,\n  hexlify,\n  ParamType,\n  toBeHex,\n} from \"ethers\"\nimport { Operator, ParameterType } from \"../../../types\"\n\nimport { abiEncode } from \"../../../abiEncode\"\nimport { describeStructure } from \"./helpers/describeStructure\"\nimport { parameterType } from \"./helpers/parameterType\"\n\nimport { ConditionFunction } from \"../types\"\n\n/**\n * Asserts that the value from calldata is equal to the given value\n * @param value The reference value to encode\n */\nexport const eq =\n  (value: any): ConditionFunction<any> =>\n  (abiType: ParamType) => {\n    const type = ParamType.from(abiType)\n    const structure = describeStructure(type)\n    return {\n      paramType: parameterType(type),\n      operator: Operator.EqualTo,\n      compValue: abiEncode([type], [value]),\n      children: structure.children,\n    }\n  }\n\n/**\n * Asserts that the value from calldata is equal to the avatar address configured on the Roles mod\n */\nexport const avatar: ConditionFunction<string> = (abiType: ParamType) => {\n  const type = ParamType.from(abiType)\n  const structure = describeStructure(type)\n  return {\n    paramType: parameterType(type),\n    operator: Operator.EqualToAvatar,\n    children: structure.children,\n  }\n}\n\n/**\n * Asserts that the value from calldata is greater than the given value\n * @param value The reference value to encode\n */\nexport const gt =\n  (value: BigNumberish): ConditionFunction<BigNumberish> =>\n  (abiType: ParamType) => {\n    const type = ParamType.from(abiType)\n    if (!type.type.startsWith(\"uint\") && !type.type.startsWith(\"int\")) {\n      throw new Error(\"`gt` is only supported for uint and int params\")\n    }\n    return {\n      paramType: ParameterType.Static,\n      operator: type.type.startsWith(\"uint\")\n        ? Operator.GreaterThan\n        : Operator.SignedIntGreaterThan,\n      compValue: abiEncode([type], [value]),\n    }\n  }\n\n/**\n * Asserts that the value from calldata is greater than or equal to the given value\n * @param value The reference value to encode\n */\nexport const gte = (value: BigNumberish) => gt(BigInt(value) - BigInt(1))\n\n/**\n * Asserts that the value from calldata is greater than the given value\n * @param value The reference value to encode\n */\nexport const lt =\n  (value: BigNumberish): ConditionFunction<BigNumberish> =>\n  (abiType: ParamType) => {\n    const type = ParamType.from(abiType)\n    if (!type.type.startsWith(\"uint\") && !type.type.startsWith(\"int\")) {\n      throw new Error(\"`lt` is only supported for uint and int params\")\n    }\n    return {\n      paramType: ParameterType.Static,\n      operator: type.type.startsWith(\"uint\")\n        ? Operator.LessThan\n        : Operator.SignedIntLessThan,\n      compValue: abiEncode([type], [value]),\n    }\n  }\n\n/**\n * Asserts that the value from calldata is less than or equal to the given value\n * @param value The reference value to encode\n */\nexport const lte = (value: BigNumberish) => lt(BigInt(value) + BigInt(1))\n\n/**\n * Asserts that the bits selected by the mask at the given bytes offset equal the given value\n */\nexport const bitmask =\n  ({ shift = 0, mask, value }: Bitmask): ConditionFunction<BytesLike> =>\n  (abiType: ParamType) => {\n    const paramType = parameterType(ParamType.from(abiType))\n\n    if (\n      paramType !== ParameterType.Static &&\n      paramType !== ParameterType.Dynamic\n    ) {\n      throw new Error(\n        `Bitmask can only be used for parameters with type Static or Dynamic, got: ${ParameterType[paramType]}`\n      )\n    }\n\n    if (shift < 0 || shift >= 65536) {\n      throw new Error(\"shift is out of range, must be between 0 and 65535\")\n    }\n\n    const maskBytes = getBytes(mask)\n    if (maskBytes.length > 15) {\n      throw new Error(\"mask is too long, maximum length is 15 bytes\")\n    }\n    const valueBytes = getBytes(value)\n    if (maskBytes.length > 15) {\n      throw new Error(\"value is too long, maximum length is 15 bytes\")\n    }\n\n    return {\n      paramType,\n      operator: Operator.Bitmask,\n      compValue: hexlify(\n        concat([\n          toBeHex(shift, 2),\n          zeroPadRight(maskBytes, 15),\n          zeroPadRight(valueBytes, 15),\n        ])\n      ) as `0x${string}`,\n    }\n  }\n\ninterface Bitmask {\n  /** Offset in bytes at which to apply the mask, defaults to `0` */\n  shift?: number\n  /** The 15 bytes bitmask, each `1` means the bit at that position will be compared against the comparison value bit at the same position  */\n  mask: BytesLike\n  /** The 15 bytes comparison value, defines the expected value (`0` or `1`) for the bit at that position */\n  value: BytesLike\n}\n\nfunction zeroPadRight(value: Uint8Array, length: number): Uint8Array {\n  const result = new Uint8Array(length)\n  result.set(value, 0)\n  return result\n}\n","import { BigNumberish, isHexString, ParamType } from \"ethers\"\nimport { Condition, Operator, ParameterType } from \"../../../types\"\n\nimport { coercePermission } from \"../../../permission/coercePermission\"\nimport { checkParameterTypeCompatibility } from \"../../../condition/conditionIntegrity\"\nimport { describeStructure } from \"./helpers/describeStructure\"\nimport { parameterType } from \"./helpers/parameterType\"\n\nimport { and } from \"./branching\"\nimport { bitmask, eq } from \"./comparison\"\n\nimport { FunctionPermission } from \"../../../permission\"\nimport {\n  ConditionFunction,\n  Scoping,\n  StructScoping,\n  TupleScopings,\n} from \"../types\"\n\ntype AbiType = string | ParamType\n\n/**\n * Matches a tuple or array against a structure of conditions.\n *\n * Throws if the type is not a tuple or array. Throws if the structure of conditions is incompatible with the type.\n * @param scoping The conditions on the tuple or array elements\n */\nexport const matches =\n  <S extends TupleScopings<any> | StructScoping<any>>(scoping: S) =>\n  (abiType: ParamType) => {\n    // The type system allows for nesting matches(matches()).\n    // While using this in practice would not make too much sense, we must make sure it's valid nonetheless.\n    if (typeof scoping === \"function\") {\n      return scoping(abiType)\n    }\n\n    let conditions: (Condition | undefined)[]\n\n    if (abiType.baseType === \"tuple\" && !abiType.components) {\n      throw new Error(\"Tuple type must have components\")\n    }\n    if (abiType.baseType === \"array\" && !abiType.arrayChildren) {\n      throw new Error(\"Array type must have arrayChildren\")\n    }\n\n    if (Array.isArray(scoping)) {\n      // scoping is an array (TupleScopings)\n\n      // supported for tuple and array types\n      if (abiType.baseType !== \"tuple\" && abiType.baseType !== \"array\") {\n        throw new Error(\n          `Can only use \\`matches\\` on tuple or array type params, got: ${abiType.type}`\n        )\n      }\n\n      // map scoping items to conditions\n      conditions = scoping.map((scoping, index) =>\n        mapScoping(\n          scoping,\n          abiType.baseType === \"tuple\"\n            ? abiType.components![index]\n            : abiType.arrayChildren!\n        )\n      )\n    } else {\n      // scoping is an object (StructScoping)\n\n      // only supported for tuple types\n      if (abiType.baseType !== \"tuple\") {\n        throw new Error(\n          `Can only use \\`matches\\` with scoping object on tuple type params, got: ${abiType.type}`\n        )\n      }\n\n      // map scoping values to conditions\n      conditions = abiType.components!.map((componentType) =>\n        mapScoping(scoping[componentType.name], componentType)\n      )\n    }\n\n    // sanity checks\n    assertValidConditionsLength(conditions, abiType)\n    assertValidConditionsKeys(scoping, abiType)\n    assertCompatibleParamTypes(conditions, abiType)\n\n    return {\n      paramType: parameterType(abiType),\n      operator: Operator.Matches,\n      children: conditions.map(\n        (condition, index) =>\n          condition ||\n          describeStructure(\n            abiType.baseType === \"tuple\"\n              ? abiType.components![index]\n              : abiType.arrayChildren!\n          )\n      ),\n    }\n  }\n\nconst calldataMatchesScopings =\n  <S extends TupleScopings<any>>(\n    scopings: S,\n    abiTypes: readonly AbiType[],\n    options: {\n      selector?: `0x${string}`\n      etherWithinAllowance?: `0x${string}`\n      callWithinAllowance?: `0x${string}`\n    } = {}\n  ) =>\n  (abiType?: ParamType) => {\n    const paramTypes = abiTypes.map((abiType) => ParamType.from(abiType))\n\n    // only supported at the top level or for bytes type params\n    if (abiType && abiType.type !== \"bytes\") {\n      throw new Error(\n        `Can only use \\`calldataMatches\\` on bytes type params, got: ${abiType.type}`\n      )\n    }\n\n    const { selector, etherWithinAllowance, callWithinAllowance } = options\n\n    // map scoping items to conditions\n    const conditions: (Condition | undefined)[] = paramTypes.map(\n      (type, index) => mapScoping(scopings[index], type)\n    )\n\n    // sanity checks\n    assertValidConditionsKeys(conditions, paramTypes)\n    assertCompatibleParamTypes(conditions, paramTypes)\n\n    const matchesCondition = {\n      paramType: ParameterType.Calldata,\n      operator: Operator.Matches,\n      children: conditions.map(\n        (condition, index) => condition || describeStructure(paramTypes[index])\n      ),\n    }\n\n    if (etherWithinAllowance) {\n      matchesCondition.children.push({\n        paramType: ParameterType.None,\n        operator: Operator.EtherWithinAllowance,\n        compValue: etherWithinAllowance,\n      })\n    }\n\n    if (callWithinAllowance) {\n      matchesCondition.children.push({\n        paramType: ParameterType.None,\n        operator: Operator.CallWithinAllowance,\n        compValue: callWithinAllowance,\n      })\n    }\n\n    if (selector) {\n      if (selector.length !== 10) {\n        throw new Error(\n          `Selector must be exactly 4 bytes long, got: ${selector.length}`\n        )\n      }\n\n      return and(\n        () => matchesCondition,\n        bitmask({ mask: \"0xffffffff\", value: selector })\n      )(ParamType.from(\"bytes\"))\n    }\n\n    return matchesCondition\n  }\n\nconst calldataMatchesFunctionPermission =\n  (functionPermission: FunctionPermission) => (abiType?: ParamType) => {\n    // only supported at the top level or for bytes type params\n    if (abiType && abiType.type !== \"bytes\") {\n      throw new Error(\n        `Can only use \\`calldataMatches\\` on bytes type params, got: ${abiType.type}`\n      )\n    }\n\n    const { selector, condition } = coercePermission(functionPermission)\n    if (condition) {\n      if (\n        condition.operator !== Operator.Matches ||\n        condition.paramType !== ParameterType.Calldata\n      ) {\n        throw new Error(\n          `calldataMatches expects a function permission with an \\`Operator.matches\\`, \\`ParamType.Calldata\\` condition, got: \\`Operator.${\n            Operator[condition.operator]\n          }\\`, \\`ParamType.${ParameterType[condition.paramType]}\\``\n        )\n      }\n    }\n\n    const selectorCondition = bitmask({\n      mask: \"0xffffffff0000000000000000000000\",\n      value: selector,\n    })\n\n    return (\n      condition ? and(() => condition, selectorCondition) : selectorCondition\n    )(ParamType.from(\"bytes\"))\n  }\n\ntype CalldataMatches = {\n  /**\n   * Matches the parameters part of EVM call data against a structure of conditions.\n   *\n   * Skips over the first 4 bytes (function selector) and matches the ABI encoded parameters against the structure of conditions.\n   * Optionally, also checks the function selector.\n   *\n   * @param scoping The conditions structure over the decoded parameters\n   * @param abiTypes The parameter types defining how to decode bytes\n   * @param selector If set, checks that the 4 bytes function selector matches the given value\n   **/\n  <S extends TupleScopings<any>>(\n    scopings: S,\n    abiTypes: readonly AbiType[],\n    options?: {\n      selector?: `0x${string}`\n      etherWithinAllowance?: `0x${string}`\n      callWithinAllowance?: `0x${string}`\n    }\n  ): (abiType?: ParamType) => Condition\n\n  /**\n   * Matches EVM call data against a reference function permission.\n   *\n   * The 4 bytes function selector is checked against the function permission selector.\n   * Also, function permission condition is evaluated on the call data.\n   *\n   * @param functionPermission The reference function permission\n   **/\n  (functionPermission: FunctionPermission): (abiType?: ParamType) => Condition\n}\n\nexport const calldataMatches: CalldataMatches = <S extends TupleScopings<any>>(\n  scopingsOrFunctionPermission: S | FunctionPermission,\n  abiTypes?: readonly AbiType[],\n  options?: {\n    selector?: `0x${string}`\n    etherWithinAllowance?: `0x${string}`\n    callWithinAllowance?: `0x${string}`\n  }\n): ((abiType?: ParamType) => Condition) => {\n  return abiTypes\n    ? calldataMatchesScopings(\n        scopingsOrFunctionPermission as S,\n        abiTypes,\n        options\n      )\n    : calldataMatchesFunctionPermission(\n        scopingsOrFunctionPermission as unknown as FunctionPermission\n      )\n}\n\n/**\n * Matches standard ABI encoded bytes against a structure of conditions.\n *\n * @param scoping The conditions structure over the decoded parameters\n * @param abiTypes The parameter types defining how to decode bytes\n **/\nexport const abiEncodedMatches =\n  <S extends TupleScopings<any>>(scopings: S, abiTypes: AbiType[]) =>\n  (abiType?: ParamType) => {\n    const paramTypes = abiTypes.map((abiType) => ParamType.from(abiType))\n\n    // only supported at the top level or for bytes type params\n    if (abiType && abiType.type !== \"bytes\") {\n      throw new Error(\n        `Can only use \\`abiEncodedMatches\\` on bytes type params, got: ${abiType.type}`\n      )\n    }\n\n    // map scoping items to conditions\n    const conditions: (Condition | undefined)[] = paramTypes.map(\n      (type, index) => mapScoping(scopings[index], type)\n    )\n\n    // sanity checks\n    assertValidConditionsKeys(conditions, paramTypes)\n    assertCompatibleParamTypes(conditions, paramTypes)\n\n    return {\n      paramType: ParameterType.AbiEncoded,\n      operator: Operator.Matches,\n      children: conditions.map(\n        (condition, index) => condition || describeStructure(paramTypes[index])\n      ),\n    }\n  }\n\n/**\n * Maps a scoping (shortcut notation or condition function) to a condition.\n * @param scoping The scoping to map.\n * @param abiType The abi type of the parameter the scoping applies to.\n * @returns\n */\nexport function mapScoping(\n  scoping: Scoping<any> | undefined,\n  abiType: ParamType\n): Condition | undefined {\n  if (scoping === undefined) {\n    return undefined\n  }\n\n  let conditionFunction: ConditionFunction<any>\n\n  if (typeof scoping === \"function\") {\n    // scoping is already a condition function\n    conditionFunction = scoping\n  } else if (\n    typeof scoping === \"boolean\" ||\n    typeof scoping === \"string\" ||\n    typeof scoping === \"number\" ||\n    Array.isArray(scoping) ||\n    isBigNumberish(scoping)\n  ) {\n    // placeholders, primitive values, and arrays default to eq condition\n    conditionFunction = eq(scoping)\n  } else {\n    // object values default to matches condition\n    conditionFunction = matches(scoping)\n  }\n\n  return conditionFunction(abiType)\n}\n\nconst assertValidConditionsLength = (\n  conditions: (Condition | undefined)[],\n  typeOrTypes: ParamType | ParamType[]\n) => {\n  let expectedLength: number\n  if (Array.isArray(typeOrTypes)) {\n    expectedLength = typeOrTypes.length\n  } else if (typeOrTypes.baseType === \"tuple\" && typeOrTypes.components) {\n    expectedLength = typeOrTypes.components.length\n  } else if (typeOrTypes.baseType === \"array\") {\n    expectedLength = typeOrTypes.arrayLength || -1\n  } else {\n    throw new Error(\n      `Can only use \\`matches\\` on tuple or array type params, got: \\`${typeOrTypes.format(\n        \"sighash\"\n      )}\\``\n    )\n  }\n\n  if (expectedLength <= 0) return\n\n  if (conditions.length > expectedLength) {\n    throw new Error(\n      `The conditions structure has too many elements (expected length: ${expectedLength}, conditions length: ${conditions.length})`\n    )\n  }\n}\n\nconst assertValidConditionsKeys = (\n  structure: TupleScopings<any> | StructScoping<any>,\n  typeOrTypes: ParamType | ParamType[]\n) => {\n  if (Array.isArray(structure)) return\n  if (!Array.isArray(typeOrTypes) && typeOrTypes.baseType !== \"tuple\") return\n\n  const types = Array.isArray(typeOrTypes)\n    ? typeOrTypes\n    : typeOrTypes.components!\n\n  const unusedStructureKeys = arrayDiff(\n    Object.keys(structure),\n    types.map((type) => type.name)\n  )\n\n  if (unusedStructureKeys.length > 0) {\n    throw new Error(\n      `The conditions structure has unknown keys: ${unusedStructureKeys.join(\n        \", \"\n      )}`\n    )\n  }\n}\n\nconst assertCompatibleParamTypes = (\n  conditions: (Condition | undefined)[],\n  typeOrTypes: ParamType | ParamType[]\n) => {\n  conditions.forEach((condition, index) => {\n    if (!condition) return\n    let type: ParamType\n\n    if (Array.isArray(typeOrTypes)) {\n      type = typeOrTypes[index]\n    } else if (typeOrTypes.baseType === \"tuple\" && typeOrTypes.components) {\n      type = typeOrTypes.components[index]\n    } else if (typeOrTypes.baseType === \"array\" && typeOrTypes.arrayChildren) {\n      type = typeOrTypes.arrayChildren\n    } else {\n      throw new Error(\n        `Can only use \\`matches\\` on tuple or array type params, got: \\`${typeOrTypes.format(\n          \"sighash\"\n        )}\\``\n      )\n    }\n\n    const expectedType = parameterType(type)\n    const scopedType = checkScopedType(condition)\n\n    if (scopedType === expectedType) return\n\n    // allow dynamic type values to be interpreted as calldata or abi encoded\n    if (\n      expectedType === ParameterType.Dynamic &&\n      (scopedType === ParameterType.Calldata ||\n        scopedType === ParameterType.AbiEncoded)\n    ) {\n      return\n    }\n\n    const fieldReference = type.name ? `'${type.name}'` : `at index ${index}`\n    throw new Error(\n      `Condition for field ${fieldReference} has wrong paramType \\`${ParameterType[scopedType]}\\` (expected: \\`${ParameterType[expectedType]}\\`)`\n    )\n  })\n}\n\n/**\n * Returns `condition.paramType` if it is not `ParameterType.None`, otherwise returns the scoped param type of its children, if any.\n * Throws if the children have mixed scoped param types.\n * @param condition The condition to get the scoped param type of.\n * @returns the `ParameterType` the condition is applied to.\n */\nconst checkScopedType = (condition: Condition): ParameterType => {\n  if (condition.paramType === ParameterType.None) {\n    if (!condition.children || condition.children.length === 0) {\n      // e.g.: Operator.EtherWithinAllowance / Operator.CallWithinAllowance\n      return ParameterType.None\n    }\n\n    const [first, ...rest] = condition.children\n    const result = checkScopedType(first)\n\n    // assert that all following children have compatible types\n    rest.forEach((child) => {\n      const childType = checkScopedType(child)\n      checkParameterTypeCompatibility(result, childType)\n    })\n\n    return result\n  }\n\n  return condition.paramType\n}\n\nconst arrayDiff = (a: string[], b: string[]) => {\n  const set = new Set(b)\n  return a.filter((x) => !set.has(x))\n}\n\nfunction isBigNumberish(value: any): value is BigNumberish {\n  return (\n    (typeof value === \"number\" && value % 1 === 0) ||\n    typeof value === \"bigint\" ||\n    (typeof value === \"string\" && !!value.match(/^-?[0-9]+$/)) ||\n    isHexString(value)\n  )\n}\n","import { ParamType } from \"ethers\"\nimport { Condition, Operator, ParameterType } from \"../../../types\"\n\nimport { mapScoping } from \"./matches\"\n\nimport { ArrayElement, ConditionFunction, Scoping } from \"../types\"\n\n/**\n * Passes if every element of the array matches the given condition.\n * @param elementScoping The condition on the array elements\n */\nexport const every =\n  <S extends Scoping<ArrayElement<T>>, T extends any[]>(\n    elementScoping: S\n  ): ConditionFunction<T> =>\n  (abiType: ParamType) => {\n    if (abiType.baseType !== \"array\") {\n      throw new Error(\"every() can only be used on array types\")\n    }\n    if (elementScoping === undefined) {\n      throw new Error(\"every() element condition must not be undefined\")\n    }\n    return {\n      paramType: ParameterType.Array,\n      operator: Operator.ArrayEvery,\n      children: [\n        mapScoping(elementScoping, abiType.arrayChildren!) as Condition, // cast is safe because of earlier elementScoping check\n      ],\n    }\n  }\n","import { BigNumberish, BytesLike, getAddress, hexlify, ParamType } from \"ethers\"\nimport { Operator, ParameterType } from \"../../../types\"\n\nimport { ConditionFunction } from \"../types\"\n\nconst AVATAR_IS_OWNER_OF_ERC_721_ADDRESS =\n  \"0x91B1bd7BCC5E623d5CE76b0152253499a9C819d1\"\n\n/**\n * Asserts that the value is scope represents an ERC721 token ID owned by the avatar.\n * Assumes that the call target is the ERC721 contract.\n */\nexport const avatarIsOwnerOfErc721: ConditionFunction<BigNumberish> = (\n  abiType: ParamType\n) => {\n  if (abiType.type !== \"uint256\") {\n    throw new Error(\n      \"`avatarIsOwnerOfErc721` is only supported for uint256 params\"\n    )\n  }\n  return {\n    paramType: ParameterType.Static,\n    operator: Operator.Custom,\n    compValue: encodeCustomCompValue(AVATAR_IS_OWNER_OF_ERC_721_ADDRESS),\n  }\n}\n\nconst encodeCustomCompValue = (\n  customConditionAddress: `0x${string}`,\n  extra: BytesLike = \"0x\"\n) => {\n  const extraHex = hexlify(extra).slice(2)\n  if (extraHex.length > 24) {\n    // 12 bytes\n    throw new Error(\"Extra data is too long\")\n  }\n  return (getAddress(customConditionAddress).toLowerCase() +\n    extraHex.padEnd(24, \"0\")) as `0x${string}`\n}\n","import { ParamType } from \"ethers\"\nimport { Operator } from \"../../../types\"\n\nimport { describeStructure } from \"./helpers/describeStructure\"\nimport { parameterType } from \"./helpers/parameterType\"\n\n/**\n * Allows any value to pass\n */\nexport const pass = (abiType: ParamType) => {\n  const type = ParamType.from(abiType)\n  const structure = describeStructure(type)\n  return {\n    paramType: parameterType(type),\n    operator: Operator.Pass,\n    children: structure.children,\n  }\n}\n","export { withinAllowance } from \"./allowance\"\nexport { every } from \"./array\"\nexport { and, or } from \"./branching\"\nexport { avatar, bitmask, eq, gt, gte, lt, lte } from \"./comparison\"\nexport { abiEncodedMatches, calldataMatches, matches } from \"./matches\"\nexport { avatarIsOwnerOfErc721 } from \"./custom\"\nexport { pass } from \"./pass\"\n","import { BytesLike } from \"ethers\"\nimport { Condition } from \"../../types\"\n\nimport { ExecutionFlags, Permission } from \"../../permission\"\n\nimport { ConditionFunction } from \"./types\"\n\ntype UntargetedFunctionPermission = (\n  | { selector: `0x${string}` }\n  | { signature: string }\n) & {\n  condition?: Condition | ConditionFunction<BytesLike>\n} & ExecutionFlags\ntype UntargetedPermission = ExecutionFlags | UntargetedFunctionPermission\n\nexport const forAll = (\n  targetAddresses: readonly `0x${string}`[],\n  allow: UntargetedPermission | UntargetedPermission[]\n): Permission[] => {\n  const allowArray = Array.isArray(allow) ? allow : [allow]\n  return targetAddresses.flatMap((targetAddress) =>\n    allowArray.map((allow) => ({ ...allow, targetAddress }))\n  )\n}\n","import { Clearance, Function, Target } from \"../types\"\n\nimport { checkRootConditionIntegrity } from \"../condition/conditionIntegrity\"\n\nexport const targetIntegrity = (targets: Target[]): void => {\n  const uniqueAddresses = new Set(\n    targets.map((target) => target.address.toLowerCase())\n  )\n  if (uniqueAddresses.size < targets.length) {\n    throw new Error(\"Duplicate target addresses\")\n  }\n\n  targets.forEach(targetEntry)\n}\n\nconst targetEntry = (target: Target): void => {\n  if (\n    target.clearance === Clearance.Function &&\n    target.functions.length === 0\n  ) {\n    throw new Error(\n      `Function-cleared targets must have at least one function (target in violation: ${target.address})`\n    )\n  }\n\n  if (target.clearance !== Clearance.Function && target.functions.length > 0) {\n    throw new Error(\n      `A target with functions must be function-cleared (target in violation: ${target.address})`\n    )\n  }\n\n  const uniqueFunctionSelectors = new Set(\n    target.functions.map((func) => func.selector.toLowerCase())\n  )\n  if (uniqueFunctionSelectors.size < target.functions.length) {\n    throw new Error(`Duplicate functions in target ${target.address}`)\n  }\n\n  target.functions.forEach(functionEntry)\n}\n\nconst functionEntry = (func: Function): void => {\n  if (func.wildcarded && func.condition) {\n    throw new Error(\n      `Wildcarded functions cannot have conditions (function in violation: ${func.selector})`\n    )\n  }\n\n  if (!func.wildcarded && !func.condition) {\n    throw new Error(\n      `Non-wildcarded functions must have conditions (function in violation: ${func.selector})`\n    )\n  }\n\n  if (func.condition) {\n    checkRootConditionIntegrity(func.condition)\n  }\n}\n","import { Condition, Operator, ParameterType } from \"../types\"\n\nexport interface ConditionFlat {\n  parent: number\n  paramType: ParameterType\n  operator: Operator\n  compValue?: string\n}\n\n/**\n * Flattens a condition with nested children conditions into a breadth-first, flat array of conditions with parent index references.\n */\nexport const flattenCondition = (root: Condition): ConditionFlat[] => {\n  const result: ConditionFlat[] = []\n  const queue = [{ condition: root, parent: 0 }]\n\n  while (queue.length > 0) {\n    const {\n      condition: { children, ...conditionFlat },\n      parent,\n    } = queue.shift()!\n\n    result.push({ ...conditionFlat, parent })\n    const index = result.length - 1\n\n    if (children) {\n      for (const child of children) {\n        queue.push({ condition: child, parent: index })\n      }\n    }\n  }\n\n  return result\n}\n","import { createHash } from \"crypto\"\nimport {\n  BytesLike,\n  concat,\n  getCreate2Address,\n  dataLength,\n  keccak256,\n  toBeHex,\n} from \"ethers\"\nimport { Condition, Operator, ParameterType } from \"../types\"\n\nimport { abiEncode } from \"../abiEncode\"\n\nimport { flattenCondition, ConditionFlat } from \"./flattenCondition\"\n\nconst ERC2470_SINGLETON_FACTORY_ADDRESS =\n  \"0xce0042b868300000d44a59004da54a005ffdcf9f\"\nconst ZERO_SALT =\n  \"0x0000000000000000000000000000000000000000000000000000000000000000\"\n\nexport function conditionHash(condition: Condition) {\n  return (\n    \"0x\" + createHash(\"sha256\").update(rawConditionId(condition)).digest(\"hex\")\n  )\n}\n\nexport const conditionId = (condition: Condition) => {\n  const conditions = flattenCondition(condition)\n  return concat(\n    conditions.flatMap((condition) => [\n      packCondition(condition),\n      condition.compValue || \"0x\",\n    ])\n  )\n}\n\nexport function rawConditionId(condition: Condition) {\n  const normalize = (c: Condition): Condition => ({\n    paramType: c.paramType,\n    operator: c.operator,\n    compValue: c.compValue || \"0x\",\n    children: (c.children || []).map(normalize),\n  })\n\n  return JSON.stringify(normalize(condition))\n}\n\n/**\n * Calculates the create2 storage address of the condition.\n */\nexport const conditionAddress = (condition: Condition) => {\n  const conditions = flattenCondition(condition)\n  removeExtraneousOffsets(conditions)\n\n  const packed = concat([\n    ...conditions.map((condition) => packCondition(condition)),\n    ...conditions.map((condition) => packCompValue(condition)),\n  ])\n\n  const initCode = initCodeFor(packed)\n\n  return getCreate2Address(\n    ERC2470_SINGLETON_FACTORY_ADDRESS,\n    ZERO_SALT,\n    keccak256(initCode)\n  ).toLowerCase()\n}\n\n// 8    bits -> parent\n// 3    bits -> param type\n// 5    bits -> operator\nconst offsetParent = 8\nconst offsetParamType = 5\nconst offsetOperator = 0\n\nconst packCondition = (condition: ConditionFlat) => {\n  return toBeHex(\n    (condition.parent << offsetParent) |\n      (condition.paramType << offsetParamType) |\n      (condition.operator << offsetOperator),\n    condition.parent >= 256 ? undefined : 2\n  )\n}\n\nconst packCompValue = (condition: ConditionFlat) => {\n  if (!hasCompValue(condition.operator)) return \"0x\"\n  if (!condition.compValue) {\n    throw new Error(\n      `compValue is required for operator ${Operator[condition.operator]}`\n    )\n  }\n\n  return condition.operator === Operator.EqualTo\n    ? keccak256(condition.compValue)\n    : abiEncode([\"bytes32\"], [condition.compValue])\n}\n\nconst removeExtraneousOffsets = (conditions: ConditionFlat[]) => {\n  for (let i = 0; i < conditions.length; i++) {\n    if (\n      conditions[i].compValue &&\n      conditions[i].operator == Operator.EqualTo &&\n      !isInline(conditions, i)\n    ) {\n      conditions[i].compValue = \"0x\" + conditions[i].compValue!.slice(66)\n    }\n  }\n}\n\nconst isInline = (conditions: ConditionFlat[], index: number) => {\n  const paramType = conditions[index].paramType\n  switch (paramType) {\n    case ParameterType.Static:\n      return true\n    case ParameterType.Tuple:\n      for (let j = index + 1; j < conditions.length; ++j) {\n        const parent = conditions[j].parent\n        if (parent < index) continue\n        if (parent > index) break\n        if (!isInline(conditions, j)) {\n          return false\n        }\n      }\n      return true\n    default:\n      return false\n  }\n}\n\nconst initCodeFor = (bytecode: BytesLike) =>\n  concat([\n    \"0x63\",\n    toBeHex(dataLength(bytecode) + 1, 4),\n    \"0x80600E6000396000F3\",\n    \"0x00\",\n    bytecode,\n  ])\n\nconst hasCompValue = (operator: Operator) => operator >= Operator.EqualTo\n","import { Condition, Operator, ParameterType } from \"../types\"\n\nexport type TypeTree = {\n  paramType: ParameterType\n  children: TypeTree[]\n}\n\nexport function typeTreeId(condition: Condition): string {\n  return JSON.stringify(createTypeTree(condition))\n  // return (\n  //   \"0x\" +\n  //   createHash(\"sha256\")\n  //     .update(JSON.stringify(createTypeTree(condition)))\n  //     .digest(\"hex\")\n  // )\n}\n\nexport function createTypeTree(condition: Condition): TypeTree | null {\n  const atLeastOne = (): Condition[] => {\n    if (!condition.children || condition.children.length == 0) {\n      throw new Error(\"Expected populated children array\")\n    }\n\n    return condition.children! as Condition[]\n  }\n\n  if (isLogical(condition)) {\n    const [child] = atLeastOne()\n    return createTypeTree(child)\n  }\n\n  if (isArray(condition)) {\n    const [child] = atLeastOne()\n    return {\n      paramType: condition.paramType,\n      children: [createTypeTree(child)!],\n    }\n  }\n\n  if (isComplex(condition)) {\n    const children = atLeastOne()\n\n    return {\n      paramType: condition.paramType,\n      children: children.map(createTypeTree).filter((t) => !!t),\n    }\n  }\n\n  if (isSimple(condition)) {\n    return {\n      paramType: condition.paramType,\n      children: [],\n    }\n  }\n\n  return null\n}\n\nexport function isLogical({ operator }: { operator: Operator }) {\n  return [Operator.And, Operator.Or].includes(operator)\n}\n\nexport function isComplex({ paramType }: { paramType: ParameterType }) {\n  return [\n    ParameterType.AbiEncoded,\n    ParameterType.Calldata,\n    ParameterType.Array,\n    ParameterType.Tuple,\n  ].includes(paramType)\n}\n\nexport function isSimple({ paramType }: { paramType: ParameterType }) {\n  return [ParameterType.Dynamic, ParameterType.Static].includes(paramType)\n}\n\nexport function isArray({ paramType }: { paramType: ParameterType }) {\n  return paramType == ParameterType.Array\n}\n","import { Condition, Operator } from \"../../types\"\nimport {\n  createTypeTree,\n  isArray,\n  isComplex,\n  isLogical,\n  TypeTree,\n  typeTreeId,\n} from \"../typeTree\"\n\nexport function padToMatchTypeTree(condition: Condition): Condition {\n  /*\n   * This function is to be used from within normalizeCondition we operate\n   * under the assumption that lower levels were recursively normalized thus we\n   * only really wanna kick off the normalization for Logical or Array nodes\n   */\n  if (!isLogical(condition) && !isArray(condition)) {\n    return condition\n  }\n\n  const isPaddeable = (c: Condition) => isLogical(c) || isComplex(c)\n\n  const typeTreeIds = new Set(\n    (condition.children || [])\n      .filter(isPaddeable)\n      .map((child) => typeTreeId(child))\n  )\n\n  // All paddeable children already match\n  if (typeTreeIds.size <= 1) {\n    return condition\n  }\n\n  /*\n   *\n   * Apply all nodes onto eachother, cumulatively\n   *\n   * Since type trees can vary in structure at different depths, no single tree\n   * is always \"longest\" everywhere. Tree A might have more nodes in one subtree\n   * while Tree B has more in another. Padding each child with the structure\n   * from all others, we ensure uniform structure across all branches, because\n   * padding is cumulative\n   */\n  const nextChildren = [...condition.children!]\n  for (let i = 0; i < condition.children!.length; i++) {\n    if (!isPaddeable(nextChildren[i])) continue\n\n    for (let j = 0; j < nextChildren.length; j++) {\n      if (j == i || !isPaddeable(nextChildren[j])) continue\n\n      nextChildren[i] = extendWithPassNodes(\n        nextChildren[i],\n        createTypeTree(nextChildren[j])!\n      )\n    }\n  }\n\n  return {\n    ...condition,\n    children: nextChildren,\n  }\n}\n\n/*\n * Pads a `condition` with Pass nodes, such that it structurally matches a typeTree\n *\n * Assumptions:\n * - `condition` and `typeTree` are structurally compatible (not checked here).\n * - Either may be a subset of the other.\n * - If `condition` is missing branches that exist in `typeTree`, they are added.\n * - If `condition` is wider (has extra nodes), they are preserved — nothing is removed.\n *\n */\nfunction extendWithPassNodes(\n  condition: Condition | undefined | null,\n  typeTree: TypeTree\n): Condition {\n  if (!condition) {\n    condition = {\n      operator: Operator.Pass,\n      paramType: typeTree.paramType,\n    }\n  }\n\n  if (isLogical(condition)) {\n    return {\n      ...condition,\n      children: condition.children!.map((child) =>\n        extendWithPassNodes(child, typeTree)\n      ),\n    }\n  }\n\n  if (isComplex(condition)) {\n    const children = (condition.children || []) as Condition[]\n\n    /*\n     * Merge the padded children with the original children array.\n     * - If condition has fewer children than typeTree: extends with padded nodes\n     * - If condition has more children than typeTree: preserves extra nodes at the end\n     * - Overlapping positions: recursively pad existing nodes with typeTree structure\n     */\n    return {\n      ...condition,\n      children: mergeArrays(\n        children,\n        typeTree.children.map((childTypeTree, index) =>\n          extendWithPassNodes(children[index], childTypeTree)\n        )\n      ),\n    }\n  }\n\n  return condition\n}\n\nfunction mergeArrays<T>(a: T[], b: T[]): T[] {\n  if (a.length <= b.length) return b\n\n  return [...b, ...a.slice(b.length)]\n}\n","import { Condition, Operator, ParameterType } from \"../../types\"\n\nimport { conditionId } from \"../conditionId\"\n\n/** push OR conditions as far down the tree as possible without changing semantics */\nexport function pushDownOr(\n  condition: Condition,\n  normalize: (c: Condition) => Condition = (c) => c\n): Condition {\n  if (condition.operator !== Operator.Or) {\n    return condition\n  }\n\n  invariant(!!condition.children?.length && condition.children.length > 1)\n\n  const children = condition.children!\n\n  // bail on mixed param types\n  if (new Set(children.map((c) => c.paramType)).size !== 1) {\n    return condition\n  }\n\n  // does not support Array\n  if (children.some(({ paramType }) => paramType == ParameterType.Array)) {\n    return condition\n  }\n\n  const isAnd = children.every(({ operator: o }) => o === Operator.And)\n  const isMatches = children.every(({ operator: o }) => o === Operator.Matches)\n\n  // only support every operator either And or Matches. Bail on mix or mismatch\n  if (!isAnd && !isMatches) {\n    return condition\n  }\n\n  const [first] = children\n\n  const nextChildren = isMatches\n    ? matches(children as Condition[])\n    : and(children as Condition[])\n\n  return children === nextChildren\n    ? condition\n    : normalize({\n        ...first,\n        children: nextChildren,\n      })\n}\n\nfunction matches(children: Condition[]): Condition[] {\n  invariant(children.length > 1)\n\n  const hingeIndex = findMatchesHingeIndex(children)\n  if (hingeIndex === null) {\n    return children\n  }\n\n  const [first] = children\n\n  return first.children!.map((child, i) =>\n    i !== hingeIndex\n      ? child\n      : {\n          paramType: ParameterType.None,\n          operator: Operator.Or,\n          children: children.map((c) => c.children![hingeIndex]),\n        }\n  )\n}\n\nfunction and(children: Condition[]): Condition[] {\n  invariant(children.length > 1)\n\n  const hingeIndices = findAndHingeIndices(children)\n  if (!hingeIndices) {\n    return children\n  }\n\n  const [first] = children\n  const [hingeIndex] = hingeIndices\n\n  return first.children!.map((child, i) =>\n    i !== hingeIndex\n      ? child\n      : {\n          paramType: ParameterType.None,\n          operator: Operator.Or,\n          children: children.map(\n            (child, j) => child.children![hingeIndices[j]]\n          ),\n        }\n  )\n}\n\n/**\n * Finds the single position (hinge) where all MATCHES conditions differ.\n *\n * MATCHES operators use positional semantics - each child at position i must be\n * compared with the child at the same position i in other conditions. This is\n * because MATCHES represents structural pattern matching where order and position\n * are significant.\n *\n * The function enforces the \"single hinge principle\": exactly one position must\n * differ across all conditions for the OR to be pushed down. If differences\n * exist at multiple positions, the transformation cannot proceed.\n *\n * @param conditions Array of MATCHES conditions to analyze\n * @returns The index of the single differing position, or null if:\n *          - Multiple positions differ\n *          - No differences found\n *          - Length mismatches exist\n *\n * @example\n * MATCHES(1, 2, 3) and MATCHES(1, X, 3) -> returns 1 (middle position)\n * MATCHES(1, 2) and MATCHES(X, Y) -> returns null (multiple differences)\n */\nfunction findMatchesHingeIndex(conditions: readonly Condition[]) {\n  invariant(conditions.length > 1)\n  const [first, ...others] = conditions\n  invariant(!!first.children && first.children!.length > 0)\n  const left = first.children!\n  for (const other of others) {\n    invariant(!!other.children && other.children!.length > 0)\n  }\n\n  let hingeIndex: number | null = null\n\n  for (const other of others) {\n    const right = other.children!\n    const length = Math.max(left.length, right.length)\n\n    for (let i = 0; i < length; i++) {\n      if (conditionsEqual(left[i], right[i])) continue\n\n      if (hingeIndex === null) {\n        hingeIndex = i\n      }\n\n      if (hingeIndex !== i) {\n        return null\n      }\n    }\n  }\n\n  return hingeIndex\n}\n\n/**\n * Finds the positions (hinges) where AND conditions differ using set-based comparison.\n *\n * AND operators use set-based semantics - elements can appear in any order within\n * each condition since AND is commutative (A ∧ B ≡ B ∧ A). This function compares\n * conditions by their content (condition IDs) rather than by position.\n *\n * The function enforces the \"single hinge principle\": exactly one element must\n * differ across all conditions for the OR to be pushed down. Unlike MATCHES,\n * the differing elements may appear at different positions in each condition.\n *\n * @param conditions Array of AND conditions to analyze\n * @returns Array of indices where each index represents the position of the\n *          unique element in that condition, or null if:\n *          - Multiple elements differ in any condition\n *          - No common elements exist across conditions\n *\n * @example\n * AND(A, B, C) and AND(C, A, X) -> returns [1, 2] (B at pos 1, X at pos 2)\n * AND(A, B, C) and AND(A, Y, Z) -> returns null (multiple differences)\n * AND(A, B) and AND(X, Y) -> returns null (no common element)\n *\n */\nfunction findAndHingeIndices(conditions: Condition[]) {\n  invariant(conditions.length > 1)\n\n  // Step 1: Extract children IDs from each condition\n  const allChildrenIds = conditions.map((c) => c.children!.map(conditionId))\n  const allChildrenIdSets = allChildrenIds.map((ids) => new Set(ids))\n\n  // Step 2: Find the intersection (common children IDs)\n  const [firstSet, ...restSets] = allChildrenIdSets\n  const commonChildrenIds = new Set(\n    Array.from(firstSet).filter((id) => restSets.every((set) => set.has(id)))\n  )\n\n  // Step 3: Compute unique IDs for each condition\n  const uniqueChildrenIds = allChildrenIds.map((ids) =>\n    ids.filter((id) => !commonChildrenIds.has(id))\n  )\n\n  // Step 4: Validate that each condition has at most one unique ID\n  if (!uniqueChildrenIds.every((ids) => ids.length === 1)) return null\n\n  // Step 5: Map the unique IDs back to their original index, or -1 if none\n  return uniqueChildrenIds.map((unique, i) =>\n    unique.length === 0 ? -1 : allChildrenIds[i].indexOf(unique[0])\n  )\n}\n\nconst conditionsEqual = (a: Condition | undefined, b: Condition | undefined) =>\n  (!a || conditionId(a)) === (!b || conditionId(b))\n\nfunction invariant(c: boolean) {\n  if (!c) throw new Error(\"Invariant\")\n}\n","import { Condition, Operator, ParameterType } from \"../../types\"\n\nimport { conditionId, rawConditionId } from \"../conditionId\"\nimport { padToMatchTypeTree } from \"./padToMatchTypeTree\"\nimport { pushDownOr } from \"./pushDownOr\"\n\n/**\n * Normalizes a condition by transforming its structure without altering its semantics.\n * The goal is to minimize tree size and produce a canonical (normal) form, so that\n * semantically equivalent conditions are structurally identical.\n *\n * This normalization enables efficient condition equality checks and supports globally\n * deduplicated storage. In particular, the Roles contract stores conditions as bytecode\n * at addresses derived from hashing the condition data — so structurally consistent\n * representations help avoid redundant storage.\n */\nexport function normalizeCondition(condition: Condition): Condition {\n  let result: Condition = {\n    ...condition,\n    children: condition.children?.map((child) => normalizeCondition(child)),\n  }\n\n  result = cleanEmptyFields(result) // Remove undefined fields\n  result = prunePassNodes(result) // Trim trailing Pass nodes\n  result = padToMatchTypeTree(result) // Ensure TypeTree compatibility\n\n  result = flattenNestedBranches(result) // Collapse nested AND/OR\n  result = dedupeChildren(result) // Remove duplicate branches\n  result = unwrapSingleChild(result) // Remove single-child Logical nodes\n\n  result = pushDownOr(result, normalizeCondition)\n  result = sortBranchesCanonical(result) // Establish canonical ordering\n\n  return result\n}\n\n/** Removes trailing Pass nodes from Matches on Calldata, AbiEncoded, and dynamic tuples (as long as the tuple stays marked dynamic) */\nconst prunePassNodes = (condition: Condition): Condition => {\n  if (!condition.children) return condition\n  if (condition.operator !== Operator.Matches) return condition\n\n  const isDynamicTuple =\n    condition.paramType === ParameterType.Tuple && isDynamicParamType(condition)\n\n  // We must not apply this to static tuples since removing Static Pass nodes would cause word shifts in the encoding.\n  const canPrune =\n    condition.paramType === ParameterType.Calldata ||\n    condition.paramType === ParameterType.AbiEncoded ||\n    isDynamicTuple\n\n  if (!canPrune) return condition\n\n  const isGlobalAllowance = (child: Condition) =>\n    child.operator === Operator.EtherWithinAllowance ||\n    child.operator === Operator.CallWithinAllowance\n\n  // keep all children nodes with ParameterType.None\n  // (EtherWithinAllowance, CallWithinAllowance conditions appear as children of Calldata.Matches)\n  const tailChildren = condition.children.filter(isGlobalAllowance)\n  const prunableChildren = condition.children.filter(\n    (child) => !isGlobalAllowance(child)\n  )\n\n  // Start from the end and prune all trailing Pass nodes.\n  // Always keep the first child, even if it is a Pass, because children must not be empty.\n  // For tuples keep all children up to the first dynamic child.\n  let keepChildrenUntil = 0\n  if (isDynamicTuple) {\n    keepChildrenUntil = prunableChildren.findIndex(isDynamicParamType)\n  }\n  let prunedChildren: Condition[] = prunableChildren.slice(\n    0,\n    keepChildrenUntil + 1\n  )\n  for (let i = prunableChildren.length - 1; i > keepChildrenUntil; i--) {\n    const child = prunableChildren[i]\n    if (child.operator !== Operator.Pass) {\n      prunedChildren = prunableChildren.slice(0, i + 1)\n      break\n    }\n  }\n\n  condition.children = [...prunedChildren, ...tailChildren]\n  return condition\n}\n\n/** flatten nested AND/OR conditions */\nconst flattenNestedBranches = (condition: Condition): Condition => {\n  if (\n    condition.operator === Operator.And ||\n    condition.operator === Operator.Or\n  ) {\n    if (!condition.children) return condition\n\n    const flattenedChildren = condition.children.flatMap((child) =>\n      child.operator === condition.operator ? child.children || [] : [child]\n    )\n    condition.children = flattenedChildren\n  }\n\n  return condition\n}\n\n/** remove duplicate child branches in AND/OR */\nconst dedupeChildren = (condition: Condition): Condition => {\n  if (\n    condition.operator === Operator.And ||\n    condition.operator === Operator.Or\n  ) {\n    const seen = new Set<string>()\n    const uniqueChildren = condition.children?.filter((child) => {\n      const id = rawConditionId(child)\n      if (seen.has(id)) return false\n\n      seen.add(id)\n      return true\n    })\n\n    condition.children = uniqueChildren\n  }\n\n  return condition\n}\n\n/** remove AND/OR wrapping if they have only a single child */\nconst unwrapSingleChild = (condition: Condition): Condition => {\n  if (\n    condition.operator === Operator.And ||\n    condition.operator === Operator.Or\n  ) {\n    return condition.children?.length === 1 ? condition.children[0] : condition\n  }\n\n  return condition\n}\n\n/** enforce a canonical order of AND/OR branches */\nconst sortBranchesCanonical = (condition: Condition): Condition => {\n  if (\n    condition.operator === Operator.And ||\n    condition.operator === Operator.Or\n  ) {\n    if (!condition.children) return condition\n\n    const sorted = condition.children\n      .map((c) => ({\n        condition: c,\n        id: conditionId(c),\n      }))\n      .sort((a, b) => (BigInt(a.id) < BigInt(b.id) ? -1 : 1))\n      .map(({ condition }) => condition)\n\n    // in case of mixed-type children (dynamic & calldata/abiEncoded), those with children must come first\n    const front = sorted.filter(\n      (child) =>\n        child.paramType === ParameterType.Calldata ||\n        child.paramType === ParameterType.AbiEncoded\n    )\n    const back = sorted.filter(\n      (child) =>\n        !(\n          child.paramType === ParameterType.Calldata ||\n          child.paramType === ParameterType.AbiEncoded\n        )\n    )\n    return {\n      ...condition,\n      children: [...front, ...back],\n    }\n  }\n\n  return condition\n}\n\nconst cleanEmptyFields = (condition: Condition): Condition => {\n  if (\"children\" in condition && !condition.children) delete condition.children\n  if (\"compValue\" in condition && !condition.compValue)\n    delete condition.compValue\n  return condition\n}\n\nconst isDynamicParamType = (condition: Condition): boolean => {\n  switch (condition.paramType) {\n    case ParameterType.Static:\n      return false\n    case ParameterType.Dynamic:\n    case ParameterType.Array:\n      return true\n    case ParameterType.Tuple:\n    case ParameterType.Calldata:\n    case ParameterType.AbiEncoded:\n    case ParameterType.None:\n      return condition.children?.some(isDynamicParamType) ?? false\n    default:\n      throw new Error(`Unknown paramType: ${condition.paramType}`)\n  }\n}\n","import { Condition, Operator } from \"../types\"\nimport { rawConditionId as conditionId } from \"./conditionId\"\n\n/**\n * Removes an independently satisfiable path from a condition.\n *\n * This function removes any condition fragment that could independently make the\n * original condition evaluate to true (satisfiable). It works with conditions that\n * have been normalized (where ORs may have been pushed down) or in their original form.\n *\n * Conceptually, if you think of a condition as a set of independent paths that\n * can satisfy it, this function removes one such path:\n * - For `A OR B`, removing A leaves B (removing an explicit path)\n * - For `AND(X, OR(Y, Z))`, removing `AND(X, Y)` leaves `AND(X, Z)`\n *   (removing a path that was pushed down during normalization)\n *\n * The \"single hinge\" principle:\n * - AND operators use set-based semantics: exactly one child must differ between\n *   condition and fragment, regardless of order. This supports commutative logic\n *   where AND(A, B) ≡ AND(B, A).\n * - MATCHES operators use positional semantics: exactly one position must differ\n *   between condition and fragment. Order matters for structural matching.\n *\n * @param condition The condition to subtract from\n * @param fragment The satisfiable path to remove\n * @returns The remainder after removing the path, or undefined if nothing remains\n * @returns The original condition if the fragment isn't a valid satisfiable path\n *\n * @example\n * - `subtract(OR(A, B, C), B)` → `OR(A, C)`\n * - `subtract(AND(X, OR(Y, Z)), AND(X, Y))` → `AND(X, Z)`\n * - `subtract(AND(A, B, C), AND(C, A, D))` → `AND(A, B, C)` (order-independent)\n */\nexport function subtractCondition(\n  condition: Condition,\n  fragment: Condition\n): Condition | undefined {\n  if (conditionId(condition) === conditionId(fragment)) {\n    return undefined\n  }\n\n  if (\n    condition.operator === Operator.Or &&\n    condition.children &&\n    fragment.operator === Operator.Or &&\n    fragment.children\n  ) {\n    return or_n_m(condition, fragment)\n  }\n\n  if (condition.operator === Operator.Or) {\n    return or_n_1(condition, fragment)\n  }\n\n  const canProceed =\n    (condition.operator == Operator.And ||\n      condition.operator == Operator.Matches) &&\n    condition.operator === fragment.operator &&\n    condition.paramType === fragment.paramType &&\n    matchingChildrenCount(condition, fragment)\n\n  if (!canProceed) {\n    return condition\n  }\n\n  if (condition.operator == Operator.And) {\n    return and(condition, fragment)\n  } else {\n    return matches(condition, fragment)\n  }\n}\n\n/**\n * Handles OR n:m subtraction.\n * Removes all fragment children from an OR condition if they exist.\n * - If all match: returns the remainder (or unwraps if 1 child remains).\n * - If not all fragment children are found: returns the original condition.\n */\nfunction or_n_m(condition: Condition, fragment: Condition) {\n  const conditionChildren = condition.children!\n  const fragmentChildren = fragment.children!\n\n  // Ensure all fragment children exist in condition\n  const conditionIds = new Set(conditionChildren.map(conditionId))\n  const allExist = fragmentChildren.every((child) =>\n    conditionIds.has(conditionId(child))\n  )\n  if (!allExist) return condition\n\n  // Filter out fragment children\n  const fragmentIds = new Set(fragmentChildren.map(conditionId))\n  const remaining = conditionChildren.filter(\n    (child) => !fragmentIds.has(conditionId(child))\n  )\n\n  // remove\n  if (remaining.length === 0) return undefined\n  // unwrap\n  if (remaining.length === 1) return remaining[0]\n  // filter\n  return { ...condition, children: remaining }\n}\n\nfunction or_n_1(condition: Condition, fragment: Condition) {\n  const nextChildren = condition\n    .children!.map((child) => subtractCondition(child, fragment))\n    .filter((t) => !!t)\n\n  // Fragment not in OR\n  if (shallowEquals(condition.children!, nextChildren)) return condition\n\n  // remove\n  if (nextChildren.length === 0) return undefined\n  // unwrap\n  if (nextChildren.length === 1) return nextChildren[0]\n  // filter\n  return { ...condition, children: nextChildren }\n}\n\nfunction and(condition: Condition, fragment: Condition) {\n  const children = condition.children!\n  const fragmentChildren = fragment.children!\n  invariant(children.length == fragmentChildren.length)\n\n  const cIds = children.map(conditionId)\n  const fIds = fragmentChildren.map(conditionId)\n\n  const conditionOnlyIds = cIds.filter((id) => !fIds.includes(id))\n  const fragmentOnlyIds = fIds.filter((id) => !cIds.includes(id))\n\n  // Single hinge principle: exactly one difference in each direction\n  if (conditionOnlyIds.length !== 1 || fragmentOnlyIds.length !== 1) {\n    return condition\n  }\n\n  const child = children.find(\n    (child) => conditionId(child) === conditionOnlyIds[0]\n  )!\n  const fragmentChild = fragmentChildren.find(\n    (child) => conditionId(child) === fragmentOnlyIds[0]\n  )!\n\n  const remainder = subtractCondition(child, fragmentChild)\n  if (!remainder || remainder === child) {\n    // If subtraction failed or didn't change anything, bail\n    return condition\n  }\n\n  return {\n    ...condition,\n    children: children.map((c) => (c === child ? remainder : c)),\n  }\n}\n\nfunction matches(condition: Condition, fragment: Condition) {\n  invariant(condition.operator === Operator.Matches)\n\n  let changes = 0\n  const newChildren = condition.children!.map((child, index) => {\n    if (changes > 1) return child\n\n    const fragmentChild = fragment.children![index]\n\n    if (conditionId(child) === conditionId(fragmentChild)) {\n      return child\n    }\n\n    changes++\n    const remainder = subtractCondition(child, fragmentChild)\n    // If couldn't subtract or would remove entirely, keep original\n    if (remainder === child || remainder === undefined) {\n      return child\n    } else {\n      return remainder\n    }\n  })\n\n  return changes == 1 ? { ...condition, children: newChildren } : condition\n}\n\nfunction shallowEquals<T>(a: readonly T[], b: readonly T[]): boolean {\n  return a.length === b.length && a.every((item, index) => item === b[index])\n}\n\nfunction matchingChildrenCount(a: Condition, b: Condition): boolean {\n  return (\n    Array.isArray(a.children) &&\n    Array.isArray(b.children) &&\n    a.children.length > 0 &&\n    a.children.length == b.children.length\n  )\n}\n\nfunction invariant(c: boolean) {\n  if (!c) {\n    throw new Error(\"Invariant\")\n  }\n}\n","import { ExecutionOptions } from \"../types\"\n\nimport { ExecutionFlags } from \"./types\"\n\nexport const executionFlagsToOptions = (\n  options: ExecutionFlags\n): ExecutionOptions => {\n  if (options.send && options.delegatecall) return ExecutionOptions.Both\n  if (options.delegatecall) return ExecutionOptions.DelegateCall\n  if (options.send) return ExecutionOptions.Send\n  return ExecutionOptions.None\n}\n","import { conditionAddress, normalizeCondition } from \"../condition\"\nimport { executionFlagsToOptions } from \"./executionFlagsToOptions\"\n\nimport {\n  PermissionCoerced,\n  FunctionPermissionCoerced,\n  TargetPermission,\n} from \"./types\"\n\nexport const targetId = (permission: PermissionCoerced) =>\n  \"selector\" in permission\n    ? `${permission.targetAddress.toLowerCase()}.${permission.selector}`\n    : `${permission.targetAddress.toLowerCase()}.*` // * will be always be sorted before any selector 0x...\n\nexport const permissionId = (permission: PermissionCoerced) => {\n  const cid =\n    \"condition\" in permission && permission.condition\n      ? conditionAddress(normalizeCondition(permission.condition))\n      : \"\"\n  return `${targetId(permission)}:${executionFlagsToOptions(permission)}:${cid}`\n}\n\nexport const isPermissionAllowed = (\n  permission: PermissionCoerced\n): permission is TargetPermission => {\n  return !(\"selector\" in permission) && !(\"signature\" in permission)\n}\n\nexport const isPermissionScoped = (\n  permission: PermissionCoerced\n): permission is FunctionPermissionCoerced => {\n  return \"selector\" in permission || \"signature\" in permission\n}\n\nexport const isPermissionWildcarded = (\n  permission: PermissionCoerced\n): permission is FunctionPermissionCoerced => {\n  return isPermissionScoped(permission) && !permission.condition\n}\n\nexport const isPermissionConditional = (\n  permission: PermissionCoerced\n): permission is FunctionPermissionCoerced => {\n  return isPermissionScoped(permission) && !!permission.condition\n}\n","import { Condition, Operator, ParameterType } from \"../types\"\n\nimport {\n  isPermissionAllowed,\n  isPermissionConditional,\n  isPermissionWildcarded,\n  targetId,\n} from \"./id\"\n\nimport { PermissionCoerced } from \"./types\"\n\n/**\n * Merges permission entries that target the same destination (targetAddress + selector)\n *\n * Merging Rules (when ExecutionOptions match):\n * ┌──────────────┬──────────────┬─────────────────────────────────────┐\n * │ Permission A │ Permission B │               Result                │\n * ├──────────────┼──────────────┼─────────────────────────────────────┤\n * │ Allowed      │ Allowed      │ Merged as duplicate                 │\n * │ Allowed      │ Scoped       │ Merged as Allowed (with warning)    │\n * │ Wildcarded   │ Wildcarded   │ Merged as duplicate                 │\n * │ Wildcarded   │ Conditional  │ Merged as Wildcarded (with warning) │\n * │ Conditional  │ Conditional  │ Merged as Conditional (children OR) │\n * └──────────────┴──────────────┴─────────────────────────────────────┘\n *\n * Note: Matching Permissions with different ExecutionOptions always throw an error\n *\n * Permission Types:\n * Allowed     -> Clearance.Target\n * Wildcarded  -> Clearance.Function AND wildcarded == true AND condition == undefined\n * Conditional -> Clearance.Function AND wildcarded == false AND condition == defined\n * Scoped      -> wilcarded or conditional\n *\n */\n\ntype Result = {\n  permissions: PermissionCoerced[]\n  violations: string[]\n  warnings: string[]\n}\n\nexport function mergePermissions(\n  permissions: readonly PermissionCoerced[]\n): Result {\n  const result = permissions.reduce(reduce, {\n    permissions: [],\n    warnings: [],\n    violations: [],\n  } as Result)\n\n  // if there are violations, don't output permissions or warnings\n  return result.violations.length > 0\n    ? { ...result, permissions: [], warnings: [] }\n    : result\n}\n\nconst reduce = (result: Result, permission: PermissionCoerced): Result => {\n  const match = result.permissions.find((match) =>\n    isPermissionAllowed(match) || isPermissionAllowed(permission)\n      ? match.targetAddress === permission.targetAddress\n      : targetId(match) === targetId(permission)\n  )\n  if (match) {\n    return {\n      permissions: result.permissions.map((entry) =>\n        entry == match ? mergeEntry(entry, permission) : entry\n      ),\n      warnings: [\n        ...result.warnings,\n        maybeMergeWarning(match, permission),\n      ].filter(Boolean) as string[],\n      violations: [\n        ...result.violations,\n        maybeMergeViolation(match, permission),\n      ].filter(Boolean) as string[],\n    }\n  }\n\n  return {\n    ...result,\n    permissions: [...result.permissions, permission],\n  }\n}\n\nconst mergeEntry = (p1: PermissionCoerced, p2: PermissionCoerced) => {\n  if (\n    \"condition\" in p1 &&\n    !!p1.condition &&\n    \"condition\" in p2 &&\n    !!p2.condition\n  ) {\n    return {\n      ...p1,\n      condition: mergeConditions(p1.condition, p2.condition),\n    }\n  }\n\n  return comparePermission(p1, p2) <= 0 ? p1 : p2\n}\n\nconst mergeConditions = (a: Condition, b: Condition): Condition | undefined => {\n  const aBranches = a.operator === Operator.Or ? a.children : [a]\n  const bBranches = b.operator === Operator.Or ? b.children : [b]\n\n  return {\n    paramType: ParameterType.None,\n    operator: Operator.Or,\n    children: [...(aBranches || []), ...(bBranches || [])],\n  }\n}\n\nconst comparePermission = (p1: PermissionCoerced, p2: PermissionCoerced) => {\n  if (isPermissionAllowed(p1) && isPermissionAllowed(p2)) return 0\n  if (isPermissionAllowed(p1) && isPermissionWildcarded(p2)) return -1\n  if (isPermissionAllowed(p1) && isPermissionConditional(p2)) return -1\n\n  if (isPermissionWildcarded(p1) && isPermissionAllowed(p2)) return 1\n  if (isPermissionWildcarded(p1) && isPermissionWildcarded(p2)) return 0\n  if (isPermissionWildcarded(p1) && isPermissionConditional(p2)) return -1\n\n  // if (isPermissionConditional(p1) && isPermissionAllowed(p2)) return 1\n  // if (isPermissionConditional(p1) && isPermissionWildcarded(p2)) return 1\n  if (isPermissionConditional(p1) && isPermissionConditional(p2)) return 0\n  return 1\n}\n\nconst maybeMergeWarning = (\n  p1: PermissionCoerced,\n  p2: PermissionCoerced\n): string | null => {\n  ;[p1, p2] = comparePermission(p1, p2) <= 0 ? [p1, p2] : [p2, p1]\n\n  if (isPermissionAllowed(p1) && isPermissionWildcarded(p2)) {\n    return `Target ${targetId(p1)} is fully allowed, and then wildcarded at function level ${targetId(p2)}. It will be fully allowed.`\n  }\n\n  if (isPermissionAllowed(p1) && isPermissionConditional(p2)) {\n    return `Target ${targetId(p1)} is fully allowed, and then allowed conditionally at function level ${targetId(p2)}. It will be fully allowed.`\n  }\n\n  if (isPermissionWildcarded(p1) && isPermissionConditional(p2)) {\n    return `Function ${targetId(p1)} is first wildcarded and then allowed conditionally. It will be wildcarded at function level.`\n  }\n\n  return null\n}\n\nconst maybeMergeViolation = (\n  p1: PermissionCoerced,\n  p2: PermissionCoerced\n): string | null => {\n  if (!matchesExecutionOptions(p1, p2)) {\n    return `The following functions appear multiple times and cannot be merged: ${targetId(p1)}, ${targetId(p2)}. This might be be due to different \\`send\\` and \\`delegatecall\\` flags in entries with the same target.`\n  }\n\n  return null\n}\n\nconst matchesExecutionOptions = (\n  p1: PermissionCoerced,\n  p2: PermissionCoerced\n): boolean => {\n  return (\n    Boolean(p1.send) === Boolean(p2.send) &&\n    Boolean(p1.delegatecall) === Boolean(p2.delegatecall)\n  )\n}\n","export const groupBy = <T, K extends keyof any>(\n  arr: readonly T[],\n  key: (i: T) => K\n) =>\n  arr.reduce(\n    (groups, item) => {\n      ;(groups[key(item)] ||= []).push(item)\n      return groups\n    },\n    {} as Record<K, T[]>\n  )\n","import {\n  Annotation,\n  Clearance,\n  ExecutionOptions,\n  Target,\n} from \"../types\"\n\nimport { groupBy } from \"../groupBy\"\nimport { normalizeCondition } from \"../condition\"\nimport { coercePermission } from \"./coercePermission\"\nimport { executionFlagsToOptions } from \"./executionFlagsToOptions\"\nimport { mergePermissions } from \"./mergePermissions\"\n\nimport { Permission, PermissionSet } from \"./types\"\n\n/**\n * Processes permissions returning the resulting list of allowed targets. Merges permission entries addressing the same function and performs sanity checks.\n * @param permissions to process\n * @returns The resulting list of allowed targets\n */\nexport const processPermissions = (\n  input: readonly (Permission | PermissionSet)[]\n): { targets: Target[]; annotations: Annotation[] } => {\n  const permissions = input.flat().map(coercePermission)\n\n  const {\n    permissions: mergedPermissions,\n    warnings,\n    violations,\n  } = mergePermissions(permissions)\n\n  throwViolations(violations)\n  showWarnings(warnings)\n\n  const permissionsAllowed = mergedPermissions.filter(\n    (entry) => !(\"selector\" in entry)\n  )\n  const permissionsScoped = mergedPermissions.filter(\n    (entry) => \"selector\" in entry\n  )\n\n  const targetsAllowed = permissionsAllowed.map((permission) => ({\n    address: permission.targetAddress.toLowerCase() as `0x${string}`,\n    clearance: Clearance.Target,\n    executionOptions: executionFlagsToOptions(permission),\n    functions: [],\n  }))\n\n  const targetsScoped = Object.entries(\n    groupBy(permissionsScoped, (entry) => entry.targetAddress)\n  ).map(([targetAddress, permissions]) => ({\n    address: targetAddress.toLowerCase() as `0x${string}`,\n    clearance: Clearance.Function,\n    executionOptions: ExecutionOptions.None,\n    functions: permissions.map(({ selector, condition, ...rest }) => ({\n      selector,\n      executionOptions: executionFlagsToOptions(rest),\n      wildcarded: !condition,\n      condition: condition && normalizeCondition(condition),\n    })),\n  }))\n\n  // collect all annotations\n  const annotations = input\n    .filter((p) => Array.isArray(p))\n    .map((permissionSet) => permissionSet.annotation)\n    .filter((annotation): annotation is Annotation => !!annotation)\n\n  return {\n    targets: [...targetsAllowed, ...targetsScoped],\n\n    // make annotations unique\n    annotations: annotations.filter(\n      (annotation, i) =>\n        annotations.findIndex((a) => a.uri === annotation.uri) === i\n    ),\n  }\n}\n\nfunction throwViolations(violations: string[]) {\n  if (violations.length) {\n    throw new Error(`Invalid Permissions:\\n` + violations.join(\"\\n\\t\"))\n  }\n}\n\nfunction showWarnings(warnings: string[]) {\n  for (const warning of warnings) {\n    console.warn(warning)\n  }\n}\n","import { Clearance, ExecutionOptions, Target } from \"../types\"\n\nimport { PermissionCoerced, TargetPermission } from \"./types\"\n\nexport const reconstructPermissions = (\n  targets: readonly Target[]\n): PermissionCoerced[] => {\n  return targets.flatMap((target) => {\n    if (target.clearance === Clearance.None) {\n      return [] as PermissionCoerced[]\n    }\n\n    if (target.clearance === Clearance.Target) {\n      return {\n        targetAddress: target.address,\n        send: allowsSend(target.executionOptions),\n        delegatecall: allowsDelegateCall(target.executionOptions),\n      } as TargetPermission\n    }\n\n    if (target.clearance === Clearance.Function) {\n      return target.functions.map((func) => ({\n        targetAddress: target.address,\n        selector: func.selector,\n        send: allowsSend(func.executionOptions),\n        delegatecall: allowsDelegateCall(func.executionOptions),\n        condition: !func.wildcarded ? func.condition : undefined,\n      }))\n    }\n\n    throw new Error(`Unknown clearance ${target.clearance}`)\n  })\n}\n\nconst allowsSend = (execOptions: ExecutionOptions) =>\n  execOptions === ExecutionOptions.Send || execOptions === ExecutionOptions.Both\n\nconst allowsDelegateCall = (execOptions: ExecutionOptions) =>\n  execOptions === ExecutionOptions.DelegateCall ||\n  execOptions === ExecutionOptions.Both\n","import { Function } from \"../types\"\n\nimport { normalizeCondition, subtractCondition } from \"../condition\"\n\n/**\n * Subtracts right function from left function, returning only what's in left but not in right.\n *\n * @param left - The function to subtract from\n * @param right - The function to subtract\n *\n * @returns A new function with only the permissions that are in left but not in right\n *\n * @note undefined is returned if nothing remains in left\n *\n */\nexport function subtractFunction(\n  left: Function,\n  right: Function\n): Function | undefined {\n  invariant(left.selector == right.selector)\n\n  // Both wildcarded: only execution options matter\n  if (left.wildcarded && right.wildcarded) {\n    return left.executionOptions === right.executionOptions ? undefined : left\n  }\n\n  // Left wildcarded, right conditional: left is more permissive\n  if (left.wildcarded && !right.wildcarded) {\n    return left\n  }\n\n  // Left conditional, right wildcarded: right covers everything\n  if (!left.wildcarded && right.wildcarded) {\n    return undefined\n  }\n\n  // Both must be conditional at this point\n  invariant(\n    !left.wildcarded &&\n      !right.wildcarded &&\n      !!left.condition &&\n      !!right.condition\n  )\n\n  // Different execution options: no overlap\n  if (left.executionOptions !== right.executionOptions) {\n    return left\n  }\n\n  // Subtract conditions\n  const condition = normalizeCondition(left.condition!)\n  const fragment = normalizeCondition(right.condition!)\n  const result = subtractCondition(condition, fragment)\n\n  return result !== undefined\n    ? {\n        ...left,\n        condition: normalizeCondition(result),\n      }\n    : undefined\n}\n\nfunction invariant(check: boolean) {\n  if (!check) throw new Error(\"Invariant\")\n}\n","import { Clearance, Target } from \"../types\"\nimport { subtractFunction } from \"./subtractFunction\"\n\n/**\n * Subtracts right target from left target, returning only what's in left but not in right.\n *\n * @param left - The target to subtract from\n * @param right - The target to subtract\n *\n * @returns A new target with only the permissions that are in left but not in right\n *\n * @note undefined is returned if nothing remains in left\n *\n */\nexport function subtractTarget(\n  left: Target,\n  right: Target\n): Target | undefined {\n  invariant(\n    left.address === right.address &&\n      (isTargetAllowed(left) || isTargetScoped(left)) &&\n      (isTargetAllowed(right) || isTargetScoped(right))\n  )\n\n  if (isTargetAllowed(left) && isTargetAllowed(right)) {\n    return left.executionOptions === right.executionOptions ? undefined : left\n  }\n\n  if (isTargetAllowed(left) && isTargetScoped(right)) {\n    return left\n  }\n\n  if (isTargetScoped(left) && isTargetAllowed(right)) {\n    return undefined\n  }\n\n  invariant(isTargetScoped(left) && isTargetScoped(right))\n\n  const nextFunctions = left.functions\n    .map((f) => ({\n      left: f,\n      right: right.functions.find(({ selector }) => f.selector === selector),\n    }))\n    /*\n     * if no match is found, return left\n     * otherwise return left - right\n     */\n    .map(({ left, right }) => (right ? subtractFunction(left, right) : left))\n    .filter((f) => !!f)\n\n  if (nextFunctions.length === 0) return undefined\n\n  return shallowEquals(left.functions, nextFunctions)\n    ? left\n    : {\n        ...left,\n        functions: nextFunctions,\n      }\n}\n\nfunction isTargetAllowed({ clearance }: { clearance: Clearance }): boolean {\n  return clearance == Clearance.Target\n}\n\nfunction isTargetScoped({ clearance }: { clearance: Clearance }): boolean {\n  return clearance == Clearance.Function\n}\n\nfunction shallowEquals<T>(a: readonly T[], b: readonly T[]): boolean {\n  return a.length === b.length && a.every((item, index) => item === b[index])\n}\n\nfunction invariant(condition: boolean): asserts condition {\n  if (!condition) {\n    throw new Error(\"Invariant\")\n  }\n}\n","import { Clearance, ExecutionOptions, Target } from \"../types\"\n\nimport { normalizeCondition, subtractCondition } from \"../condition\"\n\n/**\n * Checks if one Target includes (supersedes or equals) another Target.\n *\n * @param p1 - The potentially broader permission\n * @param p2 - The permission to check if included in p1\n * @returns true if p1 includes p2, false otherwise\n *\n */\nexport function targetIncludes(left: Target, right: Target): boolean {\n  if (!canSend(left) && canSend(right)) {\n    return false\n  }\n\n  if (!canDelegateCall(left) && canDelegateCall(right)) {\n    return false\n  }\n\n  if (isTargetAllowed(left)) {\n    return true\n  }\n\n  if (isTargetAllowed(right)) {\n    return false\n  }\n\n  // assert\n  if (!isTargetScoped(left) || !isTargetScoped(right)) {\n    throw new Error(\"Expected Both Scoped\")\n  }\n\n  return right.functions.every((rf) => {\n    const lf = left.functions.find((lf) => lf.selector == rf.selector)\n    if (!lf) return false\n\n    if (lf.wildcarded) {\n      return true\n    }\n\n    if (rf.wildcarded) {\n      return false\n    }\n\n    // assert\n    if (!lf.condition || !rf.condition) {\n      throw new Error(\"Expected Both Conditional\")\n    }\n\n    /*\n     * if we can subtract from the main condition, it means current\n     * permission is at least a top level variant, and at most\n     * matches the condition completely\n     */\n    const condition = normalizeCondition(lf.condition)\n    const fragment = normalizeCondition(rf.condition)\n    return subtractCondition(condition, fragment) !== condition\n  })\n}\n\nfunction canSend({ executionOptions }: { executionOptions: ExecutionOptions }) {\n  return (\n    executionOptions == ExecutionOptions.Send ||\n    executionOptions == ExecutionOptions.Both\n  )\n}\n\nfunction canDelegateCall({\n  executionOptions,\n}: {\n  executionOptions: ExecutionOptions\n}) {\n  return (\n    executionOptions == ExecutionOptions.DelegateCall ||\n    executionOptions == ExecutionOptions.Both\n  )\n}\n\nfunction isTargetAllowed({ clearance }: { clearance: Clearance }): boolean {\n  return clearance == Clearance.Target\n}\n\nfunction isTargetScoped({ clearance }: { clearance: Clearance }): boolean {\n  return clearance == Clearance.Function\n}\n","import { Target } from \"../types\"\n\nimport { subtractTarget } from \"../target/subtractTarget\"\nimport { targetIncludes } from \"../target/targetIncludes\"\n\nimport { mergePermissions } from \"./mergePermissions\"\nimport { processPermissions } from \"./processPermissions\"\nimport { reconstructPermissions } from \"./reconstructPermissions\"\n\nimport { PermissionCoerced } from \"./types\"\n\n/**\n * Filters and validates permission presets, returning two sets:\n * 1. Confirmed presets that are fully included onchain\n * 2. Remaining permissions that are not covered by any preset.\n */\nexport function validatePresets<\n  T extends { permissions: PermissionCoerced[] },\n>({\n  targets,\n  presets,\n}: {\n  targets: readonly Target[]\n  presets: readonly (T | null)[]\n}): {\n  presets: T[]\n  permissions: PermissionCoerced[]\n} {\n  for (const preset of presets) {\n    preset && sanityCheck(preset.permissions)\n  }\n\n  const confirmedPresets = presets.filter(\n    (preset) => !!preset && confirmPreset({ targets, preset })\n  ) as T[]\n  const confirmedPermissions = confirmedPresets.flatMap((p) => p.permissions)\n\n  sanityCheck(confirmedPermissions)\n  const { targets: targetsFromPresets } =\n    processPermissions(confirmedPermissions)\n\n  const subtractedTargets = targets\n    .map((target) => {\n      const targetFromPreset = targetsFromPresets.find(\n        ({ address }) => address == target.address\n      )\n\n      // if there's a target to subtract do it, otherwise\n      // return current\n      return targetFromPreset\n        ? subtractTarget(target, targetFromPreset)\n        : target\n    })\n    // undefined means the target was fully covered\n    .filter((t) => !!t)\n\n  return {\n    presets: confirmedPresets,\n    permissions: reconstructPermissions(subtractedTargets),\n  }\n}\n\n/**\n * Checks if all preset permissions are included in the given targets.\n *\n * @param targets - Current target permissions (from on-chain)\n * @param preset - Preset permissions to verify\n * @returns true if preset is fully covered by targets\n * @throws if preset permissions can't be merged\n */\nfunction confirmPreset({\n  targets,\n  preset,\n}: {\n  targets: readonly Target[]\n  preset: { permissions: PermissionCoerced[] }\n}): boolean {\n  const { targets: targetsFromPreset } = processPermissions(preset.permissions)\n\n  return targetsFromPreset.every((targetFromPreset) => {\n    const target = targets.find(\n      (target) => target.address === targetFromPreset.address\n    )\n\n    // was it found onchain?\n    if (!target) return false\n\n    // is it included?\n    return targetIncludes(target, targetFromPreset)\n  })\n}\n\nfunction sanityCheck(permissions: readonly PermissionCoerced[]) {\n  const { violations } = mergePermissions(permissions)\n  if (violations.length) {\n    throw new Error(`Invalid Permissions:\\n` + violations.join(\"\\n\\t\"))\n  }\n}\n","import { Roles__factory } from \"../typechain\"\n\nexport const rolesAbi = Roles__factory.abi\n\nexport const posterAbi = [\n  {\n    inputs: [\n      { internalType: \"string\", name: \"content\", type: \"string\" },\n      { internalType: \"string\", name: \"tag\", type: \"string\" },\n    ],\n    name: \"post\",\n    outputs: [],\n    stateMutability: \"nonpayable\",\n    type: \"function\",\n  },\n] as const\n","import { decodeBytes32String, encodeBytes32String } from \"ethers\"\n\n/**\n * Encodes a human-readable key for addressing roles or allowances to a bytes32 string.\n * Detects if the input is already encoded.\n */\nexport const encodeKey = (key: string) => {\n  if (key.startsWith(\"0x\") && key.length === 66) {\n    // already encoded\n    return key as `0x${string}`\n  }\n\n  return encodeBytes32String(key) as `0x${string}`\n}\n\n/**\n * Decodes a bytes32 encoded string to a human-readable key for addressing roles or allowances.\n * Detects if the input is already decoded.\n */\nexport const decodeKey = (key: string) => {\n  if (key.startsWith(\"0x\") && key.length === 66) {\n    return decodeBytes32String(key)\n  }\n\n  try {\n    encodeBytes32String(key)\n  } catch (e) {\n    throw new Error(`Invalid key: ${key}`)\n  }\n\n  return key\n}\n","import { Annotation, Target } from \"./types\"\n\nconst ZODIAC_ROLES_APP = \"https://roles.gnosisguild.org\"\n\n/**\n * Posts a role configuration to Zodiac Roles app for storage\n * @returns The hash under which permissions have been stored\n */\nexport const postRole = async ({\n  targets,\n  annotations,\n  members,\n}: {\n  targets?: Target[]\n  annotations?: Annotation[]\n  members?: `0x${string}`[]\n}) => {\n  const res = await fetch(`${ZODIAC_ROLES_APP}/api/permissions`, {\n    method: \"POST\",\n    body: JSON.stringify({ targets, annotations, members }),\n  })\n  const json = (await res.json()) as any\n  const { hash } = json\n  if (!hash) {\n    console.error(json)\n    throw new Error(\"Failed to post permissions\")\n  }\n  return hash\n}\n","import { chains } from \"./chains\"\nimport { ChainId } from \"./types\"\n\ntype LicenseErrorStatus = \"BLOCKED\" | \"UNLICENSED_FEATURE\"\n\nexport class LicenseError extends Error {\n  owner: PrefixedAddress\n  status: LicenseErrorStatus\n\n  constructor(\n    message: string,\n    owner: PrefixedAddress,\n    status: LicenseErrorStatus\n  ) {\n    super(message)\n    this.name = \"LicenseError\"\n    this.owner = owner\n    this.status = status\n  }\n}\n\ntype ChainPrefix = (typeof chains)[ChainId][\"prefix\"]\ntype PrefixedAddress = `${ChainPrefix}:0x${Lowercase<string>}`\n\nconst prefixAddress = (chainId: ChainId, address: `0x${string}`) => {\n  return `${chains[chainId][\"prefix\"]}:${address.toLowerCase()}` as PrefixedAddress\n}\n\nexport enum License {\n  None = \"none\",\n  Free = \"free\",\n  Enterprise = \"enterprise\",\n  Blocked = \"blocked\",\n}\n\nexport const fetchLicense = async ({\n  chainId,\n  owner,\n}: {\n  chainId: ChainId\n  owner: `0x${string}`\n}) => {\n  const prefixedAddress = prefixAddress(chainId, owner)\n  const response = await fetch(\n    `https://app.zodiac.eco/system/get-plan/${prefixedAddress}`\n  )\n  const data = await response.json()\n\n  if (!Object.values(License).includes(data.currentPlan)) {\n    throw new Error(`Invalid license: ${data.currentPlan}`)\n  }\n\n  return data.currentPlan as License\n}\n"],"mappings":";;;;;;AAIA,IAAY,gEAAL;AACL;AACA;AACA;AACA;;AACD;AAED,IAAY,kDAAL;AACL;AACA;AACA;;AACD;AAED,IAAY,0DAAL;AACL;AACA;AACA;AACA;AACA;AACA;AACA;;AACD;AAED,IAAY,gDAAL;AAKL;AAMA;AACA;AAMA;AACA;AAMA;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACD;AAED,IAAY,4CAAL;AACL;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AACD;;;;AC1GD,MAAa,SAAS;EACnB,IAAI;EACH,MAAM;EACN,QAAQ;EACT;EACA,KAAK;EACJ,MAAM;EACN,QAAQ;EACT;EACA,MAAM;EACL,MAAM;EACN,QAAQ;EACT;EACA,OAAO;EACN,MAAM;EACN,QAAQ;EACT;EACA,WAAW;EACV,MAAM;EACN,QAAQ;EACT;EACA,MAAM;EACL,MAAM;EACN,QAAQ;EACT;EACA,MAAM;EACL,MAAM;EACN,QAAQ;EACT;EACA,QAAQ;EACP,MAAM;EACN,QAAQ;EACT;EACA,QAAQ;EACP,MAAM;EACN,QAAQ;EACT;EACA,QAAQ;EACP,MAAM;EACN,QAAQ;EACT;EACA,KAAK;EACJ,MAAM;EACN,QAAQ;EACT;EACA,MAAM;EACL,MAAM;EACN,QAAQ;EACT;EACA,MAAM;EACL,MAAM;EACN,QAAQ;EACT;EACA,MAAO;EACN,MAA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