kawasekit 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/{chunk-VXZHS74W.js → chunk-5TTOAVHE.js} +9 -3
  2. package/dist/chunk-5TTOAVHE.js.map +1 -0
  3. package/dist/chunk-EUW7AZ4P.js +276 -0
  4. package/dist/chunk-EUW7AZ4P.js.map +1 -0
  5. package/dist/{chunk-SMAZUZFO.js → chunk-G3UC6SME.js} +3 -3
  6. package/dist/{chunk-SMAZUZFO.js.map → chunk-G3UC6SME.js.map} +1 -1
  7. package/dist/{chunk-XRSZTZVZ.js → chunk-RJLDKDWL.js} +2 -2
  8. package/dist/{chunk-XRSZTZVZ.js.map → chunk-RJLDKDWL.js.map} +1 -1
  9. package/dist/cli/index.cjs +1 -1
  10. package/dist/cli/index.js +5 -5
  11. package/dist/{index-f-Xg86P9.d.ts → index-C9tbaHPF.d.ts} +1 -1
  12. package/dist/{index-Cn6kg7KH.d.cts → index-CAmTA8xR.d.cts} +1 -1
  13. package/dist/index.cjs +222 -4
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.cts +4 -4
  16. package/dist/index.d.ts +4 -4
  17. package/dist/index.js +4 -4
  18. package/dist/policy/index.d.cts +2 -2
  19. package/dist/policy/index.d.ts +2 -2
  20. package/dist/signer/index.cjs +218 -0
  21. package/dist/signer/index.cjs.map +1 -1
  22. package/dist/signer/index.d.cts +220 -5
  23. package/dist/signer/index.d.ts +220 -5
  24. package/dist/signer/index.js +2 -2
  25. package/dist/{spending-policy-DKZN3Sg8.d.ts → spending-policy-BD2Mpm-L.d.ts} +1 -1
  26. package/dist/{spending-policy-DaajDg9B.d.cts → spending-policy-CGIaBpg-.d.cts} +1 -1
  27. package/dist/{types-IEl-iOIx.d.cts → types-BLJU67HZ.d.cts} +11 -3
  28. package/dist/{types-IEl-iOIx.d.ts → types-BLJU67HZ.d.ts} +11 -3
  29. package/dist/x402/index.cjs.map +1 -1
  30. package/dist/x402/index.d.cts +2 -2
  31. package/dist/x402/index.d.ts +2 -2
  32. package/dist/x402/index.js +2 -2
  33. package/package.json +1 -1
  34. package/dist/chunk-THTVJZ2Q.js +0 -71
  35. package/dist/chunk-THTVJZ2Q.js.map +0 -1
  36. package/dist/chunk-VXZHS74W.js.map +0 -1
@@ -15,6 +15,12 @@ var PolicyGatedSignerConfigError = class extends Error {
15
15
  this.reason = reason;
16
16
  }
17
17
  };
18
+ var CoSignUnavailableError = class extends Error {
19
+ constructor(message, options) {
20
+ super(message, options);
21
+ this.name = "CoSignUnavailableError";
22
+ }
23
+ };
18
24
 
19
25
  // src/signer/gate.ts
20
26
  function requireNonBypassable(signer) {
@@ -207,6 +213,6 @@ function splitAuthorization(signature, domain, message) {
207
213
  };
208
214
  }
209
215
 
210
- export { PolicyGatedSignerConfigError, assertNonBypassable, authorizationDeadlineFromNow, cancelAuthorizationTypes, deriveAuthorizationNonce, generateAuthorizationNonce, getKnownAssetDomain, listKnownAssetIds, receiveWithAuthorizationTypes, requireNonBypassable, resolveAssetParam, resolvedAssetToEip3009Domain, signCancelAuthorization, signReceiveWithAuthorization, signTransferWithAuthorization, transferWithAuthorizationTypes };
211
- //# sourceMappingURL=chunk-VXZHS74W.js.map
212
- //# sourceMappingURL=chunk-VXZHS74W.js.map
216
+ export { CoSignUnavailableError, PolicyGatedSignerConfigError, assertNonBypassable, authorizationDeadlineFromNow, cancelAuthorizationTypes, deriveAuthorizationNonce, generateAuthorizationNonce, getKnownAssetDomain, listKnownAssetIds, receiveWithAuthorizationTypes, requireNonBypassable, resolveAssetParam, resolvedAssetToEip3009Domain, signCancelAuthorization, signReceiveWithAuthorization, signTransferWithAuthorization, transferWithAuthorizationTypes };
217
+ //# sourceMappingURL=chunk-5TTOAVHE.js.map
218
+ //# sourceMappingURL=chunk-5TTOAVHE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/signer/errors.ts","../src/signer/gate.ts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A,EACA,MAAA,EACA,OAAA,EACgC;AAChC,EAAA,MAAM,MAAA,GAAS,eAAe,SAAS,CAAA;AAEvC,EAAA,MAAM,CAAA,GAAI,MAAA,CAAO,CAAA,KAAM,MAAA,GAAY,MAAA,CAAO,OAAO,CAAC,CAAA,GAAA,CAAK,MAAA,CAAO,OAAA,IAAW,CAAA,IAAK,EAAA;AAC9E,EAAA,OAAO;AAAA,IACN,SAAA;AAAA,IACA,CAAA;AAAA,IACA,GAAG,MAAA,CAAO,CAAA;AAAA,IACV,GAAG,MAAA,CAAO,CAAA;AAAA,IACV,MAAA;AAAA,IACA;AAAA,GACD;AACD","file":"chunk-5TTOAVHE.js","sourcesContent":["/**\n * PolicyGatedSigner error types.\n *\n * @packageDocumentation\n */\n\n/**\n * Thrown for a construction-time / configuration error in a PolicyGatedSigner\n * adapter — e.g. a `local` signer constructed without the required\n * `acknowledgeAdvisory: true`, or a non-bypassable signer asserted on an\n * advisory one (`assertNonBypassable`). Policy *denials* are NOT errors — they\n * are returned as a typed {@link PolicyRejection} in {@link SignResult}.\n *\n * @example\n * ```ts\n * import { createLocalPolicyGatedSigner, PolicyGatedSignerConfigError } from \"kawasekit/signer\";\n *\n * try {\n * // @ts-expect-error — acknowledgeAdvisory is required\n * createLocalPolicyGatedSigner({ account, policy, asset });\n * } catch (error) {\n * if (error instanceof PolicyGatedSignerConfigError) {\n * console.error(`${error.field}: ${error.reason}`);\n * }\n * }\n * ```\n */\nexport class PolicyGatedSignerConfigError extends Error {\n\t/** The offending config field. */\n\treadonly field: string;\n\t/** Short machine-readable reason. */\n\treadonly reason: string;\n\n\tconstructor(field: string, reason: string, options?: { cause?: unknown }) {\n\t\tsuper(`Invalid PolicyGatedSigner config (${field}): ${reason}`, options);\n\t\tthis.name = \"PolicyGatedSignerConfigError\";\n\t\tthis.field = field;\n\t\tthis.reason = reason;\n\t}\n}\n\n/**\n * Thrown by the `mpc-2p` cryptographic adapter when the co-signer is\n * **unreachable or the ceremony could not complete** — endpoint down, TLS\n * failure, connection dropped mid-ceremony, timeout, a malformed/missing\n * terminal frame, or an internal protocol anomaly. It is a transient / internal\n * error on the throws channel (M6-0: throws are reserved for internal/config\n * errors), **distinct from a policy denial**.\n *\n * This is the **no-silent-fallback** guarantee (RFC m6-3a constraint 3 / W8):\n * the adapter has no local-signing path, so an unavailable wire NEVER yields an\n * `{ ok: true }` signature and NEVER a {@link PolicyRejection}. A `rejection`\n * means \"the owner decided no\" (audit-meaningful); a `CoSignUnavailableError`\n * means \"the owner did not decide\" — the caller may retry the *same* intent\n * (the backend's idempotency keeps a retry safe).\n *\n * @example\n * ```ts\n * try {\n * const result = await mpc2pSigner.sign(intent);\n * if (!result.ok) handleDenial(result.rejection); // owner said no\n * } catch (error) {\n * if (error instanceof CoSignUnavailableError) retryLater(); // wire was down\n * }\n * ```\n */\nexport class CoSignUnavailableError extends Error {\n\tconstructor(message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, options);\n\t\tthis.name = \"CoSignUnavailableError\";\n\t}\n}\n","/**\n * The enforcement-level type-gate — the compile-time (and runtime) mechanism\n * that prevents an advisory signer from being substituted for an enforcing one.\n *\n * @packageDocumentation\n */\n\nimport { PolicyGatedSignerConfigError } from \"./errors\";\nimport type { NonBypassableEnforcement, PolicyGatedSigner } from \"./types\";\n\n/**\n * Compile-time gate: accepts only a non-bypassable signer\n * (`cryptographic` | `hardware`). Passing an `advisory` (or `integrator`) signer\n * is a **compile error**, because `PolicyGatedSigner<\"advisory\">` is not\n * assignable to `PolicyGatedSigner<NonBypassableEnforcement>` (covariant `E`).\n *\n * Use it at the boundary of a bounded/regulated flow so wiring an advisory\n * signer into it fails the build, not silently at runtime.\n *\n * @example\n * ```ts\n * function payBounded(signer: PolicyGatedSigner<NonBypassableEnforcement>) { ... }\n *\n * requireNonBypassable(mpc2pSigner); // ✓ ok — cryptographic\n * // requireNonBypassable(localSigner); // ✗ compile error — advisory\n * ```\n */\nexport function requireNonBypassable<E extends NonBypassableEnforcement>(\n\tsigner: PolicyGatedSigner<E>,\n): PolicyGatedSigner<E> {\n\treturn signer;\n}\n\n/**\n * Runtime mirror of {@link requireNonBypassable}, for plain-JS call sites and as\n * defense-in-depth. Throws {@link PolicyGatedSignerConfigError} if the signer is\n * advisory/integrator (i.e. bypassable). On success, narrows the signer type to\n * {@link NonBypassableEnforcement}.\n */\nexport function assertNonBypassable(\n\tsigner: PolicyGatedSigner,\n): asserts signer is PolicyGatedSigner<NonBypassableEnforcement> {\n\tif (signer.enforcement === \"advisory\" || signer.enforcement === \"integrator\") {\n\t\tthrow new PolicyGatedSignerConfigError(\n\t\t\t\"enforcement\",\n\t\t\t`expected a non-bypassable signer (cryptographic | hardware), got \"${signer.enforcement}\" — an ${signer.enforcement} signer's policy can be bypassed by a key-holder`,\n\t\t);\n\t}\n}\n","/**\n * Known-asset registry for {@link createX402PaymentSigner}'s\n * `asset: { kind: \"known\", id }` discriminated-union branch.\n *\n * kawasekit only ships pinned EIP-712 domain definitions for assets it has\n * verified empirically against the deployed contracts. Adding a new entry\n * here requires citing the source-file + line reference for the contract\n * that owns the `name` / `version` (so the next reviewer can spot-check the\n * claim, the same discipline `docs/THREAT_MODEL.md` §0 demands of any ✅\n * verdict that delegates to an out-of-scope component).\n *\n * @packageDocumentation\n */\n\nimport type { Address } from \"viem\";\nimport { getAddress } from \"viem\";\nimport { JPYC_EIP712_DOMAIN_HINT, JPYC_V2_ADDRESS } from \"./jpyc\";\n\n/** Known asset identifiers. New entries must update this union AND the table. */\nexport type KnownAssetId = \"jpyc-v2\";\n\n/** Fully-pinned EIP-712 domain for a known asset. */\nexport interface KnownAssetDomain {\n\treadonly id: KnownAssetId;\n\treadonly name: string;\n\treadonly version: string;\n\treadonly verifyingContract: Address;\n}\n\n/**\n * Canonical table. Lookups go through {@link getKnownAssetDomain}, which\n * returns a frozen copy so callers cannot mutate the registry.\n *\n * `verifyingContract` is the multi-chain canonical address — JPYC v2 is the\n * same address on Ethereum / Polygon (mainnet + Amoy) / Avalanche. The\n * signer cross-checks `requirements.asset` against this value at sign time,\n * so a server advertising a different `asset` is rejected before any\n * signature is produced.\n *\n * JPYC v2 domain: `name = \"JPY Coin\"`, `version = \"1\"`. Source of truth is\n * the deployed contract's `eip712Domain()` view — verified empirically and\n * also cached in `src/tokens/jpyc.ts:JPYC_EIP712_DOMAIN_HINT`.\n */\nconst KNOWN_ASSETS: ReadonlyArray<KnownAssetDomain> = [\n\t{\n\t\tid: \"jpyc-v2\",\n\t\tname: JPYC_EIP712_DOMAIN_HINT.name,\n\t\tversion: JPYC_EIP712_DOMAIN_HINT.version,\n\t\tverifyingContract: getAddress(JPYC_V2_ADDRESS),\n\t},\n];\n\n/**\n * Look up a known asset's pinned EIP-712 domain by id.\n *\n * @returns The domain, or `undefined` if the id is not in the registry.\n *\n * @example\n * ```ts\n * import { getKnownAssetDomain } from \"kawasekit\";\n *\n * const jpyc = getKnownAssetDomain(\"jpyc-v2\");\n * if (jpyc === undefined) throw new Error(\"unreachable\");\n * console.log(jpyc.verifyingContract); // 0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29\n * ```\n */\nexport function getKnownAssetDomain(id: KnownAssetId): KnownAssetDomain | undefined {\n\treturn KNOWN_ASSETS.find((entry) => entry.id === id);\n}\n\n/** List every known asset id (for diagnostics / error messages). */\nexport function listKnownAssetIds(): readonly KnownAssetId[] {\n\treturn KNOWN_ASSETS.map((entry) => entry.id);\n}\n","/**\n * EIP-712 asset-domain resolution for x402 / EIP-3009 signing.\n *\n * Construction-time pinning of the EIP-712 domain (`name` / `version` /\n * `verifyingContract`) a signer will use. The integrator declares an\n * {@link X402AssetParam} — either a kawasekit-maintained `known` asset or a\n * loud `unsafeOverride` — and {@link resolveAssetParam} resolves it to a pinned\n * {@link ResolvedAsset}. The signer then trusts only this pinned domain and\n * refuses to sign for a mismatched advertised asset (Threat 1.4: misadvertised\n * EIP-712 domain).\n *\n * Token-domain concern, reused by both the x402 signer (`src/x402/client.ts`)\n * and the M6 PolicyGatedSigner (`src/signer/`).\n *\n * @packageDocumentation\n */\n\nimport type { Address } from \"viem\";\nimport { getAddress, isAddress } from \"viem\";\nimport { X402InvalidConfigError } from \"../x402/errors\";\nimport type { Eip3009Domain } from \"./eip3009\";\nimport {\n\tgetKnownAssetDomain,\n\ttype KnownAssetDomain,\n\ttype KnownAssetId,\n\tlistKnownAssetIds,\n} from \"./known-assets\";\n\n/** EIP-712 token domain `name` / `version` pair. */\nexport interface X402TokenDomain {\n\treadonly name: string;\n\treadonly version: string;\n}\n\n/**\n * Asset binding for {@link createX402PaymentSigner} and the M6 PolicyGatedSigner.\n * Required, discriminated.\n *\n * **Default-on whitelist**: integrators MUST declare which asset they intend\n * to sign for. The `known` branch references a kawasekit-maintained\n * whitelist (see `src/tokens/known-assets.ts`); the `unsafeOverride` branch\n * is the deliberate escape hatch for any other asset and is named loudly so\n * it survives a code review. Either way, the signer pins the EIP-712 domain\n * at construction time and refuses to sign if `paymentRequirements.asset`\n * disagrees with the pinned `verifyingContract`.\n *\n * Closes Threat 1.4 (misadvertised EIP-712 domain): the server's advertised\n * `extra.name` / `extra.version` and `asset` are all ignored for signing\n * purposes — the signer trusts only what the integrator declared here.\n */\nexport type X402AssetParam =\n\t| {\n\t\t\t/** Use a kawasekit-maintained pinned EIP-712 domain. */\n\t\t\treadonly kind: \"known\";\n\t\t\t/** The asset id to pin. See {@link KnownAssetId} for the registry. */\n\t\t\treadonly id: KnownAssetId;\n\t }\n\t| {\n\t\t\t/**\n\t\t\t * Use a caller-supplied EIP-712 domain for an asset NOT on the\n\t\t\t * kawasekit whitelist. The name is deliberately loud — pick this\n\t\t\t * branch only when you have separately audited the contract and its\n\t\t\t * `eip712Domain()` output.\n\t\t\t */\n\t\t\treadonly kind: \"unsafeOverride\";\n\t\t\treadonly domain: {\n\t\t\t\treadonly name: string;\n\t\t\t\treadonly version: string;\n\t\t\t\treadonly verifyingContract: Address;\n\t\t\t};\n\t };\n\n/** Construction-time resolution of an {@link X402AssetParam} to a pinned domain. */\nexport interface ResolvedAsset {\n\treadonly name: string;\n\treadonly version: string;\n\treadonly verifyingContract: Address;\n}\n\n/**\n * Resolve an {@link X402AssetParam} to a pinned {@link ResolvedAsset}.\n *\n * Throws {@link X402InvalidConfigError} for an unknown `known` id or a malformed\n * `unsafeOverride` domain. Pure / construction-time — no chain RPC.\n */\nexport function resolveAssetParam(asset: X402AssetParam): ResolvedAsset {\n\tif (asset.kind === \"known\") {\n\t\tconst entry: KnownAssetDomain | undefined = getKnownAssetDomain(asset.id);\n\t\tif (entry === undefined) {\n\t\t\tthrow new X402InvalidConfigError(\n\t\t\t\t\"asset.id\",\n\t\t\t\t`unknown asset id ${JSON.stringify(asset.id)}. Supported: ${listKnownAssetIds()\n\t\t\t\t\t.map((id) => JSON.stringify(id))\n\t\t\t\t\t.join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tname: entry.name,\n\t\t\tversion: entry.version,\n\t\t\tverifyingContract: entry.verifyingContract,\n\t\t};\n\t}\n\tif (asset.kind === \"unsafeOverride\") {\n\t\tconst { domain } = asset;\n\t\tif (typeof domain.name !== \"string\" || domain.name === \"\") {\n\t\t\tthrow new X402InvalidConfigError(\n\t\t\t\t\"asset.domain.name\",\n\t\t\t\t\"`unsafeOverride.domain.name` must be a non-empty string\",\n\t\t\t);\n\t\t}\n\t\tif (typeof domain.version !== \"string\" || domain.version === \"\") {\n\t\t\tthrow new X402InvalidConfigError(\n\t\t\t\t\"asset.domain.version\",\n\t\t\t\t\"`unsafeOverride.domain.version` must be a non-empty string\",\n\t\t\t);\n\t\t}\n\t\tif (!isAddress(domain.verifyingContract, { strict: false })) {\n\t\t\tthrow new X402InvalidConfigError(\n\t\t\t\t\"asset.domain.verifyingContract\",\n\t\t\t\t`\\`unsafeOverride.domain.verifyingContract\\` must be a valid address, got ${JSON.stringify(domain.verifyingContract)}`,\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tname: domain.name,\n\t\t\tversion: domain.version,\n\t\t\tverifyingContract: getAddress(domain.verifyingContract),\n\t\t};\n\t}\n\t// Defensive: TS exhaustiveness guarantees this is unreachable at compile\n\t// time, but a JS consumer could smuggle through an unknown kind.\n\tconst exhaustive = asset as { kind: string };\n\tthrow new X402InvalidConfigError(\n\t\t\"asset.kind\",\n\t\t`unsupported kind ${JSON.stringify(exhaustive.kind)}. Expected \"known\" or \"unsafeOverride\".`,\n\t);\n}\n\n/**\n * Assemble the EIP-712 {@link Eip3009Domain} from a construction-time pinned\n * {@link ResolvedAsset} and the runtime `chainId`.\n *\n * The single place that maps `(pinned asset, chainId) -> domain`, so every\n * signing path (`src/x402/client.ts`, `src/signer/`) builds the domain\n * identically — the domain half of the EIP-712 single-source-of-truth the\n * `mpc-2p` backend relies on (RFC M6-1 §4.5, H1). `name` / `version` /\n * `verifyingContract` come from the pinned asset; only `chainId` is per-request.\n */\nexport function resolvedAssetToEip3009Domain(asset: ResolvedAsset, chainId: number): Eip3009Domain {\n\treturn {\n\t\tname: asset.name,\n\t\tversion: asset.version,\n\t\tchainId,\n\t\tverifyingContract: asset.verifyingContract,\n\t};\n}\n","/**\n * EIP-3009 typed-data builders and signing helpers.\n *\n * Token-agnostic: works for any EIP-3009-compliant token (JPYC, USDC, USDP,\n * Centre FiatToken family). Pure off-chain construction — no chain RPC, no\n * submission. Submission is the caller's job (M3 x402 flow, or arbitrary\n * gas-paying relayer).\n *\n * @packageDocumentation\n */\n\nimport {\n\ttype Account,\n\ttype Address,\n\tgetAddress,\n\ttype Hex,\n\tkeccak256,\n\tparseSignature,\n\tstringToHex,\n} from \"viem\";\n\n// ---------------------------------------------------------------------------\n// Domain & typed-data shapes\n// ---------------------------------------------------------------------------\n\n/**\n * EIP-712 domain for an EIP-3009-compliant token.\n *\n * `name` and `version` MUST match the values the token used when computing\n * its `DOMAIN_SEPARATOR`. For JPYC see {@link JPYC_EIP712_DOMAIN_HINT}.\n */\nexport interface Eip3009Domain {\n\treadonly name: string;\n\treadonly version: string;\n\treadonly chainId: number;\n\treadonly verifyingContract: Address;\n}\n\n/** Message body for {@link signTransferWithAuthorization}. */\nexport interface TransferWithAuthorizationMessage {\n\treadonly from: Address;\n\treadonly to: Address;\n\treadonly value: bigint;\n\treadonly validAfter: bigint;\n\treadonly validBefore: bigint;\n\t/** 32-byte random nonce. Generate with {@link generateAuthorizationNonce}. */\n\treadonly nonce: Hex;\n}\n\n/** Message body for {@link signReceiveWithAuthorization}. */\nexport type ReceiveWithAuthorizationMessage = TransferWithAuthorizationMessage;\n\n/** Message body for {@link signCancelAuthorization}. */\nexport interface CancelAuthorizationMessage {\n\treadonly authorizer: Address;\n\treadonly nonce: Hex;\n}\n\n/**\n * A signed EIP-3009 authorization, ready to be passed to the token's\n * `*WithAuthorization` entrypoint as `(v, r, s)`.\n */\nexport interface SignedAuthorization<TMessage> {\n\treadonly signature: Hex;\n\treadonly v: number;\n\treadonly r: Hex;\n\treadonly s: Hex;\n\treadonly domain: Eip3009Domain;\n\treadonly message: TMessage;\n}\n\n// ---------------------------------------------------------------------------\n// EIP-712 type definitions (must match EIP-3009 byte-for-byte)\n// ---------------------------------------------------------------------------\n\n/**\n * Canonical EIP-712 `TransferWithAuthorization` type definition.\n *\n * This is the **single source of truth** for the typed-data structure (field\n * names, types, and order) that EIP-3009 hashes and `ecrecover` verifies.\n * Exported so out-of-process / cross-language consumers — notably the `mpc-2p`\n * co-signer backend (RFC M6-1 §4.5, H1) — bind to this exact definition (or\n * codegen from it) instead of re-declaring it, and so the digest the policy\n * gates on is provably the digest the chain verifies (see the digest-conformance\n * corpus in `__fixtures__/eip3009-digest.vectors.json`).\n */\nexport const transferWithAuthorizationTypes = {\n\tTransferWithAuthorization: [\n\t\t{ name: \"from\", type: \"address\" },\n\t\t{ name: \"to\", type: \"address\" },\n\t\t{ name: \"value\", type: \"uint256\" },\n\t\t{ name: \"validAfter\", type: \"uint256\" },\n\t\t{ name: \"validBefore\", type: \"uint256\" },\n\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t],\n} as const;\n\n/** Canonical EIP-712 `ReceiveWithAuthorization` types. See {@link transferWithAuthorizationTypes}. */\nexport const receiveWithAuthorizationTypes = {\n\tReceiveWithAuthorization: [\n\t\t{ name: \"from\", type: \"address\" },\n\t\t{ name: \"to\", type: \"address\" },\n\t\t{ name: \"value\", type: \"uint256\" },\n\t\t{ name: \"validAfter\", type: \"uint256\" },\n\t\t{ name: \"validBefore\", type: \"uint256\" },\n\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t],\n} as const;\n\n/** Canonical EIP-712 `CancelAuthorization` types. See {@link transferWithAuthorizationTypes}. */\nexport const cancelAuthorizationTypes = {\n\tCancelAuthorization: [\n\t\t{ name: \"authorizer\", type: \"address\" },\n\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t],\n} as const;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Generates a cryptographically random 32-byte EIP-3009 nonce.\n *\n * The nonce only needs to be unique per `(authorizer, contract)` — duplicates\n * across different tokens are harmless because the contract scopes them.\n *\n * @example\n * ```ts\n * import { generateAuthorizationNonce } from \"kawasekit\";\n *\n * const nonce = generateAuthorizationNonce();\n * ```\n */\nexport function generateAuthorizationNonce(): Hex {\n\tconst bytes = new Uint8Array(32);\n\tcrypto.getRandomValues(bytes);\n\treturn `0x${Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\")}` as Hex;\n}\n\n/** Domain tag separating the nonce preimage from any other keccak use in the SDK. */\nconst EIP3009_NONCE_DOMAIN_TAG = \"kawasekit/eip3009-nonce/1\";\n\n/**\n * Derives a **deterministic** 32-byte EIP-3009 nonce from a reasoning-step\n * idempotency key, scoped to `(from, verifyingContract, chainId)` so the same\n * key never collides across tokens or chains (M5-1, Half B).\n *\n * `nonce = keccak256(DOMAIN_TAG ‖ idempotencyKey ‖ from ‖ verifyingContract ‖\n * chainId)`. **No shared secret**: determinism across replicas / sub-agents\n * needs only a shared `conversationId` (the source of the key), not secret\n * distribution. A replayed key ⇒ identical nonce ⇒ the token contract's\n * `authorizationState` rejects the second settlement — the on-chain last line of\n * defence against re-signed same-intent duplicate payments. Use in place of\n * {@link generateAuthorizationNonce} only when a key is available.\n *\n * `chainId` is in the preimage, so the same JPYC address on Polygon / Avalanche\n * / Kaia / Ethereum yields distinct nonces (cross-chain replay safety).\n *\n * @example\n * ```ts\n * import { deriveAuthorizationNonce } from \"kawasekit\";\n *\n * const nonce = deriveAuthorizationNonce(\n * { idempotencyKey },\n * { from: account.address, verifyingContract, chainId },\n * );\n * ```\n */\nexport function deriveAuthorizationNonce(\n\tinput: { readonly idempotencyKey: string },\n\tscope: { readonly from: Address; readonly verifyingContract: Address; readonly chainId: number },\n): Hex {\n\tif (input.idempotencyKey === \"\") {\n\t\tthrow new Error(\"deriveAuthorizationNonce: idempotencyKey must be a non-empty string\");\n\t}\n\tconst preimage = JSON.stringify([\n\t\tEIP3009_NONCE_DOMAIN_TAG,\n\t\tinput.idempotencyKey,\n\t\tgetAddress(scope.from),\n\t\tgetAddress(scope.verifyingContract),\n\t\tscope.chainId,\n\t]);\n\treturn keccak256(stringToHex(preimage));\n}\n\n/**\n * Returns a `validBefore` UNIX timestamp `seconds` in the future.\n *\n * @param seconds - Lifetime of the authorization, in seconds.\n * @param nowSec - Optional override of \"now\" (defaults to {@link Date.now}).\n *\n * @example\n * ```ts\n * import { authorizationDeadlineFromNow } from \"kawasekit\";\n *\n * const validBefore = authorizationDeadlineFromNow(60 * 5); // 5 minutes\n * ```\n */\nexport function authorizationDeadlineFromNow(seconds: number, nowSec?: bigint): bigint {\n\tconst now = nowSec ?? BigInt(Math.floor(Date.now() / 1000));\n\treturn now + BigInt(seconds);\n}\n\nfunction requireSignTypedData(account: Account): NonNullable<Account[\"signTypedData\"]> {\n\tif (!account.signTypedData) {\n\t\tthrow new Error(\n\t\t\t`Account ${account.address} cannot sign typed data — pass a LocalAccount or a JsonRpcAccount bound to a WalletClient.`,\n\t\t);\n\t}\n\treturn account.signTypedData.bind(account);\n}\n\nfunction assertSignerMatches(account: Account, expectedFrom: Address, role: string): void {\n\tif (getAddress(account.address) !== getAddress(expectedFrom)) {\n\t\tthrow new Error(\n\t\t\t`EIP-3009 ${role} signature must come from \\`${role === \"cancel\" ? \"authorizer\" : \"from\"}\\`: account is ${account.address}, message says ${expectedFrom}.`,\n\t\t);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Signers\n// ---------------------------------------------------------------------------\n\n/**\n * Signs an EIP-3009 `TransferWithAuthorization` message.\n *\n * The signing account MUST equal `message.from` — EIP-3009 rejects signatures\n * from anyone else (the on-chain check is pure `ecrecover` against `from`).\n *\n * @example\n * ```ts\n * import { privateKeyToAccount } from \"viem/accounts\";\n * import {\n * authorizationDeadlineFromNow,\n * generateAuthorizationNonce,\n * JPYC_EIP712_DOMAIN_HINT,\n * polygon,\n * signTransferWithAuthorization,\n * } from \"kawasekit\";\n *\n * const account = privateKeyToAccount(\"0x...\");\n * const signed = await signTransferWithAuthorization(account, {\n * ...JPYC_EIP712_DOMAIN_HINT,\n * chainId: polygon.id,\n * verifyingContract: \"0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29\",\n * }, {\n * from: account.address,\n * to: \"0xBeef...\",\n * value: 100n * 10n ** 18n,\n * validAfter: 0n,\n * validBefore: authorizationDeadlineFromNow(300),\n * nonce: generateAuthorizationNonce(),\n * });\n * // → submit (v, r, s) to token.transferWithAuthorization(...)\n * ```\n */\nexport async function signTransferWithAuthorization(\n\taccount: Account,\n\tdomain: Eip3009Domain,\n\tmessage: TransferWithAuthorizationMessage,\n): Promise<SignedAuthorization<TransferWithAuthorizationMessage>> {\n\tassertSignerMatches(account, message.from, \"transfer\");\n\tconst sign = requireSignTypedData(account);\n\tconst signature = await sign({\n\t\tdomain,\n\t\ttypes: transferWithAuthorizationTypes,\n\t\tprimaryType: \"TransferWithAuthorization\",\n\t\tmessage,\n\t});\n\treturn splitAuthorization(signature, domain, message);\n}\n\n/**\n * Signs an EIP-3009 `ReceiveWithAuthorization` message.\n *\n * Differs from {@link signTransferWithAuthorization} in two ways:\n * 1. Uses the `ReceiveWithAuthorization` EIP-712 type.\n * 2. The contract additionally enforces `msg.sender == to` at submission\n * time, so only `to` (or a relayer impersonating `to` — impossible in\n * practice) can land the tx.\n */\nexport async function signReceiveWithAuthorization(\n\taccount: Account,\n\tdomain: Eip3009Domain,\n\tmessage: ReceiveWithAuthorizationMessage,\n): Promise<SignedAuthorization<ReceiveWithAuthorizationMessage>> {\n\tassertSignerMatches(account, message.from, \"receive\");\n\tconst sign = requireSignTypedData(account);\n\tconst signature = await sign({\n\t\tdomain,\n\t\ttypes: receiveWithAuthorizationTypes,\n\t\tprimaryType: \"ReceiveWithAuthorization\",\n\t\tmessage,\n\t});\n\treturn splitAuthorization(signature, domain, message);\n}\n\n/**\n * Signs an EIP-3009 `CancelAuthorization` message.\n *\n * Cancelling consumes the nonce so a later `transferWithAuthorization` or\n * `receiveWithAuthorization` with the same nonce will revert.\n */\nexport async function signCancelAuthorization(\n\taccount: Account,\n\tdomain: Eip3009Domain,\n\tmessage: CancelAuthorizationMessage,\n): Promise<SignedAuthorization<CancelAuthorizationMessage>> {\n\tassertSignerMatches(account, message.authorizer, \"cancel\");\n\tconst sign = requireSignTypedData(account);\n\tconst signature = await sign({\n\t\tdomain,\n\t\ttypes: cancelAuthorizationTypes,\n\t\tprimaryType: \"CancelAuthorization\",\n\t\tmessage,\n\t});\n\treturn splitAuthorization(signature, domain, message);\n}\n\nfunction splitAuthorization<TMessage>(\n\tsignature: Hex,\n\tdomain: Eip3009Domain,\n\tmessage: TMessage,\n): SignedAuthorization<TMessage> {\n\tconst parsed = parseSignature(signature);\n\t// viem's parseSignature returns yParity ∈ {0, 1} as well as v when present.\n\tconst v = parsed.v !== undefined ? Number(parsed.v) : (parsed.yParity ?? 0) + 27;\n\treturn {\n\t\tsignature,\n\t\tv,\n\t\tr: parsed.r,\n\t\ts: parsed.s,\n\t\tdomain,\n\t\tmessage,\n\t};\n}\n"]}
@@ -0,0 +1,276 @@
1
+ import { PolicyGatedSignerConfigError, resolveAssetParam, signTransferWithAuthorization, resolvedAssetToEip3009Domain, transferWithAuthorizationTypes, CoSignUnavailableError } from './chunk-5TTOAVHE.js';
2
+ import { evaluateSpendingPolicy } from './chunk-6CNAYQOL.js';
3
+ import { getAddress, hashTypedData, serializeSignature } from 'viem';
4
+
5
+ function createLocalPolicyGatedSigner(params) {
6
+ if (params.acknowledgeAdvisory !== true) {
7
+ throw new PolicyGatedSignerConfigError(
8
+ "acknowledgeAdvisory",
9
+ "a local signer is advisory (a key-holder can bypass its policy); pass `acknowledgeAdvisory: true` to construct one consciously, or use a cryptographic adapter for bounded/regulated flows"
10
+ );
11
+ }
12
+ const { account, policy, spendState } = params;
13
+ const pinned = resolveAssetParam(params.asset);
14
+ const from = getAddress(account.address);
15
+ return {
16
+ enforcement: "advisory",
17
+ from,
18
+ async sign(intent) {
19
+ if (getAddress(intent.from) !== from) {
20
+ return {
21
+ ok: false,
22
+ rejection: {
23
+ reason: "from_mismatch",
24
+ detail: `intent.from ${getAddress(intent.from)} does not equal signer.from ${from}`
25
+ }
26
+ };
27
+ }
28
+ if (getAddress(intent.token) !== pinned.verifyingContract) {
29
+ return {
30
+ ok: false,
31
+ rejection: {
32
+ reason: "token_not_allowed",
33
+ detail: `intent.token ${getAddress(intent.token)} does not equal the signer's pinned verifyingContract ${pinned.verifyingContract}`
34
+ }
35
+ };
36
+ }
37
+ const state = await spendState?.() ?? { spentPerToken: [] };
38
+ const nowSeconds = BigInt(Math.floor(Date.now() / 1e3));
39
+ const decision = evaluateSpendingPolicy(policy, intent, state, nowSeconds);
40
+ if (!decision.ok) {
41
+ return { ok: false, rejection: decision.rejection };
42
+ }
43
+ const signed = await signTransferWithAuthorization(
44
+ account,
45
+ resolvedAssetToEip3009Domain(pinned, intent.chainId),
46
+ {
47
+ from,
48
+ to: intent.to,
49
+ value: intent.value,
50
+ validAfter: intent.validAfter,
51
+ validBefore: intent.validBefore,
52
+ nonce: intent.nonce
53
+ }
54
+ );
55
+ return { ok: true, signature: signed.signature, intent };
56
+ },
57
+ describe() {
58
+ return {
59
+ enforcement: "advisory",
60
+ from,
61
+ policyId: policy.session.id,
62
+ notAfter: policy.session.notAfter,
63
+ revoked: policy.revoked
64
+ };
65
+ }
66
+ };
67
+ }
68
+
69
+ // src/signer/mpc-2p-wire.ts
70
+ var WIRE_VERSION = 1;
71
+ function toWireIntent(intent) {
72
+ return {
73
+ token: intent.token.toLowerCase(),
74
+ chain_id: intent.chainId,
75
+ from: intent.from.toLowerCase(),
76
+ to: intent.to.toLowerCase(),
77
+ value: intent.value.toString(),
78
+ valid_after: intent.validAfter.toString(),
79
+ valid_before: intent.validBefore.toString(),
80
+ nonce: intent.nonce.toLowerCase()
81
+ };
82
+ }
83
+ function canonicalIntentBytes(intent) {
84
+ const lines = [
85
+ "kawasekit-mpc-2p/cosign-request/v2",
86
+ `token=${intent.token.toLowerCase()}`,
87
+ `chainId=${intent.chainId}`,
88
+ `from=${intent.from.toLowerCase()}`,
89
+ `to=${intent.to.toLowerCase()}`,
90
+ `value=${intent.value}`,
91
+ `validAfter=${intent.validAfter}`,
92
+ `validBefore=${intent.validBefore}`,
93
+ `nonce=${intent.nonce.toLowerCase()}`
94
+ ];
95
+ return new TextEncoder().encode(lines.map((l) => `${l}
96
+ `).join(""));
97
+ }
98
+ var POLICY_REASONS = /* @__PURE__ */ new Set([
99
+ "revoked",
100
+ "expired",
101
+ "token_not_allowed",
102
+ "recipient_not_allowed",
103
+ "amount_exceeds_per_sign",
104
+ "amount_exceeds_cumulative",
105
+ "intent_digest_mismatch",
106
+ "unauthenticated",
107
+ "from_mismatch",
108
+ "nonce_reuse_conflict"
109
+ ]);
110
+ function rejection(reason, detail) {
111
+ return { ok: false, rejection: { reason, detail } };
112
+ }
113
+ function createMpc2pPolicyGatedSigner(params) {
114
+ const { agent, transport, authenticator, session } = params;
115
+ const pinned = resolveAssetParam(params.asset);
116
+ const from = getAddress(params.from);
117
+ const agentEoa = getAddress(agent.groupEoa());
118
+ if (agentEoa !== from) {
119
+ throw new PolicyGatedSignerConfigError(
120
+ "from",
121
+ `the agent share controls ${agentEoa} but params.from is ${from}`
122
+ );
123
+ }
124
+ return {
125
+ enforcement: "cryptographic",
126
+ from,
127
+ async sign(intent) {
128
+ if (getAddress(intent.from) !== from) {
129
+ return rejection(
130
+ "from_mismatch",
131
+ `intent.from ${getAddress(intent.from)} does not equal signer.from ${from}`
132
+ );
133
+ }
134
+ if (getAddress(intent.token) !== pinned.verifyingContract) {
135
+ return rejection(
136
+ "token_not_allowed",
137
+ `intent.token ${getAddress(intent.token)} does not equal the signer's pinned verifyingContract ${pinned.verifyingContract}`
138
+ );
139
+ }
140
+ const digest = hashTypedData({
141
+ domain: resolvedAssetToEip3009Domain(pinned, intent.chainId),
142
+ types: transferWithAuthorizationTypes,
143
+ primaryType: "TransferWithAuthorization",
144
+ message: {
145
+ from,
146
+ to: intent.to,
147
+ value: intent.value,
148
+ validAfter: intent.validAfter,
149
+ validBefore: intent.validBefore,
150
+ nonce: intent.nonce
151
+ }
152
+ });
153
+ const authTag = await authenticator.tag(canonicalIntentBytes(intent));
154
+ const conn = await openConnection(transport);
155
+ try {
156
+ return await runCeremony(conn, agent, session.id, intent, digest, authTag);
157
+ } finally {
158
+ try {
159
+ await conn.close();
160
+ } catch {
161
+ }
162
+ }
163
+ },
164
+ describe() {
165
+ return {
166
+ enforcement: "cryptographic",
167
+ from,
168
+ policyId: session.id,
169
+ notAfter: session.notAfter,
170
+ // The backend owns authoritative revocation (a revoked session → a
171
+ // rejection at sign time); this metadata field is best-effort.
172
+ revoked: false
173
+ };
174
+ }
175
+ };
176
+ }
177
+ async function openConnection(transport) {
178
+ try {
179
+ return await transport.connect();
180
+ } catch (cause) {
181
+ throw new CoSignUnavailableError("co-signer connection failed", { cause });
182
+ }
183
+ }
184
+ async function runCeremony(conn, agent, sessionId, intent, digest, authTag) {
185
+ const send = async (frame) => {
186
+ try {
187
+ await conn.send(frame);
188
+ } catch (cause) {
189
+ throw new CoSignUnavailableError("co-sign connection dropped while sending", { cause });
190
+ }
191
+ };
192
+ const recv = async () => {
193
+ let frame;
194
+ try {
195
+ frame = await conn.recv();
196
+ } catch (cause) {
197
+ throw new CoSignUnavailableError("co-sign connection dropped mid-ceremony", { cause });
198
+ }
199
+ if (frame.wire_version !== WIRE_VERSION) {
200
+ throw new CoSignUnavailableError(
201
+ `co-signer spoke wire_version ${frame.wire_version}, expected ${WIRE_VERSION}`
202
+ );
203
+ }
204
+ return frame;
205
+ };
206
+ await send({
207
+ wire_version: WIRE_VERSION,
208
+ kind: "request",
209
+ session_id: sessionId,
210
+ intent: toWireIntent(intent),
211
+ auth_tag: authTag
212
+ });
213
+ let first;
214
+ try {
215
+ first = agent.start(digest);
216
+ } catch (cause) {
217
+ throw new CoSignUnavailableError("the agent failed to start the ceremony", { cause });
218
+ }
219
+ await send({ wire_version: WIRE_VERSION, kind: "round", payload: first });
220
+ let agentSig = null;
221
+ for (; ; ) {
222
+ const frame = await recv();
223
+ switch (frame.kind) {
224
+ case "round": {
225
+ let step;
226
+ try {
227
+ step = agent.step(frame.payload);
228
+ } catch (cause) {
229
+ throw new CoSignUnavailableError("the agent rejected a round frame", { cause });
230
+ }
231
+ if ("outbound" in step) {
232
+ await send({ wire_version: WIRE_VERSION, kind: "round", payload: step.outbound });
233
+ } else {
234
+ agentSig = step.signature;
235
+ }
236
+ break;
237
+ }
238
+ case "result": {
239
+ if (agentSig === null) {
240
+ throw new CoSignUnavailableError(
241
+ "the backend returned a result before the agent derived a signature"
242
+ );
243
+ }
244
+ if (frame.r.toLowerCase() !== agentSig.r.toLowerCase() || frame.s.toLowerCase() !== agentSig.s.toLowerCase() || frame.v !== agentSig.v) {
245
+ throw new CoSignUnavailableError("the backend and agent derived different signatures");
246
+ }
247
+ return { ok: true, signature: assembleSignature(agentSig), intent };
248
+ }
249
+ case "rejection": {
250
+ if (POLICY_REASONS.has(frame.reason)) {
251
+ return rejection(frame.reason, frame.detail);
252
+ }
253
+ throw new CoSignUnavailableError(
254
+ `co-signer returned a non-policy rejection (${frame.reason}): ${frame.detail}`
255
+ );
256
+ }
257
+ case "error": {
258
+ throw new CoSignUnavailableError(`co-signer error: ${frame.message}`);
259
+ }
260
+ default: {
261
+ throw new CoSignUnavailableError("co-signer sent an unexpected frame");
262
+ }
263
+ }
264
+ }
265
+ }
266
+ function assembleSignature(sig) {
267
+ const yParity = sig.v - 27;
268
+ if (yParity !== 0 && yParity !== 1) {
269
+ throw new CoSignUnavailableError(`malformed recovery id v=${sig.v} (expected 27 or 28)`);
270
+ }
271
+ return serializeSignature({ r: sig.r, s: sig.s, yParity });
272
+ }
273
+
274
+ export { WIRE_VERSION, canonicalIntentBytes, createLocalPolicyGatedSigner, createMpc2pPolicyGatedSigner, toWireIntent };
275
+ //# sourceMappingURL=chunk-EUW7AZ4P.js.map
276
+ //# sourceMappingURL=chunk-EUW7AZ4P.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/signer/local.ts","../src/signer/mpc-2p-wire.ts","../src/signer/mpc-2p.ts"],"names":["getAddress"],"mappings":";;;;AAgEO,SAAS,6BACf,MAAA,EACgC;AAChC,EAAA,IAAI,MAAA,CAAO,wBAAwB,IAAA,EAAM;AACxC,IAAA,MAAM,IAAI,4BAAA;AAAA,MACT,qBAAA;AAAA,MACA;AAAA,KACD;AAAA,EACD;AAEA,EAAA,MAAM,EAAE,OAAA,EAAS,MAAA,EAAQ,UAAA,EAAW,GAAI,MAAA;AACxC,EAAA,MAAM,MAAA,GAAS,iBAAA,CAAkB,MAAA,CAAO,KAAK,CAAA;AAC7C,EAAA,MAAM,IAAA,GAAO,UAAA,CAAW,OAAA,CAAQ,OAAO,CAAA;AAEvC,EAAA,OAAO;AAAA,IACN,WAAA,EAAa,UAAA;AAAA,IACb,IAAA;AAAA,IACA,MAAM,KAAK,MAAA,EAA4C;AACtD,MAAA,IAAI,UAAA,CAAW,MAAA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,uBAAuB,oCAAoC,CAAA;AAAA,MACtE;AAAA;AACD,EACD;AACD;AAGA,SAAS,kBAAkB,GAAA,EAAyC;AACnE,EAAA,MAAM,OAAA,GAAU,IAAI,CAAA,GAAI,EAAA;AACxB,EAAA,IAAI,OAAA,KAAY,CAAA,IAAK,OAAA,KAAY,CAAA,EAAG;AACnC,IAAA,MAAM,IAAI,sBAAA,CAAuB,CAAA,wBAAA,EAA2B,GAAA,CAAI,CAAC,CAAA,oBAAA,CAAsB,CAAA;AAAA,EACxF;AACA,EAAA,OAAO,kBAAA,CAAmB,EAAE,CAAA,EAAG,GAAA,CAAI,GAAG,CAAA,EAAG,GAAA,CAAI,CAAA,EAAG,OAAA,EAAS,CAAA;AAC1D","file":"chunk-EUW7AZ4P.js","sourcesContent":["/**\n * The `local` PolicyGatedSigner adapter — `enforcement: \"advisory\"`.\n *\n * Wraps a viem {@link Account} + a {@link SpendingPolicy} + a pinned EIP-712\n * domain. `sign(intent)` evaluates the policy SDK-side and, on pass, produces a\n * real EIP-3009 authorization via {@link signTransferWithAuthorization}. It is\n * **advisory** because the wrapped key can still sign anything elsewhere — the\n * gate is only reached if the caller chooses to call *this* `sign()`. Use it for\n * dev, the A1 cross-language fallback, and any flow that is explicitly not\n * bounded/regulated; the type-gate (`requireNonBypassable`) keeps it out of\n * flows that require non-bypassable enforcement.\n *\n * @packageDocumentation\n */\n\nimport type { Account } from \"viem\";\nimport { getAddress } from \"viem\";\nimport type { SpendingPolicy, SpendState } from \"../policy/spending-policy\";\nimport { evaluateSpendingPolicy } from \"../policy/spending-policy\";\nimport type { X402AssetParam } from \"../tokens/asset-domain\";\nimport { resolveAssetParam, resolvedAssetToEip3009Domain } from \"../tokens/asset-domain\";\nimport { signTransferWithAuthorization } from \"../tokens/eip3009\";\nimport { PolicyGatedSignerConfigError } from \"./errors\";\nimport type { PaymentIntent, PolicyGatedSigner, SignerDescription, SignResult } from \"./types\";\n\n/** Parameters for {@link createLocalPolicyGatedSigner}. */\nexport interface CreateLocalPolicyGatedSignerParams {\n\t/** EOA / LocalAccount that signs the EIP-3009 authorization. */\n\treadonly account: Account;\n\t/** The spending policy this signer enforces (SDK-side, advisory). */\n\treadonly policy: SpendingPolicy;\n\t/** Asset binding — pins the EIP-712 domain `name`/`version`/`verifyingContract`. */\n\treadonly asset: X402AssetParam;\n\t/**\n\t * Required literal acknowledgement that this signer is **advisory** (a\n\t * key-holder can bypass its policy). Omitting it is a compile error (TS) and\n\t * a construction-time throw (JS) — so constructing an advisory signer is a\n\t * conscious, greppable act. For bounded/regulated flows use a cryptographic\n\t * adapter instead.\n\t */\n\treadonly acknowledgeAdvisory: true;\n\t/**\n\t * Optional cumulative-spend view (read-only) the adapter evaluates\n\t * `cumulativeCap` against. `local` does not own an authoritative ledger; the\n\t * caller folds a successful spend back in (e.g. via `mergeSpendState`) before\n\t * the next call. Default: empty.\n\t */\n\treadonly spendState?: () => SpendState | Promise<SpendState>;\n}\n\n/**\n * Construct a `local` (advisory) PolicyGatedSigner.\n *\n * @example\n * ```ts\n * const signer = createLocalPolicyGatedSigner({\n * account,\n * policy: createSpendingPolicy({ session: { id, notAfter }, perToken: [{ token: JPYC, maxPerSign: 1_000n }], recipientAllowlist: \"any\" }),\n * asset: { kind: \"known\", id: \"jpyc-v2\" },\n * acknowledgeAdvisory: true,\n * });\n * const result = await signer.sign(intent);\n * ```\n */\nexport function createLocalPolicyGatedSigner(\n\tparams: CreateLocalPolicyGatedSignerParams,\n): PolicyGatedSigner<\"advisory\"> {\n\tif (params.acknowledgeAdvisory !== true) {\n\t\tthrow new PolicyGatedSignerConfigError(\n\t\t\t\"acknowledgeAdvisory\",\n\t\t\t\"a local signer is advisory (a key-holder can bypass its policy); pass `acknowledgeAdvisory: true` to construct one consciously, or use a cryptographic adapter for bounded/regulated flows\",\n\t\t);\n\t}\n\n\tconst { account, policy, spendState } = params;\n\tconst pinned = resolveAssetParam(params.asset);\n\tconst from = getAddress(account.address);\n\n\treturn {\n\t\tenforcement: \"advisory\",\n\t\tfrom,\n\t\tasync sign(intent: PaymentIntent): Promise<SignResult> {\n\t\t\tif (getAddress(intent.from) !== from) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\trejection: {\n\t\t\t\t\t\treason: \"from_mismatch\",\n\t\t\t\t\t\tdetail: `intent.from ${getAddress(intent.from)} does not equal signer.from ${from}`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (getAddress(intent.token) !== pinned.verifyingContract) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\trejection: {\n\t\t\t\t\t\treason: \"token_not_allowed\",\n\t\t\t\t\t\tdetail: `intent.token ${getAddress(intent.token)} does not equal the signer's pinned verifyingContract ${pinned.verifyingContract}`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst state: SpendState = (await spendState?.()) ?? { spentPerToken: [] };\n\t\t\tconst nowSeconds = BigInt(Math.floor(Date.now() / 1000));\n\t\t\tconst decision = evaluateSpendingPolicy(policy, intent, state, nowSeconds);\n\t\t\tif (!decision.ok) {\n\t\t\t\treturn { ok: false, rejection: decision.rejection };\n\t\t\t}\n\n\t\t\tconst signed = await signTransferWithAuthorization(\n\t\t\t\taccount,\n\t\t\t\tresolvedAssetToEip3009Domain(pinned, intent.chainId),\n\t\t\t\t{\n\t\t\t\t\tfrom,\n\t\t\t\t\tto: intent.to,\n\t\t\t\t\tvalue: intent.value,\n\t\t\t\t\tvalidAfter: intent.validAfter,\n\t\t\t\t\tvalidBefore: intent.validBefore,\n\t\t\t\t\tnonce: intent.nonce,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { ok: true, signature: signed.signature, intent };\n\t\t},\n\t\tdescribe(): SignerDescription {\n\t\t\treturn {\n\t\t\t\tenforcement: \"advisory\",\n\t\t\t\tfrom,\n\t\t\t\tpolicyId: policy.session.id,\n\t\t\t\tnotAfter: policy.session.notAfter,\n\t\t\t\trevoked: policy.revoked,\n\t\t\t};\n\t\t},\n\t};\n}\n","/**\n * The `mpc-2p` cross-process **wire** — the versioned `CoSignFrame` control\n * envelope + the A3 canonical-request encoding, as TypeScript source-of-truth.\n *\n * This is the public, TS-interpreted half of the two-layer wire (RFC m6-3a §4.2):\n * a small, versioned envelope carries the decoded {@link PaymentIntent} (never a\n * digest — A4) plus the opaque DKLs round payloads (hex, produced/consumed only\n * by the WASM crypto agent). The shapes here mirror the deployed\n * `kawasekit-mpc-2p` Rust serde **byte-for-byte** (snake_case `wire_version`,\n * `session_id`, `auth_tag`; the string-encoded {@link WireIntent}), so a frame the\n * SDK builds round-trips through the backend's `serde_json`. The richer envelope\n * (ceremonyId / ssid / A3 freshness) is a later slice.\n *\n * `canonicalIntentBytes` is the A3 analog of the EIP-712 digest corpus: it\n * reproduces the backend's `auth::canonical_intent_bytes` exactly, so the\n * injected authenticator's HMAC equals what the co-signer verifies.\n *\n * @packageDocumentation\n */\n\nimport type { Hex } from \"viem\";\nimport type { PaymentIntent } from \"./types\";\n\n/** The wire protocol version. A frame whose `wire_version` differs is rejected. */\nexport const WIRE_VERSION = 1 as const;\n\n/**\n * The string-encoded EIP-3009 intent as it crosses the wire — lowercase `0x`\n * addresses, **decimal** integer strings, `0x` hex nonce. Decoupled from any\n * library's native serde so a stdlib client reproduces it trivially; matches the\n * Rust `WireIntent` field names + encoding exactly.\n */\nexport interface WireIntent {\n\treadonly token: string;\n\treadonly chain_id: number;\n\treadonly from: string;\n\treadonly to: string;\n\treadonly value: string;\n\treadonly valid_after: string;\n\treadonly valid_before: string;\n\treadonly nonce: string;\n}\n\n/** Encode a decoded {@link PaymentIntent} for the wire. */\nexport function toWireIntent(intent: PaymentIntent): WireIntent {\n\treturn {\n\t\ttoken: intent.token.toLowerCase(),\n\t\tchain_id: intent.chainId,\n\t\tfrom: intent.from.toLowerCase(),\n\t\tto: intent.to.toLowerCase(),\n\t\tvalue: intent.value.toString(),\n\t\tvalid_after: intent.validAfter.toString(),\n\t\tvalid_before: intent.validBefore.toString(),\n\t\tnonce: intent.nonce.toLowerCase(),\n\t};\n}\n\n/**\n * A versioned control frame: the only cross-language content of the wire. The\n * DKLs round bytes ride opaque inside `payload`; everything else is the small,\n * pinned envelope. Internally tagged by `kind` (matches the Rust serde).\n */\nexport type CoSignFrame = { readonly wire_version: typeof WIRE_VERSION } & (\n\t| {\n\t\t\treadonly kind: \"request\";\n\t\t\treadonly session_id: string;\n\t\t\treadonly intent: WireIntent;\n\t\t\t/** A3 authenticator over {@link canonicalIntentBytes}, `0x`-hex. */\n\t\t\treadonly auth_tag: Hex;\n\t }\n\t| { readonly kind: \"round\"; readonly payload: Hex }\n\t| { readonly kind: \"result\"; readonly r: Hex; readonly s: Hex; readonly v: number }\n\t| { readonly kind: \"rejection\"; readonly reason: string; readonly detail: string }\n\t| { readonly kind: \"error\"; readonly message: string }\n);\n\n/**\n * The A3 canonical encoding of an intent — a byte-exact mirror of the backend's\n * `auth::canonical_intent_bytes` (domain-tag `kawasekit-mpc-2p/cosign-request/v2`,\n * one `key=value\\n` line per field, lowercase `0x` addresses, decimal integers,\n * `0x` hex nonce, trailing newline). The injected authenticator HMACs these bytes;\n * because the encoding is shared, the tag equals the co-signer's.\n */\nexport function canonicalIntentBytes(intent: PaymentIntent): Uint8Array {\n\tconst lines = [\n\t\t\"kawasekit-mpc-2p/cosign-request/v2\",\n\t\t`token=${intent.token.toLowerCase()}`,\n\t\t`chainId=${intent.chainId}`,\n\t\t`from=${intent.from.toLowerCase()}`,\n\t\t`to=${intent.to.toLowerCase()}`,\n\t\t`value=${intent.value}`,\n\t\t`validAfter=${intent.validAfter}`,\n\t\t`validBefore=${intent.validBefore}`,\n\t\t`nonce=${intent.nonce.toLowerCase()}`,\n\t];\n\treturn new TextEncoder().encode(lines.map((l) => `${l}\\n`).join(\"\"));\n}\n","/**\n * The `mpc-2p` PolicyGatedSigner adapter — `enforcement: \"cryptographic\"`.\n *\n * A 2-of-2 MPC co-signer: the agent holds ONE DKLs share, the owner backend holds\n * the other + the authoritative policy gate. No valid signature exists without a\n * **policy-passing co-sign**, so — unlike `local` — a single key-holder cannot\n * bypass the policy. That is what earns the non-bypassable `\"cryptographic\"` label\n * and lets the M6-0 type-gate (`requireNonBypassable`) reject an advisory signer at\n * compile time in bounded flows.\n *\n * **Open-core / thin adapter.** This module is pure orchestration over injected\n * interfaces — it ships in the public SDK with **no crypto, no socket, no key**:\n *\n * - {@link Mpc2pCoSignAgent} — the WASM DKLs share (the private package's compiled\n * `crypto-core`); drives the agent's half of the ceremony round-by-round.\n * - {@link CoSignTransport} — the authenticated, encrypted (wss/mTLS) frame channel\n * to the owner backend (the private package's transport).\n * - {@link CoSignRequestAuthenticator} — the A3 HMAC (the pre-shared key never\n * enters this module).\n *\n * The adapter owns the protocol: it pins the EIP-712 domain, **re-derives the\n * digest from the intent (A4)** via the shared `transferWithAuthorizationTypes`\n * source-of-truth, computes the A3 canonical bytes, frames the versioned\n * {@link CoSignFrame} envelope, pumps the ceremony, and maps the terminal frame to\n * a {@link SignResult}. Crucially it has **no local-signing path**: any\n * transport/availability failure throws {@link CoSignUnavailableError}, never an\n * `{ ok: true }` and never a {@link PolicyRejection} (the no-silent-fallback\n * guarantee, RFC m6-3a constraint 3 / W8).\n *\n * @packageDocumentation\n */\n\nimport type { Address, Hex } from \"viem\";\nimport { getAddress, hashTypedData, serializeSignature } from \"viem\";\nimport type { X402AssetParam } from \"../tokens/asset-domain\";\nimport { resolveAssetParam, resolvedAssetToEip3009Domain } from \"../tokens/asset-domain\";\nimport { transferWithAuthorizationTypes } from \"../tokens/eip3009\";\nimport { CoSignUnavailableError, PolicyGatedSignerConfigError } from \"./errors\";\nimport type { CoSignFrame } from \"./mpc-2p-wire\";\nimport { canonicalIntentBytes, toWireIntent, WIRE_VERSION } from \"./mpc-2p-wire\";\nimport type {\n\tPaymentIntent,\n\tPolicyGatedSigner,\n\tPolicyRejection,\n\tSignerDescription,\n\tSignResult,\n} from \"./types\";\n\n/** The agent's half of the 2-of-2 ceremony (the injected WASM DKLs share). */\nexport interface Mpc2pCoSignAgent {\n\t/** The group 2-of-2 EOA this share controls — must equal the signer's `from`. */\n\tgroupEoa(): Address;\n\t/** Begin signing the 32-byte EIP-712 `digest`; returns the first outbound round (hex). */\n\tstart(digest: Hex): Hex;\n\t/** Feed one inbound round (hex); returns the next outbound round, or the final signature. */\n\tstep(incoming: Hex): Mpc2pStepOutcome;\n}\n\n/** The result of one {@link Mpc2pCoSignAgent.step}. */\nexport type Mpc2pStepOutcome =\n\t| { readonly outbound: Hex }\n\t| { readonly signature: { readonly r: Hex; readonly s: Hex; readonly v: number } };\n\n/** One authenticated, encrypted ceremony connection to the owner backend. */\nexport interface CoSignConnection {\n\t/** Send one control frame. */\n\tsend(frame: CoSignFrame): Promise<void>;\n\t/** Receive the next control frame (resolves per round). */\n\trecv(): Promise<CoSignFrame>;\n\t/** Release the connection (best-effort; errors here are ignored). */\n\tclose(): void | Promise<void>;\n}\n\n/** Opens a wss/mTLS {@link CoSignConnection} for a single co-sign ceremony. */\nexport interface CoSignTransport {\n\tconnect(): Promise<CoSignConnection>;\n}\n\n/** The A3 request authenticator — HMAC (or signature) over the canonical request bytes. */\nexport interface CoSignRequestAuthenticator {\n\t/** Authenticator tag over {@link canonicalIntentBytes}; the key stays inside. */\n\ttag(canonicalRequest: Uint8Array): Hex | Promise<Hex>;\n}\n\n/** Parameters for {@link createMpc2pPolicyGatedSigner}. */\nexport interface Mpc2pSignerParams {\n\t/** The group 2-of-2 EOA; every `intent.from` must equal this (asserted vs the agent). */\n\treadonly from: Address;\n\t/** Asset binding — pins the EIP-712 domain `name`/`version`/`verifyingContract` (A4). */\n\treadonly asset: X402AssetParam;\n\t/** The bound policy session, for `describe()` (the backend holds the authoritative policy). */\n\treadonly session: { readonly id: string; readonly notAfter: bigint };\n\t/** The injected WASM DKLs share (private package). */\n\treadonly agent: Mpc2pCoSignAgent;\n\t/** The injected wss/mTLS frame channel (private package). */\n\treadonly transport: CoSignTransport;\n\t/** The injected A3 authenticator (the pre-shared key never enters the SDK). */\n\treadonly authenticator: CoSignRequestAuthenticator;\n}\n\n/**\n * The backend `rejection` reasons that are genuine **policy denials** (the owner\n * decided \"no\" — audit-meaningful → `{ ok: false, rejection }`). Any other reason\n * on a rejection frame is treated as \"the owner did not cleanly decide\" and throws\n * {@link CoSignUnavailableError} (no-silent-fallback; never a misclassified denial).\n */\nconst POLICY_REASONS: ReadonlySet<PolicyRejection[\"reason\"]> = new Set([\n\t\"revoked\",\n\t\"expired\",\n\t\"token_not_allowed\",\n\t\"recipient_not_allowed\",\n\t\"amount_exceeds_per_sign\",\n\t\"amount_exceeds_cumulative\",\n\t\"intent_digest_mismatch\",\n\t\"unauthenticated\",\n\t\"from_mismatch\",\n\t\"nonce_reuse_conflict\",\n]);\n\nfunction rejection(reason: PolicyRejection[\"reason\"], detail: string): SignResult {\n\treturn { ok: false, rejection: { reason, detail } };\n}\n\n/**\n * Construct an `mpc-2p` (cryptographic) PolicyGatedSigner over injected agent +\n * transport + authenticator.\n *\n * @example\n * ```ts\n * // The agent, transport and authenticator come from the private `kawasekit-mpc-2p`\n * // package (the WASM share, the wss/mTLS client, the HMAC key) — never bundled here.\n * const signer = createMpc2pPolicyGatedSigner({\n * from: groupEoa,\n * asset: { kind: \"known\", id: \"jpyc-v2\" },\n * session: { id: \"sess-1\", notAfter: 2_000_000_000n },\n * agent, transport, authenticator,\n * });\n * requireNonBypassable(signer); // ✓ \"cryptographic\" — passes the type-gate\n * const result = await signer.sign(intent);\n * ```\n */\nexport function createMpc2pPolicyGatedSigner(\n\tparams: Mpc2pSignerParams,\n): PolicyGatedSigner<\"cryptographic\"> {\n\tconst { agent, transport, authenticator, session } = params;\n\tconst pinned = resolveAssetParam(params.asset);\n\tconst from = getAddress(params.from);\n\n\t// The injected share MUST control the declared group EOA, or every signature\n\t// would recover to the wrong address.\n\tconst agentEoa = getAddress(agent.groupEoa());\n\tif (agentEoa !== from) {\n\t\tthrow new PolicyGatedSignerConfigError(\n\t\t\t\"from\",\n\t\t\t`the agent share controls ${agentEoa} but params.from is ${from}`,\n\t\t);\n\t}\n\n\treturn {\n\t\tenforcement: \"cryptographic\",\n\t\tfrom,\n\t\tasync sign(intent: PaymentIntent): Promise<SignResult> {\n\t\t\t// Adapter-local pre-checks (cheap; no wire needed). Same shape as `local`.\n\t\t\tif (getAddress(intent.from) !== from) {\n\t\t\t\treturn rejection(\n\t\t\t\t\t\"from_mismatch\",\n\t\t\t\t\t`intent.from ${getAddress(intent.from)} does not equal signer.from ${from}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (getAddress(intent.token) !== pinned.verifyingContract) {\n\t\t\t\treturn rejection(\n\t\t\t\t\t\"token_not_allowed\",\n\t\t\t\t\t`intent.token ${getAddress(intent.token)} does not equal the signer's pinned verifyingContract ${pinned.verifyingContract}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// A4: re-derive the EIP-712 digest from the intent + the pinned domain (the\n\t\t\t// SDK's exported types are the cross-language source of truth). The agent and\n\t\t\t// the backend each sign THIS digest; the SoT keeps them byte-identical.\n\t\t\tconst digest = hashTypedData({\n\t\t\t\tdomain: resolvedAssetToEip3009Domain(pinned, intent.chainId),\n\t\t\t\ttypes: transferWithAuthorizationTypes,\n\t\t\t\tprimaryType: \"TransferWithAuthorization\",\n\t\t\t\tmessage: {\n\t\t\t\t\tfrom,\n\t\t\t\t\tto: intent.to,\n\t\t\t\t\tvalue: intent.value,\n\t\t\t\t\tvalidAfter: intent.validAfter,\n\t\t\t\t\tvalidBefore: intent.validBefore,\n\t\t\t\t\tnonce: intent.nonce,\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t// A3: authenticate the request (the canonical bytes are the shared SoT; the\n\t\t\t// HMAC key lives inside the injected authenticator).\n\t\t\tconst authTag = await authenticator.tag(canonicalIntentBytes(intent));\n\n\t\t\tconst conn = await openConnection(transport);\n\t\t\ttry {\n\t\t\t\treturn await runCeremony(conn, agent, session.id, intent, digest, authTag);\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\tawait conn.close();\n\t\t\t\t} catch {\n\t\t\t\t\t// best-effort cleanup; a close error must not mask the result/throw.\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tdescribe(): SignerDescription {\n\t\t\treturn {\n\t\t\t\tenforcement: \"cryptographic\",\n\t\t\t\tfrom,\n\t\t\t\tpolicyId: session.id,\n\t\t\t\tnotAfter: session.notAfter,\n\t\t\t\t// The backend owns authoritative revocation (a revoked session → a\n\t\t\t\t// rejection at sign time); this metadata field is best-effort.\n\t\t\t\trevoked: false,\n\t\t\t};\n\t\t},\n\t};\n}\n\nasync function openConnection(transport: CoSignTransport): Promise<CoSignConnection> {\n\ttry {\n\t\treturn await transport.connect();\n\t} catch (cause) {\n\t\tthrow new CoSignUnavailableError(\"co-signer connection failed\", { cause });\n\t}\n}\n\n/**\n * Drive the full ceremony over `conn`: send the authenticated request + the agent's\n * first round, then pump rounds until a terminal frame. Returns a {@link SignResult}\n * (success or a policy denial) or throws {@link CoSignUnavailableError}. There is no\n * path that returns `{ ok: true }` without a backend `result` frame.\n */\nasync function runCeremony(\n\tconn: CoSignConnection,\n\tagent: Mpc2pCoSignAgent,\n\tsessionId: string,\n\tintent: PaymentIntent,\n\tdigest: Hex,\n\tauthTag: Hex,\n): Promise<SignResult> {\n\tconst send = async (frame: CoSignFrame): Promise<void> => {\n\t\ttry {\n\t\t\tawait conn.send(frame);\n\t\t} catch (cause) {\n\t\t\tthrow new CoSignUnavailableError(\"co-sign connection dropped while sending\", { cause });\n\t\t}\n\t};\n\tconst recv = async (): Promise<CoSignFrame> => {\n\t\tlet frame: CoSignFrame;\n\t\ttry {\n\t\t\tframe = await conn.recv();\n\t\t} catch (cause) {\n\t\t\tthrow new CoSignUnavailableError(\"co-sign connection dropped mid-ceremony\", { cause });\n\t\t}\n\t\tif (frame.wire_version !== WIRE_VERSION) {\n\t\t\tthrow new CoSignUnavailableError(\n\t\t\t\t`co-signer spoke wire_version ${frame.wire_version}, expected ${WIRE_VERSION}`,\n\t\t\t);\n\t\t}\n\t\treturn frame;\n\t};\n\n\tawait send({\n\t\twire_version: WIRE_VERSION,\n\t\tkind: \"request\",\n\t\tsession_id: sessionId,\n\t\tintent: toWireIntent(intent),\n\t\tauth_tag: authTag,\n\t});\n\n\tlet first: Hex;\n\ttry {\n\t\tfirst = agent.start(digest);\n\t} catch (cause) {\n\t\tthrow new CoSignUnavailableError(\"the agent failed to start the ceremony\", { cause });\n\t}\n\tawait send({ wire_version: WIRE_VERSION, kind: \"round\", payload: first });\n\n\tlet agentSig: { r: Hex; s: Hex; v: number } | null = null;\n\tfor (;;) {\n\t\tconst frame = await recv();\n\t\tswitch (frame.kind) {\n\t\t\tcase \"round\": {\n\t\t\t\tlet step: Mpc2pStepOutcome;\n\t\t\t\ttry {\n\t\t\t\t\tstep = agent.step(frame.payload);\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tthrow new CoSignUnavailableError(\"the agent rejected a round frame\", { cause });\n\t\t\t\t}\n\t\t\t\tif (\"outbound\" in step) {\n\t\t\t\t\tawait send({ wire_version: WIRE_VERSION, kind: \"round\", payload: step.outbound });\n\t\t\t\t} else {\n\t\t\t\t\tagentSig = step.signature;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"result\": {\n\t\t\t\tif (agentSig === null) {\n\t\t\t\t\tthrow new CoSignUnavailableError(\n\t\t\t\t\t\t\"the backend returned a result before the agent derived a signature\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tframe.r.toLowerCase() !== agentSig.r.toLowerCase() ||\n\t\t\t\t\tframe.s.toLowerCase() !== agentSig.s.toLowerCase() ||\n\t\t\t\t\tframe.v !== agentSig.v\n\t\t\t\t) {\n\t\t\t\t\tthrow new CoSignUnavailableError(\"the backend and agent derived different signatures\");\n\t\t\t\t}\n\t\t\t\treturn { ok: true, signature: assembleSignature(agentSig), intent };\n\t\t\t}\n\t\t\tcase \"rejection\": {\n\t\t\t\t// A genuine policy denial → typed rejection. A non-policy \"rejection\"\n\t\t\t\t// (transient/internal) is \"the owner did not decide\" → no-fallback throw.\n\t\t\t\tif (POLICY_REASONS.has(frame.reason as PolicyRejection[\"reason\"])) {\n\t\t\t\t\t// reason membership verified against POLICY_REASONS above.\n\t\t\t\t\treturn rejection(frame.reason as PolicyRejection[\"reason\"], frame.detail);\n\t\t\t\t}\n\t\t\t\tthrow new CoSignUnavailableError(\n\t\t\t\t\t`co-signer returned a non-policy rejection (${frame.reason}): ${frame.detail}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase \"error\": {\n\t\t\t\tthrow new CoSignUnavailableError(`co-signer error: ${frame.message}`);\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\t// Unknown frame kind — never a silent success.\n\t\t\t\tthrow new CoSignUnavailableError(\"co-signer sent an unexpected frame\");\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Assemble a 65-byte EIP-3009 signature from the agent's `{ r, s, v }` (v = recovery_id + 27). */\nfunction assembleSignature(sig: { r: Hex; s: Hex; v: number }): Hex {\n\tconst yParity = sig.v - 27;\n\tif (yParity !== 0 && yParity !== 1) {\n\t\tthrow new CoSignUnavailableError(`malformed recovery id v=${sig.v} (expected 27 or 28)`);\n\t}\n\treturn serializeSignature({ r: sig.r, s: sig.s, yParity });\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { X402_HEADER_PAYMENT_SIGNATURE, encodePaymentSignatureHeader, X402_HEADER_IDEMPOTENCY_KEY, X402_HEADER_PAYMENT_RESPONSE, decodePaymentResponseHeader, X402_HEADER_PAYMENT_REQUIRED, decodePaymentRequiredHeader } from './chunk-PVUKX6IF.js';
2
2
  import { invokeHookSafely } from './chunk-LEHWRDVS.js';
3
3
  import { X402_VERSION, chainIdToX402Network, x402NetworkToChainId } from './chunk-QHUCU5YX.js';
4
- import { resolveAssetParam, authorizationDeadlineFromNow, deriveAuthorizationNonce, generateAuthorizationNonce, signTransferWithAuthorization, resolvedAssetToEip3009Domain, assertNonBypassable } from './chunk-VXZHS74W.js';
4
+ import { resolveAssetParam, authorizationDeadlineFromNow, deriveAuthorizationNonce, generateAuthorizationNonce, signTransferWithAuthorization, resolvedAssetToEip3009Domain, assertNonBypassable } from './chunk-5TTOAVHE.js';
5
5
  import { X402InvalidPayloadError, X402PolicyRejectedError } from './chunk-WMVJNPX2.js';
6
6
  import { jpycAbi, JPYC_V2_ADDRESS, JPYC_EIP712_DOMAIN_HINT } from './chunk-KT7XDT2T.js';
7
7
  import { getChain, isSupportedChainId } from './chunk-SOTYGX67.js';
@@ -880,5 +880,5 @@ function wrapFetch(params) {
880
880
  }
881
881
 
882
882
  export { X402_DEFAULT_AUTHORIZATION_LIFETIME_SECONDS, X402_FACILITATOR_ERROR_CODES, createCoinbaseFacilitator, createHttpFacilitator, createSelfFacilitator, createX402PaymentSigner, deriveReceiptTimeoutMs, wrapFetch };
883
- //# sourceMappingURL=chunk-SMAZUZFO.js.map
884
- //# sourceMappingURL=chunk-SMAZUZFO.js.map
883
+ //# sourceMappingURL=chunk-G3UC6SME.js.map
884
+ //# sourceMappingURL=chunk-G3UC6SME.js.map