@haven_ai/sdk 0.1.2 → 0.1.3

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.
@@ -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":["ethers","createHash","decodeBase64Json","receipt","privateKeyToAccount","exact"],"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;AAAA,EACxD,WAAA,CACE,OAAA,EACA,UAAA,EACgB,KAAA,EAChB,IAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,UAAA,EAAY,IAAA,EAAM,KAAA,CAAM,SAAS,CAAA;AAHhC,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAIhB,IAAA,IAAA,CAAK,I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;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.cjs","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":["ethers","createHash","decodeBase64Json","receipt","privateKeyToAccount","exact"],"mappings":";;;;;;;;;;AA8dO,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;AAAA,EACxD,WAAA,CACE,OAAA,EACA,UAAA,EACgB,KAAA,EAChB,IAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,UAAA,EAAY,IAAA,EAAM,KAAA,CAAM,SAAS,CAAA;AAHhC,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAIhB,IAAA,IAAA,CAAK,IAAA,GAAO,wBAAA;AAAA,EACd;AAAA,EALkB,KAAA;AAAA,EAOlB,IAAI,MAAA,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AAM,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,qBAAA;AAAA,QACN,WAAA,EAAa,uBAAA;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.cjs","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 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\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 /** Original or freshly parsed x402 requirements. Supplying this avoids an extra merchant 402 probe. */\n paymentRequired?: X402PaymentRequired\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 X402AuthorizationOptions,\n RawCreateResponse,\n RawSignResponse,\n RawStatusResponse,\n RawPaymentStatusResult,\n X402PaymentRequired,\n X402PaymentOption,\n X402Receipt,\n ResumeAuthorizedX402Input,\n ResumeX402PaymentInput,\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}\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 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\nfunction sameAddress(a: string | null | undefined, b: string | null | undefined): boolean {\n return Boolean(a && b && a.toLowerCase() === b.toLowerCase())\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 /** 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(\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 } 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 = 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 === 'retry_original_x402_request') {\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): Promise<Response> {\n const initialInit = this.withX402Wallet(input.init, this.x402PayerAddress())\n let paymentRequired = input.paymentRequired\n\n if (!paymentRequired) {\n const response = await globalThis.fetch(input.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(input.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 receipt = await this.authorizeX402(paymentRequired, options)\n return this.retryX402Request(url, initialInit, paymentRequired, receipt)\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 ): 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 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 !== 'retry_original_x402_request') {\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 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 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, 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 } = 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 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 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 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, call get_payment_status later, and use resume_x402_payment only when next_action is retry_original_x402_request. Do not 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.'\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"]}