@haven_ai/sdk 0.1.2 → 0.1.4
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.
- package/README.md +154 -13
- package/dist/index.cjs +1111 -92
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +405 -8
- package/dist/index.d.ts +405 -8
- package/dist/index.js +1100 -93
- package/dist/index.js.map +1 -1
- package/examples/mcp-x402-sse.ts +149 -0
- package/examples/x402_openapi_python.py +114 -0
- package/package.json +4 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts","../src/signer.ts","../src/x402.ts","../src/mpp.ts","../src/client.ts","../src/tools.ts"],"names":["decodeBase64Json","createHash","receipt"],"mappings":";;;;;;;;AAkbO,IAAM,UAAA,GAAN,cAAyB,KAAA,CAAM;AAAA,EACpC,WAAA,CACE,OAAA,EACgB,IAAA,EACA,UAAA,EACA,SAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAJG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AACA,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,YAAA;AAAA,EACd;AAAA,EANkB,IAAA;AAAA,EACA,UAAA;AAAA,EACA,SAAA;AAKpB;AAEO,IAAM,aAAA,GAAN,cAA4B,UAAA,CAAW;AAAA,EAC5C,WAAA,CACE,OAAA,EACA,UAAA,EACgB,IAAA,EAChB,SAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,WAAA,EAAa,UAAA,EAAY,SAAS,CAAA;AAHjC,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAIhB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AAAA,EALkB,IAAA;AAMpB;AAEO,IAAM,sBAAA,GAAN,cAAqC,aAAA,CAAc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EAAc;AAAA,KAChB;AAAA,IACA;AAAA,MACE,IAAA,EAAM,2BAAA;AAAA,MACN,WAAA,EAAa,qCAAA;AAAA,MACb,YAAA,EAAc;AAAA;AAChB,GACF;AACF;AAiBA,SAAS,WAAA,GAA4B;AACnC,EAAA,OAAO;AAAA,IACL;AAAA,MACE,IAAA,EAAM,UAAA;AAAA,MACN,QAAA,EAAU;AAAA,QACR,IAAA,EAAM,cAAA;AAAA,QACN,WAAA,EAAa,wBAAA;AAAA,QACb,UAAA,EAAY;AAAA;AACd,KACF;AAAA,IACA;AAAA,MACE,IAAA,EAAM,UAAA;AAAA,MACN,QAAA,EAAU;AAAA,QACR,IAAA,EAAM,oBAAA;AAAA,QACN,WAAA,EAAa,sBAAA;AAAA,QACb,UAAA,EAAY;AAAA;AACd,KACF;AAAA,IACA;AAAA,MACE,IAAA,EAAM,UAAA;AAAA,MACN,QAAA,EAAU;AAAA,QACR,IAAA,EAAM,wBAAA;AAAA,QACN,WAAA,EAAa,0BAAA;AAAA,QACb,UAAA,EAAY;AAAA;AACd,KACF;AAAA,IACA;AAAA,MACE,IAAA,EAAM,UAAA;AAAA,MACN,QAAA,EAAU;AAAA,QACR,IAAA,EAAM,2BAAA;AAAA,QACN,WAAA,EAAa,qCAAA;AAAA,QACb,UAAA,EAAY;AAAA;AACd;AACF,GACF;AACF;AAIO,IAAM,UAAA,GAAa;AAAA;AAAA,EAExB,MAAA,EAAQ,WAAA;AAAA;AAAA,EAGR,MAAA,EAAQ;AACV","file":"index.js","sourcesContent":["// ── Client Configuration ─────────────────────────────────────────\n\nexport interface HavenClientConfig {\n /** Haven API key (sk_agent_xxx) */\n apiKey: string\n\n /** Agent's delegate EOA private key. If provided, the SDK handles signing automatically. */\n delegateKey?: string\n\n /** Haven API base URL (default: http://localhost:3001) */\n baseUrl?: string\n\n /** Optional wallet identity to send as the x402-wallet header. */\n x402Wallet?: string\n\n /** Timeout in ms for individual HTTP requests (default: 30000) */\n requestTimeout?: number\n\n /** Timeout in ms when polling for tx confirmation (default: 90000) */\n confirmationTimeout?: number\n\n /** Polling interval in ms when waiting for confirmation (default: 3000) */\n pollingInterval?: number\n}\n\n// ── Payment Types ────────────────────────────────────────────────\n\nexport interface PaymentRequest {\n /** Token symbol: \"EURe\", \"USDC.e\", or \"xDAI\" */\n token: string\n\n /** Amount as a decimal string, e.g. \"5.00\" */\n amount: string\n\n /** Recipient Ethereum address (0x...) */\n to: string\n}\n\nexport interface SignData {\n /** The hash to sign (keccak256, 0x-prefixed) */\n hash: string\n\n /** Breakdown of values that were hashed — useful for debugging */\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n\n /** Human-readable signing instructions */\n instructions: string\n}\n\nexport interface PaymentIntent {\n /** Unique payment ID */\n paymentId: string\n\n /** Current status */\n status: 'pending_signature'\n\n /** ISO 8601 expiry timestamp */\n expiresAt: string\n\n /** Data needed to sign the payment */\n signData: SignData\n}\n\nexport type PaymentStatus =\n | 'pending_signature'\n | 'submitted'\n | 'confirmed'\n | 'pending_approval'\n | 'approved'\n | 'proposed'\n | 'executed'\n | 'rejected'\n | 'expired'\n | 'failed'\n\nexport interface PaymentResult {\n /** Unique payment ID */\n paymentId: string\n\n /** Final status */\n status: PaymentStatus\n\n /** Token that was sent */\n token: string\n\n /** Amount that was sent (human-readable) */\n amount: string\n\n /** Recipient address */\n to: string\n\n /** On-chain transaction hash (present when confirmed) */\n txHash: string | null\n\n /** Error message (present when failed) */\n errorMessage: string | null\n\n /** Block explorer URL for the transaction (chain-dependent) */\n explorerUrl: string | null\n\n /** ISO 8601 timestamps */\n createdAt: string\n signedAt: string | null\n submittedAt: string | null\n confirmedAt: string | null\n expiresAt: string\n}\n\n// ── x402 Types ──────────────────────────────────────────────────\n\n/** Payment requirements from an HTTP 402 response (x402 protocol). */\nexport interface X402PaymentRequired {\n x402Version: number\n resource: {\n url: string\n description?: string\n mimeType?: string\n }\n accepts: X402PaymentOption[]\n error?: string\n}\n\n/** A single payment option from x402 PaymentRequired. */\nexport interface X402PaymentOption {\n scheme: string // \"exact\"\n network: string // CAIP-2 chain ID or x402 network, e.g. \"eip155:8453\" or \"base\"\n amount: string // Atomic units\n maxAmountRequired?: string // Atomic units (official x402 field)\n resource?: string\n description?: string\n mimeType?: string\n asset: string // Token contract address\n payTo: string // Recipient address\n maxTimeoutSeconds: number\n extra?: Record<string, unknown>\n}\n\n/** Receipt returned after a successful x402 payment. */\nexport interface X402Receipt {\n success: boolean\n paymentId: string\n txHash: string\n token: string\n amount: string\n to: string\n resourceUrl: string\n explorerUrl: string\n accepted?: X402PaymentOption\n paymentHeader?: string\n merchantTo?: string | null\n payer?: string\n chainId?: number\n}\n\n// ── Machine Payment Types ───────────────────────────────────────\n\nexport type MachinePaymentRail =\n | 'x402'\n | 'mpp_demo'\n | 'mpp_crypto'\n | 'stripe_deposit'\n | 'spt'\n\nexport interface MachinePaymentChallenge {\n rail: MachinePaymentRail\n version: string\n challengeId: string\n resource: string\n description: string\n network: {\n chainId: number\n name: 'base'\n }\n asset: {\n symbol: 'USDC'\n address: string\n decimals: 6\n }\n amount: {\n display: string\n atomic: string\n }\n recipient: string\n expiresAt: string\n metadata?: Record<string, unknown>\n}\n\nexport interface MachinePaymentReceipt {\n success: boolean\n rail: MachinePaymentRail\n paymentId: string\n challengeId: string\n txHash: string\n token: string\n amount: string\n to: string\n resourceUrl: string\n explorerUrl: string\n payer?: string\n chainId?: number\n proofHeader: string\n}\n\n// ── Agent Payment State Types ────────────────────────────────────\n\nexport type PaymentStateKind = 'payment_intent' | 'approval_request'\n\nexport type PaymentPhase =\n | 'agent_signature_required'\n | 'payment_submitted'\n | 'payment_confirmed'\n | 'user_approval_required'\n | 'user_execution_required'\n | 'waiting_for_additional_approvals'\n | 'funding_sent'\n | 'rejected'\n | 'expired'\n | 'failed'\n\nexport type PaymentNextAction =\n | 'sign_and_submit_payment'\n | 'check_status_later'\n | 'none'\n | 'wait_for_user_approval'\n | 'wait_for_user_to_complete_payment'\n | 'retry_original_x402_request'\n | 'stop_and_tell_user'\n | 'request_again_if_user_still_wants_it'\n\nexport interface PaymentStatusResult {\n paymentId: string\n kind: PaymentStateKind\n rail: string\n status: PaymentStatus | string\n phase: PaymentPhase\n nextAction: PaymentNextAction\n amount: string\n token: string\n resourceUrl: string | null\n merchantAddress: string | null\n txHash: string | null\n expiresAt: string\n chainId: number\n message: string\n}\n\nexport interface PendingApproval extends PaymentStatusResult {\n kind: 'approval_request'\n status: 'pending_approval' | 'pending' | string\n phase: 'user_approval_required'\n nextAction: 'wait_for_user_approval'\n requested?: string\n remaining?: string | null\n}\n\n/** @internal */\nexport interface RawMachinePaymentAuthorizeResponse {\n success?: boolean\n payment_id: string\n kind?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n tx_hash?: string\n chain_id?: number\n safe_address?: string\n payer?: string\n token?: string\n amount?: string\n to?: string\n merchant_to?: string | null\n resource_url?: string\n rail?: string\n challenge_id?: string\n explorer_url?: string\n expires_at?: string\n sign_data?: {\n hash: string\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n instructions: string\n }\n error?: string\n}\n\n/** @internal */\nexport interface RawX402AuthorizeResponse {\n success?: boolean\n payment_id: string\n kind?: string\n rail?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n tx_hash?: string\n chain_id?: number\n safe_address?: string\n payer?: string\n token?: string\n amount?: string\n to?: string\n merchant_to?: string | null\n resource_url?: string\n explorer_url?: string\n expires_at?: string\n sign_data?: {\n hash: string\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n instructions: string\n }\n error?: string\n}\n\n// ── API Response Shapes (raw, snake_case from server) ────────────\n\n/** @internal */\nexport interface RawCreateResponse {\n payment_id: string\n kind?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n expires_at: string\n sign_data: {\n hash: string\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n instructions: string\n }\n error?: string\n supported?: string[]\n}\n\n/** @internal */\nexport interface RawSignResponse {\n payment_id: string\n kind?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n tx_hash?: string\n token?: string\n amount?: string\n to?: string\n merchant_to?: string | null\n resource_url?: string\n rail?: string\n explorer_url?: string\n chain_id?: number\n expires_at?: string\n error?: string\n details?: string\n}\n\n/** @internal */\nexport interface RawStatusResponse {\n payment_id: string\n status: string\n token: string\n amount: string\n to: string\n tx_hash: string | null\n explorer_url?: string | null\n chain_id?: number\n error_message: string | null\n created_at: string\n signed_at: string | null\n submitted_at: string | null\n confirmed_at: string | null\n expires_at: string\n}\n\n/** @internal */\nexport interface RawPaymentStatusResult {\n payment_id: string\n kind: PaymentStateKind\n rail: string\n status: string\n phase: PaymentPhase\n next_action: PaymentNextAction\n amount: string\n token: string\n resource_url: string | null\n merchant_address: string | null\n tx_hash: string | null\n expires_at: string\n chain_id: number\n message: string\n}\n\n// ── Error Types ──────────────────────────────────────────────────\n\nexport class HavenError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly statusCode?: number,\n public readonly paymentId?: string,\n ) {\n super(message)\n this.name = 'HavenError'\n }\n}\n\nexport class HavenApiError extends HavenError {\n constructor(\n message: string,\n statusCode: number,\n public readonly body?: unknown,\n paymentId?: string,\n ) {\n super(message, 'API_ERROR', statusCode, paymentId)\n this.name = 'HavenApiError'\n }\n}\n\nexport class HavenPaymentStateError extends HavenApiError {\n constructor(\n message: string,\n statusCode: number,\n public readonly state: PaymentStatusResult,\n body?: unknown,\n ) {\n super(message, statusCode, body, state.paymentId)\n this.name = 'HavenPaymentStateError'\n }\n\n get status(): string {\n return this.state.status\n }\n\n get phase(): PaymentPhase {\n return this.state.phase\n }\n\n get nextAction(): PaymentNextAction {\n return this.state.nextAction\n }\n}\n\nexport class HavenSigningError extends HavenError {\n constructor(message: string) {\n super(message, 'SIGNING_ERROR')\n this.name = 'HavenSigningError'\n }\n}\n\nexport class HavenTimeoutError extends HavenError {\n constructor(paymentId: string) {\n super(\n `Timed out waiting for payment ${paymentId} to confirm`,\n 'TIMEOUT',\n undefined,\n paymentId,\n )\n this.name = 'HavenTimeoutError'\n }\n}\n","import { ethers } from 'ethers'\nimport { HavenSigningError } from './types.js'\n\n/**\n * Sign a hash using raw ECDSA (no Ethereum message prefix).\n *\n * This matches what Safe's AllowanceModule `checkSignature` expects —\n * a direct ecrecover over the hash, NOT the \"\\x19Ethereum Signed Message\" variant.\n *\n * Uses ethers.SigningKey.sign() instead of wallet.signMessage() to avoid the prefix.\n */\nexport function signHash(privateKey: string, hash: string): string {\n try {\n const signingKey = new ethers.SigningKey(privateKey)\n const sig = signingKey.sign(hash)\n return sig.serialized // 0x + r(32) + s(32) + v(1)\n } catch (err) {\n throw new HavenSigningError(\n `Failed to sign hash: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Derive the Ethereum address from a private key.\n */\nexport function addressFromKey(privateKey: string): string {\n try {\n return new ethers.Wallet(privateKey).address\n } catch (err) {\n throw new HavenSigningError(\n `Invalid private key: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Verify that a signature over a hash recovers to the expected address.\n */\nexport function verifySignature(hash: string, signature: string, expectedAddress: string): boolean {\n try {\n const recovered = ethers.recoverAddress(hash, signature)\n return recovered.toLowerCase() === expectedAddress.toLowerCase()\n } catch {\n return false\n }\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 type { X402PaymentRequired, X402PaymentOption } from './types.js'\nimport type { PaymentRequirements } from 'x402/types'\n\nconst BASE_USDC_ADDRESS = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'\nconst X402_IDEMPOTENCY_BUCKET_MS = 300_000\n\nfunction decodeBase64Json<T>(value: string, label: string): T {\n try {\n return JSON.parse(atob(value)) as T\n } catch {\n throw new Error(`Failed to decode ${label}`)\n }\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\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 maxTimeoutSeconds: candidate.maxTimeoutSeconds ?? 30,\n extra: candidate.extra,\n }\n}\n\nfunction 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)\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 const 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 }\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:100': 'Gnosis Chain',\n 'eip155:8453': 'Base',\n 'base': 'Base',\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}\n\n// ── Token address maps ────────────────────────────────────────────\n\n/** Known tokens on Gnosis Chain (chainId 100). */\nconst GNOSIS_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n '0x0000000000000000000000000000000000000000': { symbol: 'xDAI', decimals: 18 },\n '0xcb444e90d8198415266c6a2724b7900fb12fc56e': { symbol: 'EURe', decimals: 18 },\n '0x2a22f9c3b484c3629090feed35f17ff8f88f76f0': { symbol: 'USDC.e', decimals: 6 },\n}\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/** All known tokens across all supported chains (for display / resolution). */\nconst ALL_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n ...GNOSIS_TOKENS,\n ...BASE_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:100': GNOSIS_TOKENS,\n 'eip155:8453': BASE_TOKENS,\n 'base': BASE_TOKENS,\n}\n\n// ── Parser ───────────────────────────────────────────────────────\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 (networkTokens?.[opt.asset.toLowerCase()]) return opt\n }\n }\n\n // Second pass: any supported network\n for (const opt of accepts) {\n if (opt.network in SUPPORTED_X402_NETWORKS) {\n return opt\n }\n }\n\n // No compatible option found\n return null\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 */\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 if (\n opt.scheme === 'exact' &&\n opt.network in STANDARD_X402_NETWORKS &&\n opt.asset.toLowerCase() === BASE_USDC_ADDRESS\n ) {\n return opt\n }\n }\n\n return null\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 return {\n scheme: 'exact',\n network,\n maxAmountRequired: option.maxAmountRequired ?? option.amount,\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 maxTimeoutSeconds: option.maxTimeoutSeconds,\n extra: option.extra,\n }\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 option.amount,\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 btoa(JSON.stringify(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:100\").\n */\nexport function resolveTokenFromAddress(\n address: string,\n network?: string,\n): { symbol: string; decimals: number } | null {\n const lower = address.toLowerCase()\n\n if (network && network in NETWORK_TOKENS) {\n return NETWORK_TOKENS[network][lower] ?? null\n }\n\n return ALL_TOKENS[lower] ?? null\n}\n","import { createHash } from 'node:crypto'\nimport type {\n MachinePaymentChallenge,\n MachinePaymentReceipt,\n} from './types.js'\n\nfunction decodeBase64Json<T>(value: string, label: string): T {\n try {\n return JSON.parse(atob(value)) as T\n } catch {\n throw new Error(`Failed to decode ${label}`)\n }\n}\n\nfunction normalizeChallenge(value: unknown): MachinePaymentChallenge | null {\n const candidate = value as Partial<MachinePaymentChallenge> | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n candidate.rail !== 'mpp_demo' ||\n typeof candidate.version !== 'string' ||\n typeof candidate.challengeId !== 'string' ||\n typeof candidate.resource !== 'string' ||\n typeof candidate.description !== 'string' ||\n // TODO: relax these checks when non-demo machine payment rails are added.\n candidate.network?.chainId !== 8453 ||\n candidate.network?.name !== 'base' ||\n candidate.asset?.symbol !== 'USDC' ||\n typeof candidate.asset?.address !== 'string' ||\n candidate.asset.decimals !== 6 ||\n typeof candidate.amount?.display !== 'string' ||\n typeof candidate.amount?.atomic !== 'string' ||\n typeof candidate.recipient !== 'string' ||\n typeof candidate.expiresAt !== 'string'\n ) {\n return null\n }\n\n return {\n rail: candidate.rail,\n version: candidate.version,\n challengeId: candidate.challengeId,\n resource: candidate.resource,\n description: candidate.description,\n network: candidate.network,\n asset: candidate.asset,\n amount: candidate.amount,\n recipient: candidate.recipient,\n expiresAt: candidate.expiresAt,\n metadata: candidate.metadata,\n }\n}\n\nexport function parseMachinePaymentChallenge(response: Response): MachinePaymentChallenge {\n const header = response.headers.get('MACHINE-PAYMENT-CHALLENGE')\n if (!header) {\n throw new Error('No MACHINE-PAYMENT-CHALLENGE header found in 402 response.')\n }\n\n const parsed = normalizeChallenge(\n decodeBase64Json<unknown>(header, 'MACHINE-PAYMENT-CHALLENGE header'),\n )\n if (!parsed) throw new Error('Invalid machine payment challenge')\n return parsed\n}\n\nexport async function parseMachinePaymentChallengeResponse(\n response: Response,\n): Promise<MachinePaymentChallenge> {\n try {\n return parseMachinePaymentChallenge(response)\n } catch (headerErr) {\n try {\n const body = await response.clone().json() as { challenge?: unknown }\n const parsed = normalizeChallenge(body.challenge)\n if (parsed) return parsed\n } catch {\n // Fall through to the original, more specific header error.\n }\n\n throw headerErr\n }\n}\n\nexport function buildMachinePaymentIdempotencyKey(\n challenge: MachinePaymentChallenge,\n): string {\n const material = [\n challenge.rail,\n challenge.challengeId,\n challenge.resource,\n challenge.recipient.toLowerCase(),\n challenge.asset.address.toLowerCase(),\n challenge.amount.atomic,\n challenge.network.chainId,\n ].join('|')\n\n return `${challenge.rail}:${createHash('sha256').update(material).digest('hex').slice(0, 16)}`\n}\n\nexport function encodeMachinePaymentProof(receipt: Omit<MachinePaymentReceipt, 'proofHeader'>): string {\n return btoa(JSON.stringify({\n rail: receipt.rail,\n challengeId: receipt.challengeId,\n paymentId: receipt.paymentId,\n txHash: receipt.txHash,\n settledVia: 'haven',\n payer: receipt.payer,\n chainId: receipt.chainId,\n }))\n}\n","import { exact } from 'x402/schemes'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport { signHash, addressFromKey, verifySignature } from './signer.js'\nimport type {\n HavenClientConfig,\n PaymentRequest,\n PaymentIntent,\n PaymentResult,\n PaymentStatus,\n PaymentPhase,\n PaymentNextAction,\n PaymentStatusResult,\n SignData,\n RawCreateResponse,\n RawSignResponse,\n RawStatusResponse,\n RawPaymentStatusResult,\n X402PaymentRequired,\n X402PaymentOption,\n X402Receipt,\n RawX402AuthorizeResponse,\n MachinePaymentChallenge,\n MachinePaymentReceipt,\n RawMachinePaymentAuthorizeResponse,\n} from './types.js'\nimport {\n HavenApiError,\n HavenPaymentStateError,\n HavenSigningError,\n HavenTimeoutError,\n} from './types.js'\nimport {\n buildX402IdempotencyKey,\n parsePaymentRequiredResponse,\n selectStandardPaymentOption,\n toStandardPaymentRequirements,\n} from './x402.js'\nimport {\n buildMachinePaymentIdempotencyKey,\n encodeMachinePaymentProof,\n parseMachinePaymentChallengeResponse,\n} from './mpp.js'\n\nconst DEFAULT_BASE_URL = 'http://localhost:3001'\n\nconst CHAIN_EXPLORER_TX: Record<number, string> = {\n 100: 'https://gnosisscan.io/tx',\n 8453: 'https://basescan.org/tx',\n}\n\nfunction buildExplorerUrl(chainId: number | undefined, txHash: string): string {\n const base = CHAIN_EXPLORER_TX[chainId ?? 8453] ?? CHAIN_EXPLORER_TX[8453]\n return `${base}/${txHash}`\n}\nconst DEFAULT_REQUEST_TIMEOUT = 30_000\nconst DEFAULT_CONFIRMATION_TIMEOUT = 90_000\nconst DEFAULT_POLLING_INTERVAL = 3_000\n\nconst PAYMENT_STATE_STATUS_CODES: Record<string, number> = {\n pending: 202,\n pending_approval: 202,\n approved: 202,\n proposed: 202,\n executed: 200,\n pending_signature: 409,\n submitted: 409,\n expired: 410,\n failed: 502,\n rejected: 409,\n}\n\nfunction chainIdFromNetwork(network: string | undefined): number | undefined {\n if (network === 'base') return 8453\n if (!network?.startsWith('eip155:')) return undefined\n const chainId = Number(network.slice('eip155:'.length))\n return Number.isFinite(chainId) ? chainId : undefined\n}\n\nfunction phaseForStatus(status: string): PaymentPhase | null {\n if (status === 'pending_signature') return 'agent_signature_required'\n if (status === 'submitted') return 'payment_submitted'\n if (status === 'confirmed') return 'payment_confirmed'\n if (status === 'pending' || status === 'pending_approval') return 'user_approval_required'\n if (status === 'approved') return 'user_execution_required'\n if (status === 'proposed') return 'waiting_for_additional_approvals'\n if (status === 'executed') return 'funding_sent'\n if (status === 'rejected') return 'rejected'\n if (status === 'expired') return 'expired'\n if (status === 'failed') return 'failed'\n return null\n}\n\nfunction nextActionForStatus(status: string): PaymentNextAction | null {\n if (status === 'pending_signature') return 'sign_and_submit_payment'\n if (status === 'submitted') return 'check_status_later'\n if (status === 'confirmed') return 'none'\n if (status === 'pending' || status === 'pending_approval') return 'wait_for_user_approval'\n if (status === 'approved') return 'wait_for_user_to_complete_payment'\n if (status === 'proposed') return 'wait_for_user_approval'\n if (status === 'executed') return 'retry_original_x402_request'\n if (status === 'rejected') return 'stop_and_tell_user'\n if (status === 'expired') return 'request_again_if_user_still_wants_it'\n if (status === 'failed') return 'stop_and_tell_user'\n return null\n}\n\nfunction messageForState(\n label: string,\n status: string,\n paymentId: string,\n nextAction: PaymentNextAction,\n): string {\n if (status === 'pending' || status === 'pending_approval') {\n return `${label} is above the remaining agent budget and is waiting for user approval in Haven (payment_id: ${paymentId}).`\n }\n if (status === 'executed') {\n return 'The user completed the funding payment. Retry the original x402 request.'\n }\n if (status === 'rejected') {\n return `The user rejected this payment request (payment_id: ${paymentId}).`\n }\n if (status === 'expired') {\n return `This payment request expired (payment_id: ${paymentId}).`\n }\n return `${label} is ${status}; next_action=${nextAction} (payment_id: ${paymentId}).`\n}\n\nexport class HavenClient {\n private readonly apiKey: string\n private readonly delegateKey: string | undefined\n private readonly baseUrl: string\n private readonly x402Wallet: string | undefined\n private readonly requestTimeout: number\n private readonly confirmationTimeout: number\n private readonly pollingInterval: number\n private readonly inFlightX402 = new Map<string, Promise<X402Receipt>>()\n private readonly x402ReceiptCache = new Map<string, { expiresAt: number; receipt: X402Receipt }>()\n private readonly inFlightMachinePayments = new Map<string, Promise<MachinePaymentReceipt>>()\n\n /** Delegate address derived from the private key (if provided) */\n readonly delegateAddress: string | undefined\n\n constructor(config: HavenClientConfig) {\n this.apiKey = config.apiKey\n this.delegateKey = config.delegateKey\n this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n this.x402Wallet = config.x402Wallet\n this.requestTimeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT\n this.confirmationTimeout = config.confirmationTimeout ?? DEFAULT_CONFIRMATION_TIMEOUT\n this.pollingInterval = config.pollingInterval ?? DEFAULT_POLLING_INTERVAL\n\n if (this.delegateKey) {\n this.delegateAddress = addressFromKey(this.delegateKey)\n }\n }\n\n // ── High-Level API ───────────────────────────────────────────────\n\n /**\n * Send a payment in one call.\n *\n * Creates the intent, signs the hash, submits the signature,\n * and polls until confirmed (or throws on failure/timeout).\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async pay(request: PaymentRequest): Promise<PaymentResult> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot use pay() without a delegateKey. Use createIntent() + submitSignature() for manual signing.',\n )\n }\n\n // Step 1: Create intent\n const intent = await this.createIntent(request)\n\n // Step 2: Sign\n const signature = this.sign(intent.signData.hash)\n\n // Step 3: Submit\n await this.submitSignature(intent.paymentId, signature)\n\n // Step 4: Wait for confirmation\n return this.waitForConfirmation(intent.paymentId)\n }\n\n // ── Step-by-Step API ─────────────────────────────────────────────\n\n /**\n * Step 1: Create a payment intent.\n *\n * Returns the intent with the hash to sign.\n */\n async createIntent(request: PaymentRequest): Promise<PaymentIntent> {\n const raw = await this.post<RawCreateResponse>('/payments', {\n token: request.token,\n amount: request.amount,\n to: request.to,\n })\n\n // Haven returns HTTP 202 with this status when the requested amount\n // exceeds the on-chain allowance. The payment is parked for the owner\n // to approve in the dashboard — there's nothing to sign yet, so the SDK\n // surfaces it as an explicit error rather than returning a malformed\n // intent with no signData.\n if (raw.status === 'pending_approval') {\n this.throwPaymentStateError('Payment', raw)\n }\n\n return {\n paymentId: raw.payment_id,\n status: 'pending_signature',\n expiresAt: raw.expires_at,\n signData: raw.sign_data,\n }\n }\n\n /**\n * Step 2: Sign a hash with the delegate key.\n *\n * Returns the 65-byte signature (0x-prefixed).\n * Requires `delegateKey` to be set in the client config.\n */\n sign(hash: string): string {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot sign without a delegateKey. Pass the private key in HavenClient config, or sign externally.',\n )\n }\n\n const signature = signHash(this.delegateKey, hash)\n\n // Verify the signature locally before submitting\n if (!verifySignature(hash, signature, this.delegateAddress!)) {\n throw new HavenSigningError(\n 'Local signature verification failed — recovered address does not match delegate key.',\n )\n }\n\n return signature\n }\n\n /**\n * Step 3: Submit a signature to execute the payment.\n *\n * The signature can come from `client.sign()` or from external signing.\n */\n async submitSignature(\n paymentId: string,\n signature: string,\n ): Promise<{ status: string; txHash?: string }> {\n const raw = await this.post<RawSignResponse>(\n `/payments/${paymentId}/sign`,\n { signature },\n )\n\n return {\n status: raw.status,\n txHash: raw.tx_hash,\n }\n }\n\n /**\n * Get the current status of a payment.\n */\n async getPayment(paymentId: string): Promise<PaymentResult> {\n const raw = await this.get<RawStatusResponse>(`/payments/${paymentId}`)\n return this.mapPaymentResult(raw)\n }\n\n /**\n * Get agent-actionable status for a payment intent or approval request.\n *\n * Use this for IDs returned by agent tools and machine-payment/x402 flows.\n * `getPayment()` remains available for payment-intent-only integrations.\n */\n async getPaymentStatus(paymentId: string): Promise<PaymentStatusResult> {\n const raw = await this.get<RawPaymentStatusResult>(`/machine-payments/${paymentId}/status`)\n return this.mapPaymentStatusResult(raw)\n }\n\n /**\n * Poll until a payment reaches a terminal status (confirmed, failed, expired).\n */\n async waitForConfirmation(paymentId: string): Promise<PaymentResult> {\n const deadline = Date.now() + this.confirmationTimeout\n\n while (Date.now() < deadline) {\n const result = await this.getPayment(paymentId)\n\n if (result.status === 'confirmed' || result.status === 'failed' || result.status === 'expired') {\n return result\n }\n\n await sleep(this.pollingInterval)\n }\n\n throw new HavenTimeoutError(paymentId)\n }\n\n // ── x402 Protocol Support ────────────────────────────────────────\n\n /**\n * Authorize an x402 payment.\n *\n * Takes the parsed PaymentRequired from a 402 response, selects a compatible\n * option, funds the delegate wallet through Haven, and returns the standard\n * x402 header that the merchant can verify and settle.\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async authorizeX402(paymentRequired: X402PaymentRequired): Promise<X402Receipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for x402 payments. Pass it in the HavenClient config.',\n )\n }\n if (!this.delegateAddress) {\n throw new HavenSigningError('delegateAddress could not be derived from delegateKey.')\n }\n\n // 1. Select best payment option\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.',\n 400,\n )\n }\n\n const idempotencyKey = buildX402IdempotencyKey(paymentRequired, option)\n const cached = this.x402ReceiptCache.get(idempotencyKey)\n if (cached && cached.expiresAt > Date.now()) return cached.receipt\n\n const inFlight = this.inFlightX402.get(idempotencyKey)\n if (inFlight) return inFlight\n\n const promise = this.authorizeStandardX402(paymentRequired, option, idempotencyKey)\n this.inFlightX402.set(idempotencyKey, promise)\n\n try {\n return await promise\n } finally {\n this.inFlightX402.delete(idempotencyKey)\n }\n }\n\n private async authorizeStandardX402(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n idempotencyKey: string,\n ): Promise<X402Receipt> {\n // 2. Standard x402 settles from an EOA, so the SDK uses the agent-owned\n // delegate EOA for the merchant-facing EIP-3009 authorization. Haven does\n // not control this EOA or its private key.\n //\n // The only automated funding path is a separate Safe AllowanceModule\n // transfer signed by the agent key and constrained by the user's on-chain\n // allowance. Haven's backend relays that signed top-up; it is not the source\n // of payment authority.\n // Sign before funding so retries reuse one EIP-3009 nonce. If funding fails,\n // the unused authorization simply expires via validBefore.\n const paymentHeader = await this.createStandardX402Header(paymentRequired, option)\n const raw = await this.post<RawX402AuthorizeResponse>('/x402', {\n url: paymentRequired.resource.url,\n payTo: this.delegateAddress,\n merchantPayTo: option.payTo,\n amount: option.amount,\n asset: option.asset,\n network: option.network,\n description: paymentRequired.resource.description,\n idempotencyKey,\n })\n\n // If the backend already executed (shouldn't happen without sig), return\n if (raw.success && raw.tx_hash) {\n const receipt = {\n success: true,\n paymentId: raw.payment_id,\n txHash: raw.tx_hash,\n token: raw.token ?? '',\n amount: raw.amount ?? '',\n to: raw.to ?? '',\n resourceUrl: paymentRequired.resource.url,\n explorerUrl: raw.explorer_url ?? (raw.tx_hash ? buildExplorerUrl(raw.chain_id, raw.tx_hash) : ''),\n accepted: option,\n paymentHeader,\n merchantTo: raw.merchant_to ?? option.payTo,\n payer: raw.payer ?? raw.safe_address,\n chainId: raw.chain_id ?? chainIdFromNetwork(option.network),\n }\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n this.throwIfNonSignableAuthorizationState('x402 payment', raw)\n\n // 3. Sign the hash\n if (!raw.sign_data?.hash) {\n throw new HavenApiError('No sign_hash returned from x402/authorize', 500, raw)\n }\n const sig = signHash(this.delegateKey!, raw.sign_data.hash)\n\n // 4. Submit signature (reuse existing payments/:id/sign endpoint)\n const execResult = await this.post<RawSignResponse>(\n `/payments/${raw.payment_id}/sign`,\n { signature: sig },\n )\n\n if (execResult.status !== 'confirmed') {\n this.throwPaymentStateError('x402 payment', execResult)\n }\n\n const receipt = {\n success: true,\n paymentId: raw.payment_id,\n txHash: execResult.tx_hash ?? '',\n token: execResult.token ?? raw.token ?? '',\n amount: execResult.amount ?? raw.amount ?? '',\n to: execResult.to ?? raw.to ?? '',\n resourceUrl: paymentRequired.resource.url,\n explorerUrl: execResult.explorer_url ?? (execResult.tx_hash ? buildExplorerUrl(execResult.chain_id, execResult.tx_hash) : ''),\n accepted: option,\n paymentHeader,\n merchantTo: option.payTo,\n payer: raw.payer ?? raw.safe_address ?? raw.sign_data?.components.safe,\n chainId: execResult.chain_id ?? raw.chain_id ?? chainIdFromNetwork(option.network),\n }\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n /**\n * Fetch wrapper that automatically handles HTTP 402 responses.\n *\n * Works like the standard `fetch()` but intercepts 402 responses,\n * pays via x402 through Haven, and retries the request.\n *\n * ```ts\n * const response = await haven.fetch('https://paid-api.com/data')\n * const data = await response.json()\n * ```\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async fetch(url: string, init?: RequestInit): Promise<Response> {\n const initialInit = this.withX402Wallet(init, this.x402PayerAddress())\n\n // 1. Make the original request\n const response = await globalThis.fetch(url, initialInit)\n\n // 2. Not a 402 — return as-is\n if (response.status !== 402) return response\n\n const machineChallengeHeader = response.headers.get('MACHINE-PAYMENT-CHALLENGE')\n if (machineChallengeHeader) {\n const challenge = await parseMachinePaymentChallengeResponse(response)\n return this.fetchWithMachinePayment(url, initialInit, challenge)\n }\n\n // 3. Parse x402 payment requirements\n let paymentRequired: X402PaymentRequired\n try {\n paymentRequired = await parsePaymentRequiredResponse(response)\n } catch {\n let challenge: MachinePaymentChallenge\n try {\n challenge = await parseMachinePaymentChallengeResponse(response)\n } catch {\n // Not a Haven machine-payment 402 — return original response\n return response\n }\n return this.fetchWithMachinePayment(url, initialInit, challenge)\n }\n\n // 4. Pay through Haven\n const receipt = await this.authorizeX402(paymentRequired)\n if (!receipt.accepted) {\n throw new HavenApiError('No accepted x402 option was recorded for payment retry', 500)\n }\n if (!receipt.paymentHeader) {\n throw new HavenApiError('No x402 payment header was returned for payment retry', 500)\n }\n\n // 5. Retry with a merchant-verifiable x402 EIP-3009 payment header.\n const retryHeaders = new Headers(initialInit?.headers)\n retryHeaders.set('X-PAYMENT', receipt.paymentHeader)\n\n const retryResponse = await globalThis.fetch(url, {\n ...initialInit,\n headers: retryHeaders,\n })\n\n if (retryResponse.status === 402) {\n await this.recordMerchantRetryRejected({\n rail: 'x402',\n paymentId: receipt.paymentId,\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n retryResponse,\n details: {\n merchant_to: receipt.merchantTo,\n delegate_to: receipt.to,\n },\n })\n\n throw new HavenApiError(\n 'x402 retry was rejected after Haven funded the delegate wallet; reconciliation may be required.',\n 402,\n {\n marker: 'x402_retry_rejected_after_funding',\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n resource_url: receipt.resourceUrl,\n merchant_to: receipt.merchantTo,\n delegate_to: receipt.to,\n },\n )\n }\n\n await this.reportMachinePaymentEvidence({\n paymentId: receipt.paymentId,\n rail: 'x402',\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n merchantStatus: retryResponse.status,\n challengePayload: paymentRequired as unknown as Record<string, unknown>,\n selectedPayment: receipt.accepted as unknown as Record<string, unknown>,\n paymentProofHeaderName: 'X-PAYMENT',\n paymentProofHeader: receipt.paymentHeader,\n protocolReceiptHeaderName: 'PAYMENT-RESPONSE',\n protocolReceiptHeader: retryResponse.headers.get('PAYMENT-RESPONSE') ?? undefined,\n })\n\n return retryResponse\n }\n\n async authorizeMachinePayment(\n challenge: MachinePaymentChallenge,\n ): Promise<MachinePaymentReceipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for machine payments. Pass it in the HavenClient config.',\n )\n }\n\n if (challenge.rail !== 'mpp_demo') {\n throw new HavenApiError(`Unsupported machine payment rail: ${challenge.rail}`, 400)\n }\n\n const idempotencyKey = buildMachinePaymentIdempotencyKey(challenge)\n const inFlight = this.inFlightMachinePayments.get(idempotencyKey)\n if (inFlight) return inFlight\n\n const promise = this.authorizeMppDemoPayment(challenge, idempotencyKey)\n this.inFlightMachinePayments.set(idempotencyKey, promise)\n\n try {\n return await promise\n } finally {\n this.inFlightMachinePayments.delete(idempotencyKey)\n }\n }\n\n private async authorizeMppDemoPayment(\n challenge: MachinePaymentChallenge,\n idempotencyKey: string,\n ): Promise<MachinePaymentReceipt> {\n const raw = await this.post<RawMachinePaymentAuthorizeResponse>(\n '/machine-payments/authorize',\n { challenge, idempotencyKey },\n )\n\n if (raw.success && raw.tx_hash) {\n return this.mapMachinePaymentReceipt(challenge, raw, raw.tx_hash)\n }\n\n this.throwIfNonSignableAuthorizationState('Machine payment', raw)\n\n if (!raw.sign_data?.hash) {\n throw new HavenApiError('No sign_hash returned from machine payment authorization', 500, raw)\n }\n\n const sig = signHash(this.delegateKey!, raw.sign_data.hash)\n const execResult = await this.post<RawSignResponse>(\n `/payments/${raw.payment_id}/sign`,\n { signature: sig },\n )\n\n if (execResult.status !== 'confirmed' || !execResult.tx_hash) {\n this.throwPaymentStateError('Machine payment', execResult)\n }\n\n return this.mapMachinePaymentReceipt(challenge, raw, execResult.tx_hash, execResult)\n }\n\n private async fetchWithMachinePayment(\n url: string,\n initialInit: RequestInit | undefined,\n challenge: MachinePaymentChallenge,\n ): Promise<Response> {\n const receipt = await this.authorizeMachinePayment(challenge)\n\n const retryHeaders = new Headers(initialInit?.headers)\n retryHeaders.set('MACHINE-PAYMENT-PROOF', receipt.proofHeader)\n\n const retryResponse = await globalThis.fetch(url, {\n ...initialInit,\n headers: retryHeaders,\n })\n\n if (retryResponse.status === 402) {\n await this.recordMerchantRetryRejected({\n rail: receipt.rail,\n paymentId: receipt.paymentId,\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n retryResponse,\n details: {\n challenge_id: receipt.challengeId,\n },\n })\n\n throw new HavenApiError(\n 'Machine payment retry was rejected after Haven sent the payment.',\n 402,\n {\n marker: 'machine_payment_retry_rejected_after_payment',\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n resource_url: receipt.resourceUrl,\n rail: receipt.rail,\n },\n )\n }\n\n await this.reportMachinePaymentEvidence({\n paymentId: receipt.paymentId,\n rail: receipt.rail,\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n merchantStatus: retryResponse.status,\n challengePayload: challenge as unknown as Record<string, unknown>,\n paymentProofHeaderName: 'MACHINE-PAYMENT-PROOF',\n paymentProofHeader: receipt.proofHeader,\n protocolReceiptHeaderName:\n retryResponse.headers.has('Payment-Receipt')\n ? 'Payment-Receipt'\n : retryResponse.headers.has('MACHINE-PAYMENT-RESPONSE')\n ? 'MACHINE-PAYMENT-RESPONSE'\n : undefined,\n protocolReceiptHeader:\n retryResponse.headers.get('Payment-Receipt') ??\n retryResponse.headers.get('MACHINE-PAYMENT-RESPONSE') ??\n undefined,\n })\n\n return retryResponse\n }\n\n private async createStandardX402Header(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n ): Promise<string> {\n if (!this.delegateKey) {\n throw new HavenSigningError('delegateKey is required to sign x402 payment headers.')\n }\n\n const account = privateKeyToAccount(this.delegateKey as `0x${string}`)\n const requirements = toStandardPaymentRequirements(paymentRequired, option)\n\n const header = await exact.evm.createPaymentHeader(\n account,\n paymentRequired.x402Version,\n requirements,\n )\n if (paymentRequired.x402Version < 2) return header\n\n const payment = decodeBase64Json<{ payload: unknown }>(header)\n return btoa(JSON.stringify({\n x402Version: paymentRequired.x402Version,\n accepted: option,\n payload: payment.payload,\n }))\n }\n\n private cacheX402Receipt(\n idempotencyKey: string,\n paymentHeader: string,\n receipt: X402Receipt,\n ): void {\n const expiresAt = getPaymentHeaderValidBefore(paymentHeader)\n if (expiresAt > Date.now()) {\n this.x402ReceiptCache.set(idempotencyKey, { expiresAt, receipt })\n }\n }\n\n private mapMachinePaymentReceipt(\n challenge: MachinePaymentChallenge,\n raw: RawMachinePaymentAuthorizeResponse,\n txHash: string,\n execResult?: RawSignResponse,\n ): MachinePaymentReceipt {\n const receiptWithoutHeader = {\n success: true,\n rail: challenge.rail,\n paymentId: raw.payment_id,\n challengeId: challenge.challengeId,\n txHash,\n token: execResult?.token ?? raw.token ?? challenge.asset.symbol,\n amount: execResult?.amount ?? raw.amount ?? challenge.amount.display,\n to: execResult?.to ?? raw.to ?? challenge.recipient,\n resourceUrl: raw.resource_url ?? challenge.resource,\n explorerUrl:\n execResult?.explorer_url ??\n raw.explorer_url ??\n buildExplorerUrl(execResult?.chain_id ?? raw.chain_id ?? challenge.network.chainId, txHash),\n payer: raw.payer ?? raw.safe_address,\n chainId: execResult?.chain_id ?? raw.chain_id ?? challenge.network.chainId,\n }\n\n return {\n ...receiptWithoutHeader,\n proofHeader: encodeMachinePaymentProof(receiptWithoutHeader),\n }\n }\n\n private async recordMerchantRetryRejected(input: {\n rail: string\n paymentId: string\n txHash: string\n resourceUrl: string\n retryResponse: Response\n details?: Record<string, unknown>\n }): Promise<void> {\n try {\n await this.post('/machine-payments/reconciliation-events', {\n paymentId: input.paymentId,\n rail: input.rail,\n eventType: 'merchant_retry_rejected_after_payment',\n txHash: input.txHash,\n reason: `Merchant returned HTTP ${input.retryResponse.status} after Haven payment confirmation`,\n details: {\n resource_url: input.resourceUrl,\n retry_status: input.retryResponse.status,\n retry_body: await responseSnippet(input.retryResponse),\n ...input.details,\n },\n })\n } catch {\n // Best-effort durability: preserve the original retry failure for callers.\n }\n }\n\n private async reportMachinePaymentEvidence(input: {\n paymentId: string\n rail: string\n txHash: string\n resourceUrl: string\n merchantStatus: number\n challengePayload?: Record<string, unknown>\n selectedPayment?: Record<string, unknown>\n paymentProofHeaderName?: string\n paymentProofHeader?: string\n protocolReceiptHeaderName?: string\n protocolReceiptHeader?: string\n }): Promise<void> {\n try {\n await this.post('/machine-payments/evidence', {\n paymentId: input.paymentId,\n rail: input.rail,\n txHash: input.txHash,\n resourceUrl: input.resourceUrl,\n merchantStatus: input.merchantStatus,\n challengePayload: input.challengePayload,\n selectedPayment: input.selectedPayment,\n paymentProofHeaderName: input.paymentProofHeaderName,\n paymentProofHeader: input.paymentProofHeader,\n protocolReceiptHeaderName: input.protocolReceiptHeaderName,\n protocolReceiptHeader: input.protocolReceiptHeader,\n protocolReceiptPayload: input.protocolReceiptHeader\n ? parseProtocolReceiptHeader(input.protocolReceiptHeader)\n : undefined,\n })\n } catch {\n // Evidence reporting is best-effort. The paid resource response remains\n // the caller-visible result when merchant retry succeeded.\n }\n }\n\n private throwIfNonSignableAuthorizationState(\n label: string,\n raw: RawMachinePaymentAuthorizeResponse | RawX402AuthorizeResponse,\n ): void {\n if (raw.status === 'pending_signature') return\n this.throwPaymentStateError(label, raw)\n }\n\n private throwPaymentStateError(\n label: string,\n raw: RawMachinePaymentAuthorizeResponse | RawX402AuthorizeResponse | RawSignResponse,\n ): never {\n const statusCode = PAYMENT_STATE_STATUS_CODES[raw.status] ?? 502\n const state = this.paymentStateFromRaw(label, raw)\n\n if (state) {\n throw new HavenPaymentStateError(state.message, statusCode, state, raw)\n }\n\n if (raw.status === 'pending_approval') {\n throw new HavenApiError(\n `${label} exceeds the on-chain allowance and was queued for owner approval (payment_id: ${raw.payment_id}).`,\n statusCode,\n raw,\n )\n }\n\n if (raw.status === 'expired') {\n throw new HavenApiError(\n `${label} expired before it could be completed (payment_id: ${raw.payment_id}).`,\n statusCode,\n raw,\n )\n }\n\n const paymentId = raw.payment_id ? ` (payment_id: ${raw.payment_id})` : ''\n const message = raw.error ?? `${label} ${raw.status}${paymentId}`\n throw new HavenApiError(message, statusCode, raw)\n }\n\n private paymentStateFromRaw(\n label: string,\n raw: RawMachinePaymentAuthorizeResponse | RawX402AuthorizeResponse | RawSignResponse,\n ): PaymentStatusResult | null {\n if (!raw.payment_id || !raw.status) return null\n\n const phase = (raw.phase as PaymentPhase | undefined) ?? phaseForStatus(raw.status)\n const nextAction = (raw.next_action as PaymentNextAction | undefined) ?? nextActionForStatus(raw.status)\n if (!phase || !nextAction) return null\n\n const amount = raw.amount ?? raw.requested ?? ''\n const token = raw.token ?? ''\n const message =\n raw.message ??\n raw.error ??\n messageForState(label, raw.status, raw.payment_id, nextAction)\n\n return {\n paymentId: raw.payment_id,\n kind: raw.kind === 'payment_intent' ? 'payment_intent' : 'approval_request',\n rail: raw.rail ?? 'direct',\n status: raw.status === 'pending' ? 'pending_approval' : raw.status,\n phase,\n nextAction,\n amount,\n token,\n resourceUrl: raw.resource_url ?? null,\n merchantAddress: raw.merchant_to ?? null,\n txHash: raw.tx_hash ?? null,\n expiresAt: raw.expires_at ?? '',\n chainId: raw.chain_id ?? 0,\n message,\n }\n }\n\n private x402PayerAddress(): string | undefined {\n return this.delegateAddress ?? this.x402Wallet\n }\n\n private withX402Wallet(init?: RequestInit, wallet = this.x402PayerAddress()): RequestInit | undefined {\n if (!wallet) return init\n\n const headers = new Headers(init?.headers)\n if (!headers.has('x402-wallet')) {\n headers.set('x402-wallet', wallet)\n }\n\n return {\n ...init,\n headers,\n }\n }\n\n // ── Tool Execution (for agent frameworks) ────────────────────────\n\n /**\n * Execute a tool call by name and input.\n *\n * Designed to plug directly into agent tool-call handlers:\n *\n * ```ts\n * if (block.type === 'tool_use') {\n * const result = await haven.executeTool(block.name, block.input)\n * // send result back to the model\n * }\n * ```\n */\n async executeTool(\n toolName: string,\n input: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n if (toolName === 'make_payment') {\n const { token, amount, to } = input as {\n token: string\n amount: string\n to: string\n }\n\n try {\n const result = await this.pay({ token, amount, to })\n return {\n success: result.status === 'confirmed',\n payment_id: result.paymentId,\n status: result.status,\n tx_hash: result.txHash,\n token: result.token,\n amount: result.amount,\n to: result.to,\n explorer_url: result.explorerUrl,\n error: result.errorMessage,\n }\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n if (toolName === 'authorize_x402_payment') {\n const { url, payTo, amount, asset, network, description } = input as {\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n }\n\n try {\n const receipt = await this.authorizeX402({\n x402Version: 2,\n resource: { url, description },\n accepts: [\n {\n scheme: 'exact',\n network,\n amount,\n asset,\n payTo,\n maxTimeoutSeconds: 30,\n },\n ],\n })\n return {\n success: true,\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n token: receipt.token,\n amount: receipt.amount,\n to: receipt.to,\n resource_url: receipt.resourceUrl,\n explorer_url: receipt.explorerUrl,\n payment_header: receipt.paymentHeader,\n merchant_to: receipt.merchantTo,\n payer: receipt.payer,\n chain_id: receipt.chainId,\n }\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n if (toolName === 'authorize_machine_payment') {\n const { challenge } = input as { challenge: MachinePaymentChallenge }\n\n try {\n const receipt = await this.authorizeMachinePayment(challenge)\n return {\n success: true,\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n token: receipt.token,\n amount: receipt.amount,\n to: receipt.to,\n resource_url: receipt.resourceUrl,\n explorer_url: receipt.explorerUrl,\n proof_header: receipt.proofHeader,\n rail: receipt.rail,\n challenge_id: receipt.challengeId,\n payer: receipt.payer,\n chain_id: receipt.chainId,\n }\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n if (toolName === 'get_payment_status') {\n const { payment_id } = input as { payment_id: string }\n const result = await this.getPaymentStatus(payment_id)\n return {\n payment_id: result.paymentId,\n kind: result.kind,\n rail: result.rail,\n status: result.status,\n phase: result.phase,\n next_action: result.nextAction,\n tx_hash: result.txHash,\n token: result.token,\n amount: result.amount,\n resource_url: result.resourceUrl,\n merchant_address: result.merchantAddress,\n expires_at: result.expiresAt,\n chain_id: result.chainId,\n message: result.message,\n }\n }\n\n throw new Error(`Unknown tool: ${toolName}`)\n }\n\n private toolError(err: unknown): Record<string, unknown> {\n if (err instanceof HavenPaymentStateError) {\n return {\n success: false,\n payment_id: err.state.paymentId,\n kind: err.state.kind,\n rail: err.state.rail,\n status: err.state.status,\n phase: err.state.phase,\n next_action: err.state.nextAction,\n tx_hash: err.state.txHash,\n token: err.state.token,\n amount: err.state.amount,\n resource_url: err.state.resourceUrl,\n merchant_address: err.state.merchantAddress,\n expires_at: err.state.expiresAt,\n chain_id: err.state.chainId,\n message: err.state.message,\n error: err.message,\n }\n }\n\n if (err instanceof HavenApiError) {\n return {\n success: false,\n status_code: err.statusCode,\n error: err.message,\n body: err.body,\n }\n }\n\n return {\n success: false,\n error: err instanceof Error ? err.message : String(err),\n }\n }\n\n // ── HTTP Helpers ─────────────────────────────────────────────────\n\n private async post<T>(path: string, body: Record<string, unknown>): Promise<T> {\n return this.request<T>('POST', path, body)\n }\n\n private async get<T>(path: string): Promise<T> {\n return this.request<T>('GET', path)\n }\n\n private async request<T>(\n method: 'GET' | 'POST',\n path: string,\n body?: Record<string, unknown>,\n ): Promise<T> {\n const url = `${this.baseUrl}${path}`\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), this.requestTimeout)\n\n try {\n const res = await fetch(url, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n })\n\n const data = await res.json()\n\n if (!res.ok) {\n const message =\n (data as Record<string, unknown>).error as string\n ?? (data as Record<string, unknown>).details as string\n ?? `API request failed`\n throw new HavenApiError(message, res.status, data)\n }\n\n return data as T\n } catch (err) {\n if (err instanceof HavenApiError) throw err\n if (err instanceof Error && err.name === 'AbortError') {\n throw new HavenApiError(`Request to ${path} timed out`, 408)\n }\n throw new HavenApiError(\n `Request to ${path} failed: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n )\n } finally {\n clearTimeout(timeout)\n }\n }\n\n // ── Mapping Helpers ──────────────────────────────────────────────\n\n private mapPaymentResult(raw: RawStatusResponse): PaymentResult {\n return {\n paymentId: raw.payment_id,\n status: raw.status as PaymentStatus,\n token: raw.token,\n amount: raw.amount,\n to: raw.to,\n txHash: raw.tx_hash,\n errorMessage: raw.error_message,\n explorerUrl: raw.explorer_url ?? (raw.tx_hash ? buildExplorerUrl(raw.chain_id, raw.tx_hash) : null),\n createdAt: raw.created_at,\n signedAt: raw.signed_at,\n submittedAt: raw.submitted_at,\n confirmedAt: raw.confirmed_at,\n expiresAt: raw.expires_at,\n }\n }\n\n private mapPaymentStatusResult(raw: RawPaymentStatusResult): PaymentStatusResult {\n return {\n paymentId: raw.payment_id,\n kind: raw.kind,\n rail: raw.rail,\n status: raw.status,\n phase: raw.phase,\n nextAction: raw.next_action,\n amount: raw.amount,\n token: raw.token,\n resourceUrl: raw.resource_url,\n merchantAddress: raw.merchant_address,\n txHash: raw.tx_hash,\n expiresAt: raw.expires_at,\n chainId: raw.chain_id,\n message: raw.message,\n }\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction getPaymentHeaderValidBefore(paymentHeader: string): number {\n try {\n const payment = decodeBase64Json<{ payload?: { authorization?: { validBefore?: string } } }>(\n paymentHeader,\n )\n const payload = payment.payload as { authorization?: { validBefore?: string } }\n const validBeforeSeconds = Number(payload.authorization?.validBefore)\n if (Number.isFinite(validBeforeSeconds)) return validBeforeSeconds * 1000\n } catch {\n // If the header cannot be decoded, skip caching rather than hiding errors.\n }\n\n return 0\n}\n\nfunction decodeBase64Json<T>(value: string): T {\n return JSON.parse(atob(value)) as T\n}\n\nfunction parseProtocolReceiptHeader(value: string): Record<string, unknown> | undefined {\n try {\n return JSON.parse(atob(value)) as Record<string, unknown>\n } catch {\n try {\n return JSON.parse(value) as Record<string, unknown>\n } catch {\n return undefined\n }\n }\n}\n\nasync function responseSnippet(response: Response): Promise<string | null> {\n try {\n const text = await response.clone().text()\n return text.slice(0, 1000) || null\n } catch {\n return null\n }\n}\n","/**\n * Pre-built tool definitions for AI agent frameworks.\n *\n * These definitions describe the `make_payment` and `get_payment_status` tools\n * in the formats expected by Claude (Anthropic) and OpenAI.\n *\n * Usage with Claude:\n * const response = await anthropic.messages.create({\n * tools: havenTools.claude(),\n * ...\n * })\n *\n * Usage with OpenAI:\n * const response = await openai.chat.completions.create({\n * tools: havenTools.openai(),\n * ...\n * })\n */\n\n// ── JSON Schema (shared across formats) ──────────────────────────\n\nconst makePaymentSchema = {\n type: 'object' as const,\n properties: {\n token: {\n type: 'string' as const,\n description: 'Token to send. Gnosis Chain: EURe, USDC.e, xDAI. Base: USDC, ETH.',\n },\n amount: {\n type: 'string' as const,\n description: 'Amount to send as a decimal string, e.g. \"5.00\"',\n },\n to: {\n type: 'string' as const,\n description: 'Recipient Ethereum address (0x...)',\n },\n reason: {\n type: 'string' as const,\n description: 'Brief reason for this payment (for audit trail)',\n },\n },\n required: ['token', 'amount', 'to', 'reason'] as const,\n}\n\nconst getPaymentStatusSchema = {\n type: 'object' as const,\n properties: {\n payment_id: {\n type: 'string' as const,\n description: 'The payment ID returned from make_payment',\n },\n },\n required: ['payment_id'] as const,\n}\n\nconst authorizeX402Schema = {\n type: 'object' as const,\n properties: {\n url: {\n type: 'string' as const,\n description: 'The URL that returned HTTP 402',\n },\n payTo: {\n type: 'string' as const,\n description: 'Payment recipient address from the 402 response',\n },\n amount: {\n type: 'string' as const,\n description: 'Payment amount in atomic units (e.g. \"1000000\" for 1 USDC)',\n },\n asset: {\n type: 'string' as const,\n description: 'Token contract address from the 402 response',\n },\n network: {\n type: 'string' as const,\n description: 'CAIP-2 chain ID. \"eip155:100\" for Gnosis Chain, \"eip155:8453\" for Base.',\n },\n description: {\n type: 'string' as const,\n description: 'Description of the resource being paid for',\n },\n },\n required: ['url', 'payTo', 'amount', 'asset', 'network'] as const,\n}\n\nconst authorizeMachinePaymentSchema = {\n type: 'object' as const,\n properties: {\n challenge: {\n type: 'object' as const,\n description: 'Machine payment challenge returned by a Haven demo endpoint',\n },\n },\n required: ['challenge'] as const,\n}\n\nconst MAKE_PAYMENT_DESCRIPTION =\n 'Request and sign a payment from the user-controlled Safe within approved on-chain limits. ' +\n 'Haven authenticates the agent, validates the signed intent, and relays the Safe AllowanceModule transaction; it does not hold keys or control funds. ' +\n 'Gnosis Chain tokens: EURe, USDC.e, xDAI. Base tokens: USDC, ETH.'\n\nconst GET_STATUS_DESCRIPTION =\n 'Check the status of a previously initiated payment. ' +\n 'Accepts payment intent IDs and approval request IDs. Returns the current status, phase, next_action, transaction hash if available, and payment details.'\n\nconst AUTHORIZE_X402_DESCRIPTION =\n 'Authorize payment for an HTTP 402 (Payment Required) response. ' +\n 'When a paid API returns x402 payment requirements, use this tool to sign with the agent-owned delegate key and request a policy-limited Safe AllowanceModule top-up when needed. ' +\n 'Haven relays signed transactions only; the agent key authorizes payment and on-chain limits enforce spend. ' +\n 'If this returns pending_approval, tell the user it is waiting in Haven, call get_payment_status later, and retry the original x402 request only when next_action is retry_original_x402_request. Do not rewrite the SDK or loop retries while approval is pending. ' +\n 'Use the returned payment_header as the X-PAYMENT header on the retry request.'\n\nconst AUTHORIZE_MACHINE_PAYMENT_DESCRIPTION =\n 'Authorize a Haven machine-payment challenge, currently for the internal MPP demo rail. ' +\n 'The agent signs the payment, Haven relays it within the on-chain allowance, and the tool returns a proof header for the retry request.'\n\n// ── Claude (Anthropic) format ────────────────────────────────────\n\nexport interface ClaudeTool {\n name: string\n description: string\n input_schema: {\n type: 'object'\n properties: Record<string, unknown>\n required: readonly string[]\n }\n}\n\nfunction claudeTools(): ClaudeTool[] {\n return [\n {\n name: 'make_payment',\n description: MAKE_PAYMENT_DESCRIPTION,\n input_schema: makePaymentSchema,\n },\n {\n name: 'get_payment_status',\n description: GET_STATUS_DESCRIPTION,\n input_schema: getPaymentStatusSchema,\n },\n {\n name: 'authorize_x402_payment',\n description: AUTHORIZE_X402_DESCRIPTION,\n input_schema: authorizeX402Schema,\n },\n {\n name: 'authorize_machine_payment',\n description: AUTHORIZE_MACHINE_PAYMENT_DESCRIPTION,\n input_schema: authorizeMachinePaymentSchema,\n },\n ]\n}\n\n// ── OpenAI format ────────────────────────────────────────────────\n\nexport interface OpenAITool {\n type: 'function'\n function: {\n name: string\n description: string\n parameters: {\n type: 'object'\n properties: Record<string, unknown>\n required: readonly string[]\n }\n }\n}\n\nfunction openaiTools(): OpenAITool[] {\n return [\n {\n type: 'function',\n function: {\n name: 'make_payment',\n description: MAKE_PAYMENT_DESCRIPTION,\n parameters: makePaymentSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'get_payment_status',\n description: GET_STATUS_DESCRIPTION,\n parameters: getPaymentStatusSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'authorize_x402_payment',\n description: AUTHORIZE_X402_DESCRIPTION,\n parameters: authorizeX402Schema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'authorize_machine_payment',\n description: AUTHORIZE_MACHINE_PAYMENT_DESCRIPTION,\n parameters: authorizeMachinePaymentSchema,\n },\n },\n ]\n}\n\n// ── Public API ───────────────────────────────────────────────────\n\nexport const havenTools = {\n /** Tool definitions in Anthropic/Claude format */\n claude: claudeTools,\n\n /** Tool definitions in OpenAI function-calling format */\n openai: openaiTools,\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/signer.ts","../src/x402.ts","../src/mpp.ts","../src/client.ts","../src/tools.ts"],"names":["decodeBase64Json","createHash","receipt","request"],"mappings":";;;;;;;;;AA8cO,IAAM,iBAAA,GAAoB;AAAA;AAAA,EAE/B,sBAAA,EAAwB,0BAAA;AAAA;AAAA,EAExB,gBAAA,EAAkB,mBAAA;AAAA;AAAA,EAElB,gBAAA,EAAkB,mBAAA;AAAA;AAAA,EAElB,oBAAA,EAAsB,wBAAA;AAAA;AAAA,EAEtB,qBAAA,EAAuB,yBAAA;AAAA;AAAA,EAEvB,6BAAA,EAA+B,kCAAA;AAAA;AAAA,EAE/B,WAAA,EAAa,cAAA;AAAA;AAAA,EAEb,QAAA,EAAU,UAAA;AAAA;AAAA,EAEV,OAAA,EAAS,SAAA;AAAA;AAAA,EAET,MAAA,EAAQ;AACV;AAIO,IAAM,sBAAA,GAAyB;AAAA;AAAA,EAEpC,oBAAA,EAAsB,yBAAA;AAAA;AAAA,EAEtB,gBAAA,EAAkB,oBAAA;AAAA;AAAA,EAElB,IAAA,EAAM,MAAA;AAAA;AAAA,EAEN,mBAAA,EAAqB,wBAAA;AAAA;AAAA,EAErB,4BAAA,EAA8B,mCAAA;AAAA;AAAA,EAE9B,wBAAA,EAA0B,6BAAA;AAAA;AAAA,EAE1B,eAAA,EAAiB,oBAAA;AAAA;AAAA,EAEjB,8BAAA,EAAgC;AAClC;AAIO,IAAM,gBAAA,GAAmB;AAAA;AAAA,EAE9B,MAAA,EAAQ,QAAA;AAAA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B,MAAA,EAAQ,WAAA;AAAA;AAAA,EAGR,MAAA,EAAQ;AACV","file":"index.js","sourcesContent":["// ── Client Configuration ─────────────────────────────────────────\n\nexport interface HavenClientConfig {\n /** Haven API key (sk_agent_xxx) */\n apiKey: string\n\n /** Agent's delegate EOA private key. If provided, the SDK handles signing automatically. */\n delegateKey?: string\n\n /** Haven API base URL (default: http://localhost:3001) */\n baseUrl?: string\n\n /** Optional wallet identity to send as the x402-wallet header. */\n x402Wallet?: string\n\n /** Timeout in ms for individual HTTP requests (default: 30000) */\n requestTimeout?: number\n\n /** Timeout in ms when polling for tx confirmation (default: 90000) */\n confirmationTimeout?: number\n\n /** Polling interval in ms when waiting for confirmation (default: 3000) */\n pollingInterval?: number\n\n /**\n * Extra headers to attach to every request to the Haven API.\n *\n * Used by the MCP server to tag requests with `X-Haven-MCP-Tool: <name>`\n * so the backend can record an audit-log entry per tool invocation. Has\n * no effect on outbound merchant requests (x402 / MPP) — those are\n * standard HTTP and never carry Haven-internal headers.\n */\n defaultHeaders?: Record<string, string>\n}\n\n// ── Payment Types ────────────────────────────────────────────────\n\nexport interface PaymentRequest {\n /** Token symbol: \"EURe\", \"USDC.e\", or \"xDAI\" */\n token: string\n\n /** Amount as a decimal string, e.g. \"5.00\" */\n amount: string\n\n /** Recipient Ethereum address (0x...) */\n to: string\n}\n\nexport interface SignData {\n /** The hash to sign (keccak256, 0x-prefixed) */\n hash: string\n\n /** Breakdown of values that were hashed — useful for debugging */\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n\n /** Human-readable signing instructions */\n instructions: string\n}\n\nexport interface PaymentIntent {\n /** Unique payment ID */\n paymentId: string\n\n /** Current status */\n status: 'pending_signature'\n\n /** ISO 8601 expiry timestamp */\n expiresAt: string\n\n /** Data needed to sign the payment */\n signData: SignData\n}\n\nexport type PaymentStatus =\n | 'pending_signature'\n | 'submitted'\n | 'confirmed'\n | 'pending_approval'\n | 'approved'\n | 'proposed'\n | 'executed'\n | 'rejected'\n | 'expired'\n | 'failed'\n\nexport interface PaymentResult {\n /** Unique payment ID */\n paymentId: string\n\n /** Final status */\n status: PaymentStatus\n\n /** Token that was sent */\n token: string\n\n /** Amount that was sent (human-readable) */\n amount: string\n\n /** Recipient address */\n to: string\n\n /** On-chain transaction hash (present when confirmed) */\n txHash: string | null\n\n /** Error message (present when failed) */\n errorMessage: string | null\n\n /** Block explorer URL for the transaction (chain-dependent) */\n explorerUrl: string | null\n\n /** ISO 8601 timestamps */\n createdAt: string\n signedAt: string | null\n submittedAt: string | null\n confirmedAt: string | null\n expiresAt: string\n}\n\n// ── x402 Types ──────────────────────────────────────────────────\n\n/** Payment requirements from an HTTP 402 response (x402 protocol). */\nexport interface X402PaymentRequired {\n x402Version: number\n resource: {\n url: string\n description?: string\n mimeType?: string\n }\n accepts: X402PaymentOption[]\n error?: string\n}\n\n/** A single payment option from x402 PaymentRequired. */\nexport interface X402PaymentOption {\n scheme: string // \"exact\"\n network: string // CAIP-2 chain ID or x402 network, e.g. \"eip155:8453\" or \"base\"\n amount: string // Atomic units\n maxAmountRequired?: string // Atomic units (official x402 field)\n resource?: string\n description?: string\n mimeType?: string\n asset: string // Token contract address\n payTo: string // Recipient address\n maxTimeoutSeconds: number\n extra?: Record<string, unknown>\n}\n\n/** Receipt returned after a successful x402 payment. */\nexport interface X402Receipt {\n success: boolean\n paymentId: string\n txHash: string\n token: string\n amount: string\n to: string\n resourceUrl: string\n explorerUrl: string\n accepted?: X402PaymentOption\n paymentHeader?: string\n merchantTo?: string | null\n payer?: string\n chainId?: number\n haven?: {\n paymentId: string\n fundingTxHash: string\n fundingExplorerUrl: string\n }\n merchant?: {\n payTo: string | null\n settlementTxHash?: string | null\n settlementExplorerUrl?: string | null\n }\n x402?: {\n amount: string\n token: string\n network: string\n asset: string\n resource: string\n }\n}\n\nexport interface X402AuthorizationOptions {\n /** Stable caller-supplied key for this user intent. Prevents duplicate approvals across fresh 402 quotes. */\n idempotencyKey?: string\n}\n\n/** Serializable HTTP request state for retrying the same x402 merchant request. */\nexport interface X402RequestSnapshot {\n url: string\n method: string\n headers: [string, string][]\n body?: string\n}\n\n/** Quote parsed from an HTTP 402 response without creating a Haven payment. */\nexport interface X402Quote {\n rail: 'x402'\n idempotencyKey: string\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n request: X402RequestSnapshot\n resourceUrl: string\n description: string | null\n mimeType: string | null\n amountAtomic: string\n amount: string\n token: string\n asset: string\n network: string\n chainId: number | null\n merchantAddress: string\n maxTimeoutSeconds: number\n}\n\n/** State bundle an agent can persist while waiting for manual x402 approval. */\nexport interface X402ResumeState {\n rail: 'x402'\n paymentId: string\n idempotencyKey: string\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n url: string\n request?: X402RequestSnapshot\n resourceUrl: string\n description: string | null\n amountAtomic: string\n amount: string\n token: string\n asset: string\n network: string\n chainId: number | null\n merchantAddress: string\n}\n\nexport interface MppAuthorizationOptions {\n /** Stable caller-supplied key for this user intent. Prevents duplicate approvals across retries. */\n idempotencyKey?: string\n}\n\n/** Quote parsed from an MPP challenge without creating a Haven payment. */\nexport interface MppQuote {\n rail: 'mpp'\n paymentRail: MachinePaymentRail\n idempotencyKey: string\n challenge: MachinePaymentChallenge\n request: X402RequestSnapshot\n resourceUrl: string\n description: string | null\n amountAtomic: string\n amount: string\n token: string\n asset: string\n network: string\n chainId: number\n merchantAddress: string\n expiresAt: string\n}\n\n/** State bundle an agent can persist while waiting for manual MPP approval. */\nexport interface MppResumeState {\n rail: 'mpp'\n paymentRail: MachinePaymentRail\n paymentId: string\n idempotencyKey: string\n challenge: MachinePaymentChallenge\n url: string\n request?: X402RequestSnapshot\n resourceUrl: string\n description: string | null\n amountAtomic: string\n amount: string\n token: string\n asset: string\n network: string\n chainId: number\n merchantAddress: string\n expiresAt: string\n}\n\nexport type PaymentResumeState = X402ResumeState | MppResumeState\n\nexport interface ResumeAuthorizedX402Input extends X402AuthorizationOptions {\n /** Payment or approval request ID returned by authorizeX402 / haven.fetch. */\n paymentId: string\n\n /** Original or freshly parsed x402 requirements for the merchant retry. */\n paymentRequired: X402PaymentRequired\n}\n\nexport interface ResumeX402PaymentInput extends X402AuthorizationOptions {\n /** Payment or approval request ID returned by authorizeX402 / haven.fetch. */\n paymentId: string\n\n /** Original paid URL. If paymentRequired is omitted, Haven will call it once to re-read the 402 challenge. */\n url: string\n\n /** Original fetch options. Reused for the 402 probe and final merchant retry. */\n init?: RequestInit\n\n /** Serializable original request captured by quoteX402() / pending approval errors. */\n request?: X402RequestSnapshot\n\n /** Original or freshly parsed x402 requirements. Supplying this avoids an extra merchant 402 probe. */\n paymentRequired?: X402PaymentRequired\n}\n\nexport interface ResumeAuthorizedMppInput extends MppAuthorizationOptions {\n /** Payment or approval request ID returned by authorizeMachinePayment / haven.fetch. */\n paymentId: string\n\n /** Original MPP challenge returned by the paid resource. */\n challenge: MachinePaymentChallenge\n}\n\nexport interface ResumeMppPaymentInput extends MppAuthorizationOptions {\n /** Payment or approval request ID returned by authorizeMachinePayment / haven.fetch. */\n paymentId: string\n\n /** Original paid URL. If challenge is omitted, Haven will call it once to re-read the MPP challenge. */\n url: string\n\n /** Original fetch options. Reused for the 402 probe and final merchant retry. */\n init?: RequestInit\n\n /** Serializable original request captured by quoteMpp() / pending approval errors. */\n request?: X402RequestSnapshot\n\n /** Original MPP challenge. Supplying this avoids an extra paid-resource 402 probe. */\n challenge?: MachinePaymentChallenge\n}\n\n// ── Machine Payment Types ───────────────────────────────────────\n\nexport type MachinePaymentRail =\n | 'x402'\n | 'mpp_demo'\n | 'mpp_crypto'\n | 'stripe_deposit'\n | 'spt'\n\nexport interface MachinePaymentChallenge {\n rail: MachinePaymentRail\n version: string\n challengeId: string\n resource: string\n description: string\n network: {\n chainId: number\n name: 'base'\n }\n asset: {\n symbol: 'USDC'\n address: string\n decimals: 6\n }\n amount: {\n display: string\n atomic: string\n }\n recipient: string\n expiresAt: string\n metadata?: Record<string, unknown>\n}\n\nexport interface MachinePaymentReceipt {\n success: boolean\n rail: MachinePaymentRail\n paymentId: string\n challengeId: string\n txHash: string\n token: string\n amount: string\n to: string\n resourceUrl: string\n explorerUrl: string\n payer?: string\n chainId?: number\n proofHeader: string\n}\n\nexport interface HavenAgent {\n id: string\n name: string\n status: string\n safeAddress: string\n delegateAddress: string\n chainId: number\n}\n\nexport interface HavenAllowance {\n id: string\n tokenAddress: string\n tokenSymbol: string\n configuredAmount: string\n resetPeriodMin: number\n onchain: {\n amount: string\n spent: string\n remaining: string\n effectiveSpent: string\n resetTimeMin: number\n lastResetMin: number\n nonce: number\n isResetPending: boolean\n }\n}\n\nexport interface HavenAllowanceSummary {\n agentId: string\n safeAddress: string\n delegateAddress: string\n chainId: number\n allowances: HavenAllowance[]\n}\n\nexport interface HavenPaymentReceipt {\n id: string\n paymentId: string\n rail: string\n proofStatus: string\n txHash: string\n chainId: number\n resourceUrl: string\n merchantAddress: string | null\n payerAddress: string\n settlementAddress: string\n tokenSymbol: string\n tokenAddress: string\n amountRaw: string\n amount: string\n challengeId: string | null\n idempotencyKey: string | null\n challengePayload?: Record<string, unknown> | null\n selectedPayment?: Record<string, unknown> | null\n paymentProofHeaderName: string | null\n protocolReceiptHeaderName: string | null\n protocolReceiptPayload?: Record<string, unknown> | null\n merchantStatus: number | null\n confirmedAt: string | null\n createdAt: string\n updatedAt: string\n}\n\n// ── Agent Payment State Types ────────────────────────────────────\n\nexport type PaymentStateKind = 'payment_intent' | 'approval_request'\n\nexport interface AgentPaymentEnumSchema {\n type: 'string'\n enum: readonly string[]\n description: string\n 'x-enumDescriptions': Record<string, string>\n}\n\nexport const AgentPaymentPhase = {\n /** The agent must sign and submit the prepared payment before Haven can relay it. */\n AgentSignatureRequired: 'agent_signature_required',\n /** Haven has received the signed payment and the agent should poll for confirmation. */\n PaymentSubmitted: 'payment_submitted',\n /** The direct payment is confirmed; the agent does not need to do more for this payment id. */\n PaymentConfirmed: 'payment_confirmed',\n /** The payment needs wallet owner approval in Haven before it can continue. */\n UserApprovalRequired: 'user_approval_required',\n /** The wallet owner approved the request and still needs to complete the funding payment. */\n UserExecutionRequired: 'user_execution_required',\n /** The funding payment was proposed and is waiting for the remaining account approvals. */\n WaitingForAdditionalApprovals: 'waiting_for_additional_approvals',\n /** The Haven funding leg was sent; the agent can continue the merchant/protocol leg. */\n FundingSent: 'funding_sent',\n /** The wallet owner rejected the request; the agent should stop and tell the user. */\n Rejected: 'rejected',\n /** The payment or approval request expired before completion. */\n Expired: 'expired',\n /** Haven could not complete the payment; the agent should stop and surface the failure. */\n Failed: 'failed',\n} as const\n\nexport type AgentPaymentPhase = (typeof AgentPaymentPhase)[keyof typeof AgentPaymentPhase]\n\nexport const AgentPaymentNextAction = {\n /** Sign with the delegate key and submit the payment to Haven. */\n SignAndSubmitPayment: 'sign_and_submit_payment',\n /** Poll getPaymentStatus later using this payment id. */\n CheckStatusLater: 'check_status_later',\n /** No further agent action is required for this payment id. */\n None: 'none',\n /** Wait for the wallet owner to approve or reject the request in Haven. */\n WaitForUserApproval: 'wait_for_user_approval',\n /** Wait for the wallet owner to finish sending the approved funding payment. */\n WaitForUserToCompletePayment: 'wait_for_user_to_complete_payment',\n /** Resume this payment id and retry the original x402 request with the merchant payment header. */\n RetryOriginalX402Request: 'retry_original_x402_request',\n /** Stop retrying this payment and tell the user what happened. */\n StopAndTellUser: 'stop_and_tell_user',\n /** Ask again only if the user still wants the payment after expiry. */\n RequestAgainIfUserStillWantsIt: 'request_again_if_user_still_wants_it',\n} as const\n\nexport type AgentPaymentNextAction = (typeof AgentPaymentNextAction)[keyof typeof AgentPaymentNextAction]\n\nexport const AgentPaymentRail = {\n /** Standard Haven payment from the user's Safe through an approved delegate allowance. */\n Direct: 'direct',\n /** x402 HTTP 402 payment flow with a Haven funding leg and merchant retry leg. */\n X402: 'x402',\n /** Machine Payment Protocol flow. */\n Mpp: 'mpp',\n} as const\n\nexport type AgentPaymentRail = (typeof AgentPaymentRail)[keyof typeof AgentPaymentRail]\n\nexport type PaymentPhase = AgentPaymentPhase\n\nexport type PaymentNextAction = AgentPaymentNextAction\n\nexport const AGENT_PAYMENT_PHASE_VALUES = Object.values(AgentPaymentPhase)\n\nexport const AGENT_PAYMENT_NEXT_ACTION_VALUES = Object.values(AgentPaymentNextAction)\n\nexport const AGENT_PAYMENT_RAIL_VALUES = Object.values(AgentPaymentRail)\n\nexport const AgentPaymentPhaseDescriptions: Record<AgentPaymentPhase, string> = {\n [AgentPaymentPhase.AgentSignatureRequired]: 'The agent must sign and submit the prepared payment before Haven can relay it.',\n [AgentPaymentPhase.PaymentSubmitted]: 'Haven has received the signed payment and the agent should poll for confirmation.',\n [AgentPaymentPhase.PaymentConfirmed]: 'The direct payment is confirmed; the agent does not need to do more for this payment id.',\n [AgentPaymentPhase.UserApprovalRequired]: 'The payment needs wallet owner approval in Haven before it can continue.',\n [AgentPaymentPhase.UserExecutionRequired]: 'The wallet owner approved the request and still needs to complete the funding payment.',\n [AgentPaymentPhase.WaitingForAdditionalApprovals]: 'The funding payment was proposed and is waiting for the remaining account approvals.',\n [AgentPaymentPhase.FundingSent]: 'The Haven funding leg was sent; the agent can continue the merchant/protocol leg.',\n [AgentPaymentPhase.Rejected]: 'The wallet owner rejected the request; the agent should stop and tell the user.',\n [AgentPaymentPhase.Expired]: 'The payment or approval request expired before completion.',\n [AgentPaymentPhase.Failed]: 'Haven could not complete the payment; the agent should stop and surface the failure.',\n}\n\nexport const AgentPaymentNextActionDescriptions: Record<AgentPaymentNextAction, string> = {\n [AgentPaymentNextAction.SignAndSubmitPayment]: 'Sign with the delegate key and submit the payment to Haven.',\n [AgentPaymentNextAction.CheckStatusLater]: 'Poll getPaymentStatus later using this payment id.',\n [AgentPaymentNextAction.None]: 'No further agent action is required for this payment id.',\n [AgentPaymentNextAction.WaitForUserApproval]: 'Wait for the wallet owner to approve or reject the request in Haven.',\n [AgentPaymentNextAction.WaitForUserToCompletePayment]: 'Wait for the wallet owner to finish sending the approved funding payment.',\n [AgentPaymentNextAction.RetryOriginalX402Request]: 'Resume this payment id and retry the original x402 request with the merchant payment header.',\n [AgentPaymentNextAction.StopAndTellUser]: 'Stop retrying this payment and tell the user what happened.',\n [AgentPaymentNextAction.RequestAgainIfUserStillWantsIt]: 'Ask again only if the user still wants the payment after expiry.',\n}\n\nexport const AgentPaymentRailDescriptions: Record<AgentPaymentRail, string> = {\n [AgentPaymentRail.Direct]: 'Standard Haven payment from the user-controlled Safe through an approved delegate allowance.',\n [AgentPaymentRail.X402]: 'x402 HTTP 402 payment flow with a Haven funding leg and merchant retry leg.',\n [AgentPaymentRail.Mpp]: 'Machine Payment Protocol flow.',\n}\n\nexport const AgentPaymentPhaseSchema: AgentPaymentEnumSchema = {\n type: 'string',\n enum: AGENT_PAYMENT_PHASE_VALUES,\n description: 'Stable Haven agent payment state phase.',\n 'x-enumDescriptions': AgentPaymentPhaseDescriptions,\n}\n\nexport const AgentPaymentNextActionSchema: AgentPaymentEnumSchema = {\n type: 'string',\n enum: AGENT_PAYMENT_NEXT_ACTION_VALUES,\n description: 'Stable next action an agent should take for a Haven payment state.',\n 'x-enumDescriptions': AgentPaymentNextActionDescriptions,\n}\n\nexport const AgentPaymentRailSchema: AgentPaymentEnumSchema = {\n type: 'string',\n enum: AGENT_PAYMENT_RAIL_VALUES,\n description: 'Stable rail identifier for Haven agent payment states.',\n 'x-enumDescriptions': AgentPaymentRailDescriptions,\n}\n\nexport interface PaymentStatusResult {\n paymentId: string\n kind: PaymentStateKind\n rail: string\n status: PaymentStatus | string\n phase: PaymentPhase\n nextAction: PaymentNextAction\n amount: string\n token: string\n resourceUrl: string | null\n merchantAddress: string | null\n txHash: string | null\n expiresAt: string\n chainId: number\n message: string\n amountAtomic?: string | null\n asset?: string | null\n network?: string | null\n description?: string | null\n idempotencyKey?: string | null\n x402?: {\n amountAtomic: string | null\n asset: string | null\n network: string | null\n resourceUrl: string | null\n merchantAddress: string | null\n description: string | null\n idempotencyKey: string | null\n }\n mpp?: {\n amountAtomic: string | null\n asset: string | null\n network: string | null\n resourceUrl: string | null\n merchantAddress: string | null\n description: string | null\n idempotencyKey: string | null\n challengeId: string | null\n }\n}\n\nexport interface PendingApproval extends PaymentStatusResult {\n kind: 'approval_request'\n status: 'pending_approval' | 'pending' | string\n phase: typeof AgentPaymentPhase.UserApprovalRequired\n nextAction: typeof AgentPaymentNextAction.WaitForUserApproval\n requested?: string\n remaining?: string | null\n}\n\n/** @internal */\nexport interface RawMachinePaymentAuthorizeResponse {\n success?: boolean\n payment_id: string\n kind?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n tx_hash?: string\n chain_id?: number\n safe_address?: string\n payer?: string\n token?: string\n amount?: string\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n description?: string | null\n idempotency_key?: string | null\n to?: string\n merchant_to?: string | null\n merchant_address?: string | null\n resource_url?: string\n rail?: string\n x402?: RawX402StateContext\n mpp?: RawMppStateContext\n challenge_id?: string\n explorer_url?: string\n expires_at?: string\n sign_data?: {\n hash: string\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n instructions: string\n }\n error?: string\n}\n\n/** @internal */\nexport interface RawX402AuthorizeResponse {\n success?: boolean\n payment_id: string\n kind?: string\n rail?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n tx_hash?: string\n chain_id?: number\n safe_address?: string\n payer?: string\n token?: string\n amount?: string\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n description?: string | null\n idempotency_key?: string | null\n to?: string\n merchant_to?: string | null\n merchant_address?: string | null\n resource_url?: string\n explorer_url?: string\n x402?: RawX402StateContext\n mpp?: RawMppStateContext\n challenge_id?: string\n expires_at?: string\n sign_data?: {\n hash: string\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n instructions: string\n }\n error?: string\n}\n\n// ── API Response Shapes (raw, snake_case from server) ────────────\n\n/** @internal */\nexport interface RawCreateResponse {\n payment_id: string\n kind?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n expires_at: string\n sign_data: {\n hash: string\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n instructions: string\n }\n error?: string\n supported?: string[]\n}\n\n/** @internal */\nexport interface RawSignResponse {\n payment_id: string\n kind?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n tx_hash?: string\n token?: string\n amount?: string\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n description?: string | null\n idempotency_key?: string | null\n to?: string\n merchant_to?: string | null\n merchant_address?: string | null\n resource_url?: string\n rail?: string\n x402?: RawX402StateContext\n mpp?: RawMppStateContext\n challenge_id?: string\n explorer_url?: string\n chain_id?: number\n expires_at?: string\n error?: string\n details?: string\n}\n\n/** @internal */\nexport interface RawStatusResponse {\n payment_id: string\n status: string\n token: string\n amount: string\n to: string\n tx_hash: string | null\n explorer_url?: string | null\n chain_id?: number\n error_message: string | null\n created_at: string\n signed_at: string | null\n submitted_at: string | null\n confirmed_at: string | null\n expires_at: string\n}\n\n/** @internal */\nexport interface RawPaymentStatusResult {\n payment_id: string\n kind: PaymentStateKind\n rail: string\n status: string\n phase: PaymentPhase\n next_action: PaymentNextAction\n amount: string\n token: string\n resource_url: string | null\n merchant_address: string | null\n tx_hash: string | null\n expires_at: string\n chain_id: number\n message: string\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n description?: string | null\n idempotency_key?: string | null\n x402?: RawX402StateContext\n mpp?: RawMppStateContext\n}\n\n/** @internal */\nexport interface RawHavenAgent {\n id: string\n name: string\n status: string\n safe_address: string\n delegate_address: string\n chain_id: number\n}\n\n/** @internal */\nexport interface RawHavenAllowance {\n id: string\n token_address: string\n token_symbol: string\n configured_amount: string\n reset_period_min: number\n onchain: {\n amount: string\n spent: string\n remaining: string\n effective_spent: string\n reset_time_min: number\n last_reset_min: number\n nonce: number\n is_reset_pending: boolean\n }\n}\n\n/** @internal */\nexport interface RawHavenAllowanceSummary {\n agent_id: string\n safe_address: string\n delegate_address: string\n chain_id: number\n allowances: RawHavenAllowance[]\n}\n\n/** @internal */\nexport interface RawHavenPaymentReceipt {\n id: string\n payment_id: string\n rail: string\n proof_status: string\n tx_hash: string\n chain_id: number\n resource_url: string\n merchant_address: string | null\n payer_address: string\n settlement_address: string\n token_symbol: string\n token_address: string\n amount_raw: string\n amount_human: string\n challenge_id: string | null\n idempotency_key: string | null\n challenge_payload?: Record<string, unknown> | null\n selected_payment?: Record<string, unknown> | null\n payment_proof_header_name: string | null\n protocol_receipt_header_name: string | null\n protocol_receipt_payload?: Record<string, unknown> | null\n merchant_status: number | null\n confirmed_at: string | null\n created_at: string\n updated_at: string\n}\n\n/** @internal */\nexport interface RawHavenPaymentReceiptsResponse {\n receipts: RawHavenPaymentReceipt[]\n}\n\n/** @internal */\nexport interface RawX402StateContext {\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n resource_url?: string | null\n merchant_address?: string | null\n description?: string | null\n idempotency_key?: string | null\n}\n\n/** @internal */\nexport interface RawMppStateContext {\n amount_atomic?: string | null\n asset?: string | null\n network?: string | null\n resource_url?: string | null\n merchant_address?: string | null\n description?: string | null\n idempotency_key?: string | null\n challenge_id?: string | null\n}\n\n// ── Error Types ──────────────────────────────────────────────────\n\nexport class HavenError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly statusCode?: number,\n public readonly paymentId?: string,\n ) {\n super(message)\n this.name = 'HavenError'\n }\n}\n\nexport class HavenApiError extends HavenError {\n constructor(\n message: string,\n statusCode: number,\n public readonly body?: unknown,\n paymentId?: string,\n ) {\n super(message, 'API_ERROR', statusCode, paymentId)\n this.name = 'HavenApiError'\n }\n}\n\nexport class HavenPaymentStateError extends HavenApiError {\n resumeState?: X402ResumeState | MppResumeState\n\n constructor(\n message: string,\n statusCode: number,\n public readonly state: PaymentStatusResult,\n body?: unknown,\n ) {\n super(message, statusCode, body, state.paymentId)\n this.name = 'HavenPaymentStateError'\n }\n\n get status(): string {\n return this.state.status\n }\n\n get phase(): PaymentPhase {\n return this.state.phase\n }\n\n get nextAction(): PaymentNextAction {\n return this.state.nextAction\n }\n}\n\nexport class HavenSigningError extends HavenError {\n constructor(message: string) {\n super(message, 'SIGNING_ERROR')\n this.name = 'HavenSigningError'\n }\n}\n\nexport class HavenTimeoutError extends HavenError {\n constructor(paymentId: string) {\n super(\n `Timed out waiting for payment ${paymentId} to confirm`,\n 'TIMEOUT',\n undefined,\n paymentId,\n )\n this.name = 'HavenTimeoutError'\n }\n}\n","import { ethers } from 'ethers'\nimport { HavenSigningError } from './types.js'\n\n/**\n * Sign a hash using raw ECDSA (no Ethereum message prefix).\n *\n * This matches what Safe's AllowanceModule `checkSignature` expects —\n * a direct ecrecover over the hash, NOT the \"\\x19Ethereum Signed Message\" variant.\n *\n * Uses ethers.SigningKey.sign() instead of wallet.signMessage() to avoid the prefix.\n */\nexport function signHash(privateKey: string, hash: string): string {\n try {\n const signingKey = new ethers.SigningKey(privateKey)\n const sig = signingKey.sign(hash)\n return sig.serialized // 0x + r(32) + s(32) + v(1)\n } catch (err) {\n throw new HavenSigningError(\n `Failed to sign hash: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Derive the Ethereum address from a private key.\n */\nexport function addressFromKey(privateKey: string): string {\n try {\n return new ethers.Wallet(privateKey).address\n } catch (err) {\n throw new HavenSigningError(\n `Invalid private key: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Verify that a signature over a hash recovers to the expected address.\n */\nexport function verifySignature(hash: string, signature: string, expectedAddress: string): boolean {\n try {\n const recovered = ethers.recoverAddress(hash, signature)\n return recovered.toLowerCase() === expectedAddress.toLowerCase()\n } catch {\n return false\n }\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 type { X402PaymentRequired, X402PaymentOption } from './types.js'\nimport type { PaymentRequirements } from 'x402/types'\n\nconst BASE_USDC_ADDRESS = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'\nconst X402_IDEMPOTENCY_BUCKET_MS = 300_000\n\nfunction decodeBase64Json<T>(value: string, label: string): T {\n try {\n return JSON.parse(atob(value)) as T\n } catch {\n throw new Error(`Failed to decode ${label}`)\n }\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\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 maxTimeoutSeconds: candidate.maxTimeoutSeconds ?? 30,\n extra: candidate.extra,\n }\n}\n\nfunction 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)\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 const 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 }\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:100': 'Gnosis Chain',\n 'eip155:8453': 'Base',\n 'base': 'Base',\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}\n\n// ── Token address maps ────────────────────────────────────────────\n\n/** Known tokens on Gnosis Chain (chainId 100). */\nconst GNOSIS_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n '0x0000000000000000000000000000000000000000': { symbol: 'xDAI', decimals: 18 },\n '0xcb444e90d8198415266c6a2724b7900fb12fc56e': { symbol: 'EURe', decimals: 18 },\n '0x2a22f9c3b484c3629090feed35f17ff8f88f76f0': { symbol: 'USDC.e', decimals: 6 },\n}\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/** All known tokens across all supported chains (for display / resolution). */\nconst ALL_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n ...GNOSIS_TOKENS,\n ...BASE_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:100': GNOSIS_TOKENS,\n 'eip155:8453': BASE_TOKENS,\n 'base': BASE_TOKENS,\n}\n\n// ── Parser ───────────────────────────────────────────────────────\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 (networkTokens?.[opt.asset.toLowerCase()]) return opt\n }\n }\n\n // Second pass: any supported network\n for (const opt of accepts) {\n if (opt.network in SUPPORTED_X402_NETWORKS) {\n return opt\n }\n }\n\n // No compatible option found\n return null\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 */\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 if (\n opt.scheme === 'exact' &&\n opt.network in STANDARD_X402_NETWORKS &&\n opt.asset.toLowerCase() === BASE_USDC_ADDRESS\n ) {\n return opt\n }\n }\n\n return null\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 return {\n scheme: 'exact',\n network,\n maxAmountRequired: option.maxAmountRequired ?? option.amount,\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 maxTimeoutSeconds: option.maxTimeoutSeconds,\n extra: option.extra,\n }\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 option.amount,\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 btoa(JSON.stringify(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:100\").\n */\nexport function resolveTokenFromAddress(\n address: string,\n network?: string,\n): { symbol: string; decimals: number } | null {\n const lower = address.toLowerCase()\n\n if (network && network in NETWORK_TOKENS) {\n return NETWORK_TOKENS[network][lower] ?? null\n }\n\n return ALL_TOKENS[lower] ?? null\n}\n","import { createHash } from 'node:crypto'\nimport type {\n MachinePaymentChallenge,\n MachinePaymentReceipt,\n} from './types.js'\n\nfunction decodeBase64Json<T>(value: string, label: string): T {\n try {\n return JSON.parse(atob(value)) as T\n } catch {\n throw new Error(`Failed to decode ${label}`)\n }\n}\n\nfunction normalizeChallenge(value: unknown): MachinePaymentChallenge | null {\n const candidate = value as Partial<MachinePaymentChallenge> | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n candidate.rail !== 'mpp_demo' ||\n typeof candidate.version !== 'string' ||\n typeof candidate.challengeId !== 'string' ||\n typeof candidate.resource !== 'string' ||\n typeof candidate.description !== 'string' ||\n // TODO: relax these checks when non-demo machine payment rails are added.\n candidate.network?.chainId !== 8453 ||\n candidate.network?.name !== 'base' ||\n candidate.asset?.symbol !== 'USDC' ||\n typeof candidate.asset?.address !== 'string' ||\n candidate.asset.decimals !== 6 ||\n typeof candidate.amount?.display !== 'string' ||\n typeof candidate.amount?.atomic !== 'string' ||\n typeof candidate.recipient !== 'string' ||\n typeof candidate.expiresAt !== 'string'\n ) {\n return null\n }\n\n return {\n rail: candidate.rail,\n version: candidate.version,\n challengeId: candidate.challengeId,\n resource: candidate.resource,\n description: candidate.description,\n network: candidate.network,\n asset: candidate.asset,\n amount: candidate.amount,\n recipient: candidate.recipient,\n expiresAt: candidate.expiresAt,\n metadata: candidate.metadata,\n }\n}\n\nexport function parseMachinePaymentChallenge(response: Response): MachinePaymentChallenge {\n const header = response.headers.get('MACHINE-PAYMENT-CHALLENGE')\n if (!header) {\n throw new Error('No MACHINE-PAYMENT-CHALLENGE header found in 402 response.')\n }\n\n const parsed = normalizeChallenge(\n decodeBase64Json<unknown>(header, 'MACHINE-PAYMENT-CHALLENGE header'),\n )\n if (!parsed) throw new Error('Invalid machine payment challenge')\n return parsed\n}\n\nexport async function parseMachinePaymentChallengeResponse(\n response: Response,\n): Promise<MachinePaymentChallenge> {\n try {\n return parseMachinePaymentChallenge(response)\n } catch (headerErr) {\n try {\n const body = await response.clone().json() as { challenge?: unknown }\n const parsed = normalizeChallenge(body.challenge)\n if (parsed) return parsed\n } catch {\n // Fall through to the original, more specific header error.\n }\n\n throw headerErr\n }\n}\n\nexport function buildMachinePaymentIdempotencyKey(\n challenge: MachinePaymentChallenge,\n): string {\n const material = [\n challenge.rail,\n challenge.challengeId,\n challenge.resource,\n challenge.recipient.toLowerCase(),\n challenge.asset.address.toLowerCase(),\n challenge.amount.atomic,\n challenge.network.chainId,\n ].join('|')\n\n return `${challenge.rail}:${createHash('sha256').update(material).digest('hex').slice(0, 16)}`\n}\n\nexport function encodeMachinePaymentProof(receipt: Omit<MachinePaymentReceipt, 'proofHeader'>): string {\n return btoa(JSON.stringify({\n rail: receipt.rail,\n challengeId: receipt.challengeId,\n paymentId: receipt.paymentId,\n txHash: receipt.txHash,\n settledVia: 'haven',\n payer: receipt.payer,\n chainId: receipt.chainId,\n }))\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { exact } from 'x402/schemes'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport { signHash, addressFromKey, verifySignature } from './signer.js'\nimport type {\n HavenClientConfig,\n PaymentRequest,\n PaymentIntent,\n PaymentResult,\n PaymentStatus,\n PaymentPhase,\n PaymentNextAction,\n PaymentStatusResult,\n PaymentResumeState,\n SignData,\n X402AuthorizationOptions,\n RawCreateResponse,\n RawSignResponse,\n RawStatusResponse,\n RawPaymentStatusResult,\n X402PaymentRequired,\n X402PaymentOption,\n X402Quote,\n X402Receipt,\n X402RequestSnapshot,\n X402ResumeState,\n ResumeAuthorizedX402Input,\n ResumeX402PaymentInput,\n MppAuthorizationOptions,\n MppQuote,\n MppResumeState,\n ResumeAuthorizedMppInput,\n ResumeMppPaymentInput,\n RawX402AuthorizeResponse,\n MachinePaymentChallenge,\n MachinePaymentReceipt,\n RawMachinePaymentAuthorizeResponse,\n HavenAgent,\n HavenAllowanceSummary,\n HavenPaymentReceipt,\n RawHavenAgent,\n RawHavenAllowanceSummary,\n RawHavenPaymentReceiptsResponse,\n RawHavenPaymentReceipt,\n} from './types.js'\nimport {\n AgentPaymentNextAction,\n AgentPaymentPhase,\n HavenApiError,\n HavenPaymentStateError,\n HavenSigningError,\n HavenTimeoutError,\n} from './types.js'\nimport {\n buildX402IdempotencyKey,\n parsePaymentRequiredResponse,\n resolveTokenFromAddress,\n selectStandardPaymentOption,\n toStandardPaymentRequirements,\n} from './x402.js'\nimport {\n buildMachinePaymentIdempotencyKey,\n encodeMachinePaymentProof,\n parseMachinePaymentChallengeResponse,\n} from './mpp.js'\n\nconst DEFAULT_BASE_URL = 'http://localhost:3001'\n\nconst CHAIN_EXPLORER_TX: Record<number, string> = {\n 100: 'https://gnosisscan.io/tx',\n 8453: 'https://basescan.org/tx',\n}\n\nfunction buildExplorerUrl(chainId: number | undefined, txHash: string): string {\n const base = CHAIN_EXPLORER_TX[chainId ?? 8453] ?? CHAIN_EXPLORER_TX[8453]\n return `${base}/${txHash}`\n}\n\nfunction explorerUrlOrEmpty(chainId: number | undefined, txHash: string | null | undefined): string {\n return txHash ? buildExplorerUrl(chainId, txHash) : ''\n}\n\nconst DEFAULT_REQUEST_TIMEOUT = 30_000\nconst DEFAULT_CONFIRMATION_TIMEOUT = 90_000\nconst DEFAULT_POLLING_INTERVAL = 3_000\n\nconst PAYMENT_STATE_STATUS_CODES: Record<string, number> = {\n pending: 202,\n pending_approval: 202,\n approved: 202,\n proposed: 202,\n executed: 200,\n pending_signature: 409,\n submitted: 409,\n expired: 410,\n failed: 502,\n rejected: 409,\n}\n\nfunction chainIdFromNetwork(network: string | undefined): number | undefined {\n if (network === 'base') return 8453\n if (!network?.startsWith('eip155:')) return undefined\n const chainId = Number(network.slice('eip155:'.length))\n return Number.isFinite(chainId) ? chainId : undefined\n}\n\nfunction chainIdOrNull(network: string | undefined): number | null {\n return chainIdFromNetwork(network) ?? null\n}\n\nfunction phaseForStatus(status: string): PaymentPhase | null {\n if (status === 'pending_signature') return AgentPaymentPhase.AgentSignatureRequired\n if (status === 'submitted') return AgentPaymentPhase.PaymentSubmitted\n if (status === 'confirmed') return AgentPaymentPhase.PaymentConfirmed\n if (status === 'pending' || status === 'pending_approval') return AgentPaymentPhase.UserApprovalRequired\n if (status === 'approved') return AgentPaymentPhase.UserExecutionRequired\n if (status === 'proposed') return AgentPaymentPhase.WaitingForAdditionalApprovals\n if (status === 'executed') return AgentPaymentPhase.FundingSent\n if (status === 'rejected') return AgentPaymentPhase.Rejected\n if (status === 'expired') return AgentPaymentPhase.Expired\n if (status === 'failed') return AgentPaymentPhase.Failed\n return null\n}\n\nfunction nextActionForStatus(status: string): PaymentNextAction | null {\n if (status === 'pending_signature') return AgentPaymentNextAction.SignAndSubmitPayment\n if (status === 'submitted') return AgentPaymentNextAction.CheckStatusLater\n if (status === 'confirmed') return AgentPaymentNextAction.None\n if (status === 'pending' || status === 'pending_approval') return AgentPaymentNextAction.WaitForUserApproval\n if (status === 'approved') return AgentPaymentNextAction.WaitForUserToCompletePayment\n if (status === 'proposed') return AgentPaymentNextAction.WaitForUserApproval\n if (status === 'executed') return AgentPaymentNextAction.RetryOriginalX402Request\n if (status === 'rejected') return AgentPaymentNextAction.StopAndTellUser\n if (status === 'expired') return AgentPaymentNextAction.RequestAgainIfUserStillWantsIt\n if (status === 'failed') return AgentPaymentNextAction.StopAndTellUser\n return null\n}\n\nfunction messageForState(\n label: string,\n status: string,\n paymentId: string,\n nextAction: PaymentNextAction,\n): string {\n if (status === 'pending' || status === 'pending_approval') {\n return `${label} is above the remaining agent budget and is waiting for user approval in Haven (payment_id: ${paymentId}).`\n }\n if (status === 'executed') {\n return 'The user completed the funding payment. Retry the original x402 request.'\n }\n if (status === 'rejected') {\n return `The user rejected this payment request (payment_id: ${paymentId}).`\n }\n if (status === 'expired') {\n return `This payment request expired (payment_id: ${paymentId}).`\n }\n return `${label} is ${status}; next_action=${nextAction} (payment_id: ${paymentId}).`\n}\n\nfunction sameAddress(a: string | null | undefined, b: string | null | undefined): boolean {\n return Boolean(a && b && a.toLowerCase() === b.toLowerCase())\n}\n\nfunction isMppRail(rail: string | null | undefined): boolean {\n return rail === 'mpp' || Boolean(rail?.startsWith('mpp_'))\n}\n\nfunction decimalFromUsdcAtomic(value: string): string {\n const amount = BigInt(value)\n const whole = amount / 1_000_000n\n const fraction = (amount % 1_000_000n).toString().padStart(6, '0').replace(/0+$/, '')\n return fraction ? `${whole}.${fraction}` : whole.toString()\n}\n\nfunction normalizeDecimal(value: string): string {\n if (!value.includes('.')) return value.replace(/^0+(?=\\d)/, '') || '0'\n const [whole, fraction = ''] = value.split('.')\n const normalizedWhole = whole.replace(/^0+(?=\\d)/, '') || '0'\n const normalizedFraction = fraction.replace(/0+$/, '')\n return normalizedFraction ? `${normalizedWhole}.${normalizedFraction}` : normalizedWhole\n}\n\nfunction parseMerchantSettlement(header: string | null): {\n settlementTxHash?: string | null\n} {\n if (!header) return {}\n const parsed = parseProtocolReceiptHeader(header)\n const tx =\n typeof parsed?.transaction === 'string'\n ? parsed.transaction\n : typeof parsed?.txHash === 'string'\n ? parsed.txHash\n : typeof parsed?.tx_hash === 'string'\n ? parsed.tx_hash\n : null\n return { settlementTxHash: tx }\n}\n\nexport class HavenClient {\n private readonly apiKey: string\n private readonly delegateKey: string | undefined\n private readonly baseUrl: string\n private readonly x402Wallet: string | undefined\n private readonly requestTimeout: number\n private readonly confirmationTimeout: number\n private readonly pollingInterval: number\n private readonly inFlightX402 = new Map<string, Promise<X402Receipt>>()\n private readonly x402ReceiptCache = new Map<string, { expiresAt: number; receipt: X402Receipt }>()\n private readonly inFlightMachinePayments = new Map<string, Promise<MachinePaymentReceipt>>()\n /**\n * Setup-time headers configured via `HavenClientConfig.defaultHeaders`.\n * Read-only after construction — use `withRequestContext` for per-call\n * scoping so concurrent requests don't race on shared mutable state.\n */\n private readonly defaultHeaders: Record<string, string>\n /**\n * Async-local store for per-request context (currently: extra headers).\n * Each `withRequestContext` invocation produces an isolated store, so\n * overlapping async work — like two MCP tool dispatches in flight at\n * the same time — see their own headers without stepping on each other.\n */\n private readonly requestContext = new AsyncLocalStorage<{ headers: Record<string, string> }>()\n\n /** Delegate address derived from the private key (if provided) */\n readonly delegateAddress: string | undefined\n\n constructor(config: HavenClientConfig) {\n this.apiKey = config.apiKey\n this.delegateKey = config.delegateKey\n this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n this.x402Wallet = config.x402Wallet\n this.requestTimeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT\n this.confirmationTimeout = config.confirmationTimeout ?? DEFAULT_CONFIRMATION_TIMEOUT\n this.pollingInterval = config.pollingInterval ?? DEFAULT_POLLING_INTERVAL\n this.defaultHeaders = { ...(config.defaultHeaders ?? {}) }\n\n if (this.delegateKey) {\n this.delegateAddress = addressFromKey(this.delegateKey)\n }\n }\n\n /**\n * Run `fn` with extra Haven-API headers scoped to the async work it\n * performs. Used by the MCP server to tag every Haven API request that\n * a single tool dispatch makes with `X-Haven-MCP-Tool: <name>` so the\n * backend can write an audit-log row attributing the call.\n *\n * The headers are held in an `AsyncLocalStorage` so overlapping\n * dispatches do not leak headers into each other's requests. The store\n * inherits across `await` boundaries, so any Haven API call made while\n * `fn` is awaiting will pick up the right headers.\n *\n * Has no effect on outbound merchant requests (x402 / MPP) — those\n * never go through the internal `request<T>` path that reads the\n * context.\n */\n withRequestContext<T>(headers: Record<string, string>, fn: () => Promise<T>): Promise<T> {\n return this.requestContext.run({ headers: { ...headers } }, fn)\n }\n\n // ── High-Level API ───────────────────────────────────────────────\n\n /**\n * Send a payment in one call.\n *\n * Creates the intent, signs the hash, submits the signature,\n * and polls until confirmed (or throws on failure/timeout).\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async pay(request: PaymentRequest): Promise<PaymentResult> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot use pay() without a delegateKey. Use createIntent() + submitSignature() for manual signing.',\n )\n }\n\n // Step 1: Create intent\n const intent = await this.createIntent(request)\n\n // Step 2: Sign\n const signature = this.sign(intent.signData.hash)\n\n // Step 3: Submit\n await this.submitSignature(intent.paymentId, signature)\n\n // Step 4: Wait for confirmation\n return this.waitForConfirmation(intent.paymentId)\n }\n\n // ── Step-by-Step API ─────────────────────────────────────────────\n\n /**\n * Step 1: Create a payment intent.\n *\n * Returns the intent with the hash to sign.\n */\n async createIntent(request: PaymentRequest): Promise<PaymentIntent> {\n const raw = await this.post<RawCreateResponse>('/payments', {\n token: request.token,\n amount: request.amount,\n to: request.to,\n })\n\n // Haven returns HTTP 202 with this status when the requested amount\n // exceeds the on-chain allowance. The payment is parked for the owner\n // to approve in the dashboard — there's nothing to sign yet, so the SDK\n // surfaces it as an explicit error rather than returning a malformed\n // intent with no signData.\n if (raw.status === 'pending_approval') {\n this.throwPaymentStateError('Payment', raw)\n }\n\n return {\n paymentId: raw.payment_id,\n status: 'pending_signature',\n expiresAt: raw.expires_at,\n signData: raw.sign_data,\n }\n }\n\n /**\n * Step 2: Sign a hash with the delegate key.\n *\n * Returns the 65-byte signature (0x-prefixed).\n * Requires `delegateKey` to be set in the client config.\n */\n sign(hash: string): string {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot sign without a delegateKey. Pass the private key in HavenClient config, or sign externally.',\n )\n }\n\n const signature = signHash(this.delegateKey, hash)\n\n // Verify the signature locally before submitting\n if (!verifySignature(hash, signature, this.delegateAddress!)) {\n throw new HavenSigningError(\n 'Local signature verification failed — recovered address does not match delegate key.',\n )\n }\n\n return signature\n }\n\n /**\n * Step 3: Submit a signature to execute the payment.\n *\n * The signature can come from `client.sign()` or from external signing.\n */\n async submitSignature(\n paymentId: string,\n signature: string,\n ): Promise<{ status: string; txHash?: string }> {\n const raw = await this.post<RawSignResponse>(\n `/payments/${paymentId}/sign`,\n { signature },\n )\n\n return {\n status: raw.status,\n txHash: raw.tx_hash,\n }\n }\n\n /**\n * Get the current status of a payment.\n */\n async getPayment(paymentId: string): Promise<PaymentResult> {\n const raw = await this.get<RawStatusResponse>(`/payments/${paymentId}`)\n return this.mapPaymentResult(raw)\n }\n\n /**\n * Get agent-actionable status for a payment intent or approval request.\n *\n * Use this for IDs returned by agent tools and machine-payment/x402 flows.\n * `getPayment()` remains available for payment-intent-only integrations.\n */\n async getPaymentStatus(paymentId: string): Promise<PaymentStatusResult> {\n const raw = await this.get<RawPaymentStatusResult>(`/machine-payments/${paymentId}/status`)\n return this.mapPaymentStatusResult(raw)\n }\n\n /**\n * Get the agent identity tied to this API key.\n */\n async getAgent(): Promise<HavenAgent> {\n const raw = await this.get<RawHavenAgent>('/machine-payments/agent')\n return {\n id: raw.id,\n name: raw.name,\n status: raw.status,\n safeAddress: raw.safe_address,\n delegateAddress: raw.delegate_address,\n chainId: raw.chain_id,\n }\n }\n\n /**\n * Get configured and on-chain allowances for the authenticated agent.\n */\n async getAllowances(): Promise<HavenAllowanceSummary> {\n const raw = await this.get<RawHavenAllowanceSummary>('/machine-payments/allowances')\n return {\n agentId: raw.agent_id,\n safeAddress: raw.safe_address,\n delegateAddress: raw.delegate_address,\n chainId: raw.chain_id,\n allowances: raw.allowances.map((allowance) => ({\n id: allowance.id,\n tokenAddress: allowance.token_address,\n tokenSymbol: allowance.token_symbol,\n configuredAmount: allowance.configured_amount,\n resetPeriodMin: allowance.reset_period_min,\n onchain: {\n amount: allowance.onchain.amount,\n spent: allowance.onchain.spent,\n remaining: allowance.onchain.remaining,\n effectiveSpent: allowance.onchain.effective_spent,\n resetTimeMin: allowance.onchain.reset_time_min,\n lastResetMin: allowance.onchain.last_reset_min,\n nonce: allowance.onchain.nonce,\n isResetPending: allowance.onchain.is_reset_pending,\n },\n })),\n }\n }\n\n /**\n * List recent machine-payment receipts/evidence for bookkeeping.\n */\n async listReceipts(options: { limit?: number } = {}): Promise<HavenPaymentReceipt[]> {\n const query = options.limit ? `?limit=${encodeURIComponent(String(options.limit))}` : ''\n const raw = await this.get<RawHavenPaymentReceiptsResponse>(`/machine-payments/receipts${query}`)\n return raw.receipts.map((receipt) => this.mapPaymentReceipt(receipt))\n }\n\n /**\n * Rehydrate the x402/MPP resume-state bundle for a payment id.\n *\n * The server returns stored protocol context only. The client still signs the\n * merchant proof locally when resumeX402Payment() or resumeMppPayment() runs.\n */\n async getResumeState(paymentId: string): Promise<PaymentResumeState> {\n return this.get<PaymentResumeState>(`/payments/${paymentId}/resume_state`)\n }\n\n /**\n * Poll until a payment reaches a terminal status (confirmed, failed, expired).\n */\n async waitForConfirmation(paymentId: string): Promise<PaymentResult> {\n const deadline = Date.now() + this.confirmationTimeout\n\n while (Date.now() < deadline) {\n const result = await this.getPayment(paymentId)\n\n if (result.status === 'confirmed' || result.status === 'failed' || result.status === 'expired') {\n return result\n }\n\n await sleep(this.pollingInterval)\n }\n\n throw new HavenTimeoutError(paymentId)\n }\n\n // ── x402 Protocol Support ────────────────────────────────────────\n\n /**\n * Authorize an x402 payment.\n *\n * Takes the parsed PaymentRequired from a 402 response, selects a compatible\n * option, funds the delegate wallet through Haven, and returns the standard\n * x402 header that the merchant can verify and settle.\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async authorizeX402(\n paymentRequired: X402PaymentRequired,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Receipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for x402 payments. Pass it in the HavenClient config.',\n )\n }\n if (!this.delegateAddress) {\n throw new HavenSigningError('delegateAddress could not be derived from delegateKey.')\n }\n\n // 1. Select best payment option\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.',\n 400,\n )\n }\n\n const idempotencyKey = options.idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option)\n const cached = this.x402ReceiptCache.get(idempotencyKey)\n if (cached && cached.expiresAt > Date.now()) return cached.receipt\n\n const inFlight = this.inFlightX402.get(idempotencyKey)\n if (inFlight) return inFlight\n\n const promise = this.authorizeStandardX402(paymentRequired, option, idempotencyKey)\n this.inFlightX402.set(idempotencyKey, promise)\n\n try {\n return await promise\n } catch (err) {\n this.attachResumeState(err, {\n rail: 'x402',\n paymentRequired,\n accepted: option,\n idempotencyKey,\n })\n throw err\n } finally {\n this.inFlightX402.delete(idempotencyKey)\n }\n }\n\n /**\n * Probe a paid endpoint and return its x402 quote without creating a Haven\n * payment or approval request.\n */\n async quoteX402(\n url: string,\n init?: RequestInit,\n options: X402AuthorizationOptions = {},\n ): Promise<X402Quote> {\n const initialInit = this.withX402Wallet(init, this.x402PayerAddress())\n const request = this.snapshotX402Request(url, initialInit)\n const response = await globalThis.fetch(url, initialInit)\n\n if (response.status !== 402) {\n throw new HavenApiError(\n `Expected an x402 quote response with HTTP 402, got HTTP ${response.status}.`,\n response.status || 400,\n )\n }\n\n if (response.headers.get('MACHINE-PAYMENT-CHALLENGE')) {\n throw new HavenApiError('quoteX402 only supports standard x402 Payment Required responses.', 400)\n }\n\n const paymentRequired = await parsePaymentRequiredResponse(response)\n return this.buildX402Quote(paymentRequired, request, options.idempotencyKey)\n }\n\n /**\n * Pay a previously inspected x402 quote and retry the exact captured request.\n */\n async payX402Quote(\n quote: X402Quote,\n options: X402AuthorizationOptions = {},\n ): Promise<Response> {\n const idempotencyKey = options.idempotencyKey ?? quote.idempotencyKey\n\n try {\n const receipt = await this.authorizeX402(quote.paymentRequired, { idempotencyKey })\n return this.retryX402Request(\n quote.request.url,\n this.requestInitFromSnapshot(quote.request),\n quote.paymentRequired,\n receipt,\n )\n } catch (err) {\n this.attachResumeState(err, {\n rail: 'x402',\n paymentRequired: quote.paymentRequired,\n accepted: quote.accepted,\n idempotencyKey,\n request: quote.request,\n })\n throw err\n }\n }\n\n private async authorizeStandardX402(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n idempotencyKey: string,\n ): Promise<X402Receipt> {\n // 2. Standard x402 settles from an EOA, so the SDK uses the agent-owned\n // delegate EOA for the merchant-facing EIP-3009 authorization. Haven does\n // not control this EOA or its private key.\n //\n // The only automated funding path is a separate Safe AllowanceModule\n // transfer signed by the agent key and constrained by the user's on-chain\n // allowance. Haven's backend relays that signed top-up; it is not the source\n // of payment authority.\n // Sign before funding so retries reuse one EIP-3009 nonce. If funding fails,\n // the unused authorization simply expires via validBefore.\n const paymentHeader = await this.createStandardX402Header(paymentRequired, option)\n const raw = await this.post<RawX402AuthorizeResponse>('/x402', {\n url: paymentRequired.resource.url,\n payTo: this.delegateAddress,\n merchantPayTo: option.payTo,\n amount: option.amount,\n asset: option.asset,\n network: option.network,\n description: paymentRequired.resource.description,\n idempotencyKey,\n })\n\n // If the backend already executed (shouldn't happen without sig), return\n if (raw.success && raw.tx_hash) {\n const receipt = this.mapX402ReceiptFromAuthorization(paymentRequired, option, paymentHeader, raw)\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n const state = this.paymentStateFromRaw('x402 payment', raw)\n if (state?.nextAction === AgentPaymentNextAction.RetryOriginalX402Request) {\n const receipt = this.mapX402ReceiptFromStatus(paymentRequired, option, paymentHeader, state)\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n this.throwIfNonSignableAuthorizationState('x402 payment', raw)\n\n // 3. Sign the hash\n if (!raw.sign_data?.hash) {\n throw new HavenApiError('No sign_hash returned from x402/authorize', 500, raw)\n }\n const sig = signHash(this.delegateKey!, raw.sign_data.hash)\n\n // 4. Submit signature (reuse existing payments/:id/sign endpoint)\n const execResult = await this.post<RawSignResponse>(\n `/payments/${raw.payment_id}/sign`,\n { signature: sig },\n )\n\n if (execResult.status !== 'confirmed') {\n this.throwPaymentStateError('x402 payment', execResult)\n }\n\n const receipt = this.mapX402ReceiptFromAuthorization(paymentRequired, option, paymentHeader, raw, execResult)\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n async resumeAuthorizedX402(input: ResumeAuthorizedX402Input): Promise<X402Receipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for x402 payments. Pass it in the HavenClient config.',\n )\n }\n if (!this.delegateAddress) {\n throw new HavenSigningError('delegateAddress could not be derived from delegateKey.')\n }\n\n const option = selectStandardPaymentOption(input.paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.',\n 400,\n )\n }\n\n const idempotencyKey = input.idempotencyKey ?? buildX402IdempotencyKey(input.paymentRequired, option)\n const cached = this.x402ReceiptCache.get(idempotencyKey)\n if (cached && cached.expiresAt > Date.now()) return cached.receipt\n\n const status = await this.getPaymentStatus(input.paymentId)\n this.assertCanResumeX402(status, input.paymentRequired, option)\n\n const paymentHeader = await this.createStandardX402Header(input.paymentRequired, option)\n const receipt = this.mapX402ReceiptFromStatus(input.paymentRequired, option, paymentHeader, status)\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n async resumeX402Payment(input: ResumeX402PaymentInput | X402ResumeState): Promise<Response> {\n const inputInit = 'init' in input ? input.init : undefined\n const initialInit = this.withX402Wallet(\n inputInit ?? (input.request ? this.requestInitFromSnapshot(input.request) : undefined),\n this.x402PayerAddress(),\n )\n let paymentRequired = input.paymentRequired\n const url = input.url ?? input.request?.url\n\n if (!paymentRequired) {\n if (!url) {\n throw new HavenApiError('x402 resume requires the original URL or a captured request snapshot.', 400)\n }\n const response = await globalThis.fetch(url, initialInit)\n if (response.status !== 402) {\n throw new HavenApiError('Expected the original x402 request to return HTTP 402 before resuming.', 400)\n }\n paymentRequired = await parsePaymentRequiredResponse(response)\n }\n\n const receipt = await this.resumeAuthorizedX402({\n paymentId: input.paymentId,\n paymentRequired,\n idempotencyKey: input.idempotencyKey,\n })\n\n return this.retryX402Request(url ?? paymentRequired.resource.url, initialInit, paymentRequired, receipt)\n }\n\n /**\n * Fetch wrapper that automatically handles HTTP 402 responses.\n *\n * Works like the standard `fetch()` but intercepts 402 responses,\n * pays via x402 through Haven, and retries the request.\n *\n * ```ts\n * const response = await haven.fetch('https://paid-api.com/data')\n * const data = await response.json()\n * ```\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async fetch(\n url: string,\n init?: RequestInit,\n options: X402AuthorizationOptions = {},\n ): Promise<Response> {\n const initialInit = this.withX402Wallet(init, this.x402PayerAddress())\n\n // 1. Make the original request\n const response = await globalThis.fetch(url, initialInit)\n\n // 2. Not a 402 — return as-is\n if (response.status !== 402) return response\n\n const machineChallengeHeader = response.headers.get('MACHINE-PAYMENT-CHALLENGE')\n if (machineChallengeHeader) {\n const challenge = await parseMachinePaymentChallengeResponse(response)\n return this.fetchWithMachinePayment(url, initialInit, challenge)\n }\n\n // 3. Parse x402 payment requirements\n let paymentRequired: X402PaymentRequired\n try {\n paymentRequired = await parsePaymentRequiredResponse(response)\n } catch {\n let challenge: MachinePaymentChallenge\n try {\n challenge = await parseMachinePaymentChallengeResponse(response)\n } catch {\n // Not a Haven machine-payment 402 — return original response\n return response\n }\n return this.fetchWithMachinePayment(url, initialInit, challenge)\n }\n\n // 4. Pay through Haven\n const request = this.snapshotX402Request(url, initialInit)\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n const idempotencyKey = options.idempotencyKey ?? (option ? buildX402IdempotencyKey(paymentRequired, option) : undefined)\n let receipt: X402Receipt\n try {\n receipt = await this.authorizeX402(paymentRequired, options)\n } catch (err) {\n if (option && idempotencyKey) {\n this.attachResumeState(err, {\n rail: 'x402',\n paymentRequired,\n accepted: option,\n idempotencyKey,\n request,\n })\n }\n throw err\n }\n return this.retryX402Request(url, initialInit, paymentRequired, receipt)\n }\n\n /**\n * Probe a paid MPP endpoint or inspect an existing challenge without creating\n * a Haven payment or approval request.\n */\n async quoteMpp(\n challengeOrUrl: MachinePaymentChallenge | string,\n init?: RequestInit,\n options: MppAuthorizationOptions = {},\n ): Promise<MppQuote> {\n if (typeof challengeOrUrl !== 'string') {\n const request = this.snapshotX402Request(challengeOrUrl.resource, init)\n return this.buildMppQuote(challengeOrUrl, request, options.idempotencyKey)\n }\n\n const request = this.snapshotX402Request(challengeOrUrl, init)\n const response = await globalThis.fetch(challengeOrUrl, init)\n\n if (response.status !== 402) {\n throw new HavenApiError(\n `Expected an MPP quote response with HTTP 402, got HTTP ${response.status}.`,\n response.status || 400,\n )\n }\n\n const challenge = await parseMachinePaymentChallengeResponse(response)\n return this.buildMppQuote(challenge, request, options.idempotencyKey)\n }\n\n /**\n * Pay a previously inspected MPP quote and retry the exact captured request.\n */\n async payMppChallenge(\n quote: MppQuote,\n options: MppAuthorizationOptions = {},\n ): Promise<Response> {\n const idempotencyKey = options.idempotencyKey ?? quote.idempotencyKey\n\n try {\n const receipt = await this.authorizeMachinePayment(quote.challenge, { idempotencyKey })\n return this.retryMppRequest(\n quote.request.url,\n this.requestInitFromSnapshot(quote.request),\n quote.challenge,\n receipt,\n )\n } catch (err) {\n this.attachResumeState(err, {\n rail: 'mpp',\n challenge: quote.challenge,\n idempotencyKey,\n request: quote.request,\n })\n throw err\n }\n }\n\n private async retryX402Request(\n url: string,\n initialInit: RequestInit | undefined,\n paymentRequired: X402PaymentRequired,\n receipt: X402Receipt,\n ): Promise<Response> {\n if (!receipt.accepted) {\n throw new HavenApiError('No accepted x402 option was recorded for payment retry', 500)\n }\n if (!receipt.paymentHeader) {\n throw new HavenApiError('No x402 payment header was returned for payment retry', 500)\n }\n\n // 5. Retry with a merchant-verifiable x402 EIP-3009 payment header.\n const retryHeaders = new Headers(initialInit?.headers)\n retryHeaders.set('X-PAYMENT', receipt.paymentHeader)\n\n const retryResponse = await globalThis.fetch(url, {\n ...initialInit,\n headers: retryHeaders,\n })\n\n if (retryResponse.status === 402) {\n await this.recordMerchantRetryRejected({\n rail: 'x402',\n paymentId: receipt.paymentId,\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n retryResponse,\n details: {\n merchant_to: receipt.merchantTo,\n delegate_to: receipt.to,\n },\n })\n\n throw new HavenApiError(\n 'x402 retry was rejected after Haven funded the delegate wallet; reconciliation may be required.',\n 402,\n {\n marker: 'x402_retry_rejected_after_funding',\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n resource_url: receipt.resourceUrl,\n merchant_to: receipt.merchantTo,\n delegate_to: receipt.to,\n },\n )\n }\n\n const merchantSettlement = parseMerchantSettlement(retryResponse.headers.get('PAYMENT-RESPONSE'))\n if (receipt.merchant && merchantSettlement.settlementTxHash) {\n receipt.merchant.settlementTxHash = merchantSettlement.settlementTxHash\n receipt.merchant.settlementExplorerUrl = buildExplorerUrl(\n receipt.chainId,\n merchantSettlement.settlementTxHash,\n )\n }\n\n await this.reportMachinePaymentEvidence({\n paymentId: receipt.paymentId,\n rail: 'x402',\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n merchantStatus: retryResponse.status,\n challengePayload: paymentRequired as unknown as Record<string, unknown>,\n selectedPayment: receipt.accepted as unknown as Record<string, unknown>,\n paymentProofHeaderName: 'X-PAYMENT',\n paymentProofHeader: receipt.paymentHeader,\n protocolReceiptHeaderName: 'PAYMENT-RESPONSE',\n protocolReceiptHeader: retryResponse.headers.get('PAYMENT-RESPONSE') ?? undefined,\n })\n\n return retryResponse\n }\n\n async authorizeMachinePayment(\n challenge: MachinePaymentChallenge,\n options: MppAuthorizationOptions = {},\n ): Promise<MachinePaymentReceipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for machine payments. Pass it in the HavenClient config.',\n )\n }\n\n if (challenge.rail !== 'mpp_demo') {\n throw new HavenApiError(`Unsupported machine payment rail: ${challenge.rail}`, 400)\n }\n\n const idempotencyKey = options.idempotencyKey ?? buildMachinePaymentIdempotencyKey(challenge)\n const inFlight = this.inFlightMachinePayments.get(idempotencyKey)\n if (inFlight) return inFlight\n\n const promise = this.authorizeMppDemoPayment(challenge, idempotencyKey)\n this.inFlightMachinePayments.set(idempotencyKey, promise)\n\n try {\n return await promise\n } catch (err) {\n this.attachResumeState(err, {\n rail: 'mpp',\n challenge,\n idempotencyKey,\n })\n throw err\n } finally {\n this.inFlightMachinePayments.delete(idempotencyKey)\n }\n }\n\n private async authorizeMppDemoPayment(\n challenge: MachinePaymentChallenge,\n idempotencyKey: string,\n ): Promise<MachinePaymentReceipt> {\n const raw = await this.post<RawMachinePaymentAuthorizeResponse>(\n '/machine-payments/authorize',\n { challenge, idempotencyKey },\n )\n\n if (raw.success && raw.tx_hash) {\n return this.mapMachinePaymentReceipt(challenge, raw, raw.tx_hash)\n }\n\n this.throwIfNonSignableAuthorizationState('Machine payment', raw)\n\n if (!raw.sign_data?.hash) {\n throw new HavenApiError('No sign_hash returned from machine payment authorization', 500, raw)\n }\n\n const sig = signHash(this.delegateKey!, raw.sign_data.hash)\n const execResult = await this.post<RawSignResponse>(\n `/payments/${raw.payment_id}/sign`,\n { signature: sig },\n )\n\n if (execResult.status !== 'confirmed' || !execResult.tx_hash) {\n this.throwPaymentStateError('Machine payment', execResult)\n }\n\n return this.mapMachinePaymentReceipt(challenge, raw, execResult.tx_hash, execResult)\n }\n\n async resumeAuthorizedMpp(input: ResumeAuthorizedMppInput): Promise<MachinePaymentReceipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for machine payments. Pass it in the HavenClient config.',\n )\n }\n\n const status = await this.getPaymentStatus(input.paymentId)\n this.assertCanResumeMpp(status, input.challenge)\n\n return this.mapMachinePaymentReceiptFromStatus(input.challenge, status)\n }\n\n async resumeMppPayment(input: ResumeMppPaymentInput | MppResumeState): Promise<Response> {\n const inputInit = 'init' in input ? input.init : undefined\n const initialInit = inputInit ?? (input.request ? this.requestInitFromSnapshot(input.request) : undefined)\n let challenge = input.challenge\n const url = input.url ?? input.request?.url\n\n if (!challenge) {\n if (!url) {\n throw new HavenApiError('MPP resume requires the original URL or a captured request snapshot.', 400)\n }\n const response = await globalThis.fetch(url, initialInit)\n if (response.status !== 402) {\n throw new HavenApiError('Expected the original MPP request to return HTTP 402 before resuming.', 400)\n }\n challenge = await parseMachinePaymentChallengeResponse(response)\n }\n\n const receipt = await this.resumeAuthorizedMpp({\n paymentId: input.paymentId,\n challenge,\n idempotencyKey: input.idempotencyKey,\n })\n\n return this.retryMppRequest(url ?? challenge.resource, initialInit, challenge, receipt)\n }\n\n private async fetchWithMachinePayment(\n url: string,\n initialInit: RequestInit | undefined,\n challenge: MachinePaymentChallenge,\n ): Promise<Response> {\n const request = this.snapshotX402Request(url, initialInit)\n const idempotencyKey = buildMachinePaymentIdempotencyKey(challenge)\n let receipt: MachinePaymentReceipt\n try {\n receipt = await this.authorizeMachinePayment(challenge, { idempotencyKey })\n } catch (err) {\n this.attachResumeState(err, {\n rail: 'mpp',\n challenge,\n idempotencyKey,\n request,\n })\n throw err\n }\n\n return this.retryMppRequest(url, initialInit, challenge, receipt)\n }\n\n private async retryMppRequest(\n url: string,\n initialInit: RequestInit | undefined,\n challenge: MachinePaymentChallenge,\n receipt: MachinePaymentReceipt,\n ): Promise<Response> {\n const retryHeaders = new Headers(initialInit?.headers)\n retryHeaders.set('MACHINE-PAYMENT-PROOF', receipt.proofHeader)\n\n const retryResponse = await globalThis.fetch(url, {\n ...initialInit,\n headers: retryHeaders,\n })\n\n if (retryResponse.status === 402) {\n await this.recordMerchantRetryRejected({\n rail: receipt.rail,\n paymentId: receipt.paymentId,\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n retryResponse,\n details: {\n challenge_id: receipt.challengeId,\n },\n })\n\n throw new HavenApiError(\n 'Machine payment retry was rejected after Haven sent the payment.',\n 402,\n {\n marker: 'machine_payment_retry_rejected_after_payment',\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n resource_url: receipt.resourceUrl,\n rail: receipt.rail,\n },\n )\n }\n\n await this.reportMachinePaymentEvidence({\n paymentId: receipt.paymentId,\n rail: receipt.rail,\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n merchantStatus: retryResponse.status,\n challengePayload: challenge as unknown as Record<string, unknown>,\n paymentProofHeaderName: 'MACHINE-PAYMENT-PROOF',\n paymentProofHeader: receipt.proofHeader,\n protocolReceiptHeaderName:\n retryResponse.headers.has('Payment-Receipt')\n ? 'Payment-Receipt'\n : retryResponse.headers.has('MACHINE-PAYMENT-RESPONSE')\n ? 'MACHINE-PAYMENT-RESPONSE'\n : undefined,\n protocolReceiptHeader:\n retryResponse.headers.get('Payment-Receipt') ??\n retryResponse.headers.get('MACHINE-PAYMENT-RESPONSE') ??\n undefined,\n })\n\n return retryResponse\n }\n\n private assertCanResumeX402(\n status: PaymentStatusResult,\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n ): void {\n if (status.rail !== 'x402') {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} is ${status.rail}, not x402.`,\n 409,\n status,\n )\n }\n\n if (status.nextAction !== AgentPaymentNextAction.RetryOriginalX402Request) {\n throw new HavenPaymentStateError(status.message, PAYMENT_STATE_STATUS_CODES[status.status] ?? 409, status)\n }\n\n if (!status.txHash) {\n throw new HavenApiError(\n `x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n if (status.resourceUrl && status.resourceUrl !== paymentRequired.resource.url) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved resource URL.',\n 409,\n { status, paymentRequired },\n status.paymentId,\n )\n }\n\n if (status.merchantAddress && !sameAddress(status.merchantAddress, option.payTo)) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved merchant.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n\n const optionChainId = chainIdFromNetwork(option.network)\n if (status.chainId && optionChainId && status.chainId !== optionChainId) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved network.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n\n if (status.token && status.token !== 'USDC') {\n throw new HavenApiError(\n 'x402 resume request does not match the approved token.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n\n const approvedAmount = status.amount ? normalizeDecimal(status.amount) : ''\n const requestedAmount = normalizeDecimal(decimalFromUsdcAtomic(option.amount))\n if (approvedAmount && approvedAmount !== requestedAmount) {\n throw new HavenApiError(\n 'x402 resume request does not match the approved amount.',\n 409,\n { status, selectedPayment: option },\n status.paymentId,\n )\n }\n }\n\n private assertCanResumeMpp(\n status: PaymentStatusResult,\n challenge: MachinePaymentChallenge,\n ): void {\n if (!isMppRail(status.rail)) {\n throw new HavenPaymentStateError(\n `Payment ${status.paymentId} is ${status.rail}, not MPP.`,\n 409,\n status,\n )\n }\n\n if (status.nextAction !== AgentPaymentNextAction.RetryOriginalX402Request) {\n throw new HavenPaymentStateError(status.message, PAYMENT_STATE_STATUS_CODES[status.status] ?? 409, status)\n }\n\n if (!status.txHash) {\n throw new HavenApiError(\n `MPP payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n if (status.resourceUrl && status.resourceUrl !== challenge.resource) {\n throw new HavenApiError(\n 'MPP resume request does not match the approved resource URL.',\n 409,\n { status, challenge },\n status.paymentId,\n )\n }\n\n if (status.merchantAddress && !sameAddress(status.merchantAddress, challenge.recipient)) {\n throw new HavenApiError(\n 'MPP resume request does not match the approved merchant.',\n 409,\n { status, challenge },\n status.paymentId,\n )\n }\n\n if (status.chainId && status.chainId !== challenge.network.chainId) {\n throw new HavenApiError(\n 'MPP resume request does not match the approved network.',\n 409,\n { status, challenge },\n status.paymentId,\n )\n }\n\n if (status.token && status.token !== challenge.asset.symbol) {\n throw new HavenApiError(\n 'MPP resume request does not match the approved token.',\n 409,\n { status, challenge },\n status.paymentId,\n )\n }\n\n const approvedAmount = status.amount ? normalizeDecimal(status.amount) : ''\n const requestedAmount = normalizeDecimal(challenge.amount.display)\n if (approvedAmount && approvedAmount !== requestedAmount) {\n throw new HavenApiError(\n 'MPP resume request does not match the approved amount.',\n 409,\n { status, challenge },\n status.paymentId,\n )\n }\n }\n\n private mapX402ReceiptFromAuthorization(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n paymentHeader: string,\n raw: RawX402AuthorizeResponse,\n execResult?: RawSignResponse,\n ): X402Receipt {\n const txHash = execResult?.tx_hash ?? raw.tx_hash ?? ''\n const chainId = execResult?.chain_id ?? raw.chain_id ?? chainIdFromNetwork(option.network)\n const token = execResult?.token ?? raw.token ?? 'USDC'\n const amount = execResult?.amount ?? raw.amount ?? decimalFromUsdcAtomic(option.amount)\n const to = execResult?.to ?? raw.to ?? this.delegateAddress ?? ''\n const explorerUrl = execResult?.explorer_url ?? raw.explorer_url ?? explorerUrlOrEmpty(chainId, txHash)\n const merchantTo = execResult?.merchant_to ?? raw.merchant_to ?? option.payTo\n const payer = raw.payer ?? raw.safe_address ?? raw.sign_data?.components.safe\n\n return this.buildX402Receipt({\n paymentId: raw.payment_id,\n txHash,\n token,\n amount,\n to,\n resourceUrl: paymentRequired.resource.url,\n explorerUrl,\n accepted: option,\n paymentHeader,\n merchantTo,\n payer,\n chainId,\n })\n }\n\n private mapX402ReceiptFromStatus(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n paymentHeader: string,\n status: PaymentStatusResult,\n ): X402Receipt {\n if (!status.txHash) {\n throw new HavenApiError(\n `x402 payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n return this.buildX402Receipt({\n paymentId: status.paymentId,\n txHash: status.txHash,\n token: status.token || 'USDC',\n amount: status.amount || decimalFromUsdcAtomic(option.amount),\n to: this.delegateAddress ?? '',\n resourceUrl: paymentRequired.resource.url,\n explorerUrl: explorerUrlOrEmpty(status.chainId, status.txHash),\n accepted: option,\n paymentHeader,\n merchantTo: status.merchantAddress ?? option.payTo,\n payer: this.x402Wallet,\n chainId: status.chainId || chainIdFromNetwork(option.network),\n })\n }\n\n private buildX402Receipt(input: {\n paymentId: string\n txHash: string\n token: string\n amount: string\n to: string\n resourceUrl: string\n explorerUrl: string\n accepted: X402PaymentOption\n paymentHeader: string\n merchantTo?: string | null\n payer?: string\n chainId?: number\n }): X402Receipt {\n const fundingExplorerUrl = input.explorerUrl || explorerUrlOrEmpty(input.chainId, input.txHash)\n\n return {\n success: true,\n paymentId: input.paymentId,\n txHash: input.txHash,\n token: input.token,\n amount: input.amount,\n to: input.to,\n resourceUrl: input.resourceUrl,\n explorerUrl: input.explorerUrl,\n accepted: input.accepted,\n paymentHeader: input.paymentHeader,\n merchantTo: input.merchantTo ?? input.accepted.payTo,\n payer: input.payer,\n chainId: input.chainId,\n haven: {\n paymentId: input.paymentId,\n fundingTxHash: input.txHash,\n fundingExplorerUrl,\n },\n merchant: {\n payTo: input.merchantTo ?? input.accepted.payTo,\n },\n x402: {\n amount: input.accepted.amount,\n token: input.token,\n network: input.accepted.network,\n asset: input.accepted.asset,\n resource: input.accepted.resource ?? input.resourceUrl,\n },\n }\n }\n\n private async createStandardX402Header(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n ): Promise<string> {\n if (!this.delegateKey) {\n throw new HavenSigningError('delegateKey is required to sign x402 payment headers.')\n }\n\n const account = privateKeyToAccount(this.delegateKey as `0x${string}`)\n const requirements = toStandardPaymentRequirements(paymentRequired, option)\n\n const header = await exact.evm.createPaymentHeader(\n account,\n paymentRequired.x402Version,\n requirements,\n )\n if (paymentRequired.x402Version < 2) return header\n\n const payment = decodeBase64Json<{ payload: unknown }>(header)\n return btoa(JSON.stringify({\n x402Version: paymentRequired.x402Version,\n accepted: option,\n payload: payment.payload,\n }))\n }\n\n private cacheX402Receipt(\n idempotencyKey: string,\n paymentHeader: string,\n receipt: X402Receipt,\n ): void {\n const expiresAt = getPaymentHeaderValidBefore(paymentHeader)\n if (expiresAt > Date.now()) {\n this.x402ReceiptCache.set(idempotencyKey, { expiresAt, receipt })\n }\n }\n\n private mapMachinePaymentReceipt(\n challenge: MachinePaymentChallenge,\n raw: RawMachinePaymentAuthorizeResponse,\n txHash: string,\n execResult?: RawSignResponse,\n ): MachinePaymentReceipt {\n const receiptWithoutHeader = {\n success: true,\n rail: challenge.rail,\n paymentId: raw.payment_id,\n challengeId: challenge.challengeId,\n txHash,\n token: execResult?.token ?? raw.token ?? challenge.asset.symbol,\n amount: execResult?.amount ?? raw.amount ?? challenge.amount.display,\n to: execResult?.to ?? raw.to ?? challenge.recipient,\n resourceUrl: raw.resource_url ?? challenge.resource,\n explorerUrl:\n execResult?.explorer_url ??\n raw.explorer_url ??\n buildExplorerUrl(execResult?.chain_id ?? raw.chain_id ?? challenge.network.chainId, txHash),\n payer: raw.payer ?? raw.safe_address,\n chainId: execResult?.chain_id ?? raw.chain_id ?? challenge.network.chainId,\n }\n\n return {\n ...receiptWithoutHeader,\n proofHeader: encodeMachinePaymentProof(receiptWithoutHeader),\n }\n }\n\n private mapMachinePaymentReceiptFromStatus(\n challenge: MachinePaymentChallenge,\n status: PaymentStatusResult,\n ): MachinePaymentReceipt {\n if (!status.txHash) {\n throw new HavenApiError(\n `MPP payment ${status.paymentId} is ready to retry but has no Haven transaction hash.`,\n 502,\n status,\n status.paymentId,\n )\n }\n\n const receiptWithoutHeader = {\n success: true,\n rail: challenge.rail,\n paymentId: status.paymentId,\n challengeId: challenge.challengeId,\n txHash: status.txHash,\n token: status.token || challenge.asset.symbol,\n amount: status.amount || challenge.amount.display,\n to: status.merchantAddress ?? challenge.recipient,\n resourceUrl: status.resourceUrl ?? challenge.resource,\n explorerUrl: explorerUrlOrEmpty(status.chainId || challenge.network.chainId, status.txHash),\n chainId: status.chainId || challenge.network.chainId,\n }\n\n return {\n ...receiptWithoutHeader,\n proofHeader: encodeMachinePaymentProof(receiptWithoutHeader),\n }\n }\n\n private async recordMerchantRetryRejected(input: {\n rail: string\n paymentId: string\n txHash: string\n resourceUrl: string\n retryResponse: Response\n details?: Record<string, unknown>\n }): Promise<void> {\n try {\n await this.post('/machine-payments/reconciliation-events', {\n paymentId: input.paymentId,\n rail: input.rail,\n eventType: 'merchant_retry_rejected_after_payment',\n txHash: input.txHash,\n reason: `Merchant returned HTTP ${input.retryResponse.status} after Haven payment confirmation`,\n details: {\n resource_url: input.resourceUrl,\n retry_status: input.retryResponse.status,\n retry_body: await responseSnippet(input.retryResponse),\n ...input.details,\n },\n })\n } catch {\n // Best-effort durability: preserve the original retry failure for callers.\n }\n }\n\n private async reportMachinePaymentEvidence(input: {\n paymentId: string\n rail: string\n txHash: string\n resourceUrl: string\n merchantStatus: number\n challengePayload?: Record<string, unknown>\n selectedPayment?: Record<string, unknown>\n paymentProofHeaderName?: string\n paymentProofHeader?: string\n protocolReceiptHeaderName?: string\n protocolReceiptHeader?: string\n }): Promise<void> {\n try {\n await this.post('/machine-payments/evidence', {\n paymentId: input.paymentId,\n rail: input.rail,\n txHash: input.txHash,\n resourceUrl: input.resourceUrl,\n merchantStatus: input.merchantStatus,\n challengePayload: input.challengePayload,\n selectedPayment: input.selectedPayment,\n paymentProofHeaderName: input.paymentProofHeaderName,\n paymentProofHeader: input.paymentProofHeader,\n protocolReceiptHeaderName: input.protocolReceiptHeaderName,\n protocolReceiptHeader: input.protocolReceiptHeader,\n protocolReceiptPayload: input.protocolReceiptHeader\n ? parseProtocolReceiptHeader(input.protocolReceiptHeader)\n : undefined,\n })\n } catch {\n // Evidence reporting is best-effort. The paid resource response remains\n // the caller-visible result when merchant retry succeeded.\n }\n }\n\n private throwIfNonSignableAuthorizationState(\n label: string,\n raw: RawMachinePaymentAuthorizeResponse | RawX402AuthorizeResponse,\n ): void {\n if (raw.status === 'pending_signature') return\n this.throwPaymentStateError(label, raw)\n }\n\n private throwPaymentStateError(\n label: string,\n raw: RawMachinePaymentAuthorizeResponse | RawX402AuthorizeResponse | RawSignResponse,\n ): never {\n const statusCode = PAYMENT_STATE_STATUS_CODES[raw.status] ?? 502\n const state = this.paymentStateFromRaw(label, raw)\n\n if (state) {\n throw new HavenPaymentStateError(state.message, statusCode, state, raw)\n }\n\n if (raw.status === 'pending_approval') {\n throw new HavenApiError(\n `${label} exceeds the on-chain allowance and was queued for owner approval (payment_id: ${raw.payment_id}).`,\n statusCode,\n raw,\n )\n }\n\n if (raw.status === 'expired') {\n throw new HavenApiError(\n `${label} expired before it could be completed (payment_id: ${raw.payment_id}).`,\n statusCode,\n raw,\n )\n }\n\n const paymentId = raw.payment_id ? ` (payment_id: ${raw.payment_id})` : ''\n const message = raw.error ?? `${label} ${raw.status}${paymentId}`\n throw new HavenApiError(message, statusCode, raw)\n }\n\n private paymentStateFromRaw(\n label: string,\n raw: RawMachinePaymentAuthorizeResponse | RawX402AuthorizeResponse | RawSignResponse,\n ): PaymentStatusResult | null {\n if (!raw.payment_id || !raw.status) return null\n\n const phase = (raw.phase as PaymentPhase | undefined) ?? phaseForStatus(raw.status)\n const nextAction = (raw.next_action as PaymentNextAction | undefined) ?? nextActionForStatus(raw.status)\n if (!phase || !nextAction) return null\n\n const amount = raw.amount ?? raw.requested ?? ''\n const token = raw.token ?? ''\n const message =\n raw.message ??\n raw.error ??\n messageForState(label, raw.status, raw.payment_id, nextAction)\n\n return {\n paymentId: raw.payment_id,\n kind: raw.kind === 'payment_intent' ? 'payment_intent' : 'approval_request',\n rail: raw.rail ?? 'direct',\n status: raw.status === 'pending' ? 'pending_approval' : raw.status,\n phase,\n nextAction,\n amount,\n token,\n resourceUrl: raw.resource_url ?? null,\n merchantAddress: raw.merchant_address ?? raw.merchant_to ?? null,\n txHash: raw.tx_hash ?? null,\n expiresAt: raw.expires_at ?? '',\n chainId: raw.chain_id ?? 0,\n message,\n amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? raw.mpp?.amount_atomic ?? null,\n asset: raw.asset ?? raw.x402?.asset ?? raw.mpp?.asset ?? null,\n network: raw.network ?? raw.x402?.network ?? raw.mpp?.network ?? null,\n description: raw.description ?? raw.x402?.description ?? raw.mpp?.description ?? null,\n idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? raw.mpp?.idempotency_key ?? null,\n x402: raw.x402\n ? {\n amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,\n asset: raw.x402.asset ?? raw.asset ?? null,\n network: raw.x402.network ?? raw.network ?? null,\n resourceUrl: raw.x402.resource_url ?? raw.resource_url ?? null,\n merchantAddress: raw.x402.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,\n description: raw.x402.description ?? raw.description ?? null,\n idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null,\n }\n : undefined,\n mpp: raw.mpp\n ? {\n amountAtomic: raw.mpp.amount_atomic ?? raw.amount_atomic ?? null,\n asset: raw.mpp.asset ?? raw.asset ?? null,\n network: raw.mpp.network ?? raw.network ?? null,\n resourceUrl: raw.mpp.resource_url ?? raw.resource_url ?? null,\n merchantAddress: raw.mpp.merchant_address ?? raw.merchant_address ?? raw.merchant_to ?? null,\n description: raw.mpp.description ?? raw.description ?? null,\n idempotencyKey: raw.mpp.idempotency_key ?? raw.idempotency_key ?? null,\n challengeId: raw.mpp.challenge_id ?? raw.challenge_id ?? null,\n }\n : undefined,\n }\n }\n\n private x402PayerAddress(): string | undefined {\n return this.delegateAddress ?? this.x402Wallet\n }\n\n private snapshotX402Request(url: string, init?: RequestInit): X402RequestSnapshot {\n return {\n url,\n method: init?.method ?? 'GET',\n headers: Array.from(new Headers(init?.headers).entries()),\n body: this.snapshotRequestBody(init?.body),\n }\n }\n\n private snapshotRequestBody(body: BodyInit | null | undefined): string | undefined {\n if (body == null) return undefined\n if (typeof body === 'string') return body\n if (body instanceof URLSearchParams) return body.toString()\n\n throw new HavenApiError(\n 'Quote helpers can only capture resumable request bodies that are strings or URLSearchParams. ' +\n 'For streams, blobs, or binary bodies, preserve the original request yourself and call the matching resume method with fresh init.',\n 400,\n )\n }\n\n private requestInitFromSnapshot(request: X402RequestSnapshot): RequestInit {\n return {\n method: request.method,\n headers: request.headers,\n body: request.body,\n }\n }\n\n private withX402Wallet(init?: RequestInit, wallet = this.x402PayerAddress()): RequestInit | undefined {\n if (!wallet) return init\n\n const headers = new Headers(init?.headers)\n if (!headers.has('x402-wallet')) {\n headers.set('x402-wallet', wallet)\n }\n\n return {\n ...init,\n headers,\n }\n }\n\n private buildX402Quote(\n paymentRequired: X402PaymentRequired,\n request: X402RequestSnapshot,\n idempotencyKey?: string,\n ): X402Quote {\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.',\n 400,\n )\n }\n\n const token = resolveTokenFromAddress(option.asset, option.network)\n return {\n rail: 'x402',\n idempotencyKey: idempotencyKey ?? buildX402IdempotencyKey(paymentRequired, option),\n paymentRequired,\n accepted: option,\n request,\n resourceUrl: paymentRequired.resource.url,\n description: paymentRequired.resource.description ?? option.description ?? null,\n mimeType: paymentRequired.resource.mimeType ?? option.mimeType ?? null,\n amountAtomic: option.amount,\n amount: decimalFromUsdcAtomic(option.amount),\n token: token?.symbol ?? 'USDC',\n asset: option.asset,\n network: option.network,\n chainId: chainIdOrNull(option.network),\n merchantAddress: option.payTo,\n maxTimeoutSeconds: option.maxTimeoutSeconds,\n }\n }\n\n private buildX402ResumeState(input: {\n paymentId: string\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n idempotencyKey: string\n request?: X402RequestSnapshot\n }): X402ResumeState {\n const token = resolveTokenFromAddress(input.accepted.asset, input.accepted.network)\n return {\n rail: 'x402',\n paymentId: input.paymentId,\n idempotencyKey: input.idempotencyKey,\n paymentRequired: input.paymentRequired,\n accepted: input.accepted,\n url: input.request?.url ?? input.paymentRequired.resource.url,\n request: input.request,\n resourceUrl: input.paymentRequired.resource.url,\n description: input.paymentRequired.resource.description ?? input.accepted.description ?? null,\n amountAtomic: input.accepted.amount,\n amount: decimalFromUsdcAtomic(input.accepted.amount),\n token: token?.symbol ?? 'USDC',\n asset: input.accepted.asset,\n network: input.accepted.network,\n chainId: chainIdOrNull(input.accepted.network),\n merchantAddress: input.accepted.payTo,\n }\n }\n\n private buildMppQuote(\n challenge: MachinePaymentChallenge,\n request: X402RequestSnapshot,\n idempotencyKey?: string,\n ): MppQuote {\n return {\n rail: 'mpp',\n paymentRail: challenge.rail,\n idempotencyKey: idempotencyKey ?? buildMachinePaymentIdempotencyKey(challenge),\n challenge,\n request,\n resourceUrl: challenge.resource,\n description: challenge.description ?? null,\n amountAtomic: challenge.amount.atomic,\n amount: challenge.amount.display,\n token: challenge.asset.symbol,\n asset: challenge.asset.address,\n network: challenge.network.name,\n chainId: challenge.network.chainId,\n merchantAddress: challenge.recipient,\n expiresAt: challenge.expiresAt,\n }\n }\n\n private buildMppResumeState(input: {\n paymentId: string\n challenge: MachinePaymentChallenge\n idempotencyKey: string\n request?: X402RequestSnapshot\n }): MppResumeState {\n const quote = this.buildMppQuote(\n input.challenge,\n input.request ?? this.snapshotX402Request(input.challenge.resource),\n input.idempotencyKey,\n )\n\n return {\n rail: 'mpp',\n paymentRail: quote.paymentRail,\n paymentId: input.paymentId,\n idempotencyKey: quote.idempotencyKey,\n challenge: input.challenge,\n url: input.request?.url ?? input.challenge.resource,\n request: input.request,\n resourceUrl: quote.resourceUrl,\n description: quote.description,\n amountAtomic: quote.amountAtomic,\n amount: quote.amount,\n token: quote.token,\n asset: quote.asset,\n network: quote.network,\n chainId: quote.chainId,\n merchantAddress: quote.merchantAddress,\n expiresAt: quote.expiresAt,\n }\n }\n\n private attachResumeState(\n err: unknown,\n input:\n | {\n rail: 'x402'\n paymentRequired: X402PaymentRequired\n accepted: X402PaymentOption\n idempotencyKey: string\n request?: X402RequestSnapshot\n }\n | {\n rail: 'mpp'\n challenge: MachinePaymentChallenge\n idempotencyKey: string\n request?: X402RequestSnapshot\n },\n ): void {\n if (input.rail === 'x402') {\n this.attachX402ResumeState(\n err,\n input.paymentRequired,\n input.accepted,\n input.idempotencyKey,\n input.request,\n )\n return\n }\n\n this.attachMppResumeState(err, input.challenge, input.idempotencyKey, input.request)\n }\n\n private attachX402ResumeState(\n err: unknown,\n paymentRequired: X402PaymentRequired,\n accepted: X402PaymentOption,\n idempotencyKey: string,\n request?: X402RequestSnapshot,\n ): void {\n if (!(err instanceof HavenPaymentStateError)) return\n if (err.state.rail !== 'x402') return\n\n err.resumeState = this.buildX402ResumeState({\n paymentId: err.state.paymentId,\n paymentRequired,\n accepted,\n idempotencyKey,\n request,\n })\n }\n\n private attachMppResumeState(\n err: unknown,\n challenge: MachinePaymentChallenge,\n idempotencyKey: string,\n request?: X402RequestSnapshot,\n ): void {\n if (!(err instanceof HavenPaymentStateError)) return\n if (!isMppRail(err.state.rail)) return\n\n err.resumeState = this.buildMppResumeState({\n paymentId: err.state.paymentId,\n challenge,\n idempotencyKey,\n request,\n })\n }\n\n // ── Tool Execution (for agent frameworks) ────────────────────────\n\n /**\n * Execute a tool call by name and input.\n *\n * Designed to plug directly into agent tool-call handlers:\n *\n * ```ts\n * if (block.type === 'tool_use') {\n * const result = await haven.executeTool(block.name, block.input)\n * // send result back to the model\n * }\n * ```\n */\n async executeTool(\n toolName: string,\n input: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n if (toolName === 'make_payment') {\n const { token, amount, to } = input as {\n token: string\n amount: string\n to: string\n }\n\n try {\n const result = await this.pay({ token, amount, to })\n return {\n success: result.status === 'confirmed',\n payment_id: result.paymentId,\n status: result.status,\n tx_hash: result.txHash,\n token: result.token,\n amount: result.amount,\n to: result.to,\n explorer_url: result.explorerUrl,\n error: result.errorMessage,\n }\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n if (toolName === 'authorize_x402_payment') {\n const { url, payTo, amount, asset, network, description, idempotencyKey } = input as {\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n idempotencyKey?: string\n }\n\n try {\n const receipt = await this.authorizeX402(\n this.toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),\n { idempotencyKey },\n )\n return this.x402ToolReceipt(receipt)\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n if (toolName === 'resume_x402_payment') {\n const { payment_id, url, payTo, amount, asset, network, description, idempotencyKey } = input as {\n payment_id: string\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n idempotencyKey?: string\n }\n\n try {\n const receipt = await this.resumeAuthorizedX402({\n paymentId: payment_id,\n paymentRequired: this.toolX402PaymentRequired({ url, payTo, amount, asset, network, description }),\n idempotencyKey,\n })\n return this.x402ToolReceipt(receipt)\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n if (toolName === 'authorize_machine_payment') {\n const { challenge, idempotencyKey } = input as {\n challenge: MachinePaymentChallenge\n idempotencyKey?: string\n }\n\n try {\n const receipt = await this.authorizeMachinePayment(challenge, { idempotencyKey })\n return {\n success: true,\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n token: receipt.token,\n amount: receipt.amount,\n to: receipt.to,\n resource_url: receipt.resourceUrl,\n explorer_url: receipt.explorerUrl,\n proof_header: receipt.proofHeader,\n rail: receipt.rail,\n challenge_id: receipt.challengeId,\n payer: receipt.payer,\n chain_id: receipt.chainId,\n }\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n if (toolName === 'get_payment_status') {\n const { payment_id } = input as { payment_id: string }\n const result = await this.getPaymentStatus(payment_id)\n return {\n payment_id: result.paymentId,\n kind: result.kind,\n rail: result.rail,\n status: result.status,\n phase: result.phase,\n next_action: result.nextAction,\n tx_hash: result.txHash,\n token: result.token,\n amount: result.amount,\n resource_url: result.resourceUrl,\n merchant_address: result.merchantAddress,\n amount_atomic: result.amountAtomic,\n asset: result.asset,\n network: result.network,\n description: result.description,\n idempotency_key: result.idempotencyKey,\n x402: result.x402,\n mpp: result.mpp,\n expires_at: result.expiresAt,\n chain_id: result.chainId,\n message: result.message,\n }\n }\n\n throw new Error(`Unknown tool: ${toolName}`)\n }\n\n private toolX402PaymentRequired(input: {\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n }): X402PaymentRequired {\n return {\n x402Version: 2,\n resource: { url: input.url, description: input.description },\n accepts: [\n {\n scheme: 'exact',\n network: input.network,\n amount: input.amount,\n asset: input.asset,\n payTo: input.payTo,\n maxTimeoutSeconds: 30,\n },\n ],\n }\n }\n\n private x402ToolReceipt(receipt: X402Receipt): Record<string, unknown> {\n return {\n success: true,\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n token: receipt.token,\n amount: receipt.amount,\n to: receipt.to,\n resource_url: receipt.resourceUrl,\n explorer_url: receipt.explorerUrl,\n payment_header: receipt.paymentHeader,\n merchant_to: receipt.merchantTo,\n payer: receipt.payer,\n chain_id: receipt.chainId,\n haven: receipt.haven,\n merchant: receipt.merchant,\n x402: receipt.x402,\n }\n }\n\n private toolError(err: unknown): Record<string, unknown> {\n if (err instanceof HavenPaymentStateError) {\n return {\n success: false,\n payment_id: err.state.paymentId,\n kind: err.state.kind,\n rail: err.state.rail,\n status: err.state.status,\n phase: err.state.phase,\n next_action: err.state.nextAction,\n tx_hash: err.state.txHash,\n token: err.state.token,\n amount: err.state.amount,\n resource_url: err.state.resourceUrl,\n merchant_address: err.state.merchantAddress,\n amount_atomic: err.state.amountAtomic,\n asset: err.state.asset,\n network: err.state.network,\n description: err.state.description,\n idempotency_key: err.state.idempotencyKey,\n x402: err.state.x402\n ? {\n amount_atomic: err.state.x402.amountAtomic,\n asset: err.state.x402.asset,\n network: err.state.x402.network,\n resource_url: err.state.x402.resourceUrl,\n merchant_address: err.state.x402.merchantAddress,\n description: err.state.x402.description,\n idempotency_key: err.state.x402.idempotencyKey,\n }\n : undefined,\n mpp: err.state.mpp\n ? {\n amount_atomic: err.state.mpp.amountAtomic,\n asset: err.state.mpp.asset,\n network: err.state.mpp.network,\n resource_url: err.state.mpp.resourceUrl,\n merchant_address: err.state.mpp.merchantAddress,\n description: err.state.mpp.description,\n idempotency_key: err.state.mpp.idempotencyKey,\n challenge_id: err.state.mpp.challengeId,\n }\n : undefined,\n resume_state: err.resumeState,\n expires_at: err.state.expiresAt,\n chain_id: err.state.chainId,\n message: err.state.message,\n error: err.message,\n }\n }\n\n if (err instanceof HavenApiError) {\n return {\n success: false,\n status_code: err.statusCode,\n error: err.message,\n body: err.body,\n }\n }\n\n return {\n success: false,\n error: err instanceof Error ? err.message : String(err),\n }\n }\n\n // ── HTTP Helpers ─────────────────────────────────────────────────\n\n private async post<T>(path: string, body: Record<string, unknown>): Promise<T> {\n return this.request<T>('POST', path, body)\n }\n\n private async get<T>(path: string): Promise<T> {\n return this.request<T>('GET', path)\n }\n\n private async request<T>(\n method: 'GET' | 'POST',\n path: string,\n body?: Record<string, unknown>,\n ): Promise<T> {\n const url = `${this.baseUrl}${path}`\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), this.requestTimeout)\n\n try {\n const contextHeaders = this.requestContext.getStore()?.headers ?? {}\n const res = await fetch(url, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n ...this.defaultHeaders,\n ...contextHeaders,\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n })\n\n const data = await res.json()\n\n if (!res.ok) {\n const message =\n (data as Record<string, unknown>).error as string\n ?? (data as Record<string, unknown>).details as string\n ?? `API request failed`\n throw new HavenApiError(message, res.status, data)\n }\n\n return data as T\n } catch (err) {\n if (err instanceof HavenApiError) throw err\n if (err instanceof Error && err.name === 'AbortError') {\n throw new HavenApiError(`Request to ${path} timed out`, 408)\n }\n throw new HavenApiError(\n `Request to ${path} failed: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n )\n } finally {\n clearTimeout(timeout)\n }\n }\n\n // ── Mapping Helpers ──────────────────────────────────────────────\n\n private mapPaymentResult(raw: RawStatusResponse): PaymentResult {\n return {\n paymentId: raw.payment_id,\n status: raw.status as PaymentStatus,\n token: raw.token,\n amount: raw.amount,\n to: raw.to,\n txHash: raw.tx_hash,\n errorMessage: raw.error_message,\n explorerUrl: raw.explorer_url ?? (raw.tx_hash ? buildExplorerUrl(raw.chain_id, raw.tx_hash) : null),\n createdAt: raw.created_at,\n signedAt: raw.signed_at,\n submittedAt: raw.submitted_at,\n confirmedAt: raw.confirmed_at,\n expiresAt: raw.expires_at,\n }\n }\n\n private mapPaymentStatusResult(raw: RawPaymentStatusResult): PaymentStatusResult {\n return {\n paymentId: raw.payment_id,\n kind: raw.kind,\n rail: raw.rail,\n status: raw.status,\n phase: raw.phase,\n nextAction: raw.next_action,\n amount: raw.amount,\n token: raw.token,\n resourceUrl: raw.resource_url,\n merchantAddress: raw.merchant_address,\n txHash: raw.tx_hash,\n expiresAt: raw.expires_at,\n chainId: raw.chain_id,\n message: raw.message,\n amountAtomic: raw.amount_atomic ?? raw.x402?.amount_atomic ?? null,\n asset: raw.asset ?? raw.x402?.asset ?? null,\n network: raw.network ?? raw.x402?.network ?? null,\n description: raw.description ?? raw.x402?.description ?? null,\n idempotencyKey: raw.idempotency_key ?? raw.x402?.idempotency_key ?? null,\n x402: raw.x402\n ? {\n amountAtomic: raw.x402.amount_atomic ?? raw.amount_atomic ?? null,\n asset: raw.x402.asset ?? raw.asset ?? null,\n network: raw.x402.network ?? raw.network ?? null,\n resourceUrl: raw.x402.resource_url ?? raw.resource_url,\n merchantAddress: raw.x402.merchant_address ?? raw.merchant_address,\n description: raw.x402.description ?? raw.description ?? null,\n idempotencyKey: raw.x402.idempotency_key ?? raw.idempotency_key ?? null,\n }\n : undefined,\n }\n }\n\n private mapPaymentReceipt(raw: RawHavenPaymentReceipt): HavenPaymentReceipt {\n return {\n id: raw.id,\n paymentId: raw.payment_id,\n rail: raw.rail,\n proofStatus: raw.proof_status,\n txHash: raw.tx_hash,\n chainId: raw.chain_id,\n resourceUrl: raw.resource_url,\n merchantAddress: raw.merchant_address,\n payerAddress: raw.payer_address,\n settlementAddress: raw.settlement_address,\n tokenSymbol: raw.token_symbol,\n tokenAddress: raw.token_address,\n amountRaw: raw.amount_raw,\n amount: raw.amount_human,\n challengeId: raw.challenge_id,\n idempotencyKey: raw.idempotency_key,\n challengePayload: raw.challenge_payload,\n selectedPayment: raw.selected_payment,\n paymentProofHeaderName: raw.payment_proof_header_name,\n protocolReceiptHeaderName: raw.protocol_receipt_header_name,\n protocolReceiptPayload: raw.protocol_receipt_payload,\n merchantStatus: raw.merchant_status,\n confirmedAt: raw.confirmed_at,\n createdAt: raw.created_at,\n updatedAt: raw.updated_at,\n }\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction getPaymentHeaderValidBefore(paymentHeader: string): number {\n try {\n const payment = decodeBase64Json<{ payload?: { authorization?: { validBefore?: string } } }>(\n paymentHeader,\n )\n const payload = payment.payload as { authorization?: { validBefore?: string } }\n const validBeforeSeconds = Number(payload.authorization?.validBefore)\n if (Number.isFinite(validBeforeSeconds)) return validBeforeSeconds * 1000\n } catch {\n // If the header cannot be decoded, skip caching rather than hiding errors.\n }\n\n return 0\n}\n\nfunction decodeBase64Json<T>(value: string): T {\n return JSON.parse(atob(value)) as T\n}\n\nfunction parseProtocolReceiptHeader(value: string): Record<string, unknown> | undefined {\n try {\n return JSON.parse(atob(value)) as Record<string, unknown>\n } catch {\n try {\n return JSON.parse(value) as Record<string, unknown>\n } catch {\n return undefined\n }\n }\n}\n\nasync function responseSnippet(response: Response): Promise<string | null> {\n try {\n const text = await response.clone().text()\n return text.slice(0, 1000) || null\n } catch {\n return null\n }\n}\n","/**\n * Pre-built tool definitions for AI agent frameworks.\n *\n * These definitions describe the `make_payment` and `get_payment_status` tools\n * in the formats expected by Claude (Anthropic) and OpenAI.\n *\n * Usage with Claude:\n * const response = await anthropic.messages.create({\n * tools: havenTools.claude(),\n * ...\n * })\n *\n * Usage with OpenAI:\n * const response = await openai.chat.completions.create({\n * tools: havenTools.openai(),\n * ...\n * })\n */\n\n// ── JSON Schema (shared across formats) ──────────────────────────\n\nconst makePaymentSchema = {\n type: 'object' as const,\n properties: {\n token: {\n type: 'string' as const,\n description: 'Token to send. Gnosis Chain: EURe, USDC.e, xDAI. Base: USDC, ETH.',\n },\n amount: {\n type: 'string' as const,\n description: 'Amount to send as a decimal string, e.g. \"5.00\"',\n },\n to: {\n type: 'string' as const,\n description: 'Recipient Ethereum address (0x...)',\n },\n reason: {\n type: 'string' as const,\n description: 'Brief reason for this payment (for audit trail)',\n },\n },\n required: ['token', 'amount', 'to', 'reason'] as const,\n}\n\nconst getPaymentStatusSchema = {\n type: 'object' as const,\n properties: {\n payment_id: {\n type: 'string' as const,\n description: 'The payment ID returned from make_payment',\n },\n },\n required: ['payment_id'] as const,\n}\n\nconst authorizeX402Schema = {\n type: 'object' as const,\n properties: {\n url: {\n type: 'string' as const,\n description: 'The URL that returned HTTP 402',\n },\n payTo: {\n type: 'string' as const,\n description: 'Payment recipient address from the 402 response',\n },\n amount: {\n type: 'string' as const,\n description: 'Payment amount in atomic units (e.g. \"1000000\" for 1 USDC)',\n },\n asset: {\n type: 'string' as const,\n description: 'Token contract address from the 402 response',\n },\n network: {\n type: 'string' as const,\n description: 'CAIP-2 chain ID. \"eip155:100\" for Gnosis Chain, \"eip155:8453\" for Base.',\n },\n description: {\n type: 'string' as const,\n description: 'Description of the resource being paid for',\n },\n idempotencyKey: {\n type: 'string' as const,\n description: 'Stable caller-supplied key for this user intent. Reuse it when resuming after user approval.',\n },\n },\n required: ['url', 'payTo', 'amount', 'asset', 'network'] as const,\n}\n\nconst resumeX402Schema = {\n type: 'object' as const,\n properties: {\n payment_id: {\n type: 'string' as const,\n description: 'The payment or approval request ID returned by authorize_x402_payment.',\n },\n url: {\n type: 'string' as const,\n description: 'The original URL that returned HTTP 402.',\n },\n payTo: {\n type: 'string' as const,\n description: 'Payment recipient address from the original 402 response.',\n },\n amount: {\n type: 'string' as const,\n description: 'Payment amount in atomic units from the original 402 response.',\n },\n asset: {\n type: 'string' as const,\n description: 'Token contract address from the original 402 response.',\n },\n network: {\n type: 'string' as const,\n description: 'CAIP-2 chain ID or x402 network from the original 402 response.',\n },\n description: {\n type: 'string' as const,\n description: 'Description of the resource being paid for.',\n },\n idempotencyKey: {\n type: 'string' as const,\n description: 'Stable caller-supplied key used for the original authorization.',\n },\n },\n required: ['payment_id', 'url', 'payTo', 'amount', 'asset', 'network'] as const,\n}\n\nconst authorizeMachinePaymentSchema = {\n type: 'object' as const,\n properties: {\n challenge: {\n type: 'object' as const,\n description: 'Machine payment challenge returned by a Haven demo endpoint',\n },\n },\n required: ['challenge'] as const,\n}\n\nconst MAKE_PAYMENT_DESCRIPTION =\n 'Request and sign a payment from the user-controlled Safe within approved on-chain limits. ' +\n 'Haven authenticates the agent, validates the signed intent, and relays the Safe AllowanceModule transaction; it does not hold keys or control funds. ' +\n 'Gnosis Chain tokens: EURe, USDC.e, xDAI. Base tokens: USDC, ETH.'\n\nconst GET_STATUS_DESCRIPTION =\n 'Check the status of a previously initiated payment. ' +\n 'Accepts payment intent IDs and approval request IDs. Returns the current status, phase, next_action, transaction hash if available, and payment details.'\n\nconst AUTHORIZE_X402_DESCRIPTION =\n 'Authorize payment for an HTTP 402 (Payment Required) response. ' +\n 'When a paid API returns x402 payment requirements, use this tool to sign with the agent-owned delegate key and request a policy-limited Safe AllowanceModule top-up when needed. ' +\n 'Haven relays signed transactions only; the agent key authorizes payment and on-chain limits enforce spend. ' +\n 'If this returns pending_approval, tell the user it is waiting in Haven, preserve the original merchant/MCP session and x402 details, call get_payment_status later, and use resume_x402_payment only when next_action is retry_original_x402_request. Do not start a new merchant session or loop retries while approval is pending. ' +\n 'Use the returned payment_header as the X-PAYMENT header on the retry request when doing a manual HTTP retry.'\n\nconst RESUME_X402_DESCRIPTION =\n 'Resume an x402 payment after the user approved it in Haven. ' +\n 'Use this only after get_payment_status returns next_action=retry_original_x402_request. ' +\n 'It checks the approved payment, validates the original x402 details, and returns a merchant X-PAYMENT header without creating a new approval request or merchant session.'\n\nconst AUTHORIZE_MACHINE_PAYMENT_DESCRIPTION =\n 'Authorize a Haven machine-payment challenge, currently for the internal MPP demo rail. ' +\n 'The agent signs the payment, Haven relays it within the on-chain allowance, and the tool returns a proof header for the retry request.'\n\n// ── Claude (Anthropic) format ────────────────────────────────────\n\nexport interface ClaudeTool {\n name: string\n description: string\n input_schema: {\n type: 'object'\n properties: Record<string, unknown>\n required: readonly string[]\n }\n}\n\nfunction claudeTools(): ClaudeTool[] {\n return [\n {\n name: 'make_payment',\n description: MAKE_PAYMENT_DESCRIPTION,\n input_schema: makePaymentSchema,\n },\n {\n name: 'get_payment_status',\n description: GET_STATUS_DESCRIPTION,\n input_schema: getPaymentStatusSchema,\n },\n {\n name: 'authorize_x402_payment',\n description: AUTHORIZE_X402_DESCRIPTION,\n input_schema: authorizeX402Schema,\n },\n {\n name: 'resume_x402_payment',\n description: RESUME_X402_DESCRIPTION,\n input_schema: resumeX402Schema,\n },\n {\n name: 'authorize_machine_payment',\n description: AUTHORIZE_MACHINE_PAYMENT_DESCRIPTION,\n input_schema: authorizeMachinePaymentSchema,\n },\n ]\n}\n\n// ── OpenAI format ────────────────────────────────────────────────\n\nexport interface OpenAITool {\n type: 'function'\n function: {\n name: string\n description: string\n parameters: {\n type: 'object'\n properties: Record<string, unknown>\n required: readonly string[]\n }\n }\n}\n\nfunction openaiTools(): OpenAITool[] {\n return [\n {\n type: 'function',\n function: {\n name: 'make_payment',\n description: MAKE_PAYMENT_DESCRIPTION,\n parameters: makePaymentSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'get_payment_status',\n description: GET_STATUS_DESCRIPTION,\n parameters: getPaymentStatusSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'authorize_x402_payment',\n description: AUTHORIZE_X402_DESCRIPTION,\n parameters: authorizeX402Schema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'resume_x402_payment',\n description: RESUME_X402_DESCRIPTION,\n parameters: resumeX402Schema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'authorize_machine_payment',\n description: AUTHORIZE_MACHINE_PAYMENT_DESCRIPTION,\n parameters: authorizeMachinePaymentSchema,\n },\n },\n ]\n}\n\n// ── Public API ───────────────────────────────────────────────────\n\nexport const havenTools = {\n /** Tool definitions in Anthropic/Claude format */\n claude: claudeTools,\n\n /** Tool definitions in OpenAI function-calling format */\n openai: openaiTools,\n}\n"]}
|