@haven_ai/sdk 0.8.0-alpha.0 → 0.9.0-alpha.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 (39) hide show
  1. package/dist/base64-BZDPJ8M1.d.ts +1344 -0
  2. package/dist/base64-Cyxhsvqd.d.cts +1344 -0
  3. package/dist/{chunk-UXULZ3ZY.js → chunk-424S4QMG.js} +10 -5
  4. package/dist/chunk-424S4QMG.js.map +1 -0
  5. package/dist/{chunk-HX34HOW4.cjs → chunk-4Z6ATE44.cjs} +2 -2
  6. package/dist/chunk-4Z6ATE44.cjs.map +1 -0
  7. package/dist/chunk-7UTWSJC5.cjs +106 -0
  8. package/dist/chunk-7UTWSJC5.cjs.map +1 -0
  9. package/dist/{chunk-H4APV67M.js → chunk-J7N4LUZZ.js} +2 -2
  10. package/dist/chunk-J7N4LUZZ.js.map +1 -0
  11. package/dist/chunk-VRKWNJ7H.js +103 -0
  12. package/dist/chunk-VRKWNJ7H.js.map +1 -0
  13. package/dist/{chunk-WJFDXCYP.cjs → chunk-ZDKNPNI3.cjs} +41 -35
  14. package/dist/chunk-ZDKNPNI3.cjs.map +1 -0
  15. package/dist/edge.cjs +97 -89
  16. package/dist/edge.d.cts +4 -2
  17. package/dist/edge.d.ts +4 -2
  18. package/dist/edge.js +4 -4
  19. package/dist/index.cjs +1033 -490
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +103 -147
  22. package/dist/index.d.ts +103 -147
  23. package/dist/index.js +705 -189
  24. package/dist/index.js.map +1 -1
  25. package/dist/receipt-D4Roey3D.d.cts +130 -0
  26. package/dist/receipt-WkXHZGbu.d.ts +130 -0
  27. package/dist/test-support.cjs +71 -18
  28. package/dist/test-support.cjs.map +1 -1
  29. package/dist/test-support.d.cts +21 -1
  30. package/dist/test-support.d.ts +21 -1
  31. package/dist/test-support.js +53 -3
  32. package/dist/test-support.js.map +1 -1
  33. package/dist/{base64-znjJJQqu.d.cts → types-CrszUJ7Z.d.cts} +208 -1306
  34. package/dist/{base64-znjJJQqu.d.ts → types-CrszUJ7Z.d.ts} +208 -1306
  35. package/package.json +1 -1
  36. package/dist/chunk-H4APV67M.js.map +0 -1
  37. package/dist/chunk-HX34HOW4.cjs.map +0 -1
  38. package/dist/chunk-UXULZ3ZY.js.map +0 -1
  39. package/dist/chunk-WJFDXCYP.cjs.map +0 -1
@@ -1,4 +1,4 @@
1
- import { HavenSigningError, deriveDelegateAccountAddress, DELEGATION_MANAGER, assertRedeemsOwnBudgetDelegation, verifySettlementChild, REDEEM_DELEGATIONS_ABI, chainIdForNetwork, ROOT_AUTHORITY, CAVEAT_ENFORCERS, DELEGATION_TUPLE_COMPONENTS } from './chunk-H4APV67M.js';
1
+ import { HavenSigningError, deriveDelegateAccountAddress, DELEGATION_MANAGER, assertRedeemsOwnBudgetDelegation, verifySettlementChild, REDEEM_DELEGATIONS_ABI, chainIdForNetwork, ROOT_AUTHORITY, CAVEAT_ENFORCERS, DELEGATION_TUPLE_COMPONENTS } from './chunk-J7N4LUZZ.js';
2
2
  import { decodeFunctionData, encodeFunctionData, encodePacked, recoverTypedDataAddress, serializeSignature, hashTypedData, encodeAbiParameters, keccak256 } from 'viem';
3
3
  import { createHash } from 'crypto';
4
4
  import { secp256k1 } from '@noble/curves/secp256k1';
@@ -446,6 +446,11 @@ function x402PaymentHeaderNamesFor(paymentHeader) {
446
446
  if (!accepted || typeof accepted !== "object" || Array.isArray(accepted)) return both;
447
447
  return isErc7710Option(accepted) ? [X402_PAYMENT_HEADER_NAME] : both;
448
448
  }
449
+ function x402RetryHeadersFor(paymentHeader) {
450
+ return Object.fromEntries(
451
+ x402PaymentHeaderNamesFor(paymentHeader).map((name) => [name, paymentHeader])
452
+ );
453
+ }
449
454
  function x402PaymentHeaderNamesSent(paymentHeader) {
450
455
  return x402PaymentHeaderNamesFor(paymentHeader).join(", ");
451
456
  }
@@ -775,7 +780,7 @@ function stableStringify2(value) {
775
780
  }
776
781
 
777
782
  // src/client-identity.ts
778
- var SDK_VERSION = "0.8.0-alpha.0";
783
+ var SDK_VERSION = "0.9.0-alpha.0";
779
784
  var HAVEN_CLIENT_HEADER = "X-Haven-Client";
780
785
  function havenClientIdentity(pkg, version) {
781
786
  return `${pkg}/${version}`;
@@ -1375,6 +1380,6 @@ function hashDelegation(delegation) {
1375
1380
  return keccak256(encoded);
1376
1381
  }
1377
1382
 
1378
- export { CAVEAT_TYPEHASH, DEFAULT_NEXT_TOOL_BY_ACTION, DELEGATION_TYPEHASH, DIRECT_PAYMENT_CHAIN_IDS, ERC7710_ASSET_TRANSFER_METHOD, EXECUTE_ABI, HAVEN_CLIENT_HEADER, HAVEN_MINIMUM_NODE_VERSION, HavenTypedDataRefusedError, MAX_TASK_BUDGET_TTL_SECONDS, NEXT_TOOL_SERVER_NAMES, NEXT_TOOL_SERVER_ROLES, SDK_CLIENT_IDENTITY, SDK_VERSION, SWEEP_BASE_CHAIN_ID, SWEEP_BASE_SEPOLIA_CHAIN_ID, SWEEP_BASE_SEPOLIA_USDC_ADDRESS, SWEEP_BASE_USDC_ADDRESS, TAX_DECLARATION_DOMAIN, TAX_DECLARATION_PRIMARY_TYPE, TAX_DECLARATION_TYPES, TRANSFER_WITH_AUTHORIZATION_TYPES, TYPED_DATA_NOT_ALLOWED, TaxDeclarationRefusedError, X402PaymentHeaderValidationError, X402_LEGACY_PAYMENT_HEADER_NAME, X402_MAX_AUTHORIZATION_WINDOW_SECONDS, X402_PAYMENT_HEADER_NAME, X402_PAYMENT_HEADER_NAMES, X402_PAYMENT_HEADER_NAMES_SENT, X402_PAYMENT_REQUIRED_HEADER_NAME, X402_PAYMENT_RESPONSE_HEADER_NAME, X402_SETTLEMENT_FORWARD_MARGIN_SECONDS, X_TAX_DECLARATION_HEADER, addressFromKey, assertBoundDirectPaymentUserOp, assertFundingLegPaysDelegate, assertOwnSettlementChild, assertOwnTaskBudgetCloseUserOp, assertOwnTaskChild, buildSignedTaxDeclaration, buildSweepAuthorizationMessage, buildSweepTypedData, buildX402ExpectedMessage, buildX402IdempotencyKey, compareNodeVersions, createNextStepBuilder, decodeBase64Json, decodeBase64Utf8, defaultNextToolFor, encodeBase64Json, encodeBase64Utf8, encodePaymentProof, encodeTaxDeclarationHeader, hashDelegation, havenClientIdentity, isErc7710Option, isSupportedNodeVersion, isSweepableChain, isTaskChildTypedData, normalizePaymentRequired, parseNextTool, parsePaymentRequired, parsePaymentRequiredResponse, principalAttributionHash, readClientUpdate, renderNextTool, resolveTokenBySymbol, resolveTokenFromAddress, selectErc7710PaymentOption, selectPaymentOption, selectStandardPaymentOption, selectX402SettlementScheme, signHash, sweepUsdcAddress, sweepUsdcDomain, taxPrincipalId, toStandardPaymentRequirements, unsupportedNodeVersionMessage, validateStandardX402PaymentHeader, verifySignature, verifyTaxDeclarationSignature, x402AssetTransferMethod, x402AuthorizationAmount, x402FacilitatorAddresses, x402PaymentHeaderNamesFor, x402PaymentHeaderNamesSent, x402V2PaymentEnvelope };
1379
- //# sourceMappingURL=chunk-UXULZ3ZY.js.map
1380
- //# sourceMappingURL=chunk-UXULZ3ZY.js.map
1383
+ export { CAVEAT_TYPEHASH, DEFAULT_NEXT_TOOL_BY_ACTION, DELEGATION_TYPEHASH, DIRECT_PAYMENT_CHAIN_IDS, ERC7710_ASSET_TRANSFER_METHOD, EXECUTE_ABI, HAVEN_CLIENT_HEADER, HAVEN_MINIMUM_NODE_VERSION, HavenTypedDataRefusedError, MAX_TASK_BUDGET_TTL_SECONDS, NEXT_TOOL_SERVER_NAMES, NEXT_TOOL_SERVER_ROLES, SDK_CLIENT_IDENTITY, SDK_VERSION, SWEEP_BASE_CHAIN_ID, SWEEP_BASE_SEPOLIA_CHAIN_ID, SWEEP_BASE_SEPOLIA_USDC_ADDRESS, SWEEP_BASE_USDC_ADDRESS, TAX_DECLARATION_DOMAIN, TAX_DECLARATION_PRIMARY_TYPE, TAX_DECLARATION_TYPES, TRANSFER_WITH_AUTHORIZATION_TYPES, TYPED_DATA_NOT_ALLOWED, TaxDeclarationRefusedError, X402PaymentHeaderValidationError, X402_LEGACY_PAYMENT_HEADER_NAME, X402_MAX_AUTHORIZATION_WINDOW_SECONDS, X402_PAYMENT_HEADER_NAME, X402_PAYMENT_HEADER_NAMES, X402_PAYMENT_HEADER_NAMES_SENT, X402_PAYMENT_REQUIRED_HEADER_NAME, X402_PAYMENT_RESPONSE_HEADER_NAME, X402_SETTLEMENT_FORWARD_MARGIN_SECONDS, X_TAX_DECLARATION_HEADER, addressFromKey, assertBoundDirectPaymentUserOp, assertFundingLegPaysDelegate, assertOwnSettlementChild, assertOwnTaskBudgetCloseUserOp, assertOwnTaskChild, buildSignedTaxDeclaration, buildSweepAuthorizationMessage, buildSweepTypedData, buildX402ExpectedMessage, buildX402IdempotencyKey, compareNodeVersions, createNextStepBuilder, decodeBase64Json, decodeBase64Utf8, defaultNextToolFor, encodeBase64Json, encodeBase64Utf8, encodePaymentProof, encodeTaxDeclarationHeader, hashDelegation, havenClientIdentity, isErc7710Option, isSupportedNodeVersion, isSweepableChain, isTaskChildTypedData, normalizePaymentRequired, parseNextTool, parsePaymentRequired, parsePaymentRequiredResponse, principalAttributionHash, readClientUpdate, renderNextTool, resolveTokenBySymbol, resolveTokenFromAddress, selectErc7710PaymentOption, selectPaymentOption, selectStandardPaymentOption, selectX402SettlementScheme, signHash, sweepUsdcAddress, sweepUsdcDomain, taxPrincipalId, toStandardPaymentRequirements, unsupportedNodeVersionMessage, validateStandardX402PaymentHeader, verifySignature, verifyTaxDeclarationSignature, x402AssetTransferMethod, x402AuthorizationAmount, x402FacilitatorAddresses, x402PaymentHeaderNamesFor, x402PaymentHeaderNamesSent, x402RetryHeadersFor, x402V2PaymentEnvelope };
1384
+ //# sourceMappingURL=chunk-424S4QMG.js.map
1385
+ //# sourceMappingURL=chunk-424S4QMG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/direct-payment-guard.ts","../src/base64.ts","../src/sweep.ts","../src/x402.ts","../src/client-identity.ts","../src/edge-signing.ts","../src/tax-declaration.ts","../src/next-step.ts","../src/node-version.ts","../src/task-budget-guards.ts"],"names":["stableStringify","sameAddress","hex","createHash","decodeFunctionData","encodeFunctionData"],"mappings":";;;;;;AAiCO,IAAM,sBAAA,GAAyB;AAO/B,IAAM,0BAAA,GAAN,cAAyC,iBAAA,CAAkB;AAAA,EAGhE,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACZ,IAAC,KAA0B,IAAA,GAAO,sBAAA;AACnC,IAAA,IAAA,CAAK,IAAA,GAAO,4BAAA;AAAA,EACd;AACF;AASO,IAAM,2CAAgD,IAAI,GAAA,CAAI,CAAC,IAAA,EAAM,KAAK,CAAC;AAG3E,IAAM,WAAA,GAAc;AAAA,EACzB;AAAA,IACE,IAAA,EAAM,UAAA;AAAA,IACN,IAAA,EAAM,SAAA;AAAA,IACN,MAAA,EAAQ;AAAA,MACN;AAAA,QACE,IAAA,EAAM,YAAA;AAAA,QACN,IAAA,EAAM,OAAA;AAAA,QACN,UAAA,EAAY;AAAA,UACV,EAAE,IAAA,EAAM,QAAA,EAAU,IAAA,EAAM,SAAA,EAAU;AAAA,UAClC,EAAE,IAAA,EAAM,OAAA,EAAS,IAAA,EAAM,SAAA,EAAU;AAAA,UACjC,EAAE,IAAA,EAAM,UAAA,EAAY,IAAA,EAAM,OAAA;AAAQ;AACpC;AACF,KACF;AAAA,IACA,SAAS,EAAC;AAAA,IACV,eAAA,EAAiB;AAAA;AAErB;AAUO,SAAS,8BAAA,CACd,WACA,eAAA,EACM;AACN,EAAA,MAAM,MAAA,GAAU,SAAA,CAAU,MAAA,IAAU,EAAC;AACrC,EAAA,MAAM,OAAA,GAAW,SAAA,CAAU,OAAA,IAAW,EAAC;AAQvC,EAAA,IAAI,OAAO,MAAA,CAAO,OAAA,KAAY,YAAY,OAAO,MAAA,CAAO,YAAY,QAAA,EAAU;AAC5E,IAAA,MAAM,IAAI,0BAAA;AAAA,MACR,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;AAEA,SAAS,iBAAiB,OAAA,EAA4D;AACpF,EAAA,MAAM,YAAA,GAAe,CAAA,EAAA,EAAK,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,KAAM,UAAA,CAAW,CAAC,CAAA,CAAE,MAAM,CAAC,CAAC,CAAA,CAAE,IAAA,CAAK,EAAE,CAAC,CAAA,CAAA;AAC7E,EAAA,OAAO,UAAU,YAAY,CAAA;AAC/B;AAQO,SAAS,eAAe,UAAA,EAAuC;AACpE,EAAA,MAAM,WAAA,GAAc,gBAAA,CAAiB,UAAA,CAAW,OAAO,CAAA;AACvD,EAAA,MAAM,OAAA,GAAU,mBAAA;AAAA,IACd;AAAA,MACE,EAAE,MAAM,SAAA,EAAU;AAAA,MAClB,EAAE,MAAM,SAAA,EAAU;AAAA,MAClB,EAAE,MAAM,SAAA,EAAU;AAAA,MAClB,EAAE,MAAM,SAAA,EAAU;AAAA,MAClB,EAAE,MAAM,SAAA,EAAU;AAAA,MAClB,EAAE,MAAM,SAAA;AAAU,KACpB;AAAA,IACA,CAAC,mBAAA,EAAqB,UAAA,CAAW,QAAA,EAAU,UAAA,CAAW,WAAW,UAAA,CAAW,SAAA,EAAW,WAAA,EAAa,UAAA,CAAW,IAAI;AAAA,GACrH;AACA,EAAA,OAAO,UAAU,OAAO,CAAA;AAC1B","file":"chunk-424S4QMG.js","sourcesContent":["/**\n * The direct-payment content allowlist (#3272, moved here by #3283).\n *\n * `assertUserOpTypedDataBinding` (#3271) proves a `PackedUserOperation`'s\n * typed data and its hash describe the SAME operation — necessary, never\n * sufficient, because whoever serves the payload serves both values, so a\n * self-consistent forgery binds perfectly to itself. This module is the rest\n * of the property: the operation described is the ONE shape a delegate key\n * may sign for a direct payment — a redemption of the agent's own budget\n * delegation, for its own account, on a chain the delegation rail runs on.\n * Everything else (another account, a self-call such as `transferOwnership`,\n * a batch `execute`, a call to any contract other than the DelegationManager,\n * an empty-context redemption) is refused.\n *\n * ONE implementation, two callers (epic #3284): `@haven_ai/signer`'s\n * `haven_sign` (which wraps the refusal in its own structured error with a\n * next step) and `HavenClient.signForData` (the SDK's own in-process signing,\n * where a compromised Haven API would otherwise be enough to get an\n * account-capturing UserOp signed). Both also run the funding-leg recipient\n * pin, `assertFundingLegPaysDelegate`, on an x402 funding leg (#3281, #3375).\n */\nimport { decodeFunctionData, encodeFunctionData, encodePacked, type Address, type Hex } from 'viem'\nimport { HavenSigningError } from './types.js'\nimport {\n DELEGATION_MANAGER,\n verifySettlementChild,\n type SettlementChildExpectation,\n type SettlementChildTypedData,\n} from './settlement-child.js'\nimport { deriveDelegateAccountAddress } from './delegate-account.js'\nimport { assertRedeemsOwnBudgetDelegation, REDEEM_DELEGATIONS_ABI } from './redemption-guard.js'\n\n/** Wire code for a typed-data payload outside the signable allowlist. */\nexport const TYPED_DATA_NOT_ALLOWED = 'TYPED_DATA_NOT_ALLOWED' as const\n\n/**\n * A typed-data payload was refused before signing because it is not a shape\n * a delegate key may sign. Nothing was signed. `@haven_ai/signer` subclasses\n * this to attach its MCP next step; the `code` is the same on both.\n */\nexport class HavenTypedDataRefusedError extends HavenSigningError {\n declare readonly code: typeof TYPED_DATA_NOT_ALLOWED\n\n constructor(message: string) {\n super(message)\n ;(this as { code: string }).code = TYPED_DATA_NOT_ALLOWED\n this.name = 'HavenTypedDataRefusedError'\n }\n}\n\n/**\n * Chains the delegation rail has PINNED delegation contracts for\n * (`packages/backend/src/rails/delegation-contracts.ts`) — the only chains a\n * direct-payment UserOp may be scoped to. No other chain has a pinned\n * DelegationManager/enforcer set, so every other chain is deliberately\n * excluded even where the delegate account itself could exist.\n */\nexport const DIRECT_PAYMENT_CHAIN_IDS: ReadonlySet<number> = new Set([8453, 84532])\n\n/** The DeleGator's single-execution `execute((address,uint256,bytes))` — selector `0x5c1c6dcd`. */\nexport const EXECUTE_ABI = [\n {\n type: 'function',\n name: 'execute',\n inputs: [\n {\n name: '_execution',\n type: 'tuple',\n components: [\n { name: 'target', type: 'address' },\n { name: 'value', type: 'uint256' },\n { name: 'callData', type: 'bytes' },\n ],\n },\n ],\n outputs: [],\n stateMutability: 'payable',\n },\n] as const\n\n/**\n * The content + provenance allowlist (#3272 criteria 1–2). Call ONLY after\n * `assertUserOpTypedDataBinding` has already proven `typedData` is a\n * well-formed `PackedUserOperation` matching its own hash — this function\n * trusts `typedData.domain`/`message` are shaped correctly and checks only\n * what they SAY. Throws `HavenTypedDataRefusedError` (never returns) on any\n * disagreement.\n */\nexport function assertBoundDirectPaymentUserOp(\n typedData: Record<string, unknown>,\n delegateAddress: string,\n): void {\n const domain = (typedData.domain ?? {}) as Record<string, unknown>\n const message = (typedData.message ?? {}) as Record<string, unknown>\n\n // (N1) chainId must already be a number/bigint. `Number(domain.chainId)`\n // below would happily parse a numeric STRING, but viem's own EIP-712\n // domain encoding does not accept a string chainId the same way — passing\n // one through to the signer can silently drop it from the domain the\n // digest actually covers, producing a different signed payload than this\n // check evaluated. Refuse before that gap can matter.\n if (typeof domain.chainId !== 'number' && typeof domain.chainId !== 'bigint') {\n throw new HavenTypedDataRefusedError(\n `This UserOperation's domain.chainId is ${typeof domain.chainId} (${String(domain.chainId)}), ` +\n 'not a number — refusing rather than risk signing a different EIP-712 domain than this ' +\n 'check evaluated.',\n )\n }\n\n // (c) chain: only where the delegation rail has pinned contracts.\n const chainId = Number(domain.chainId)\n if (!DIRECT_PAYMENT_CHAIN_IDS.has(chainId)) {\n throw new HavenTypedDataRefusedError(\n 'This signer only signs direct payments on chains the delegation rail has pinned ' +\n `contracts for (${[...DIRECT_PAYMENT_CHAIN_IDS].join(', ')}); this typed data names ` +\n `chain ${String(domain.chainId)}. Refusing.`,\n )\n }\n\n // (d) sender: only this key's OWN counterfactual delegate account —\n // `assertUserOpTypedDataBinding` already proved `sender === verifyingContract`.\n const ownAccount = deriveDelegateAccountAddress(delegateAddress as Address)\n const sender = typeof message.sender === 'string' ? message.sender : ''\n if (sender.toLowerCase() !== ownAccount.toLowerCase()) {\n throw new HavenTypedDataRefusedError(\n `This UserOperation's account (${sender || 'unknown'}) is not this signer's own delegate ` +\n `account (${ownAccount}) — signing it would authorize a DIFFERENT account's operation. ` +\n 'Sign only your own agent\\'s Haven-prepared payloads.',\n )\n }\n\n // (e) callData: a single execute(DelegationManager, 0, redeemDelegations(...)) —\n // never a batch execute (ERC-7579 `execute(bytes32,bytes)`, selector\n // `0xe9ae5c53`), an executeFromExecutor, a self-call, or a call to any\n // other contract.\n const callData = message.callData as `0x${string}`\n let decoded: { target: `0x${string}`; value: bigint; callData: `0x${string}` }\n try {\n const { args } = decodeFunctionData({\n abi: EXECUTE_ABI,\n data: callData,\n })\n decoded = args[0] as unknown as typeof decoded\n } catch {\n throw new HavenTypedDataRefusedError(\n \"This UserOperation's callData is not a single execute((address,uint256,bytes)) call \" +\n '— a batch execute, executeFromExecutor, or any other selector is refused. This ' +\n 'signer only signs direct payments.',\n )\n }\n // Canonical encoding: re-encoding the decoded call must reproduce the EXACT\n // bytes, or `decodeFunctionData`'s tolerance of trailing/non-canonical\n // padding would let calldata smuggle bytes past every check below.\n const reEncodedExecute = encodeFunctionData({\n abi: EXECUTE_ABI,\n functionName: 'execute',\n args: [decoded],\n })\n if (reEncodedExecute.toLowerCase() !== callData.toLowerCase()) {\n throw new HavenTypedDataRefusedError(\n \"This UserOperation's execute() call does not re-encode to the exact callData bytes \" +\n '(trailing or non-canonical bytes). Refusing.',\n )\n }\n if (decoded.target.toLowerCase() !== DELEGATION_MANAGER.toLowerCase()) {\n throw new HavenTypedDataRefusedError(\n `This UserOperation's execute() calls ${decoded.target}, not the DelegationManager ` +\n `(${DELEGATION_MANAGER}). A direct payment only ever redeems the agent's own budget ` +\n 'delegation — refusing what looks like a self-call (e.g. transferOwnership, ' +\n 'updateSigners, upgradeToAndCall) or a call to an unrelated contract.',\n )\n }\n if (decoded.value !== 0n) {\n throw new HavenTypedDataRefusedError(\n `This UserOperation's execute() sends ${decoded.value} wei of native value alongside the ` +\n 'DelegationManager call — a direct payment never does. Refusing.',\n )\n }\n // #3272 (B1): decode the redemption ARGUMENTS, not just the selector — an\n // empty (or otherwise not-this-key's) delegation chain is a capture\n // vector, not a shape the redeemDelegations selector alone rules out.\n try {\n assertRedeemsOwnBudgetDelegation(decoded.callData, ownAccount)\n } catch (err) {\n throw new HavenTypedDataRefusedError(err instanceof Error ? err.message : String(err))\n }\n}\n\nexport type { SettlementChildExpectation }\n\n/**\n * The settlement-child half of the same surface (#3283): verify an erc7710\n * child against `expectation` (from somewhere Haven did not write — the\n * merchant's 402 in the SDK, the Haven-signed expected context in the\n * signer), AND that it is re-delegated from this key's OWN account. Throws\n * `HavenTypedDataRefusedError` (code `TYPED_DATA_NOT_ALLOWED`) on any\n * disagreement.\n */\nexport function assertOwnSettlementChild(\n typedData: unknown,\n expectation: SettlementChildExpectation,\n delegateAddress: string,\n): void {\n try {\n verifySettlementChild(typedData as SettlementChildTypedData, {\n ...expectation,\n delegatorAccount: deriveDelegateAccountAddress(delegateAddress as Address),\n })\n } catch (err) {\n // One refusal code for everything this surface refuses, so an agent sees\n // TYPED_DATA_NOT_ALLOWED for a bad child exactly as for a bad UserOp —\n // including a MALFORMED child whose caveat terms do not even parse\n // (#3281 doc review: a truncated term used to escape as a raw BigInt error).\n if (err instanceof HavenTypedDataRefusedError) throw err\n if (err instanceof HavenSigningError) throw new HavenTypedDataRefusedError(err.message)\n throw new HavenTypedDataRefusedError(\n `Refusing to sign the x402 settlement child: it is malformed (${err instanceof Error ? err.message : String(err)}).`,\n )\n }\n}\n\n/** ERC-20 `transfer(address,uint256)` — selector `0xa9059cbb`. */\nconst ERC20_TRANSFER_ABI = [\n {\n type: 'function',\n name: 'transfer',\n inputs: [\n { name: 'to', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n outputs: [{ type: 'bool' }],\n stateMutability: 'nonpayable',\n },\n] as const\n\n/**\n * #3281 (epic #3284, criterion 5): pin WHERE an x402 EIP-3009 funding leg's\n * redemption sends the money. The funding leg is always\n * `transfer(<delegate EOA>, <amount>)` of the quoted token\n * (`delegation-authorize.ts` → `prepareDelegationPayment(agent, token,\n * payTo = the delegate EOA, amountRaw)`), so the single execution must be\n * exactly `encodePacked(asset, 0, transfer(delegateAddress, amount))`.\n *\n * `delegateAddress` is the signing key's OWN address — local, not from Haven —\n * so even a compromised Haven can at most move budget into the agent's own\n * EOA (the hot-delegate residual the sweep returns), never to an attacker.\n * `asset` and `amount` keep the leg consistent with what is being paid. Two\n * callers, two sources: the signer's x402 arm (#3281) passes the Haven-signed\n * expected context's; `HavenClient.signForData` (#3375) passes the 402 option\n * the SDK is paying, never the `/x402` response.\n *\n * Call ONLY after `assertBoundDirectPaymentUserOp` has passed on the same\n * typed data (it proves the `execute` → `redeemDelegations` shape this reads).\n * Throws `HavenTypedDataRefusedError` on any disagreement.\n */\nexport function assertFundingLegPaysDelegate(\n typedData: Record<string, unknown>,\n expected: { delegateAddress: string; asset: string; amount: string },\n): void {\n const refuse = (detail: string): never => {\n throw new HavenTypedDataRefusedError(\n `Refusing to sign this x402 funding leg: ${detail}. A funding leg only ever moves the quoted ` +\n \"amount of the quoted token from the account to this agent's own delegate wallet.\",\n )\n }\n const message = (typedData.message ?? {}) as Record<string, unknown>\n let executionCallData: Hex\n try {\n const { args: executeArgs } = decodeFunctionData({ abi: EXECUTE_ABI, data: message.callData as Hex })\n const inner = (executeArgs[0] as { callData: Hex }).callData\n const { args } = decodeFunctionData({ abi: REDEEM_DELEGATIONS_ABI, data: inner })\n const executions = args[2] as readonly Hex[]\n executionCallData = executions[0]\n } catch {\n return refuse('its redemption could not be decoded')\n }\n // SingleDefault execution calldata = encodePacked(address target, uint256 value, bytes callData).\n const body = executionCallData.slice(2)\n if (body.length < (20 + 32) * 2) refuse('its execution is too short to be a token transfer')\n const target = `0x${body.slice(0, 40)}` as Address\n const value = BigInt(`0x${body.slice(40, 104)}`)\n const callData = `0x${body.slice(104)}` as Hex\n if (target.toLowerCase() !== expected.asset.toLowerCase()) {\n refuse(`it calls ${target}, not the quoted token ${expected.asset}`)\n }\n if (value !== 0n) refuse(`it sends ${value} wei of native value`)\n let to: Address\n let amount: bigint\n try {\n const decoded = decodeFunctionData({ abi: ERC20_TRANSFER_ABI, data: callData })\n ;[to, amount] = decoded.args as unknown as [Address, bigint]\n } catch {\n return refuse('its execution is not an ERC-20 transfer(address,uint256)')\n }\n // Canonical encoding of the whole execution: no trailing or smuggled bytes.\n const reEncoded = encodePacked(\n ['address', 'uint256', 'bytes'],\n [target, value, encodeFunctionData({ abi: ERC20_TRANSFER_ABI, functionName: 'transfer', args: [to, amount] })],\n )\n if (reEncoded.toLowerCase() !== executionCallData.toLowerCase()) {\n refuse('its execution does not re-encode to the exact bytes signed (trailing or non-canonical bytes)')\n }\n if (to.toLowerCase() !== expected.delegateAddress.toLowerCase()) {\n refuse(`it pays ${to}, not this agent's own delegate wallet (${expected.delegateAddress})`)\n }\n if (amount !== BigInt(expected.amount)) {\n refuse(`it moves ${amount}, not the quoted amount ${expected.amount}`)\n }\n}\n","/**\n * Runtime-agnostic base64 helpers — the single source of truth for the wire\n * encoding shared by the SDK and the edge signer (#325).\n *\n * Why this module exists: the SDK used `atob`/`btoa` (Web globals) while the\n * signer used `Buffer` (Node-only). Both worked because both currently run in\n * Node ≥ 16, but the duplication was a latent wire-incompatibility — and the\n * signer is headed for non-Node runtimes (browsers, Cloudflare Workers) where\n * `Buffer` does not exist (#314).\n *\n * Encoding contract:\n * - Output is ALWAYS standard base64 (`+`, `/`, padded). The x402 protocol's\n * reference implementation validates headers against\n * `/^[A-Za-z0-9+/]*={0,2}$/` — URL-safe output would be rejected.\n * - Decoding is tolerant: URL-safe input (`-`, `_`, unpadded) is normalized\n * before decoding, since third-party merchants are not guaranteed to be as\n * strict as the reference implementation.\n * - UTF-8 throughout. Naive `btoa(JSON.stringify(...))` throws on any\n * non-Latin-1 character (e.g. a merchant description with an emoji or\n * non-ASCII name); these helpers route through TextEncoder/TextDecoder on\n * the Web path so multibyte characters round-trip identically on both\n * runtimes.\n */\n\n/** Normalize URL-safe alphabet and missing padding to standard base64. */\nfunction normalizeBase64(value: string): string {\n const standard = value.replace(/-/g, '+').replace(/_/g, '/')\n const remainder = standard.length % 4\n return remainder === 0 ? standard : standard + '='.repeat(4 - remainder)\n}\n\n/** Encode a UTF-8 string as standard base64. */\nexport function encodeBase64Utf8(value: string): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(value, 'utf8').toString('base64')\n }\n const bytes = new TextEncoder().encode(value)\n let binary = ''\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i])\n }\n return btoa(binary)\n}\n\n/** Decode standard or URL-safe base64 to a UTF-8 string. */\nexport function decodeBase64Utf8(value: string): string {\n const normalized = normalizeBase64(value)\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(normalized, 'base64').toString('utf8')\n }\n const binary = atob(normalized)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i)\n }\n return new TextDecoder().decode(bytes)\n}\n\n/** Encode a JSON-serializable value as a standard-base64 string. */\nexport function encodeBase64Json(value: unknown): string {\n return encodeBase64Utf8(JSON.stringify(value))\n}\n\n/**\n * Decode a base64 JSON payload.\n *\n * Pass a `label` to get a wrapped error message instead of the raw\n * JSON/base64 error — call sites parsing untrusted merchant headers use this\n * to produce actionable failures.\n */\nexport function decodeBase64Json<T>(value: string, label?: string): T {\n try {\n return JSON.parse(decodeBase64Utf8(value)) as T\n } catch (err) {\n if (label) throw new Error(`Failed to decode ${label}`)\n throw err\n }\n}\n","import { HavenSigningError } from './types.js'\n\n/**\n * Gasless delegate-sweep primitives — the single source of truth shared by the\n * edge signer (which signs) and the Haven backend (which relays).\n *\n * A stranded delegate EOA holds USDC but no ETH, so a raw ERC-20 transfer can't\n * pay for its own gas. Instead the delegate signs an *off-chain* EIP-3009\n * `TransferWithAuthorization` and the Haven relayer submits it on-chain and pays\n * gas. The relayer is only a gas payer: it holds no allowance and is never a\n * spender, so a relayer compromise cannot move user funds.\n *\n * Framework-neutral on purpose: `buildSweepTypedData` returns a plain\n * `{ domain, types, primaryType, message }` that both viem\n * (`signTypedData`/`recoverTypedDataAddress`) and ethers v6\n * (`signTypedData`/`verifyTypedData`) accept, so the signer (viem) and backend\n * (ethers) stay in lockstep without sharing a crypto library.\n */\n\n/** Base mainnet. The only chain Haven sweeps today. */\nexport const SWEEP_BASE_CHAIN_ID = 8453\n\n/** Base Sepolia testnet — used by the dev environment / QA harness. */\nexport const SWEEP_BASE_SEPOLIA_CHAIN_ID = 84532\n\n/** Canonical Circle USDC on Base (FiatTokenV2_2). */\nexport const SWEEP_BASE_USDC_ADDRESS =\n '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'\n\n/** Circle's canonical Base Sepolia testnet USDC. */\nexport const SWEEP_BASE_SEPOLIA_USDC_ADDRESS =\n '0x036CbD53842c5426634e7929541eC2318f3dCF7e'\n\n/**\n * EIP-712 domain per chain. `name`/`version` are the on-chain `FiatTokenV2_2`\n * values; a mismatch makes the relayer's `transferWithAuthorization` revert, so\n * each is pinned to the known-good, **on-chain-verified** USDC values. Base\n * mainnet is \"USD Coin\"/\"2\"; Base Sepolia is \"USDC\"/\"2\" (verified via `name()`/\n * `version()`). Add a chain here only after verifying its USDC EIP-712 domain.\n */\nconst USDC_EIP712_DOMAIN_BY_CHAIN: Record<number, SweepEip712Domain> = {\n [SWEEP_BASE_CHAIN_ID]: {\n name: 'USD Coin',\n version: '2',\n chainId: SWEEP_BASE_CHAIN_ID,\n verifyingContract: SWEEP_BASE_USDC_ADDRESS,\n },\n [SWEEP_BASE_SEPOLIA_CHAIN_ID]: {\n name: 'USDC',\n version: '2',\n chainId: SWEEP_BASE_SEPOLIA_CHAIN_ID,\n verifyingContract: SWEEP_BASE_SEPOLIA_USDC_ADDRESS,\n },\n}\n\n/** USDC contract per sweepable chain. */\nconst USDC_ADDRESS_BY_CHAIN: Record<number, string> = {\n [SWEEP_BASE_CHAIN_ID]: SWEEP_BASE_USDC_ADDRESS,\n [SWEEP_BASE_SEPOLIA_CHAIN_ID]: SWEEP_BASE_SEPOLIA_USDC_ADDRESS,\n}\n\n/** Sweepable chains, for error messages. */\nconst SWEEPABLE_CHAIN_IDS = Object.keys(USDC_ADDRESS_BY_CHAIN).map(Number)\n\n/** True when the gasless sweep supports a chain (its USDC domain + address are known). */\nexport function isSweepableChain(chainId: number): boolean {\n return chainId in USDC_ADDRESS_BY_CHAIN\n}\n\n/** EIP-712 `TransferWithAuthorization` struct, per EIP-3009. */\nexport const TRANSFER_WITH_AUTHORIZATION_TYPES = {\n TransferWithAuthorization: [\n { name: 'from', type: 'address' },\n { name: 'to', type: 'address' },\n { name: 'value', type: 'uint256' },\n { name: 'validAfter', type: 'uint256' },\n { name: 'validBefore', type: 'uint256' },\n { name: 'nonce', type: 'bytes32' },\n ],\n} as const\n\nexport interface SweepEip712Domain {\n name: string\n version: string\n chainId: number\n verifyingContract: string\n}\n\n/**\n * A fully-specified EIP-3009 authorization. All amounts/times are decimal\n * strings (JSON-safe) and `nonce` is a 0x-prefixed 32-byte hex value. `token`\n * and `chainId` are carried explicitly so the signer can assert they are\n * canonical before signing.\n */\nexport interface SweepAuthorization {\n /** Delegate EOA the funds are swept FROM. */\n from: string\n /** The agent's Haven account the funds are swept TO. */\n to: string\n /** Atomic USDC amount (decimal string). */\n value: string\n /** Unix seconds the authorization becomes valid (decimal string, usually \"0\"). */\n validAfter: string\n /** Unix seconds the authorization expires (decimal string). */\n validBefore: string\n /** Random 0x-prefixed 32-byte hex nonce. */\n nonce: string\n /** USDC contract address. */\n token: string\n /** Chain id (8453 today). */\n chainId: number\n}\n\n/**\n * Haven's signature over the sweep authorization context, signed with the same\n * binding key the x402 expected-context uses. Lets the edge signer verify the\n * authorization actually came from Haven (and wasn't crafted by a compromised\n * hosted server pointing `to` at an attacker) before it signs.\n */\nexport interface SweepExpectedAuth {\n /**\n * Currently always 1. Typed as `number` for the same reason as\n * `X402ExpectedAuth.version` (#1143): it is inbound, so a stale signer must be\n * able to *receive* an unknown version in order to report it. The signer's\n * `SUPPORTED_SWEEP_BINDING_VERSIONS` is the authority on what it will sign.\n */\n version: number\n message: string\n signature: string\n signer: string\n}\n\n/** What `POST /machine-payments/sweep/prepare` returns when funds are stranded. */\nexport interface SweepPreparation {\n authorization: SweepAuthorization\n expectedAuth: SweepExpectedAuth\n}\n\n/** Wire response from `POST /machine-payments/sweep/prepare` (snake_case). */\nexport interface SweepPrepareResponse {\n /** Present and true when the delegate holds nothing to recover. */\n nothing_stranded?: boolean\n /**\n * Present and true when the stranded balance is below the sweep floor (#700):\n * it is left on the delegate as dust rather than recovered, because the gas to\n * sweep it would exceed its value. `min_usdc` carries the configured floor. No\n * `authorization` is built.\n */\n below_min?: boolean\n min_usdc?: string\n /** The authorization to sign — absent when nothing is stranded or below the floor. */\n authorization?: SweepAuthorization\n /** Haven's binding over the authorization — absent when nothing is stranded. */\n expected_auth?: SweepExpectedAuth\n asset?: string\n amount?: string\n amount_atomic?: string\n chain_id: number\n sign_instructions?: string\n message?: string\n}\n\n/** Wire response from `POST /machine-payments/sweep/submit` (snake_case). */\nexport interface SweepSubmitResponse {\n tx_hash: string\n asset: string\n amount: string\n amount_atomic: string\n from_address: string\n to_address: string\n chain_id: number\n explorer_url: string\n idempotent_replay?: boolean\n}\n\n/** Result of a submitted gasless sweep. */\nexport interface SweepSubmitResult {\n txHash: string\n amount: string\n amountAtomic: string\n asset: string\n fromAddress: string\n toAddress: string\n chainId: number\n explorerUrl: string\n}\n\nexport interface SweepTypedData {\n domain: SweepEip712Domain\n types: typeof TRANSFER_WITH_AUTHORIZATION_TYPES\n primaryType: 'TransferWithAuthorization'\n message: {\n from: string\n to: string\n value: bigint\n validAfter: bigint\n validBefore: bigint\n nonce: string\n }\n}\n\n/** Resolve the canonical USDC contract for a sweepable chain, or throw. */\nexport function sweepUsdcAddress(chainId: number): string {\n const address = USDC_ADDRESS_BY_CHAIN[chainId]\n if (!address) {\n throw new HavenSigningError(\n `Sweep is not supported on chain ${chainId}. Supported: ${SWEEPABLE_CHAIN_IDS.join(', ')}.`,\n )\n }\n return address\n}\n\n/** Resolve the USDC EIP-712 domain for a sweepable chain, or throw. */\nexport function sweepUsdcDomain(chainId: number): SweepEip712Domain {\n const domain = USDC_EIP712_DOMAIN_BY_CHAIN[chainId]\n if (!domain) {\n throw new HavenSigningError(\n `Sweep is not supported on chain ${chainId}. Supported: ${SWEEPABLE_CHAIN_IDS.join(', ')}.`,\n )\n }\n return domain\n}\n\nfunction sameAddress(a: string, b: string): boolean {\n return a.toLowerCase() === b.toLowerCase()\n}\n\n/**\n * Build the EIP-712 typed data for an authorization, validating that the token\n * and chain are canonical (the domain's `verifyingContract` must match the\n * authorization's `token`). Returns bigint-valued fields so both viem and\n * ethers v6 sign/recover identically.\n */\nexport function buildSweepTypedData(auth: SweepAuthorization): SweepTypedData {\n const domain = sweepUsdcDomain(auth.chainId)\n const expectedToken = sweepUsdcAddress(auth.chainId)\n if (!sameAddress(auth.token, expectedToken)) {\n throw new HavenSigningError(\n `Sweep token ${auth.token} is not the canonical USDC contract for chain ${auth.chainId}.`,\n )\n }\n if (!/^0x[0-9a-fA-F]{64}$/.test(auth.nonce)) {\n throw new HavenSigningError('Sweep nonce must be a 0x-prefixed 32-byte hex string.')\n }\n return {\n domain,\n types: TRANSFER_WITH_AUTHORIZATION_TYPES,\n primaryType: 'TransferWithAuthorization',\n message: {\n from: auth.from,\n to: auth.to,\n value: BigInt(auth.value),\n validAfter: BigInt(auth.validAfter),\n validBefore: BigInt(auth.validBefore),\n nonce: auth.nonce,\n },\n }\n}\n\n/**\n * Canonical, deterministic string the backend signs and the signer re-derives\n * for the authorization binding. The `Haven sweep authorization v1` namespace\n * (and `kind`) is distinct from the x402 expected-context namespace so an x402\n * binding can never be replayed as a sweep authorization even though they share\n * a signing key.\n */\nexport function buildSweepAuthorizationMessage(auth: SweepAuthorization): string {\n return `Haven sweep authorization v1\\n${stableStringify({\n version: 1,\n kind: 'haven.sweep.authorization',\n from: auth.from.toLowerCase(),\n to: auth.to.toLowerCase(),\n value: auth.value,\n validAfter: auth.validAfter,\n validBefore: auth.validBefore,\n nonce: auth.nonce.toLowerCase(),\n token: auth.token.toLowerCase(),\n chainId: auth.chainId,\n })}`\n}\n\n/** Deterministic JSON: object keys sorted, no incidental whitespace. */\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value)\n if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(',')}]`\n const object = value as Record<string, unknown>\n return `{${Object.keys(object)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(object[key])}`)\n .join(',')}}`\n}\n","/**\n * x402 protocol support for the Haven SDK.\n *\n * Provides:\n * - parsePaymentRequired() — extract payment requirements from a 402 response\n * - parsePaymentRequiredResponse() — async parser with JSON body fallback\n * - encodePaymentProof() — encode a receipt as a PAYMENT-SIGNATURE header\n *\n * The main authorizeX402() and fetchWithPayment() are methods on HavenClient\n * (see client.ts) since they need API access and signing.\n */\n\nimport { createHash } from 'node:crypto'\nimport { recoverTypedDataAddress } from 'viem'\nimport type { X402ExpectedContext, X402PaymentRequired, X402PaymentOption } from './types.js'\nimport type { PaymentRequirements } from 'x402/types'\nimport { decodeBase64Json, encodeBase64Json } from './base64.js'\nimport { buildSweepTypedData } from './sweep.js'\n\nconst BASE_USDC_ADDRESS = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'\nconst BASE_SEPOLIA_USDC_ADDRESS = '0x036cbd53842c5426634e7929541ec2318f3dcf7e'\n/** USDC addresses the standard EIP-3009 exact scheme can pay (Base mainnet + Base Sepolia). */\nconst STANDARD_X402_USDC_ADDRESSES = new Set([BASE_USDC_ADDRESS, BASE_SEPOLIA_USDC_ADDRESS])\nconst X402_IDEMPOTENCY_BUCKET_MS = 300_000\nconst DECIMAL_ATOMIC_AMOUNT_RE = /^[0-9]+$/\nconst X402_PAYMENT_HEADER_MAX_LENGTH = 65_536\nconst BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/\nconst SIGNATURE_RE = /^0x[0-9a-fA-F]{130}$/\nconst NONCE_RE = /^0x[0-9a-fA-F]{64}$/\n\n/**\n * Persisted, agent-scoped facts used to preflight a signed standard x402\n * payment header. This is an integrity comparison only: it never rebuilds,\n * modifies, persists, or submits the supplied authorization.\n */\nexport interface X402PaymentHeaderContext {\n merchantTo: string\n amountAtomic: string\n asset: string\n network: string\n resourceUrl: string\n payer: string\n chainId: number\n}\n\n/** A deliberately value-free refusal for untrusted payment-header input. */\nexport class X402PaymentHeaderValidationError extends Error {\n constructor() {\n super('Invalid X-PAYMENT header.')\n this.name = 'X402PaymentHeaderValidationError'\n }\n}\n\nfunction isPositiveDecimalAtomicAmount(value: string): boolean {\n return DECIMAL_ATOMIC_AMOUNT_RE.test(value) && BigInt(value) > 0n\n}\n\nfunction optionAuthorizationAmount(option: X402PaymentOption): string {\n return option.maxAmountRequired ?? option.amount\n}\n\n/**\n * Upper bound on the MERCHANT-requested part of the EIP-3009 authorization\n * window (#715, epic #713). The x402 library sets\n * `validBefore = now + maxTimeoutSeconds` straight from the MERCHANT's 402\n * challenge — without a cap, a malicious or sloppy merchant can request a\n * year-long window and a leaked signed authorization stays spendable that\n * whole time. 600 s is generous for any facilitator settle (typical is\n * 30–60 s). This cap applies only to the signed authorization, never to the\n * advertised requirements echoed in `accepted`. A merchant requiring more\n * than the bounded lifetime can still reject at verification; preserving its\n * offer does not widen Haven's signing policy.\n */\nexport const X402_MAX_AUTHORIZATION_WINDOW_SECONDS = 600\n\n/**\n * Forward margin ADDED on top of the (clamped) merchant timeout when the\n * authorization is actually signed (#1256). The x402 verify rule requires\n * `validBefore ≥ now + maxTimeoutSeconds` AT THE FACILITATOR — but the\n * upstream library computes `validBefore = now + maxTimeoutSeconds` at\n * SIGNING time, leaving zero forward margin. Haven's flow guarantees elapsed\n * time between the two (the funding UserOp confirms before the merchant\n * retry, ~1 min plus latency), so every purchase against a merchant whose\n * `maxTimeoutSeconds` exceeded that latency failed structurally — measured\n * live on Base mainnet: Anchor requires 300 s, and 226 s remained at verify.\n *\n * 300 s covers funding + retry latency with room to spare. The #715 exposure\n * ceiling becomes clamped-timeout + margin ≤ 900 s total forward — a\n * deliberate widening from 600 s, recorded on #1256: an authorization that\n * cannot pass verify protects no one, and 900 s is still bounded by the same\n * clamp discipline.\n */\nexport const X402_SETTLEMENT_FORWARD_MARGIN_SECONDS = 300\n\nfunction clampAuthorizationWindow(seconds: number | undefined): number {\n const requested = typeof seconds === 'number' && Number.isFinite(seconds) ? seconds : 30\n return Math.min(Math.max(Math.floor(requested), 1), X402_MAX_AUTHORIZATION_WINDOW_SECONDS)\n}\n\nfunction normalizePaymentOption(value: unknown): X402PaymentOption | null {\n const candidate = value as Partial<X402PaymentOption> | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n typeof candidate.scheme !== 'string' ||\n typeof candidate.network !== 'string' ||\n typeof candidate.asset !== 'string' ||\n typeof candidate.payTo !== 'string'\n ) {\n return null\n }\n\n const amount =\n typeof candidate.amount === 'string'\n ? candidate.amount\n : typeof candidate.maxAmountRequired === 'string'\n ? candidate.maxAmountRequired\n : null\n\n if (!amount) return null\n if (!isPositiveDecimalAtomicAmount(amount)) return null\n if (\n candidate.maxAmountRequired !== undefined &&\n (\n typeof candidate.maxAmountRequired !== 'string' ||\n !isPositiveDecimalAtomicAmount(candidate.maxAmountRequired)\n )\n ) {\n return null\n }\n\n return {\n scheme: candidate.scheme,\n network: candidate.network,\n amount,\n maxAmountRequired: candidate.maxAmountRequired,\n resource: candidate.resource,\n description: candidate.description,\n mimeType: candidate.mimeType,\n asset: candidate.asset,\n payTo: candidate.payTo,\n // Keep the merchant offer intact for v2 `accepted` matching. Only the\n // signing conversion may cap its authorization lifetime (#3117).\n // Retain legacy fallback behavior for missing or unusable timeouts.\n // Integer, because the authorize body types it `integer` and the child's\n // timestamp caveat is built from it — the old clamp floored, so keeping a\n // fractional value here would 400 a merchant that used to work (#3117).\n maxTimeoutSeconds:\n typeof candidate.maxTimeoutSeconds === 'number' &&\n Number.isFinite(candidate.maxTimeoutSeconds) && candidate.maxTimeoutSeconds >= 1\n ? Math.floor(candidate.maxTimeoutSeconds)\n : clampAuthorizationWindow(candidate.maxTimeoutSeconds),\n extra: candidate.extra,\n }\n}\n\nexport function normalizePaymentRequired(value: unknown): X402PaymentRequired | null {\n const candidate = value as Partial<X402PaymentRequired> | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n typeof candidate.x402Version !== 'number' ||\n !Array.isArray(candidate.accepts)\n ) {\n return null\n }\n\n const accepts = candidate.accepts\n .map((option) => normalizePaymentOption(option))\n .filter((option): option is X402PaymentOption => !!option && typeof option === 'object')\n\n if (accepts.length === 0) return null\n\n const first = accepts[0]\n const resourceUrl = candidate.resource?.url ?? first.resource\n if (!resourceUrl) return null\n\n // #2361: spread the merchant's resource object FIRST so unknown fields\n // survive — the v2 payment envelope echoes `resource` verbatim, and a\n // reconstructed subset is a different object than the merchant advertised.\n const resource = {\n ...(candidate.resource && typeof candidate.resource === 'object' ? candidate.resource : {}),\n url: resourceUrl,\n description: candidate.resource?.description ?? first.description,\n mimeType: candidate.resource?.mimeType ?? first.mimeType,\n }\n\n return {\n x402Version: candidate.x402Version,\n resource,\n accepts,\n error: candidate.error,\n ...(candidate.extensions && typeof candidate.extensions === 'object'\n ? { extensions: candidate.extensions as Record<string, unknown> }\n : {}),\n }\n}\n\n// ── Supported networks ───────────────────────────────────────────\n\n/** Network identifiers that Haven can recognise in x402 payment requests. */\nexport const SUPPORTED_X402_NETWORKS: Record<string, string> = {\n 'eip155:8453': 'Base',\n 'base': 'Base',\n 'eip155:84532': 'Base Sepolia',\n 'base-sepolia': 'Base Sepolia',\n}\n\n/** Networks supported by the official x402 EIP-3009 exact scheme. */\nconst STANDARD_X402_NETWORKS: Record<string, PaymentRequirements['network']> = {\n 'eip155:8453': 'base',\n 'base': 'base',\n 'eip155:84532': 'base-sepolia',\n 'base-sepolia': 'base-sepolia',\n}\n\n// ── Token address maps ────────────────────────────────────────────\n\n/** Known tokens on Base (chainId 8453). */\nconst BASE_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n '0x0000000000000000000000000000000000000000': { symbol: 'ETH', decimals: 18 },\n '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913': { symbol: 'USDC', decimals: 6 },\n}\n\n/** Known tokens on Base Sepolia (chainId 84532) — testnet. */\nconst BASE_SEPOLIA_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n '0x0000000000000000000000000000000000000000': { symbol: 'ETH', decimals: 18 },\n '0x036cbd53842c5426634e7929541ec2318f3dcf7e': { symbol: 'USDC', decimals: 6 },\n}\n\n/** All known tokens across all supported chains (for display / resolution). */\nconst ALL_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n ...BASE_TOKENS,\n ...BASE_SEPOLIA_TOKENS,\n}\n\n/** Maps CAIP-2 network ID → token address map. */\nconst NETWORK_TOKENS: Record<string, Record<string, { symbol: string; decimals: number }>> = {\n 'eip155:8453': BASE_TOKENS,\n 'base': BASE_TOKENS,\n 'eip155:84532': BASE_SEPOLIA_TOKENS,\n 'base-sepolia': BASE_SEPOLIA_TOKENS,\n}\n\n// ── Parser ───────────────────────────────────────────────────────\n\n/**\n * The x402 wire header names, in one place (#2289).\n *\n * v2 renamed all three; v1's only name was `X-PAYMENT`, used in BOTH\n * directions. Haven had adopted the v2 names for everything it *reads* and\n * kept the v1 name for the one thing it *writes*, which is how a strict v2\n * merchant came to never see a payment header at all.\n *\n * The 2026-08-31 owner decision was to send both outbound names on every\n * retry rather than switch on `x402Version`: a v1 merchant ignores the name it\n * does not know, a v2 merchant ignores the legacy one, and no version\n * heuristic has to be right for a payment to land.\n *\n * **That is no longer unconditional (#2341).** It held while the cost of a\n * spare header was zero, and on the EIP-3009 bridge it still is. On erc7710 it\n * is not: that header carries a whole delegation chain, and duplicating it\n * overflowed the merchant's header limit — HTTP 431, every erc7710 settlement\n * refused. `x402PaymentHeaderNamesFor` below is the live rule; read it rather\n * than this paragraph, which records why the simpler rule was right first.\n */\n/** v2 client→server payment payload. The name a strict v2 merchant reads. */\nexport const X402_PAYMENT_HEADER_NAME = 'PAYMENT-SIGNATURE'\n/** v1 client→server payment payload; still accepted by most v2 merchants. */\nexport const X402_LEGACY_PAYMENT_HEADER_NAME = 'X-PAYMENT'\n/** v2 server→client payment requirements. */\nexport const X402_PAYMENT_REQUIRED_HEADER_NAME = 'PAYMENT-REQUIRED'\n/** v2 server→client settlement receipt. */\nexport const X402_PAYMENT_RESPONSE_HEADER_NAME = 'PAYMENT-RESPONSE'\n/**\n * Both wire names, v2 first — the value an EIP-3009 retry actually sends.\n *\n * **Not the general answer any more (#2341), and not what a recorder should\n * reach for.** This was the evidence record's `paymentProofHeaderName` while\n * both names always went on the wire; erc7710 now sends one, so a recorder\n * still reading this constant would log a legacy header that was never sent —\n * exactly the drift the previous wording promised it prevented. Use\n * `x402PaymentHeaderNamesSent(paymentHeader)`. Kept exported because it is a\n * published surface and removing it would break consumers.\n */\nexport const X402_PAYMENT_HEADER_NAMES_SENT =\n `${X402_PAYMENT_HEADER_NAME}, ${X402_LEGACY_PAYMENT_HEADER_NAME}`\n\n/**\n * Every payment header name Haven may put on the wire, v2 first.\n *\n * `deliverPayment` iterates this rather than the pair it is sending, so a name\n * it is NOT sending is explicitly deleted from the caller's headers instead of\n * being left as-is. Leaving one would resurrect the stale-header bug #2289\n * closed with `set`, one scheme over.\n */\nexport const X402_PAYMENT_HEADER_NAMES = [\n X402_PAYMENT_HEADER_NAME,\n X402_LEGACY_PAYMENT_HEADER_NAME,\n] as const\n\n/**\n * Which payment header names to put on the wire for THIS payload (#2341).\n *\n * #2289 set both names unconditionally, and on the EIP-3009 bridge that is\n * right: the header is a signature plus a six-field authorization, doubling it\n * costs nothing, and lenient v1-only merchants are real. On **erc7710** it is\n * not right, and it is not merely wasteful — the header carries the whole\n * `[child, budget]` delegation chain plus the UserOperation, so sending it\n * twice pushed the request past the server header-size limit and merchants\n * answered **HTTP 431 Request Header Fields Too Large**. Every erc7710\n * settlement failed, with the funding leg already spent on the hosted path.\n *\n * The rule is by SCHEME, not by byte count, because the scheme is what makes\n * the alias pointless rather than merely large: an erc7710 payload is always\n * `x402Version: 2` (the backend's `encodeXPaymentHeader` hardcodes it), and a\n * merchant that can redeem a delegation chain is by construction running x402\n * v2 plus the MetaMask erc7710 extension — it reads `PAYMENT-SIGNATURE`. The\n * legacy name cannot help it and can only cost the request. A size threshold\n * would be an arbitrary number that changes behaviour silently near its edge.\n *\n * An unreadable header falls back to BOTH names — the #2289 behaviour. Haven\n * builds this value itself, so a parse failure means something is already\n * wrong; the conservative answer there is the one that keeps v1 merchants\n * working rather than the one that happens to fix a size problem we cannot\n * confirm this payload has.\n */\nexport function x402PaymentHeaderNamesFor(paymentHeader: string): readonly string[] {\n const both = [X402_PAYMENT_HEADER_NAME, X402_LEGACY_PAYMENT_HEADER_NAME]\n let decoded: { accepted?: unknown } | null\n try {\n decoded = decodeBase64Json<{ accepted?: unknown }>(paymentHeader)\n } catch {\n return both\n }\n const accepted = decoded?.accepted\n if (!accepted || typeof accepted !== 'object' || Array.isArray(accepted)) return both\n return isErc7710Option(accepted as X402PaymentOption) ? [X402_PAYMENT_HEADER_NAME] : both\n}\n\n/**\n * The retry headers an agent sets on its own merchant retry, ready-made:\n * `{ <name>: <paymentHeader> }` for every name `x402PaymentHeaderNamesFor`\n * puts on the wire for this payload (#3727).\n *\n * Exists so no caller re-derives the names from prose: the rule is the SDK's\n * live one (both `PAYMENT-SIGNATURE` and `X-PAYMENT` on eip3009,\n * `PAYMENT-SIGNATURE` only on erc7710 — the #2341 rule), and a change to it\n * flows here through the same function the request path uses. Every value is\n * the header verbatim; only the NAMES vary.\n */\nexport function x402RetryHeadersFor(paymentHeader: string): Record<string, string> {\n return Object.fromEntries(\n x402PaymentHeaderNamesFor(paymentHeader).map((name) => [name, paymentHeader]),\n )\n}\n\n/**\n * What the evidence record's `paymentProofHeaderName` must say for THIS\n * payload, derived from the same decision the request makes.\n *\n * `X402_PAYMENT_HEADER_NAMES_SENT` was a constant when the answer was always\n * both. It no longer always is, so a recorder still reading the constant would\n * claim an erc7710 request carried a legacy header it never sent — the exact\n * drift that constant's own comment was written to prevent, one scheme later.\n */\nexport function x402PaymentHeaderNamesSent(paymentHeader: string): string {\n return x402PaymentHeaderNamesFor(paymentHeader).join(', ')\n}\n\n/**\n * The x402 v2 payment envelope: `{x402Version, resource?, accepted, payload,\n * extensions?}` per the spec's PaymentPayload (§5.2.2).\n *\n * The `resource` and `extensions` echoes are the #2361 fix, and they are not\n * optional politeness: the spec makes the extensions echo a MUST (\"the client\n * must include at least the info received\"), and CoinGecko's facilitator was\n * live-bisected rejecting the echo-less envelope with a bare 400 while\n * accepting the identical signature and `accepted`/`payload` bytes with the\n * echoes added (#2360, Base mainnet, 2026-09-01). Both objects are echoed\n * VERBATIM from the merchant's 402 — never reconstructed — and omitted when\n * the challenge carries none, which keeps the envelope byte-identical to the\n * pre-#2361 shape for echo-less merchants (Ampersend and Soundside settled\n * that shape live, so omission is the proven-compatible default).\n *\n * The `accepted` wrap itself is #303's shape and predates this helper — see\n * the #300/#303 history before \"fixing\" it: scheme/network live INSIDE\n * `accepted` in v2, never at the top level.\n */\nexport function x402V2PaymentEnvelope(\n paymentRequired: Pick<X402PaymentRequired, 'x402Version' | 'resource' | 'extensions'>,\n accepted: X402PaymentOption,\n payload: unknown,\n): Record<string, unknown> {\n const resource = paymentRequired.resource\n const extensions = paymentRequired.extensions\n return {\n x402Version: paymentRequired.x402Version,\n ...(resource && typeof resource === 'object' && !Array.isArray(resource)\n ? { resource }\n : {}),\n accepted,\n payload,\n ...(extensions && typeof extensions === 'object' && !Array.isArray(extensions)\n ? { extensions }\n : {}),\n }\n}\n\n/**\n * Parse an HTTP 402 response into x402 PaymentRequired data.\n *\n * Supports:\n * - v2: PAYMENT-REQUIRED header (base64 JSON)\n * - v1 fallback: X-PAYMENT header or response body\n */\nexport function parsePaymentRequired(response: Response): X402PaymentRequired {\n // v2: PAYMENT-REQUIRED header\n const v2Header = response.headers.get('PAYMENT-REQUIRED')\n if (v2Header) {\n const parsed = normalizePaymentRequired(\n decodeBase64Json<unknown>(v2Header, 'PAYMENT-REQUIRED header'),\n )\n if (parsed) return parsed\n }\n\n // v1: X-PAYMENT header\n const v1Header = response.headers.get('X-PAYMENT')\n if (v1Header) {\n const parsed = normalizePaymentRequired(\n decodeBase64Json<unknown>(v1Header, 'X-PAYMENT header'),\n )\n if (parsed) return parsed\n }\n\n throw new Error(\n 'No x402 payment headers found in 402 response. ' +\n 'Expected PAYMENT-REQUIRED (v2) or X-PAYMENT (v1) header.',\n )\n}\n\n/**\n * Parse an HTTP 402 response into x402 PaymentRequired data.\n *\n * Soundside and other Bazaar-style MCP endpoints return the PaymentRequired\n * object in the JSON body, while older Haven demos and many x402 examples use\n * base64 headers. This keeps the synchronous header parser intact and adds the\n * body fallback needed for those endpoints.\n */\nexport async function parsePaymentRequiredResponse(\n response: Response,\n): Promise<X402PaymentRequired> {\n try {\n return parsePaymentRequired(response)\n } catch (headerErr) {\n try {\n const body = await response.clone().json()\n const parsed = normalizePaymentRequired(body)\n if (parsed) return parsed\n } catch {\n // Fall through to the original, more specific header error below.\n }\n\n throw headerErr\n }\n}\n\n/**\n * Select the best payment option from the x402 accepts array.\n *\n * Preference order:\n * 1. Option on a Haven-supported network with a known token\n * 2. Any option on a Haven-supported network\n * 3. null — no compatible option\n */\nexport function selectPaymentOption(\n accepts: X402PaymentOption[],\n): X402PaymentOption | null {\n if (!accepts || accepts.length === 0) return null\n\n // First pass: find a supported network with a known token\n for (const opt of accepts) {\n if (opt.network in SUPPORTED_X402_NETWORKS) {\n const networkTokens = NETWORK_TOKENS[opt.network]\n if (\n networkTokens?.[opt.asset.toLowerCase()] &&\n isPositiveDecimalAtomicAmount(optionAuthorizationAmount(opt))\n ) {\n return opt\n }\n }\n }\n\n // Second pass: any supported network\n for (const opt of accepts) {\n if (\n opt.network in SUPPORTED_X402_NETWORKS &&\n isPositiveDecimalAtomicAmount(optionAuthorizationAmount(opt))\n ) {\n return opt\n }\n }\n\n // No compatible option found\n return null\n}\n\n/** The `extra.assetTransferMethod` value that marks an erc7710-settleable entry. */\nexport const ERC7710_ASSET_TRANSFER_METHOD = 'erc7710'\n\n/**\n * True when the entry is EIP-3009-`authorization`-shaped: what this SDK can\n * construct with `exact.evm.createPaymentHeader` (#3116).\n *\n * The [exact EVM specification](https://github.com/x402-foundation/x402/blob/main/specs/schemes/exact/scheme_exact_evm.md)\n * distinguishes three payloads by `extra.assetTransferMethod`: EIP-3009 signs\n * `signature`/`authorization`, Permit2 signs `signature`/`permit2Authorization`,\n * and erc7710 carries a delegation chain. Haven constructs exactly one of\n * those payloads — the EIP-3009 `authorization` one — so an entry counts as\n * EIP-3009-compatible ONLY when its advertised method and flow agree with\n * that payload, by name: an omitted key means the mechanism default\n * (`eip3009` / `authorization`), and any value that is present but not\n * exactly the supported string — including a non-string, malformed value —\n * makes the entry unsupported.\n *\n * `extra.assetTransferMethod` / `extra.paymentFlow` are protocol-reserved\n * keys ([v2 specification §6.1](https://github.com/x402-foundation/x402/blob/main/specs/x402-specification-v2.md),\n * which also requires clients to refuse a `paymentFlow` they do not\n * recognize), so their values are READ as claims, never ignored. Merchant\n * shape is untrusted, same defensive posture as `x402AssetTransferMethod` —\n * but here a malformed value reads as UNSUPPORTED rather than as the\n * default, because the cost of guessing the default wrong is a signature\n * the merchant's verifier refuses after the funding leg has already moved\n * funds. 'erc7710' fails this test like any other non-3009 method and is\n * selected by `selectErc7710PaymentOption` instead.\n */\nfunction isEip3009ConstructibleOption(option: X402PaymentOption): boolean {\n const rawMethod = option.extra?.assetTransferMethod\n if (rawMethod !== undefined && rawMethod !== 'eip3009') return false\n const rawFlow = option.extra?.paymentFlow\n if (rawFlow !== undefined && rawFlow !== 'authorization') return false\n return true\n}\n\n/**\n * Read `extra.assetTransferMethod` defensively. `extra` is the merchant's own\n * object, so it is untrusted shape: anything that is not the exact string is\n * treated as \"not erc7710\" rather than coerced.\n */\nexport function x402AssetTransferMethod(option: X402PaymentOption): string | null {\n const raw = option.extra?.assetTransferMethod\n return typeof raw === 'string' ? raw : null\n}\n\n/** True when the merchant advertises this entry as erc7710-settleable. */\nexport function isErc7710Option(option: X402PaymentOption): boolean {\n return x402AssetTransferMethod(option) === ERC7710_ASSET_TRANSFER_METHOD\n}\n\n/**\n * The facilitator addresses a merchant advertises for an erc7710 entry, for\n * the #1058 redeemer pin — or `null` when it pins nothing.\n *\n * **An EMPTY array is `null`, not `[]`.** The backend rejects an empty\n * `redeemers` list with a 400 (`routes/x402.ts`), and the QA scenario already\n * treats empty as absent. Returning `[]` here would hand callers a value that\n * means \"pin to nobody\" — which is not a narrower pin, it is an unbuildable\n * delegation.\n *\n * Malformed entries are DROPPED rather than failing the whole option, and that\n * asymmetry is deliberate. A pin narrowed by a merchant's typo means the\n * facilitator that actually tries to redeem is not on the list, so redemption\n * reverts — and erc7710 has no funding leg, so nothing moved and nothing is\n * stranded. Refusing the option outright would instead deny a payment the\n * remaining valid facilitators could have settled. Losing the payment is the\n * worse outcome, precisely because the failure this issue closes (#1453) is the\n * one where funds move BEFORE the rejection.\n */\nexport function x402FacilitatorAddresses(option: X402PaymentOption): string[] | null {\n const raw = option.extra?.facilitatorAddresses\n if (!Array.isArray(raw)) return null\n const addresses = raw.filter((a): a is string => typeof a === 'string' && ADDRESS_RE.test(a))\n return addresses.length > 0 ? addresses : null\n}\n\n/** Shared shape test: scheme/network/asset/amount, ignoring settlement scheme. */\nfunction isPayableStandardOption(opt: X402PaymentOption): boolean {\n return (\n opt.scheme === 'exact' &&\n opt.network in STANDARD_X402_NETWORKS &&\n STANDARD_X402_USDC_ADDRESSES.has(opt.asset.toLowerCase()) &&\n isPositiveDecimalAtomicAmount(optionAuthorizationAmount(opt))\n )\n}\n\n/**\n * Select an option that can be paid with the official x402 EIP-3009 exact\n * scheme. Haven's older tx-hash proof path can describe more networks; the\n * merchant-verified path currently needs Base USDC.\n *\n * **Skips erc7710-tagged entries (#1453).** It used to return the first\n * positional match and never look at `extra.assetTransferMethod`, so a merchant\n * that listed its erc7710 entry first made a Haven client echo that option\n * while signing a standard EIP-3009 authorization. The merchant rejects the\n * mismatch cleanly — but on the two-leg bridge the account→delegate funding\n * transfer has already executed, so the visible result is a stranded delegate\n * balance for the sweep to reclaim. Only our own demo merchant's ordering was\n * holding that shut, and that pin binds our merchant, not the ones we do not\n * control.\n */\nexport function selectStandardPaymentOption(\n accepts: X402PaymentOption[],\n): X402PaymentOption | null {\n if (!accepts || accepts.length === 0) return null\n\n for (const opt of accepts) {\n // #1469: a null hole in accepts[] is unpayable data, not a crash. The\n // parsed-Response path filters these in normalizePaymentRequired, but at\n // least one caller (mcp-server, agent-supplied payment_required) reaches\n // here unsanitized — and a throw there became a 500 where every other\n // caller gets the clean no-compatible-option refusal.\n if (opt === null || typeof opt !== 'object') continue\n // #3116: non-erc7710 is no longer assumed EIP-3009-compatible. A permit2\n // entry, or one advertising a paymentFlow this SDK does not recognize,\n // must be skipped here rather than signed into an EIP-3009 payload the\n // exact-EVM specification does not define for it.\n if (!isEip3009ConstructibleOption(opt)) continue\n if (isPayableStandardOption(opt)) return opt\n }\n\n return null\n}\n\n/**\n * Select the erc7710-settleable option, if the merchant advertises one.\n */\nexport function selectErc7710PaymentOption(\n accepts: X402PaymentOption[],\n): X402PaymentOption | null {\n if (!accepts || accepts.length === 0) return null\n\n for (const opt of accepts) {\n // #1469: a null hole in accepts[] is unpayable data, not a crash. The\n // parsed-Response path filters these in normalizePaymentRequired, but at\n // least one caller (mcp-server, agent-supplied payment_required) reaches\n // here unsanitized — and a throw there became a 500 where every other\n // caller gets the clean no-compatible-option refusal.\n if (opt === null || typeof opt !== 'object') continue\n if (isErc7710Option(opt) && isPayableStandardOption(opt)) return opt\n // #3116: an erc7710 selector must not fall through to an entry whose\n // method/flow is neither erc7710 nor constructible EIP-3009 — an\n // unsupported entry stays unsupported on BOTH selectors, so a challenge\n // that offers only incompatible shapes is refused, never guessed at.\n if (!isEip3009ConstructibleOption(opt)) continue\n }\n\n return null\n}\n\n/** What a settlement-scheme decision resolved to. */\nexport interface X402SchemeSelection {\n scheme: 'erc7710' | 'eip3009'\n option: X402PaymentOption\n /** Redeemer pin for the settlement child; only ever set on erc7710. */\n facilitatorAddresses: string[] | null\n}\n\n/**\n * THE preference rule, in one place (#1450 owner decision, #1453).\n *\n * Prefer erc7710 whenever the account is on the delegation rail and the\n * merchant advertises `extra.assetTransferMethod: \"erc7710\"`; fall back to\n * the EIP-3009 bridge otherwise.\n *\n * Both halves of that condition are required, and the rail half is the\n * caller's to supply — the SDK cannot see which rail an account is on from a\n * 402 response alone. A legacy AllowanceModule account passing\n * `delegationRail: true` would select a scheme its account cannot settle; the\n * backend refuses that at authorize with the #1986 retired-rail 410 (#2245 —\n * previously a scheme-specific 400 that wrongly implied the legacy rail could\n * still settle via EIP-3009), which is where a rail mismatch SHOULD fail,\n * on-chain-adjacent rather than in a client that could be lying to itself.\n *\n * Returns `null` when neither scheme has a payable entry — the caller decides\n * whether that is an error or a reason to look elsewhere.\n */\nexport function selectX402SettlementScheme(\n accepts: X402PaymentOption[],\n opts: { delegationRail: boolean },\n): X402SchemeSelection | null {\n if (opts.delegationRail) {\n const preferred = selectErc7710PaymentOption(accepts)\n if (preferred) {\n return {\n scheme: 'erc7710',\n option: preferred,\n facilitatorAddresses: x402FacilitatorAddresses(preferred),\n }\n }\n }\n\n const fallback = selectStandardPaymentOption(accepts)\n if (fallback) return { scheme: 'eip3009', option: fallback, facilitatorAddresses: null }\n\n return null\n}\n\nexport function x402AuthorizationAmount(option: X402PaymentOption): string {\n const amount = optionAuthorizationAmount(option)\n if (!isPositiveDecimalAtomicAmount(amount)) {\n throw new Error('Invalid x402 amount: must be a positive decimal atomic amount')\n }\n return amount\n}\n\n/**\n * Canonical Haven-authenticated x402 expected context, recomputed byte-for-byte\n * by the edge signer before it signs anything.\n *\n * **Two versions, and the version is derived — never passed in (#1138).**\n * `typedDataHash` present ⇒ v2, absent ⇒ v1. A v1 message is byte-identical to\n * what shipped before, so existing signers keep verifying legacy-rail bindings\n * unchanged.\n *\n * The version lives in both the header line and the payload so neither can be\n * reinterpreted as the other: a v2 context cannot be replayed as a v1 one that\n * drops the typed-data commitment, and a v1 context cannot be presented as v2.\n * That downgrade is exactly the attack the digest exists to stop — see\n * `assertExpectedBinding` in `@haven_ai/signer`, which refuses to raw-sign a\n * hash under a v2 binding and refuses to sign typed data without one.\n */\nexport function buildX402ExpectedMessage(context: X402ExpectedContext): string {\n // Contents-derived, never caller-chosen (#1138, #1690): payerDelegate ⇒ 3,\n // else typedDataHash ⇒ 2, else 1. A v3 context still carries typedDataHash\n // on the delegation rail — the MODE rules key on typedDataHash presence\n // independently of the version, so v3 works in both hash and typed-data\n // modes.\n const version = context.payerDelegate ? 3 : context.typedDataHash ? 2 : 1\n const payload: Record<string, unknown> = {\n version,\n kind: 'haven.x402.expected',\n paymentId: context.paymentId,\n payloadHash: context.payloadHash.toLowerCase(),\n resourceUrl: context.resourceUrl,\n merchantTo: context.merchantTo.toLowerCase(),\n amount: context.amount,\n asset: context.asset.toLowerCase(),\n network: context.network,\n }\n if (context.expiresAt) {\n payload.expiresAt = context.expiresAt\n }\n if (context.typedDataHash) {\n payload.typedDataHash = context.typedDataHash.toLowerCase()\n }\n if (context.payerDelegate) {\n payload.payerDelegate = context.payerDelegate.toLowerCase()\n // Only meaningful alongside the delegate it identifies — an agent id with\n // no payer claim would be diagnosis without a guard.\n if (context.payerAgentId) {\n payload.payerAgentId = context.payerAgentId\n }\n }\n return `Haven x402 expected context v${version}\\n${stableStringify(payload)}`\n}\n\nexport function toStandardPaymentRequirements(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n): PaymentRequirements {\n const network = STANDARD_X402_NETWORKS[option.network]\n if (!network) {\n throw new Error(`x402 exact payments are not supported on ${option.network}`)\n }\n\n if (option.scheme !== 'exact') {\n throw new Error(`Unsupported x402 scheme: ${option.scheme}`)\n }\n\n // #3116, last stop before `exact.evm.createPaymentHeader`: the requirements\n // produced here can ONLY become an EIP-3009 `authorization` payload, so an\n // entry advertising any other transfer method or an unrecognized payment\n // flow must refuse here even if a future caller bypasses the selectors.\n // Permit2 signs `signature`/`permit2Authorization` — a payload this SDK\n // does not construct (implementing Permit2 is out of scope by design) —\n // and §6.1 forbids constructing a payment for a paymentFlow the client\n // does not recognize. Both refuse BEFORE any funding or signing.\n if (!isEip3009ConstructibleOption(option)) {\n throw new Error(\n 'Unsupported x402 payment requirements: this SDK constructs EIP-3009 ' +\n 'authorization payments only. The merchant advertised a different ' +\n 'extra.assetTransferMethod or an unrecognized extra.paymentFlow.',\n )\n }\n\n return {\n scheme: 'exact',\n network,\n maxAmountRequired: x402AuthorizationAmount(option),\n resource: option.resource ?? paymentRequired.resource.url,\n description:\n option.description ??\n paymentRequired.resource.description ??\n 'Haven x402 payment',\n mimeType:\n option.mimeType ??\n paymentRequired.resource.mimeType ??\n 'application/octet-stream',\n payTo: option.payTo,\n asset: option.asset,\n // Signing-only policy (#715/#3117): parsed and directly supplied options\n // share this cap before the library computes validBefore. Keep the offer\n // echoed in `accepted` unchanged. The forward margin (#1256) adds time\n // for funding/retry, but does not guarantee a merchant timeout above the\n // total bounded lifetime can pass facilitator verification.\n maxTimeoutSeconds:\n clampAuthorizationWindow(option.maxTimeoutSeconds) +\n X402_SETTLEMENT_FORWARD_MARGIN_SECONDS,\n extra: option.extra,\n }\n}\n\n/**\n * Strictly validate an edge-signed EIP-3009 X-PAYMENT header against the\n * persisted x402 intent context before a hosted relay can submit funding.\n *\n * The merchant/facilitator remains the final protocol verifier. This closes a\n * separate hosted-relay integrity gap: malformed or context-mismatched input\n * must never cause Haven to relay the funding signature first.\n */\nexport async function validateStandardX402PaymentHeader(\n paymentHeader: string,\n context: X402PaymentHeaderContext,\n): Promise<void> {\n try {\n if (\n typeof paymentHeader !== 'string' ||\n paymentHeader.length === 0 ||\n paymentHeader.length > X402_PAYMENT_HEADER_MAX_LENGTH ||\n paymentHeader.length % 4 !== 0 ||\n !BASE64_RE.test(paymentHeader)\n ) {\n throw new Error('wire')\n }\n\n const decoded = decodeBase64Json<Record<string, unknown>>(paymentHeader)\n if (!decoded || typeof decoded !== 'object' || Array.isArray(decoded)) throw new Error('shape')\n const version = decoded.x402Version\n const payload = decoded.payload\n if ((version !== 1 && version !== 2) || !payload || typeof payload !== 'object' || Array.isArray(payload)) {\n throw new Error('shape')\n }\n\n if (version === 1) {\n if (!hasOnlyKeys(decoded, ['x402Version', 'scheme', 'network', 'payload'])) throw new Error('shape')\n if (decoded.scheme !== 'exact' || decoded.network !== standardX402WireNetwork(context.network)) {\n throw new Error('context')\n }\n } else {\n // #2361: the v2 envelope may carry the `resource`/`extensions` echoes\n // (spec PaymentPayload §5.2.2; the extensions echo is a spec MUST when\n // the challenge advertises them). They are echoes of merchant data, not\n // spend authority — validated structurally here, while the required\n // key set stays exactly what it was.\n if (!hasOnlyKeys(decoded, ['x402Version', 'accepted', 'payload'], ['resource', 'extensions'])) {\n throw new Error('shape')\n }\n if ('resource' in decoded && (!decoded.resource || typeof decoded.resource !== 'object' || Array.isArray(decoded.resource))) {\n throw new Error('shape')\n }\n if ('extensions' in decoded && (!decoded.extensions || typeof decoded.extensions !== 'object' || Array.isArray(decoded.extensions))) {\n throw new Error('shape')\n }\n const accepted = selectStandardPaymentOption([decoded.accepted as X402PaymentOption])\n if (!accepted || !matchesHeaderContext(accepted, context)) throw new Error('context')\n }\n\n const record = payload as Record<string, unknown>\n if (!hasOnlyKeys(record, ['signature', 'authorization'])) throw new Error('shape')\n if (typeof record.signature !== 'string' || !SIGNATURE_RE.test(record.signature)) throw new Error('shape')\n const authorization = record.authorization\n if (!authorization || typeof authorization !== 'object' || Array.isArray(authorization)) throw new Error('shape')\n const auth = authorization as Record<string, unknown>\n if (!hasOnlyKeys(auth, ['from', 'to', 'value', 'validAfter', 'validBefore', 'nonce'])) throw new Error('shape')\n if (\n typeof auth.from !== 'string' || !ADDRESS_RE.test(auth.from) ||\n typeof auth.to !== 'string' || !ADDRESS_RE.test(auth.to) ||\n typeof auth.value !== 'string' || !isPositiveDecimalAtomicAmount(auth.value) ||\n typeof auth.validAfter !== 'string' || !DECIMAL_ATOMIC_AMOUNT_RE.test(auth.validAfter) ||\n typeof auth.validBefore !== 'string' || !DECIMAL_ATOMIC_AMOUNT_RE.test(auth.validBefore) ||\n typeof auth.nonce !== 'string' || !NONCE_RE.test(auth.nonce)\n ) {\n throw new Error('shape')\n }\n if (!sameAddress(auth.from, context.payer) || !sameAddress(auth.to, context.merchantTo) || auth.value !== context.amountAtomic) {\n throw new Error('context')\n }\n\n const validAfter = BigInt(auth.validAfter)\n const validBefore = BigInt(auth.validBefore)\n const now = BigInt(Math.floor(Date.now() / 1000))\n if (validBefore <= now || validAfter > validBefore) throw new Error('expired')\n\n // `buildSweepTypedData` pins the correct USDC EIP-712 domain for the\n // persisted chain + asset pair. Successful recovery makes the nonce and\n // every authorization field cryptographically covered by the delegate.\n const typedData = buildSweepTypedData({\n from: auth.from,\n to: auth.to,\n value: auth.value,\n validAfter: auth.validAfter,\n validBefore: auth.validBefore,\n nonce: auth.nonce,\n token: context.asset,\n chainId: context.chainId,\n })\n const recovered = await recoverTypedDataAddress({\n ...typedData,\n // `buildSweepTypedData` keeps the public domain framework-neutral;\n // viem brands contract addresses at this crypto call boundary only.\n domain: {\n ...typedData.domain,\n verifyingContract: typedData.domain.verifyingContract as `0x${string}`,\n },\n message: {\n ...typedData.message,\n from: typedData.message.from as `0x${string}`,\n to: typedData.message.to as `0x${string}`,\n nonce: typedData.message.nonce as `0x${string}`,\n },\n signature: record.signature as `0x${string}`,\n })\n if (!sameAddress(recovered, context.payer)) throw new Error('recovery')\n } catch {\n // Header values are attacker-controlled and may include merchant data.\n // Never propagate them into hosted errors, logs, or serialized telemetry.\n throw new X402PaymentHeaderValidationError()\n }\n}\n\nfunction hasOnlyKeys(\n value: Record<string, unknown>,\n required: string[],\n optional: string[] = [],\n): boolean {\n return Object.keys(value).every((key) => required.includes(key) || optional.includes(key)) &&\n required.every((key) => key in value)\n}\n\nfunction sameAddress(left: string, right: string): boolean {\n return left.toLowerCase() === right.toLowerCase()\n}\n\nfunction standardX402WireNetwork(network: string): PaymentRequirements['network'] | null {\n return STANDARD_X402_NETWORKS[network] ?? null\n}\n\nfunction matchesHeaderContext(option: X402PaymentOption, context: X402PaymentHeaderContext): boolean {\n if (\n option.scheme !== 'exact' ||\n !sameAddress(option.payTo, context.merchantTo) ||\n !sameAddress(option.asset, context.asset) ||\n option.network !== context.network ||\n x402AuthorizationAmount(option) !== context.amountAtomic\n ) return false\n // x402 v2 may scope an accepted option to a resource. When it does, that\n // resource is part of the header context and must match the intent.\n return option.resource === undefined || option.resource === context.resourceUrl\n}\n\nexport function buildX402IdempotencyKey(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n now = Date.now(),\n): string {\n const bucket = Math.floor(now / X402_IDEMPOTENCY_BUCKET_MS)\n const material = [\n paymentRequired.resource.url,\n paymentRequired.resource.description ?? '',\n option.payTo.toLowerCase(),\n option.asset.toLowerCase(),\n x402AuthorizationAmount(option),\n option.network,\n bucket,\n ].join('|')\n\n return `x402:${createHash('sha256').update(material).digest('hex').slice(0, 16)}`\n}\n\n/**\n * Encode a payment receipt as a base64 PAYMENT-SIGNATURE header value.\n *\n * This follows the x402 v2 protocol — the server's facilitator will\n * verify the on-chain transaction referenced by tx_hash.\n */\nexport function encodePaymentProof(receipt: {\n txHash: string\n paymentId: string\n token: string\n amount: string\n to: string\n resourceUrl?: string\n accepted?: X402PaymentOption\n payer?: string\n chainId?: number\n}): string {\n const payload = {\n x402Version: 2,\n resource: receipt.resourceUrl ? { url: receipt.resourceUrl } : undefined,\n accepted: receipt.accepted,\n payload: {\n type: 'haven_tx_hash',\n txHash: receipt.txHash,\n paymentId: receipt.paymentId,\n settledVia: 'haven',\n payer: receipt.payer,\n chainId: receipt.chainId,\n },\n }\n return encodeBase64Json(payload)\n}\n\n/**\n * Resolve a token symbol from a contract address.\n *\n * Checks all supported chains. For chain-specific resolution,\n * pass the optional `network` CAIP-2 string (e.g. \"eip155:8453\").\n */\nexport function resolveTokenFromAddress(\n address: string,\n network?: string,\n): { symbol: string; decimals: number } | null {\n const lower = address.toLowerCase()\n\n // #3638: a NAMED network resolves only in its own table. Falling back to the\n // cross-chain table bound one chain's decimals to another chain's option\n // (Base USDC's 6 decimals for an address on an unregistered network).\n if (network) return NETWORK_TOKENS[network]?.[lower] ?? null\n\n return ALL_TOKENS[lower] ?? null\n}\n\n/**\n * #3410: token decimals from a SYMBOL + CHAIN — the same registry\n * `resolveTokenFromAddress` reads, keyed the other way. The address-based\n * resolver needs the token's contract address, which the consent seed path\n * (setup-time credential files) does not carry; the symbol and chain it does\n * carry. Null when the symbol is not registered on that chain (unknown or\n * custom tokens) — callers must fall back to an explicit atomic label rather\n * than reading an atomic amount as whole tokens.\n */\nexport function resolveTokenBySymbol(chainId: number, symbol: string): { symbol: string; decimals: number } | null {\n const table = NETWORK_TOKENS[`eip155:${chainId}`]\n if (!table) return null\n const hit = Object.entries(table).find(([, token]) => token.symbol === symbol)\n return hit ? { ...hit[1] } : null\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n const primitive = JSON.stringify(value)\n return primitive === undefined ? 'undefined' : primitive\n }\n // Match JSON.stringify's Date handling: serialize to the ISO string, not the\n // empty object the generic-object branch would produce (Object.keys(date) is\n // []). The backend builds the x402 expected-context message from a Postgres\n // TIMESTAMPTZ (a Date at runtime), so without this the signed message carried\n // \"expiresAt\":{} while the edge signer recomputed \"expiresAt\":\"<ISO>\" — a\n // mismatch that broke x402 signature verification once expires_at entered the\n // signed context.\n if (value instanceof Date) return JSON.stringify(value.toISOString())\n if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(',')}]`\n const object = value as Record<string, unknown>\n return `{${Object.keys(object)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(object[key])}`)\n .join(',')}}`\n}\n","/**\n * Client identity on Haven API requests (#3303, epic #3302).\n *\n * Every published Haven client names itself with one header,\n * `X-Haven-Client: <package>/<version>`, so the backend can tell an outdated\n * client what to run — a `client_update` hint on its responses, or, only below\n * a minimum the deployment has explicitly set, a 426 `client_outdated` refusal\n * at the payment-initiating routes (the signer: at sign-context). The backend's\n * table and decision live in `@haven_ai/core`'s `client-compat.ts`; this module\n * is the client half and deliberately holds no thresholds.\n *\n * Deliberately free of any other SDK import so `@haven_ai/sdk/edge` (the\n * signer's ethers-free entry) can re-export it.\n */\n\n/**\n * This SDK's own version. Owned by `scripts/release-bump.mjs`, which rewrites\n * it with the package version on every release — never hand-edit it.\n */\nexport const SDK_VERSION = '0.9.0-alpha.0'\n\n/** The request header every published Haven client sends. */\nexport const HAVEN_CLIENT_HEADER = 'X-Haven-Client'\n\n/** `<package>/<version>` — the value of {@link HAVEN_CLIENT_HEADER}. */\nexport function havenClientIdentity(pkg: string, version: string): string {\n return `${pkg}/${version}`\n}\n\n/** What a bare SDK embedder sends when it names no package of its own. */\nexport const SDK_CLIENT_IDENTITY = havenClientIdentity('@haven_ai/sdk', SDK_VERSION)\n\n/**\n * The `client_update` object the backend attaches to a response when this\n * client is behind (`required: false`) or below a set minimum\n * (`required: true`). Every field is the backend's; the SDK never computes one.\n */\nexport interface HavenClientUpdate {\n package: string\n current: string\n recommended: string | null\n min_version: string | null\n required: boolean\n upgrade_command: string\n notes_url: string | null\n}\n\n/** Narrow an unknown response field to a {@link HavenClientUpdate}, or undefined. */\nexport function readClientUpdate(value: unknown): HavenClientUpdate | undefined {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined\n const v = value as Record<string, unknown>\n if (\n typeof v.package !== 'string' ||\n typeof v.current !== 'string' ||\n typeof v.required !== 'boolean' ||\n typeof v.upgrade_command !== 'string'\n ) {\n return undefined\n }\n return {\n package: v.package,\n current: v.current,\n recommended: typeof v.recommended === 'string' ? v.recommended : null,\n min_version: typeof v.min_version === 'string' ? v.min_version : null,\n required: v.required,\n upgrade_command: v.upgrade_command,\n notes_url: typeof v.notes_url === 'string' ? v.notes_url : null,\n }\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport { privateKeyToAddress, publicKeyToAddress } from 'viem/accounts'\nimport { serializeSignature, type Hex } from 'viem'\nimport { HavenSigningError } from './types.js'\n\n/**\n * #3173: the three key helpers the edge signer needs, without ethers.\n *\n * `./signer.ts` implements the same three on ethers, and the SDK barrel pulls\n * ethers in for them (and for `provider.ts` / `receipt.ts`). The edge signer\n * already ships viem, and viem signs with `@noble/curves` underneath — these\n * use the same curve library directly, synchronously (viem's own `sign` is\n * async), so `@haven_ai/sdk/edge` stays ethers-free and a signer session stops\n * paying for module init it never uses. Byte-equivalence with the ethers forms\n * is pinned in `edge-signing.test.ts`: same address, same 65-byte `r‖s‖v`\n * serialisation with low-s and v = 27/28, same recovery verdicts, and the same\n * refusals (high-s twin, wrong lengths) — with three stated strict-direction\n * exceptions, see `hexBytes`. Raw ECDSA over the hash — never the EIP-191\n * prefixed digest.\n */\n\n/** secp256k1 order / 2 — a signature with s above this is the malleable twin ethers rejects. */\nconst HALF_N = BigInt('0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0')\n\n/**\n * Stricter than ethers, never looser: the lowercase `0x` prefix and the exact\n * byte length are required. Ethers accepts an uppercase `0X` prefix on a\n * signature and the 64-byte EIP-2098 compact form, and is inconsistent on a\n * private key (`Wallet` accepts unprefixed and refuses `0X`; `SigningKey` does\n * the reverse); every such form is refused here — the divergences are pinned\n * in `edge-signing.test.ts` with ethers control assertions, and every\n * well-formed input is byte-equivalent.\n */\nfunction hexBytes(value: string, bytes: number, what: string): string {\n if (!/^0x[0-9a-fA-F]+$/.test(value) || value.length !== 2 + bytes * 2) {\n throw new Error(`${what} must be a 0x-prefixed ${bytes}-byte hex string`)\n }\n return value.slice(2)\n}\n\nexport function addressFromKey(privateKey: string): string {\n try {\n // Same gate as signHash: a key that derives an address must also sign.\n return privateKeyToAddress(`0x${hexBytes(privateKey, 32, 'private key')}`)\n } catch (err) {\n throw new HavenSigningError(\n `Invalid private key: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\nexport function signHash(privateKey: string, hash: string): string {\n try {\n const { r, s, recovery } = secp256k1.sign(hexBytes(hash, 32, 'hash'), hexBytes(privateKey, 32, 'private key'), { lowS: true })\n // viem serialises the trailing byte from yParity (0/1 → 27/28), the same\n // `v` ethers' `Signature.serialized` writes.\n return serializeSignature({\n r: `0x${r.toString(16).padStart(64, '0')}`,\n s: `0x${s.toString(16).padStart(64, '0')}`,\n yParity: recovery,\n })\n } catch (err) {\n throw new HavenSigningError(\n `Failed to sign hash: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\nexport function verifySignature(hash: string, signature: string, expectedAddress: string): boolean {\n try {\n const sig = hexBytes(signature, 65, 'signature')\n const hashHex = hexBytes(hash, 32, 'hash')\n // Reject the high-s malleable twin, as ethers does — one signature per message.\n if (BigInt(`0x${sig.slice(64, 128)}`) > HALF_N) return false\n const yParityOrV = Number.parseInt(sig.slice(128), 16)\n const recoveryBit = yParityOrV === 0 || yParityOrV === 27 ? 0 : yParityOrV === 1 || yParityOrV === 28 ? 1 : -1\n if (recoveryBit < 0) return false\n const publicKey = secp256k1.Signature.fromCompact(sig.slice(0, 128))\n .addRecoveryBit(recoveryBit)\n .recoverPublicKey(hashHex)\n .toHex(false)\n const recovered = publicKeyToAddress(`0x${publicKey}`)\n return recovered.toLowerCase() === expectedAddress.toLowerCase()\n } catch {\n return false\n }\n}\n","import { hashTypedData } from 'viem'\nimport { createHash } from 'node:crypto'\nimport { addressFromKey, signHash, verifySignature } from './edge-signing.js'\nimport { chainIdForNetwork } from './settlement-child.js'\nimport { HavenSigningError } from './types.js'\n\n/**\n * The x402 buyer-side tax declaration (#3427, wg-tax #5 §2.2\n * `buyer-side-tax-declaration.md`).\n *\n * The agent's own payment key — the same delegate EOA that signs the\n * EIP-3009 payment authorization — signs the §2.1 declaration content, and\n * the signed declaration travels to the SELLER ONLY, as\n * `X-Tax-Declaration: <base64url(JSON)>` on the paid merchant retry\n * (`MerchantCompletion.retryRequest`). It never reaches Haven or any\n * facilitator, and it is never part of the payment payload.\n *\n * Why this lives on the edge (`docs/architecture/07-edge-signer.md`, #3283's\n * shared-guard rule): the declaration MUST be signed by the key that signs\n * the payment authorization (§2.2), and on the EIP-3009 bridge that key is\n * held by this local SDK process. The builder therefore lives in\n * `@haven_ai/sdk/edge` beside the other signing guards, and every property\n * the threat model requires is enforced HERE, not by callers:\n *\n * - The EIP-712 typed data is built LOCALLY from the §2.1 fields. Typed data\n * is never accepted from Haven — the wire content is validated to exactly\n * the five §2.1 fields, and anything else (including a `principalId` or\n * `principalAttributionHash` arriving pre-set) is REFUSED, never stripped\n * and continued. A polluted declaration aborts the payment loudly rather\n * than being silently laundered into a signature.\n * - `principalId = did:pkh:<CAIP-2 network>:<delegate EOA>` — the chain\n * comes from the ACCEPTED payment option's `network` (§6.6.5 Equality),\n * never from configuration. An alias (`base`) is resolved through the same\n * `chainIdForNetwork` map the settlement child uses; a network with no\n * chain id refuses, so an unknown chain cannot mint a mis-scoped\n * principal.\n * - `principalAttributionHash = \"sha-256:<hex>\"` over the JCS-canonical bytes\n * of `{ principalId }` (§6.6.2, §6.6.5 Effect).\n *\n * Residual accepted by the owner (issue threat model, 2026-09-28): Haven\n * supplies `jurisdiction`, `taxableStatus` and `taxId`, so a compromised\n * Haven could produce a declaration with a wrong VAT number. Nothing moves\n * funds, the seller checks the VAT number in VIES, and the values are the\n * owner's own onboarding data. The SDK logs the `taxId` it signs (stderr, so\n * an MCP stdio session's JSON-RPC framing on stdout is untouched).\n */\n\n/**\n * PROVISIONAL EIP-712 domain (wg-tax PR #5 §2.2: the domain and types\n * \"remain to be defined\"). No chainId and no salt: the declaration is\n * portable across the settlement networks a seller may accept, and the\n * principal is already chain-scoped by `principalId`. Recorded in the PR\n * body for the working group; changing these constants changes every\n * signature produced, so they are pinned by the fixed-vector tests.\n */\nexport const TAX_DECLARATION_DOMAIN = { name: 'x402 Tax Declaration', version: '1' } as const\n\n/** The declaration's EIP-712 primary type name. */\nexport const TAX_DECLARATION_PRIMARY_TYPE = 'TaxDeclaration'\n\n/**\n * PROVISIONAL typed-data types for the signed §2.1 declaration plus the two\n * locally computed principal fields. Field order here is the ABI encoding\n * order of every signature produced by this module.\n */\nexport const TAX_DECLARATION_TYPES = {\n TaxDeclaration: [\n { name: 'version', type: 'string' },\n { name: 'jurisdiction', type: 'string' },\n { name: 'taxableStatus', type: 'string' },\n { name: 'taxId', type: 'string' },\n { name: 'validUntil', type: 'uint256' },\n { name: 'principalId', type: 'string' },\n { name: 'principalAttributionHash', type: 'string' },\n ],\n} as const\n\n/** The x402 header this module's output is serialised into. */\nexport const X_TAX_DECLARATION_HEADER = 'X-Tax-Declaration'\n\n/**\n * The §2.1 unsigned content exactly as `#3426`'s content endpoint emits it\n * (`GET /agents/:id/tax-declaration`, `{ available: true, declaration }`).\n */\nexport interface TaxDeclarationContent {\n /** §2.1 version discriminator, e.g. `x402-tax-1`. */\n version: string\n /** ISO 3166-1 alpha-2 country code. */\n jurisdiction: string\n /** §2.1's closed enumeration, e.g. `TAXABLE_PERSON`. */\n taxableStatus: string\n /** The owner's VAT number, normalised by the backend. */\n taxId: string\n /** Integer milliseconds — the declaration's validity bound. */\n validUntil: number\n}\n\n/** The signed declaration object carried (base64url-encoded) in the header. */\nexport interface SignedTaxDeclaration extends TaxDeclarationContent {\n /** `did:pkh:<CAIP-2 network>:<delegate EOA>` — computed locally. */\n principalId: string\n /** `sha-256:<hex>` over the JCS bytes of `{ principalId }`. */\n principalAttributionHash: string\n}\n\nexport interface SignedTaxDeclarationResult {\n declaration: SignedTaxDeclaration\n /** EIP-712 signature (65-byte `r‖s‖v`, 27/28) over the typed declaration. */\n signature: string\n}\n\n/**\n * The strict §2.1 content validator, run before anything is signed.\n *\n * Returns the five known fields. A payload carrying a `principalId` or\n * `principalAttributionHash` — the two fields only the LOCAL builder may set\n * — is refused with `TAX_DECLARATION_FIELD_REFUSED`, never laundered. An\n * extra field, a wrong type, or a missing field is refused the same way:\n * the signed shape is what THIS module builds, and anything else arriving\n * from Haven is an attempt to widen it.\n *\n * Mutation proofs (each refusal, with its test): removing the\n * principal-field check lets a Haven-supplied principal reach the signature\n * (`refuses content that arrives with a principalId/principalAttributionHash\n * set`); removing the exact-fields check lets an extra field change the\n * signed bytes (`refuses content with fields beyond the §2.1 five`).\n */\nfunction validateContent(content: unknown): TaxDeclarationContent {\n if (typeof content !== 'object' || content === null || Array.isArray(content)) {\n throw new HavenSigningError('Tax declaration content must be an object.')\n }\n const record = content as Record<string, unknown>\n for (const field of ['principalId', 'principalAttributionHash'] as const) {\n if (record[field] !== undefined) {\n throw new TaxDeclarationRefusedError(\n `Tax declaration content arrives with ${field} already set; that field is computed locally ` +\n 'from the delegate key and the accepted payment option, never accepted from Haven.',\n )\n }\n }\n const allowed = new Set(['version', 'jurisdiction', 'taxableStatus', 'taxId', 'validUntil'])\n for (const key of Object.keys(record)) {\n if (!allowed.has(key)) {\n throw new TaxDeclarationRefusedError(\n `Tax declaration content carries an unknown field '${key}'; the signed shape is built locally ` +\n 'from the §2.1 fields only.',\n )\n }\n }\n const strings = ['version', 'jurisdiction', 'taxableStatus', 'taxId'] as const\n for (const key of strings) {\n if (typeof record[key] !== 'string' || (record[key] as string).length === 0) {\n throw new TaxDeclarationRefusedError(\n `Tax declaration content field '${key}' must be a non-empty string.`,\n )\n }\n }\n if (\n typeof record.validUntil !== 'number' ||\n !Number.isInteger(record.validUntil) ||\n record.validUntil <= 0\n ) {\n throw new TaxDeclarationRefusedError(\n \"Tax declaration content field 'validUntil' must be a positive integer (milliseconds).\",\n )\n }\n return {\n version: record.version as string,\n jurisdiction: record.jurisdiction as string,\n taxableStatus: record.taxableStatus as string,\n taxId: record.taxId as string,\n validUntil: record.validUntil,\n }\n}\n\n/**\n * JCS (RFC 8785) canonical bytes for the `{ principalId }` attribution\n * object. RFC 8785 sorts object keys by UTF-16 code units and serialises\n * string values exactly as ECMAScript's `JSON.stringify` does, so for an\n * all-string-keyed object the canonical form is `JSON.stringify` over the\n * sorted keys. The sort is a no-op for this single-key shape but is written\n * out so the claim \"JCS bytes\" is implemented, not inherited from a\n * coincidence of one key.\n */\nfunction jcsCanonicalBytes(value: Record<string, string>): string {\n const keys = Object.keys(value).sort()\n const members = keys.map((key) => `${JSON.stringify(key)}:${JSON.stringify(value[key])}`)\n return `{${members.join(',')}}`\n}\n\n/** `sha-256:<hex>` over the UTF-8 JCS bytes of `{ principalId }` (§6.6.2). */\nexport function principalAttributionHash(principalId: string): string {\n const canonical = jcsCanonicalBytes({ principalId })\n const hex = createHash('sha256').update(canonical, 'utf8').digest('hex')\n return `sha-256:${hex}`\n}\n\n/**\n * `did:pkh:<CAIP-2 network>:<address>` from the accepted option's `network`.\n *\n * The chain comes from the settlement's network — a `eip155:<n>` value passes\n * through verbatim, the x402 aliases (`base`, `base-sepolia`) resolve through\n * the same `chainIdForNetwork` map the settlement child uses, and anything\n * else refuses: a network this SDK cannot name cannot produce a principal\n * that names its own chain.\n */\nexport function taxPrincipalId(network: string, delegateAddress: string): string {\n if (network.startsWith('eip155:')) {\n return `did:pkh:${network}:${delegateAddress}`\n }\n const chainId = chainIdForNetwork(network)\n if (chainId === undefined) {\n throw new TaxDeclarationRefusedError(\n `The accepted payment option's network '${network}' is not a CAIP-2 eip155 chain this SDK ` +\n 'can name; refusing to build a tax principal without the settlement network.',\n )\n }\n return `did:pkh:eip155:${chainId}:${delegateAddress}`\n}\n\n/**\n * Build the EIP-712 typed data for the §2.1 content LOCALLY, set the two\n * principal fields, and sign with the delegate key.\n *\n * The caller passes the raw content from `#3426`'s endpoint (parsed JSON) —\n * `validateContent` refuses anything beyond the five §2.1 fields before any\n * principal is computed or any byte is signed. The signature recovers to the\n * delegate EOA (pinned by the sign+recover test), which is the §2.2\n * requirement: the declaration signer is the payment authorizer.\n */\nexport function buildSignedTaxDeclaration(input: {\n /** The UNSIGNED §2.1 content from #3426's endpoint — `declaration` field of the response. */\n content: unknown\n /** The ACCEPTED payment option's network — the only chain source (§6.6.5). */\n network: string\n /** The agent's delegate key — the same key that signs the EIP-3009 authorization. */\n delegateKey: string\n}): SignedTaxDeclarationResult {\n const content = validateContent(input.content)\n const principalId = taxPrincipalId(input.network, addressFromKeyForTax(input.delegateKey))\n const attributionHash = principalAttributionHash(principalId)\n const declaration: SignedTaxDeclaration = { ...content, principalId, principalAttributionHash: attributionHash }\n\n // The wire JSON carries `validUntil` as a number (§2.1: integer\n // milliseconds); the EIP-712 encoding widens it to the `uint256` bigint.\n const message = { ...declaration, validUntil: BigInt(declaration.validUntil) }\n const digest = hashTypedData({\n domain: TAX_DECLARATION_DOMAIN,\n types: TAX_DECLARATION_TYPES,\n primaryType: TAX_DECLARATION_PRIMARY_TYPE,\n message,\n })\n const signature = signHash(input.delegateKey, digest)\n return { declaration, signature }\n}\n\n/**\n * Recompute the EIP-712 digest for a signed declaration and check the\n * signature recovers to `expectedAddress` — the seller-side verification\n * this SDK runs on itself in tests, kept next to the builder so the digest\n * rule cannot drift from the signing one.\n */\nexport function verifyTaxDeclarationSignature(\n declaration: SignedTaxDeclaration,\n signature: string,\n expectedAddress: string,\n): boolean {\n const message = { ...declaration, validUntil: BigInt(declaration.validUntil) }\n const digest = hashTypedData({\n domain: TAX_DECLARATION_DOMAIN,\n types: TAX_DECLARATION_TYPES,\n primaryType: TAX_DECLARATION_PRIMARY_TYPE,\n message,\n })\n return verifySignature(digest, signature, expectedAddress)\n}\n\n/**\n * The base64url(JSON) header value for the paid merchant retry. The JSON is\n * the signed declaration object with the `signature` field alongside — one\n * object, so the seller decodes, re-derives the digest from the known\n * provisional domain/types, and recovers the signer.\n */\nexport function encodeTaxDeclarationHeader(result: SignedTaxDeclarationResult): string {\n const json = JSON.stringify({ ...result.declaration, signature: result.signature })\n return base64Url(json)\n}\n\nfunction base64Url(value: string): string {\n const standard = typeof Buffer !== 'undefined'\n ? Buffer.from(value, 'utf8').toString('base64')\n : btoa(String.fromCharCode(...new TextEncoder().encode(value)))\n return standard.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nfunction addressFromKeyForTax(delegateKey: string): string {\n try {\n return addressFromKey(delegateKey)\n } catch (err) {\n throw new HavenSigningError(\n `Invalid delegate key for tax declaration signing: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * A refused declaration: the content was not exactly the locally built shape\n * (a pre-set principal field, an unknown field, a malformed value) or the\n * settlement network could not be named. Extends `HavenSigningError` so the\n * existing signing-error handling catches it; the `code` lets callers tell\n * the refusal apart from a key problem.\n */\nexport class TaxDeclarationRefusedError extends HavenSigningError {\n readonly code = 'TAX_DECLARATION_REFUSED'\n constructor(message: string) {\n super(message)\n this.name = 'TaxDeclarationRefusedError'\n }\n}\n","import type { AgentNextStep, AgentPaymentNextAction } from './types.js'\n\n/**\n * #3101 (epic #3105, slice 2/5): the typed next-step builder.\n *\n * Every hosted payment tool ends by naming the agent's next tool and its\n * arguments (#1308). Until this module, the tool was a free string and the\n * arguments a `Record<string, unknown>`, so nothing tied the keys to the tool\n * named beside them — three sites handed `{ payment_id: null }` to a tool\n * whose `payment_id` is a required string, and the compiler could not see it.\n *\n * The builder is generic over a TARGET MAP the caller supplies: bare tool\n * name → { role, validate }. It is deliberately schema-library-agnostic (the\n * SDK carries no zod): the hosted server derives each target's argument type\n * from its own zod shape and passes a `validate` closure; this module only\n * needs to know the role (to render `mcp__<server>__<tool>`) and how to say\n * whether arguments parse. Keyed on the bare name + role (decision 1) so the\n * namespaced string is rendered in exactly one place and the runtime-neutral\n * `next_tool_server` / `next_tool_name` / `next_tool_server_role` fields are\n * derived from the same input rather than parsed back out of a literal.\n *\n * Decisions 3 and 8: `nextTool` is REQUIRED on the input and may be `null` —\n * a site that forgets it is a compile error; a site with no next tool says\n * why, and the wire omits `next_tool` and carries `next_tool_omitted_reason`.\n * `next_tool` is never null on the wire.\n */\nexport type NextToolServerRole = 'hosted' | 'signer'\n\n/** The DEFAULT server name each role is wired under (#1588, #2550). */\nexport const NEXT_TOOL_SERVER_NAMES: Record<NextToolServerRole, string> = {\n hosted: 'haven',\n signer: 'haven-signer',\n}\n\n/** Default server name → role. An unknown server yields no role rather than a guess (#2550). */\nexport const NEXT_TOOL_SERVER_ROLES: Record<string, NextToolServerRole> = {\n haven: 'hosted',\n 'haven-signer': 'signer',\n}\n\n/** Renders the Claude-family namespaced tool name — the one string clients have followed since #1308. */\nexport function renderNextTool(role: NextToolServerRole, name: string): string {\n return `mcp__${NEXT_TOOL_SERVER_NAMES[role]}__${name}`\n}\n\n/** Parses a namespaced literal back into its parts; `role` is absent for an unknown server. */\nexport function parseNextTool(literal: string): { server: string; name: string; role?: NextToolServerRole } | null {\n const m = /^mcp__([a-z0-9-]+)__([a-z0-9_]+)$/.exec(literal)\n if (!m) return null\n const role = NEXT_TOOL_SERVER_ROLES[m[1]]\n return { server: m[1], name: m[2], ...(role ? { role } : {}) }\n}\n\n/**\n * One target the builder may hand off to. `TArgs` is the argument type the\n * caller derived from the tool's declared schema; `validate` is the runtime\n * twin of that type and returns `null` when the arguments parse, else why not.\n */\nexport interface NextStepTarget<TArgs> {\n role: NextToolServerRole\n validate: (input: unknown) => string | null\n /** Phantom carrier for the argument type; never read at runtime. */\n readonly _args?: TArgs\n}\n\nexport type NextStepTargets = Record<string, NextStepTarget<unknown>>\n\n/** The argument type a target carries. */\nexport type NextStepArguments<Targets extends NextStepTargets, T extends keyof Targets> =\n Targets[T] extends NextStepTarget<infer A> ? A : never\n\n/**\n * The handoff half of a next step: a registered tool with arguments that\n * tool accepts, or no tool with the reason. A discriminated union over the\n * target map's keys, so a wrong key, a missing required key, an unregistered\n * tool name and an omitted `nextTool` are each a compile error at the site.\n */\nexport type NextStepHandoff<Targets extends NextStepTargets> =\n | { [T in keyof Targets & string]: { nextTool: T; nextArguments: NextStepArguments<Targets, T> } }[keyof Targets & string]\n | { nextTool: null; nextToolOmittedReason: string }\n\nexport type NextStepInput<Targets extends NextStepTargets> = NextStepHandoff<Targets> & {\n nextAction: AgentPaymentNextAction\n safeToContinue: boolean\n reason: string\n}\n\n/** The wire shape: `AgentNextStep` (its `next_tool` family) — never a null `next_tool`. */\nexport type NextStep = AgentNextStep\n\n/**\n * Per-`next_action` default tool (decision 9): the tool a site names unless it\n * has a reason to override. Only actions with ONE sensible target are listed;\n * `retry_original_x402_request` is absent because its only live emitter names\n * no tool on purpose (the agent's own HTTP retry); `sign_and_submit_payment`\n * is absent because the signer tool\n * depends on the settlement scheme (`haven_sign` for erc7710 delegations,\n * `haven_sign_x402` for the EIP-3009 bridge) and a wrong default there would be\n * worse than none.\n */\nexport const DEFAULT_NEXT_TOOL_BY_ACTION = {\n check_status_later: 'haven_get_payment_status',\n sweep_stranded_funds: 'haven_sweep_delegate',\n // `retry_original_x402_request` is NOT here: its only live emitter\n // (state-direct-recovery.ts, erc7710) names no tool on purpose — the retry\n // is the agent's own HTTP call — so a default would contradict the site.\n} as const satisfies Partial<Record<AgentPaymentNextAction, string>>\n\nexport function defaultNextToolFor(action: AgentPaymentNextAction): string | undefined {\n return (DEFAULT_NEXT_TOOL_BY_ACTION as Partial<Record<AgentPaymentNextAction, string>>)[action]\n}\n\n/**\n * Builds a `nextStep` function bound to a target map. The returned function\n * renders the wire fields from the bare name + role, and re-validates the\n * arguments at runtime: on a mismatch it FAILS SAFE — omits the tool and says\n * why in `next_tool_omitted_reason` — rather than throwing out of a handler\n * that has already moved money. The compile-time twin makes that branch\n * unreachable from typed sites; it exists for callers that bypass the types.\n */\nexport function createNextStepBuilder<Targets extends NextStepTargets>(targets: Targets) {\n return function nextStep(input: NextStepInput<Targets>): NextStep {\n // The generic mapped union does not narrow inside this body; the\n // structural view below is what the union guarantees at every call site.\n const i = input as unknown as {\n nextTool: string | null\n nextArguments?: unknown\n nextToolOmittedReason?: string\n }\n const base = {\n next_action: input.nextAction,\n safe_to_continue: input.safeToContinue,\n reason: input.reason,\n }\n if (i.nextTool === null) {\n return { ...base, next_tool_omitted_reason: i.nextToolOmittedReason ?? 'no next tool' }\n }\n const target = targets[i.nextTool]\n if (!target) {\n return { ...base, next_tool_omitted_reason: `${i.nextTool} is not a registered next-step target` }\n }\n const problem = target.validate(i.nextArguments)\n if (problem) {\n return { ...base, next_tool_omitted_reason: `next_arguments do not parse under ${i.nextTool}: ${problem}` }\n }\n return {\n ...base,\n next_tool: renderNextTool(target.role, i.nextTool),\n next_tool_server: NEXT_TOOL_SERVER_NAMES[target.role],\n next_tool_name: i.nextTool,\n next_tool_server_role: target.role,\n next_arguments: i.nextArguments as Record<string, unknown>,\n }\n }\n}\n","/**\n * The Node.js floor Haven's published packages support (#1161).\n *\n * ## Why this lives in the SDK\n *\n * Three packages need to enforce the same floor — `connect` (at setup),\n * `signer` and `mcp` (at startup) — and `@haven_ai/sdk` is the only dependency\n * all three already share. A copy per package is how the floor drifted in the\n * first place: `engines` said `>=24` everywhere while connect's runtime manifest\n * enforced `20.0.0`, so a connect run on Node v23 passed the guard, installed\n * the signer, and signed a real payment. Two numbers for one fact is one number\n * too many.\n *\n * Each consumer still owns its own refusal — the error type, the exit code, the\n * wording of \"what to do next\" — because a library must never terminate its\n * host process. This module only answers *is this version supported* and *what\n * should we tell the user*.\n *\n * ## Why a floor is enforced at all\n *\n * `engines` is advisory: npm emits `EBADENGINE` and installs anyway unless the\n * user happens to have `engine-strict` set. For a normal library that is a\n * reasonable default. For the **signer** it is not — it holds the delegate key\n * and produces every payment signature, so a subtle runtime incompatibility\n * shows up as a wrong or missing signature on a money path. \"It seemed to work\"\n * is precisely the evidence that cannot be relied on there.\n */\n\n/**\n * The minimum supported Node.js version, as `major.minor.patch`.\n *\n * MUST equal the `engines.node` floor declared by every published Haven\n * package. A guard test in each package asserts exactly that against its own\n * `package.json`, so the two cannot drift again silently.\n */\nexport const HAVEN_MINIMUM_NODE_VERSION = '22.0.0'\n\n/** Parse `v22.1.0` / `22.1` / `22` into a comparable triple. */\nfunction parseNodeVersion(value: string): [number, number, number] {\n const match = value.trim().match(/^v?(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?/)\n if (!match) return [0, 0, 0]\n return [Number(match[1] ?? 0), Number(match[2] ?? 0), Number(match[3] ?? 0)]\n}\n\n/**\n * Compare two Node versions. Negative when `left` is older.\n *\n * An unparseable version parses to `0.0.0` and therefore compares as older than\n * any real floor — fail-closed. A version string Haven cannot read is not\n * evidence of a supported runtime, and treating it as one would reopen exactly\n * the hole this module closes.\n */\nexport function compareNodeVersions(left: string, right: string): number {\n const leftParts = parseNodeVersion(left)\n const rightParts = parseNodeVersion(right)\n for (let i = 0; i < 3; i += 1) {\n if (leftParts[i] !== rightParts[i]) return leftParts[i] > rightParts[i] ? 1 : -1\n }\n return 0\n}\n\nexport function isSupportedNodeVersion(\n nodeVersion: string = process.versions.node,\n minimumNodeVersion: string = HAVEN_MINIMUM_NODE_VERSION,\n): boolean {\n return compareNodeVersions(nodeVersion, minimumNodeVersion) >= 0\n}\n\nexport interface UnsupportedNodeVersionMessageOptions {\n /**\n * What is being refused, in the user's terms — \"Haven setup\", \"The Haven\n * signer\". Leads the message so the reader knows what just stopped.\n */\n subject: string\n nodeVersion?: string\n minimumNodeVersion?: string\n /** Appended verbatim as the closing line. Used for the re-run instruction. */\n retryHint?: string\n}\n\n/**\n * The refusal text.\n *\n * Names the detected version, the required version, and **how to fix it** — the\n * previous message stopped after the two version numbers, which tells a user\n * they are stuck without telling them how to get unstuck. The version-manager\n * lines are the fix for nearly everyone; the closing caveat is there because the\n * runtime that *spawns* the signer is frequently not the shell that was\n * upgraded, and a desktop app can keep launching the old Node long after\n * `node -v` in a terminal says otherwise.\n */\nexport function unsupportedNodeVersionMessage(\n options: UnsupportedNodeVersionMessageOptions,\n): string {\n const nodeVersion = options.nodeVersion ?? process.versions.node\n const minimum = options.minimumNodeVersion ?? HAVEN_MINIMUM_NODE_VERSION\n const lines = [\n `${options.subject} requires Node.js >=${minimum}, but this is Node.js ${nodeVersion}.`,\n '',\n 'Upgrade Node, then try again:',\n ` nvm install ${major(minimum)} && nvm use ${major(minimum)} (nvm)`,\n ` fnm install ${major(minimum)} && fnm use ${major(minimum)} (fnm)`,\n ` volta install node@${major(minimum)} (volta)`,\n ` or download Node ${major(minimum)} from https://nodejs.org`,\n '',\n 'If you use a version manager, check that the agent runtime launching Haven picks ' +\n 'up the same version — upgrading your shell does not always change what a desktop ' +\n 'app spawns.',\n ]\n if (options.retryHint) lines.push('', options.retryHint)\n return lines.join('\\n')\n}\n\nfunction major(version: string): string {\n return String(parseNodeVersion(version)[0])\n}\n","/**\n * Task budgets (#3329): independent verification of a task child delegation\n * and its close UserOp, mirroring `settlement-child.ts` / `direct-payment-\n * guard.ts` for a DIFFERENT typed-data class.\n *\n * A task budget's child is a SELF-delegation: the agent's own delegate\n * account grants itself a narrower, time-boxed slice of its budget\n * delegation (`delegate === delegator === the agent's own account`), chained\n * under the budget via `authority`. That is what separates it from an x402\n * settlement child, whose `delegate` is a facilitator/ANY_BENEFICIARY — never\n * the agent's own account. `isSettlementChildTypedData` (`settlement-\n * child.ts`) was narrowed to return `false` for a self-delegated payload so\n * the two classes cannot be confused by either verifier; this file is the\n * task-child counterpart, verified against a different expectation\n * (`GET /task-budgets/:id/sign-context`, never a merchant's 402).\n *\n * Two shapes, two functions:\n * - `assertOwnTaskChild` verifies the `Delegation` typed data signed to OPEN\n * a task budget.\n * - `assertOwnTaskBudgetCloseUserOp` verifies the `PackedUserOperation`\n * typed data signed to CLOSE one early (an on-chain\n * `disableDelegation(child)` call from the agent's own account) — an\n * authority-REDUCING action only, never a grant.\n *\n * `hashDelegation` below reproduces `@metamask/smart-accounts-kit/utils`'s\n * struct hash (via `@metamask/delegation-core`) byte-for-byte, WITHOUT taking\n * the kit as a runtime dependency (this package installs on users' machines —\n * same reasoning `delegate-account.ts` and `settlement-child.ts` give for\n * their own vendored constants). `DELEGATION_TYPEHASH` / `CAVEAT_TYPEHASH`\n * are pinned literals, cross-checked against the kit's own `hashDelegation`\n * by a test vector in `task-budget-guards.test.ts` (which imports the kit\n * ONLY in that test file).\n */\nimport { decodeFunctionData, encodeAbiParameters, encodeFunctionData, keccak256, type Address, type Hex } from 'viem'\nimport { HavenTypedDataRefusedError, DIRECT_PAYMENT_CHAIN_IDS, EXECUTE_ABI } from './direct-payment-guard.js'\nimport { DELEGATION_MANAGER, ROOT_AUTHORITY, CAVEAT_ENFORCERS } from './settlement-child.js'\nimport { DELEGATION_TUPLE_COMPONENTS } from './redemption-guard.js'\nimport { deriveDelegateAccountAddress } from './delegate-account.js'\n\n/** The backend's own ceiling (`MAX_TASK_BUDGET_TTL_SECONDS`), enforced again here. */\nexport const MAX_TASK_BUDGET_TTL_SECONDS = 86_400\n\nexport interface TaskChildTypedData {\n domain: { name?: string; version?: string; chainId?: number | string; verifyingContract?: string }\n types: Record<string, unknown>\n primaryType: string\n message: Record<string, unknown>\n}\n\ninterface Caveat {\n enforcer: string\n terms: string\n}\n\n/**\n * The pinned `types` shape for a task-budget child's `Delegation` EIP-712\n * payload — identical to `@metamask/smart-accounts-kit/utils`'s\n * `SIGNABLE_DELEGATION_TYPED_DATA` (cross-checked by the `hashDelegation`\n * pin test). Checked verbatim (order and all) in `assertOwnTaskChild` so a\n * caveat cannot be reinterpreted through a renamed/reordered field, and so a\n * domain carrying an unrelated `primaryType: 'Delegation'` struct (same\n * name, different shape) is refused rather than partially trusted.\n */\nconst EXPECTED_DELEGATION_TYPES = {\n Caveat: [\n { name: 'enforcer', type: 'address' },\n { name: 'terms', type: 'bytes' },\n ],\n Delegation: [\n { name: 'delegate', type: 'address' },\n { name: 'delegator', type: 'address' },\n { name: 'authority', type: 'bytes32' },\n { name: 'caveats', type: 'Caveat[]' },\n { name: 'salt', type: 'uint256' },\n ],\n} as const\n\n/** `DelegationManager`'s EIP-712 domain `name`/`version` — pinned alongside `verifyingContract`. */\nconst DELEGATION_DOMAIN_NAME = 'DelegationManager'\nconst DELEGATION_DOMAIN_VERSION = '1'\n\nfunction same(a: string | undefined, b: string | undefined): boolean {\n return !!a && !!b && a.toLowerCase() === b.toLowerCase()\n}\n\nfunction hex(value: string): string {\n return value.startsWith('0x') ? value.slice(2).toLowerCase() : value.toLowerCase()\n}\n\nfunction slice(terms: string, start: number, end?: number): string {\n const body = hex(terms)\n return end === undefined ? body.slice(start * 2) : body.slice(start * 2, end * 2)\n}\n\nfunction findCaveat(caveats: Caveat[], enforcer: string): Caveat | undefined {\n return caveats.find((c) => same(c.enforcer, enforcer))\n}\n\n/**\n * True when this typed data is a task-budget child: a `Delegation` whose\n * `delegate` equals its own `delegator` (self-delegation). This is the ONLY\n * shape distinguishing it from an x402 settlement child (whose `delegate` is\n * a facilitator or `ANY_BENEFICIARY`) — `isSettlementChildTypedData` is\n * narrowed to return `false` for this same shape so the two verifiers never\n * overlap.\n */\nexport function isTaskChildTypedData(value: unknown): value is TaskChildTypedData {\n const td = value as TaskChildTypedData | undefined\n if (\n !td ||\n td.primaryType !== 'Delegation' ||\n typeof td.domain?.verifyingContract !== 'string' ||\n !Array.isArray((td.message as { caveats?: unknown })?.caveats)\n ) {\n return false\n }\n const delegate = td.message?.delegate\n const delegator = td.message?.delegator\n return typeof delegate === 'string' && typeof delegator === 'string' && same(delegate, delegator)\n}\n\nexport interface TaskChildExpectation {\n chainId: number\n tokenAddress: string\n maxAmountAtomic: string\n recipientAddress: string | null\n /** unix seconds — the `TimestampEnforcer`'s `beforeThreshold`. */\n expiresAt: number\n parentDelegationHash: string\n}\n\nfunction refuseTaskChild(what: string, detail: string): never {\n throw new HavenTypedDataRefusedError(\n `Refusing to sign the task-budget child: ${what}. ${detail} ` +\n 'This signature opens a self-delegated slice of the agent budget, so it is verified ' +\n 'locally against the expectation Haven declared, rather than trusted.',\n )\n}\n\n/**\n * Verify a task-budget child delegation is EXACTLY what\n * `GET /task-budgets/:id/sign-context` (purpose `open`) declared, AND that\n * both `delegate` and `delegator` are this signer's OWN account. Throws\n * `HavenTypedDataRefusedError` (never returns) on any disagreement.\n */\nexport function assertOwnTaskChild(\n typedData: unknown,\n expected: TaskChildExpectation,\n delegateAddress: string,\n now: number = Date.now(),\n): void {\n const td = typedData as TaskChildTypedData\n if (td?.primaryType !== 'Delegation') {\n refuseTaskChild('it is not a Delegation payload', `primaryType was '${String(td?.primaryType)}'.`)\n }\n if (!same(td.domain?.verifyingContract, DELEGATION_MANAGER)) {\n refuseTaskChild(\n 'the EIP-712 domain names an unknown DelegationManager',\n `Expected ${DELEGATION_MANAGER}, got ${td.domain?.verifyingContract}.`,\n )\n }\n if (td.domain?.name !== DELEGATION_DOMAIN_NAME || td.domain?.version !== DELEGATION_DOMAIN_VERSION) {\n refuseTaskChild(\n 'the EIP-712 domain name/version does not match the pinned DelegationManager domain',\n `Expected name '${DELEGATION_DOMAIN_NAME}' version '${DELEGATION_DOMAIN_VERSION}'; got name ` +\n `'${String(td.domain?.name)}' version '${String(td.domain?.version)}'.`,\n )\n }\n if (\n JSON.stringify(td.types?.Caveat) !== JSON.stringify(EXPECTED_DELEGATION_TYPES.Caveat) ||\n JSON.stringify(td.types?.Delegation) !== JSON.stringify(EXPECTED_DELEGATION_TYPES.Delegation)\n ) {\n refuseTaskChild(\n 'its EIP-712 type definitions do not match the pinned Delegation/Caveat shape',\n 'A renamed, reordered, or additional field on Delegation or Caveat could change what the ' +\n 'caveats below mean without changing this check\\'s field-by-field comparisons.',\n )\n }\n const domainChain = Number(td.domain?.chainId)\n if (!Number.isFinite(domainChain) || !DIRECT_PAYMENT_CHAIN_IDS.has(domainChain)) {\n refuseTaskChild(\n 'it is scoped to a chain the delegation rail has no pinned contracts for',\n `Chains with pinned contracts: ${[...DIRECT_PAYMENT_CHAIN_IDS].join(', ')}; the child says ${String(td.domain?.chainId)}.`,\n )\n }\n if (domainChain !== expected.chainId) {\n refuseTaskChild(\n 'it is scoped to the wrong chain',\n `Expected chain ${expected.chainId}; the child says ${td.domain?.chainId}.`,\n )\n }\n\n const ownAccount = deriveDelegateAccountAddress(delegateAddress as Address)\n const delegator = td.message?.delegator\n if (typeof delegator !== 'string' || !same(delegator, ownAccount)) {\n refuseTaskChild(\n \"it is not delegated by this agent's own account\",\n `Expected delegator ${ownAccount}; the child names ${String(delegator)}.`,\n )\n }\n const delegate = td.message?.delegate\n if (typeof delegate !== 'string' || !same(delegate, ownAccount)) {\n refuseTaskChild(\n \"it is not self-delegated to this agent's own account\",\n `Expected delegate ${ownAccount}; the child names ${String(delegate)}.`,\n )\n }\n\n const authority = td.message?.authority\n if (typeof authority !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(authority)) {\n refuseTaskChild('its authority is not a 32-byte delegation hash', `Got ${String(authority)}.`)\n }\n if (authority.toLowerCase() === ROOT_AUTHORITY) {\n refuseTaskChild(\n 'it is a ROOT delegation, not a re-delegation of the agent budget',\n 'A task budget always chains under the agent budget delegation.',\n )\n }\n if (!same(authority, expected.parentDelegationHash)) {\n refuseTaskChild(\n 'it chains under a different parent delegation',\n `Expected authority ${expected.parentDelegationHash}; the child says ${authority}.`,\n )\n }\n\n const caveats = (td.message?.caveats as Caveat[] | undefined) ?? []\n\n const transfer = findCaveat(caveats, CAVEAT_ENFORCERS.erc20TransferAmount)\n if (!transfer) {\n refuseTaskChild(\n 'it has no ERC-20 transfer-amount caveat',\n 'Without it the child is not bounded to an amount.',\n )\n }\n const token = `0x${slice(transfer.terms, 0, 20)}`\n if (!same(token, expected.tokenAddress)) {\n refuseTaskChild('it spends a different token', `Expected ${expected.tokenAddress}, child pins ${token}.`)\n }\n const amount = BigInt(`0x${slice(transfer.terms, 20, 52)}`)\n if (amount !== BigInt(expected.maxAmountAtomic)) {\n refuseTaskChild(\n 'the amount does not match',\n `Expected ${expected.maxAmountAtomic}; the child allows ${amount.toString()}.`,\n )\n }\n\n const timestamp = findCaveat(caveats, CAVEAT_ENFORCERS.timestamp)\n if (!timestamp) {\n refuseTaskChild('it never expires', 'A task-budget child without a timestamp caveat is open-ended.')\n }\n const beforeThreshold = Number(BigInt(`0x${slice(timestamp.terms, 16, 32)}`))\n const nowSec = Math.floor(now / 1000)\n if (beforeThreshold <= nowSec) {\n refuseTaskChild('it has already expired', `Expiry ${beforeThreshold} is not in the future.`)\n }\n if (beforeThreshold > nowSec + MAX_TASK_BUDGET_TTL_SECONDS) {\n refuseTaskChild(\n 'its window is longer than a task budget may live',\n `Expiry is ${beforeThreshold - nowSec}s out; the ceiling is ${MAX_TASK_BUDGET_TTL_SECONDS}s.`,\n )\n }\n if (beforeThreshold !== expected.expiresAt) {\n refuseTaskChild(\n 'its expiry does not match what Haven declared',\n `Expected ${expected.expiresAt}; the child says ${beforeThreshold}.`,\n )\n }\n\n const calldata = findCaveat(caveats, CAVEAT_ENFORCERS.allowedCalldata)\n if (expected.recipientAddress) {\n if (!calldata) {\n refuseTaskChild(\n 'it has no recipient pin',\n 'The task budget was opened with a pinned recipient, so the child must carry one.',\n )\n }\n const startIndex = BigInt(`0x${slice(calldata.terms, 0, 32)}`)\n if (startIndex !== 4n) {\n refuseTaskChild(\n 'the recipient pin points at the wrong calldata offset',\n `Expected offset 4, got ${startIndex.toString()}.`,\n )\n }\n const paddedRecipient = slice(calldata.terms, 32, 64)\n if (paddedRecipient.slice(0, 24) !== '0'.repeat(24)) {\n refuseTaskChild('the pinned recipient is not a plain address', 'Its 32-byte word is not a padded address.')\n }\n const recipient = `0x${paddedRecipient.slice(24)}`\n if (!same(recipient, expected.recipientAddress)) {\n refuseTaskChild(\n 'it pins a different recipient than Haven declared',\n `Expected ${expected.recipientAddress}; the child pins ${recipient}.`,\n )\n }\n } else if (calldata) {\n refuseTaskChild(\n 'it pins a recipient the task budget was not opened with',\n 'This task budget is open (no recipient pin); the child must not add one.',\n )\n }\n}\n\n// ── Close UserOp verification ──────────────────────────────────────────────\n\n/** `DelegationManager.disableDelegation((address,address,bytes32,(address,bytes,bytes)[],uint256,bytes))`. */\nconst DISABLE_DELEGATION_ABI = [\n {\n type: 'function',\n name: 'disableDelegation',\n inputs: [{ name: 'delegation', type: 'tuple', components: DELEGATION_TUPLE_COMPONENTS }],\n outputs: [],\n stateMutability: 'nonpayable',\n },\n] as const\n\nexport interface TaskBudgetCloseExpectation {\n /** The child delegation's own struct hash (`agent_task_budgets.delegation_hash`). */\n delegationHash: string\n}\n\n/**\n * Verify a task-budget close UserOp is EXACTLY an on-chain\n * `disableDelegation(child)` call from the agent's own delegate account —\n * authority-REDUCING only, never a grant. Throws `HavenTypedDataRefusedError`\n * (never returns) on any disagreement.\n */\nexport function assertOwnTaskBudgetCloseUserOp(\n typedData: Record<string, unknown>,\n expected: TaskBudgetCloseExpectation,\n delegateAddress: string,\n): void {\n const domain = (typedData.domain ?? {}) as Record<string, unknown>\n const message = (typedData.message ?? {}) as Record<string, unknown>\n\n if (typeof domain.chainId !== 'number' && typeof domain.chainId !== 'bigint') {\n throw new HavenTypedDataRefusedError(\n `This close UserOperation's domain.chainId is ${typeof domain.chainId} (${String(domain.chainId)}), ` +\n 'not a number — refusing rather than risk signing a different EIP-712 domain than this check evaluated.',\n )\n }\n const chainId = Number(domain.chainId)\n if (!DIRECT_PAYMENT_CHAIN_IDS.has(chainId)) {\n throw new HavenTypedDataRefusedError(\n 'This signer only signs a task-budget close on chains the delegation rail has pinned ' +\n `contracts for (${[...DIRECT_PAYMENT_CHAIN_IDS].join(', ')}); this typed data names chain ` +\n `${String(domain.chainId)}. Refusing.`,\n )\n }\n\n const ownAccount = deriveDelegateAccountAddress(delegateAddress as Address)\n const sender = typeof message.sender === 'string' ? message.sender : ''\n if (sender.toLowerCase() !== ownAccount.toLowerCase()) {\n throw new HavenTypedDataRefusedError(\n `This close UserOperation's account (${sender || 'unknown'}) is not this signer's own delegate ` +\n `account (${ownAccount}). Sign only your own agent's Haven-prepared payloads.`,\n )\n }\n\n const callData = message.callData as Hex\n let decoded: { target: Hex; value: bigint; callData: Hex }\n try {\n const { args } = decodeFunctionData({ abi: EXECUTE_ABI, data: callData })\n decoded = args[0] as unknown as typeof decoded\n } catch {\n throw new HavenTypedDataRefusedError(\n \"This close UserOperation's callData is not a single execute((address,uint256,bytes)) call. \" +\n 'This signer only signs a task-budget close of that exact shape.',\n )\n }\n const reEncodedExecute = encodeFunctionData({ abi: EXECUTE_ABI, functionName: 'execute', args: [decoded] })\n if (reEncodedExecute.toLowerCase() !== callData.toLowerCase()) {\n throw new HavenTypedDataRefusedError(\n \"This close UserOperation's execute() call does not re-encode to the exact callData bytes \" +\n '(trailing or non-canonical bytes). Refusing.',\n )\n }\n if (decoded.target.toLowerCase() !== DELEGATION_MANAGER.toLowerCase()) {\n throw new HavenTypedDataRefusedError(\n `This close UserOperation's execute() calls ${decoded.target}, not the DelegationManager ` +\n `(${DELEGATION_MANAGER}). Refusing what looks like a self-call or a call to an unrelated contract.`,\n )\n }\n if (decoded.value !== 0n) {\n throw new HavenTypedDataRefusedError(\n `This close UserOperation's execute() sends ${decoded.value} wei of native value alongside the ` +\n 'DelegationManager call — a task-budget close never does. Refusing.',\n )\n }\n\n let delegation: {\n delegate: Address\n delegator: Address\n authority: Hex\n caveats: readonly { enforcer: Address; terms: Hex; args: Hex }[]\n salt: bigint\n signature: Hex\n }\n try {\n const { args } = decodeFunctionData({ abi: DISABLE_DELEGATION_ABI, data: decoded.callData })\n delegation = args[0] as unknown as typeof delegation\n } catch {\n throw new HavenTypedDataRefusedError(\n \"This close UserOperation's execute() does not call disableDelegation(Delegation) — this \" +\n 'signer only signs a task-budget close of that exact shape.',\n )\n }\n const reEncodedDisable = encodeFunctionData({\n abi: DISABLE_DELEGATION_ABI,\n functionName: 'disableDelegation',\n args: [delegation],\n })\n if (reEncodedDisable.toLowerCase() !== decoded.callData.toLowerCase()) {\n throw new HavenTypedDataRefusedError(\n 'This close UserOperation\\'s disableDelegation call does not re-encode to the exact bytes ' +\n 'signed (trailing or non-canonical bytes). Refusing.',\n )\n }\n if (delegation.delegator.toLowerCase() !== ownAccount.toLowerCase()) {\n throw new HavenTypedDataRefusedError(\n `This close UserOperation disables a delegation granted by ${delegation.delegator}, not this ` +\n `signer's own account (${ownAccount}). Refusing.`,\n )\n }\n if (delegation.delegate.toLowerCase() !== ownAccount.toLowerCase()) {\n throw new HavenTypedDataRefusedError(\n `This close UserOperation disables a delegation granted to ${delegation.delegate}, not this ` +\n `signer's own account (${ownAccount}) — a task-budget child is always self-delegated. Refusing.`,\n )\n }\n if (delegation.authority.toLowerCase() === ROOT_AUTHORITY) {\n throw new HavenTypedDataRefusedError(\n 'This close UserOperation disables a ROOT delegation, not a re-delegation of the agent budget. ' +\n 'A task-budget child always chains under the agent budget delegation. Refusing.',\n )\n }\n const actualHash = hashDelegation(delegation)\n if (actualHash.toLowerCase() !== expected.delegationHash.toLowerCase()) {\n throw new HavenTypedDataRefusedError(\n `This close UserOperation disables delegation ${actualHash}, not the task budget's own child ` +\n `(${expected.delegationHash}). Refusing.`,\n )\n }\n}\n\n// ── Delegation struct hashing, vendored (no kit at runtime) ────────────────\n\n/**\n * `@metamask/delegation-core`'s `DELEGATION_TYPEHASH` — pinned, cross-checked\n * against the kit by a test vector in `task-budget-guards.test.ts`.\n */\nexport const DELEGATION_TYPEHASH: Hex = '0x88c1d2ecf185adf710588203a5f263f0ff61be0d33da39792cde19ba9aa4331e'\n\n/** `@metamask/delegation-core`'s `CAVEAT_TYPEHASH` — pinned, same cross-check. */\nexport const CAVEAT_TYPEHASH: Hex = '0x80ad7e1b04ee6d994a125f4714ca0720908bd80ed16063ec8aee4b88e9253e2d'\n\nexport interface DelegationForHashing {\n delegate: Address\n delegator: Address\n authority: Hex\n caveats: readonly { enforcer: Address; terms: Hex }[]\n salt: bigint\n}\n\nfunction hashCaveat(caveat: { enforcer: Address; terms: Hex }): Hex {\n const termsHash = keccak256(caveat.terms)\n const encoded = encodeAbiParameters(\n [{ type: 'bytes32' }, { type: 'address' }, { type: 'bytes32' }],\n [CAVEAT_TYPEHASH, caveat.enforcer, termsHash],\n )\n return keccak256(encoded)\n}\n\nfunction hashCaveatsArray(caveats: readonly { enforcer: Address; terms: Hex }[]): Hex {\n const concatenated = `0x${caveats.map((c) => hashCaveat(c).slice(2)).join('')}` as Hex\n return keccak256(concatenated)\n}\n\n/**\n * Reproduces `@metamask/smart-accounts-kit/utils`'s `hashDelegation`\n * byte-for-byte, WITHOUT the kit at runtime (see the file header). Ignores\n * `signature` — the kit's own `hashDelegation` does the same (it hashes with\n * `signature: '0x'` regardless of what the caller passes).\n */\nexport function hashDelegation(delegation: DelegationForHashing): Hex {\n const caveatsHash = hashCaveatsArray(delegation.caveats)\n const encoded = encodeAbiParameters(\n [\n { type: 'bytes32' },\n { type: 'address' },\n { type: 'address' },\n { type: 'bytes32' },\n { type: 'bytes32' },\n { type: 'uint256' },\n ],\n [DELEGATION_TYPEHASH, delegation.delegate, delegation.delegator, delegation.authority, caveatsHash, delegation.salt],\n )\n return keccak256(encoded)\n}\n"]}
@@ -1081,5 +1081,5 @@ exports.packedUserOperationHash = packedUserOperationHash;
1081
1081
  exports.resolveConnectorChannel = resolveConnectorChannel;
1082
1082
  exports.signerUpdateFallback = signerUpdateFallback;
1083
1083
  exports.verifySettlementChild = verifySettlementChild;
1084
- //# sourceMappingURL=chunk-HX34HOW4.cjs.map
1085
- //# sourceMappingURL=chunk-HX34HOW4.cjs.map
1084
+ //# sourceMappingURL=chunk-4Z6ATE44.cjs.map
1085
+ //# sourceMappingURL=chunk-4Z6ATE44.cjs.map