{"version":3,"file":"signatureArgs.cjs","names":["parseAbiItem","handleToRef"],"sources":["../../src/authoring/signatureArgs.ts"],"sourcesContent":["import type { Ref, SolType } from '@lifi/compose-spec';\nimport { type ParseAbiItem, parseAbiItem } from 'abitype';\n\nimport type {\n  AbiTypeToOutputKind,\n  TypedGuard,\n  TypedLiteral,\n} from '../types.js';\n\nimport type { CallArgs } from './FlowBuilderCore.js';\nimport type { AnyRefBindable, OutputHandle, RefBindable } from './handles.js';\nimport { handleToRef } from './handles.js';\n\n/**\n * Any value a signature-derived bind slot accepts, with no per-slot type\n * constraint: a ref-resolving bindable or a typed literal.\n */\ntype AnySignatureBindable = AnyRefBindable | TypedLiteral;\n\n// The literal arm of a signature-derived slot. A positional arg is encoded by\n// its parameter's ABI type, not by the literal's `kind`, so the kind must equal\n// that type exactly: the `bytes32` widening `Bindable<T>` applies would admit an\n// `address` literal the encoder then rejects. A parameter whose ABI type is no\n// `SolType` (a tuple, an array, `uint24`) has no literal kind to name, so its\n// slot stays ref-only.\ntype SignatureLiteral<TAbiType extends string> = TAbiType extends SolType\n  ? TypedLiteral<TAbiType>\n  : never;\n\n/**\n * Type-level extraction of named bind keys from a function signature string.\n * When `TSig` is a string literal matching a Solidity function signature,\n * resolves to a record whose keys are the parameter names and whose values are\n * `RefBindable<kind>`, where the kind is derived from each parameter's Solidity\n * type via `AbiTypeToOutputKind`, or a `TypedLiteral` (`raw.literal`) of that\n * exact Solidity type. For recognised `SolType` parameters (e.g. `uint256`,\n * `address`, `bytes`) the slot is precisely typed; other Solidity types (e.g.\n * tuples) accept any scalar handle and no literal.\n * Falls back to `Record<string, AnySignatureBindable>` for non-literal strings.\n *\n * These slots are lowered into `config.args`, positional calldata: a ref\n * becomes `{ $ref }` and a literal becomes its `value` string, which the\n * backend encodes against the parameter's type.\n */\nexport type SignatureBind<TSig extends string> = string extends TSig\n  ? Record<string, AnySignatureBindable>\n  : ParseAbiItem<TSig> extends {\n        type: 'function';\n        inputs: infer I extends readonly { name: string; type: string }[];\n      }\n    ? {\n        readonly [P in I[number] as P['name']]:\n          | RefBindable<AbiTypeToOutputKind<P['type']>>\n          | SignatureLiteral<P['type']>;\n      }\n    : Record<string, AnySignatureBindable>;\n\n// ---------------------------------------------------------------------------\n// Return-type inference from function signatures\n// ---------------------------------------------------------------------------\n\n/**\n * Describes the output type(s) of a parsed function signature as a\n * human-readable string for inclusion in type-level error messages.\n */\ntype DescribeOutputs<O extends readonly { type: string }[]> =\n  O extends readonly [{ type: infer T extends string }] ? T : 'multiple values';\n\n/**\n * A string-literal type that surfaces a clear error when the user provides a\n * function signature whose return type is not supported by core.call.\n * The message is visible in IDE tooltips and compiler diagnostics.\n */\ntype UnsupportedReturnTypeError<TLabel extends string, TSig extends string> =\n  ParseAbiItem<TSig> extends {\n    type: 'function';\n    outputs: infer O extends readonly { type: string }[];\n  }\n    ? `[TypeError] ${TLabel}: return type '${DescribeOutputs<O>}' is not supported — only 'uint256' or void signatures are allowed`\n    : `[TypeError] ${TLabel}: unable to parse return type from signature`;\n\n/**\n * Conditional output type for `core.call` based on the function signature's\n * return type:\n *\n * - `returns (uint256)` → `{ result: OutputHandle }`\n * - No returns clause   → `{ result: undefined }`\n * - Anything else        → `{ result: \"[TypeError] ...\" }` (compile-time error)\n *\n * When `TSig` is a non-literal `string` (e.g. a variable, not a string\n * constant), the type falls back to `{ result: OutputHandle | undefined }`\n * so that both void and uint256 call sites remain assignable.\n */\nexport type CoreCallResult<TSig extends string> = string extends TSig\n  ? { readonly result: OutputHandle<'uint256'> | undefined }\n  : ParseAbiItem<TSig> extends { type: 'function'; outputs: readonly [] }\n    ? { readonly result: undefined }\n    : ParseAbiItem<TSig> extends {\n          type: 'function';\n          outputs: readonly [{ type: 'uint256' }];\n        }\n      ? { readonly result: OutputHandle<'uint256'> }\n      : { readonly result: UnsupportedReturnTypeError<'core.call', TSig> };\n\n/**\n * Conditional output type for `core.staticCall`. staticCall always reads a\n * value, so void signatures are also rejected:\n *\n * - `returns (uint256)` → `{ result: OutputHandle }`\n * - No returns / other  → `{ result: \"[TypeError] ...\" }` (compile-time error)\n */\nexport type StaticCallResult<TSig extends string> = string extends TSig\n  ? { readonly result: OutputHandle<'uint256'> }\n  : ParseAbiItem<TSig> extends {\n        type: 'function';\n        outputs: readonly [{ type: 'uint256' }];\n      }\n    ? { readonly result: OutputHandle<'uint256'> }\n    : ParseAbiItem<TSig> extends { type: 'function'; outputs: readonly [] }\n      ? {\n          readonly result: `[TypeError] core.staticCall: function has no return value — staticCall requires a 'returns (uint256)' signature`;\n        }\n      : {\n          readonly result: UnsupportedReturnTypeError<'core.staticCall', TSig>;\n        };\n\n/**\n * Parses a Solidity function signature and returns parameter names in order.\n * Delegates to abitype's runtime `parseAbiItem` — the same parser that powers\n * the compile-time `ParseAbiItem<TSig>` type — so runtime and type-level\n * parsing can never diverge.\n *\n * @throws if the signature is not a valid function signature or a parameter is unnamed\n */\nexport const parseFunctionParams = (functionSignature: string): string[] => {\n  const parsed = parseAbiItem(functionSignature);\n  if (parsed.type !== 'function') {\n    throw new Error(\n      `core.call: expected a function signature, got \"${parsed.type}\": \"${functionSignature}\"`,\n    );\n  }\n\n  return parsed.inputs.map((input, index) => {\n    if (!input.name) {\n      throw new Error(\n        `core.call: parameter at index ${index} in signature has no name. All parameters must be named for named binds to work.`,\n      );\n    }\n    return input.name;\n  });\n};\n\n/**\n * Converts a ref-resolving bindable to a `Ref` (`{ $ref: string }`).\n * Handles carry a `_tag` property and are converted via `handleToRef`;\n * `Ref` objects pass through as-is.\n */\nexport const toBindRef = (bindable: AnyRefBindable): Ref => {\n  if ('_tag' in bindable) return handleToRef(bindable);\n  return bindable;\n};\n\n/**\n * Converts one signature-derived bind to its positional `config.args` entry: a\n * ref-resolving bindable becomes `{ $ref }`; a literal becomes its `value`\n * verbatim, which the backend encodes against the parameter's ABI type (a\n * decimal or hex integer, a hex address or byte string, `'true'`/`'false'`).\n */\nconst toPositionalArg = (bindable: AnySignatureBindable): Ref | string =>\n  'kind' in bindable ? bindable.value : toBindRef(bindable);\n\nexport interface BuildCallWireFormatInput {\n  readonly resource?: AnyRefBindable;\n  readonly bind: Record<string, AnySignatureBindable>;\n  readonly config: Record<string, unknown>;\n  readonly guards?: readonly TypedGuard[];\n}\n\nexport interface CallWireResult {\n  readonly op: 'core.call' | 'core.invoke';\n  readonly bind: Record<string, Ref>;\n  readonly config: Record<string, unknown>;\n  readonly guards?: readonly TypedGuard[];\n}\n\n/**\n * Parses a function signature from `config`, validates bind keys against it,\n * and converts named binds to positional args.\n */\nconst resolvePositionalArgs = (\n  label: string,\n  bind: Record<string, AnySignatureBindable>,\n  config: Record<string, unknown>,\n): (Ref | string)[] => {\n  const functionSignature = config.functionSignature;\n  if (typeof functionSignature !== 'string') {\n    throw new Error(\n      `${label}: config.functionSignature is required and must be a string`,\n    );\n  }\n\n  const paramNames = parseFunctionParams(functionSignature);\n  const paramSet = new Set(paramNames);\n  const bindKeys = Object.keys(bind);\n  const bindSet = new Set(bindKeys);\n\n  const missing = paramNames.filter((n) => !bindSet.has(n));\n  const extra = bindKeys.filter((k) => !paramSet.has(k));\n\n  if (missing.length > 0 || extra.length > 0) {\n    throw new Error(\n      `${label}: bind keys [${bindKeys.join(\n        ', ',\n      )}] do not match signature parameters [${paramNames.join(\n        ', ',\n      )}]. Missing: ${missing.join(', ') || '(none)'}. Extra: ${\n        extra.join(', ') || '(none)'\n      }.`,\n    );\n  }\n\n  return paramNames.map((name) => {\n    const bindable = bind[name];\n    if (bindable === undefined) {\n      throw new Error(\n        `${label}: bind value for parameter \"${name}\" is undefined`,\n      );\n    }\n    return toPositionalArg(bindable);\n  });\n};\n\n/**\n * Transforms the user-facing `resource` + named `bind` API into the wire\n * format that the backend expects:\n * - With resource: `core.call` with `bind: { input: <resourceRef> }`\n * - Without resource: `core.invoke` with `bind: {}`\n * - `config: { ...userConfig, args: [positional refs and literal values...] }`\n */\nexport const buildCallWireFormat = (\n  args: BuildCallWireFormatInput,\n): CallWireResult => {\n  const positionalArgs = resolvePositionalArgs(\n    'core.call',\n    args.bind,\n    args.config,\n  );\n  const hasResource = args.resource !== undefined;\n\n  return {\n    op: hasResource ? 'core.call' : 'core.invoke',\n    bind: hasResource ? { input: toBindRef(args.resource) } : {},\n    config: { ...args.config, args: positionalArgs },\n    ...(args.guards && args.guards.length > 0 && { guards: args.guards }),\n  };\n};\n\nexport interface BuildStaticCallWireFormatInput {\n  readonly bind: Record<string, AnySignatureBindable>;\n  readonly config: Record<string, unknown>;\n  readonly guards?: readonly TypedGuard[];\n}\n\n/**\n * Transforms the user-facing named `bind` API into the wire format that the\n * backend expects for `core.staticCall`. Same as `buildCallWireFormat` but\n * with no `resource` field — staticCall has no resource inputs.\n */\nexport const buildStaticCallWireFormat = (\n  args: BuildStaticCallWireFormatInput,\n): CallArgs => {\n  const positionalArgs = resolvePositionalArgs(\n    'core.staticCall',\n    args.bind,\n    args.config,\n  );\n\n  return {\n    bind: {},\n    config: { ...args.config, args: positionalArgs },\n    ...(args.guards && args.guards.length > 0 && { guards: args.guards }),\n  };\n};\n"],"mappings":";;;;;;;;;;;;AAsIA,MAAa,uBAAuB,sBAAwC;CAC1E,MAAM,UAAA,GAASA,QAAAA,aAAAA,CAAa,iBAAiB;CAC7C,IAAI,OAAO,SAAS,YAClB,MAAM,IAAI,MACR,kDAAkD,OAAO,KAAK,MAAM,kBAAkB,EACxF;CAGF,OAAO,OAAO,OAAO,KAAK,OAAO,UAAU;EACzC,IAAI,CAAC,MAAM,MACT,MAAM,IAAI,MACR,iCAAiC,MAAM,iFACzC;EAEF,OAAO,MAAM;CACf,CAAC;AACH;;;;;;AAOA,MAAa,aAAa,aAAkC;CAC1D,IAAI,UAAU,UAAU,OAAOC,0BAAAA,YAAY,QAAQ;CACnD,OAAO;AACT;;;;;;;AAQA,MAAM,mBAAmB,aACvB,UAAU,WAAW,SAAS,QAAQ,UAAU,QAAQ;;;;;AAoB1D,MAAM,yBACJ,OACA,MACA,WACqB;CACrB,MAAM,oBAAoB,OAA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