@haven_ai/sdk 0.1.0 → 0.1.1

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/client.ts","../src/tools.ts"],"names":["ethers"],"mappings":";;;;;;;AAwOO,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;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,aAAa,UAAU,CAAA;AAFtB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AAAA,EAJkB,IAAA;AAKpB;AAEO,IAAM,iBAAA,GAAN,cAAgC,UAAA,CAAW;AAAA,EAChD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,SAAS,eAAe,CAAA;AAC9B,IAAA,IAAA,CAAK,IAAA,GAAO,mBAAA;AAAA,EACd;AACF;AAEO,IAAM,iBAAA,GAAN,cAAgC,UAAA,CAAW;AAAA,EAChD,YAAY,SAAA,EAAmB;AAC7B,IAAA,KAAA;AAAA,MACE,iCAAiC,SAAS,CAAA,WAAA,CAAA;AAAA,MAC1C,SAAA;AAAA,MAC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AAA,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;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 /** 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 | '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, e.g. \"eip155:100\"\n amount: string // Atomic units\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}\n\n/** @internal */\nexport interface RawX402AuthorizeResponse {\n success?: boolean\n payment_id: string\n status: string\n tx_hash?: string\n chain_id?: number\n token?: string\n amount?: string\n to?: string\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 status: 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 status: string\n tx_hash?: string\n token?: string\n amount?: string\n to?: string\n explorer_url?: string\n chain_id?: number\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// ── 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 ) {\n super(message, 'API_ERROR', statusCode)\n this.name = 'HavenApiError'\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 * - 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 type { X402PaymentRequired, X402PaymentOption } from './types.js'\n\n// ── Supported networks (CAIP-2 chain IDs) ────────────────────────\n\n/** CAIP-2 chain IDs that Haven supports for x402 payments. */\nexport const SUPPORTED_X402_NETWORKS: Record<string, string> = {\n 'eip155:100': 'Gnosis Chain',\n 'eip155:8453': '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}\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 try {\n return JSON.parse(atob(v2Header)) as X402PaymentRequired\n } catch {\n throw new Error('Failed to decode PAYMENT-REQUIRED header')\n }\n }\n\n // v1: X-PAYMENT header\n const v1Header = response.headers.get('X-PAYMENT')\n if (v1Header) {\n try {\n return JSON.parse(atob(v1Header)) as X402PaymentRequired\n } catch {\n throw new Error('Failed to decode X-PAYMENT header')\n }\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 * 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 * 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}): string {\n const payload = {\n x402Version: 2,\n payload: {\n txHash: receipt.txHash,\n paymentId: receipt.paymentId,\n settledVia: 'haven',\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 { signHash, addressFromKey, verifySignature } from './signer.js'\nimport type {\n HavenClientConfig,\n PaymentRequest,\n PaymentIntent,\n PaymentResult,\n PaymentStatus,\n SignData,\n RawCreateResponse,\n RawSignResponse,\n RawStatusResponse,\n X402PaymentRequired,\n X402Receipt,\n RawX402AuthorizeResponse,\n} from './types.js'\nimport {\n HavenApiError,\n HavenSigningError,\n HavenTimeoutError,\n} from './types.js'\nimport {\n parsePaymentRequired,\n selectPaymentOption,\n encodePaymentProof,\n} from './x402.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 ?? 100] ?? CHAIN_EXPLORER_TX[100]\n return `${base}/${txHash}`\n}\nconst DEFAULT_REQUEST_TIMEOUT = 30_000\nconst DEFAULT_CONFIRMATION_TIMEOUT = 90_000\nconst DEFAULT_POLLING_INTERVAL = 3_000\n\nexport class HavenClient {\n private readonly apiKey: string\n private readonly delegateKey: string | undefined\n private readonly baseUrl: string\n private readonly requestTimeout: number\n private readonly confirmationTimeout: number\n private readonly pollingInterval: number\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.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 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 * 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\n * compatible payment option, signs and executes the payment through Haven.\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\n // 1. Select best payment option\n const option = selectPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports Gnosis Chain (eip155:100) and Base (eip155:8453).',\n 400,\n )\n }\n\n // 2. Create intent via x402/authorize (without signature first to get hash)\n const raw = await this.post<RawX402AuthorizeResponse>('/x402', {\n url: paymentRequired.resource.url,\n payTo: option.payTo,\n amount: option.amount,\n asset: option.asset,\n network: option.network,\n description: paymentRequired.resource.description,\n })\n\n // If the backend already executed (shouldn't happen without sig), return\n if (raw.success && raw.tx_hash) {\n return {\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 }\n }\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 throw new HavenApiError(\n execResult.error ?? `x402 payment ${execResult.status}`,\n 502,\n execResult,\n )\n }\n\n return {\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 }\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 // 1. Make the original request\n const response = await globalThis.fetch(url, init)\n\n // 2. Not a 402 — return as-is\n if (response.status !== 402) return response\n\n // 3. Parse x402 payment requirements\n let paymentRequired: X402PaymentRequired\n try {\n paymentRequired = parsePaymentRequired(response)\n } catch {\n // Not an x402 402 — return original response\n return response\n }\n\n // 4. Pay through Haven\n const receipt = await this.authorizeX402(paymentRequired)\n\n // 5. Retry with payment proof\n const retryHeaders = new Headers(init?.headers)\n retryHeaders.set('PAYMENT-SIGNATURE', encodePaymentProof(receipt))\n\n return globalThis.fetch(url, {\n ...init,\n headers: retryHeaders,\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 {\n success: false,\n error: err instanceof Error ? err.message : String(err),\n }\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 }\n } catch (err) {\n return {\n success: false,\n error: err instanceof Error ? err.message : String(err),\n }\n }\n }\n\n if (toolName === 'get_payment_status') {\n const { payment_id } = input as { payment_id: string }\n const result = await this.getPayment(payment_id)\n return {\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 }\n }\n\n throw new Error(`Unknown tool: ${toolName}`)\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\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\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 MAKE_PAYMENT_DESCRIPTION =\n 'Send a payment from the Haven-managed Safe wallet. ' +\n \"The payment will be validated against the agent's on-chain spending policy. \" +\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 'Returns the current status, transaction hash (if confirmed), and payment details.'\n\nconst AUTHORIZE_X402_DESCRIPTION =\n 'Authorize payment for an HTTP 402 (Payment Required) response. ' +\n 'When a paid API returns 402 with x402 payment requirements, use this tool to pay and get access. ' +\n 'Haven evaluates the payment against policy and executes from the Safe wallet.'\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}\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}\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/client.ts","../src/tools.ts"],"names":["ethers","createHash","receipt","privateKeyToAccount","exact","decodeBase64Json"],"mappings":";;;;;;;;;;AAuPO,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;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,aAAa,UAAU,CAAA;AAFtB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,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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 | '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/** @internal */\nexport interface RawX402AuthorizeResponse {\n success?: boolean\n payment_id: string\n status: 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 status: 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 status: string\n tx_hash?: string\n token?: string\n amount?: string\n to?: string\n explorer_url?: string\n chain_id?: number\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// ── 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 ) {\n super(message, 'API_ERROR', statusCode)\n this.name = 'HavenApiError'\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 { 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 SignData,\n RawCreateResponse,\n RawSignResponse,\n RawStatusResponse,\n X402PaymentRequired,\n X402PaymentOption,\n X402Receipt,\n RawX402AuthorizeResponse,\n} from './types.js'\nimport {\n HavenApiError,\n HavenSigningError,\n HavenTimeoutError,\n} from './types.js'\nimport {\n buildX402IdempotencyKey,\n parsePaymentRequiredResponse,\n selectStandardPaymentOption,\n toStandardPaymentRequirements,\n} from './x402.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\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\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\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 throw new HavenApiError(\n `Payment exceeds the on-chain allowance and was queued for owner approval (payment_id: ${raw.payment_id}).`,\n 202,\n raw,\n )\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 * 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. Move the required USDC from the Haven wallet to the delegate EOA.\n // The merchant then verifies and settles the standard EIP-3009 x402\n // authorization signed by this same delegate wallet.\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 // 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 throw new HavenApiError(\n execResult.error ?? `x402 payment ${execResult.status}`,\n 502,\n execResult,\n )\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 // 3. Parse x402 payment requirements\n let paymentRequired: X402PaymentRequired\n try {\n paymentRequired = await parsePaymentRequiredResponse(response)\n } catch {\n // Not an x402 402 — return original response\n return response\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 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 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 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 {\n success: false,\n error: err instanceof Error ? err.message : String(err),\n }\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 {\n success: false,\n error: err instanceof Error ? err.message : String(err),\n }\n }\n }\n\n if (toolName === 'get_payment_status') {\n const { payment_id } = input as { payment_id: string }\n const result = await this.getPayment(payment_id)\n return {\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 }\n }\n\n throw new Error(`Unknown tool: ${toolName}`)\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\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","/**\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 MAKE_PAYMENT_DESCRIPTION =\n 'Send a payment from the Haven-managed Safe wallet. ' +\n \"The payment will be validated against the agent's on-chain spending policy. \" +\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 'Returns the current status, transaction hash (if confirmed), and payment details.'\n\nconst AUTHORIZE_X402_DESCRIPTION =\n 'Authorize payment for an HTTP 402 (Payment Required) response. ' +\n 'When a paid API returns 402 with x402 payment requirements, use this tool to fund the agent wallet and get a merchant payment header. ' +\n 'Haven evaluates the payment against policy before moving funds from the Haven wallet. ' +\n 'Use the returned payment_header as the X-PAYMENT header on 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}\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}\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"]}
package/dist/index.d.cts CHANGED
@@ -5,6 +5,8 @@ interface HavenClientConfig {
5
5
  delegateKey?: string;
6
6
  /** Haven API base URL (default: http://localhost:3001) */
7
7
  baseUrl?: string;
8
+ /** Optional wallet identity to send as the x402-wallet header. */
9
+ x402Wallet?: string;
8
10
  /** Timeout in ms for individual HTTP requests (default: 30000) */
9
11
  requestTimeout?: number;
10
12
  /** Timeout in ms when polling for tx confirmation (default: 90000) */
@@ -87,6 +89,10 @@ interface X402PaymentOption {
87
89
  scheme: string;
88
90
  network: string;
89
91
  amount: string;
92
+ maxAmountRequired?: string;
93
+ resource?: string;
94
+ description?: string;
95
+ mimeType?: string;
90
96
  asset: string;
91
97
  payTo: string;
92
98
  maxTimeoutSeconds: number;
@@ -102,6 +108,11 @@ interface X402Receipt {
102
108
  to: string;
103
109
  resourceUrl: string;
104
110
  explorerUrl: string;
111
+ accepted?: X402PaymentOption;
112
+ paymentHeader?: string;
113
+ merchantTo?: string | null;
114
+ payer?: string;
115
+ chainId?: number;
105
116
  }
106
117
  declare class HavenError extends Error {
107
118
  readonly code: string;
@@ -124,9 +135,12 @@ declare class HavenClient {
124
135
  private readonly apiKey;
125
136
  private readonly delegateKey;
126
137
  private readonly baseUrl;
138
+ private readonly x402Wallet;
127
139
  private readonly requestTimeout;
128
140
  private readonly confirmationTimeout;
129
141
  private readonly pollingInterval;
142
+ private readonly inFlightX402;
143
+ private readonly x402ReceiptCache;
130
144
  /** Delegate address derived from the private key (if provided) */
131
145
  readonly delegateAddress: string | undefined;
132
146
  constructor(config: HavenClientConfig);
@@ -172,12 +186,14 @@ declare class HavenClient {
172
186
  /**
173
187
  * Authorize an x402 payment.
174
188
  *
175
- * Takes the parsed PaymentRequired from a 402 response, selects a
176
- * compatible payment option, signs and executes the payment through Haven.
189
+ * Takes the parsed PaymentRequired from a 402 response, selects a compatible
190
+ * option, funds the delegate wallet through Haven, and returns the standard
191
+ * x402 header that the merchant can verify and settle.
177
192
  *
178
193
  * Requires `delegateKey` to be set in the client config.
179
194
  */
180
195
  authorizeX402(paymentRequired: X402PaymentRequired): Promise<X402Receipt>;
196
+ private authorizeStandardX402;
181
197
  /**
182
198
  * Fetch wrapper that automatically handles HTTP 402 responses.
183
199
  *
@@ -192,6 +208,10 @@ declare class HavenClient {
192
208
  * Requires `delegateKey` to be set in the client config.
193
209
  */
194
210
  fetch(url: string, init?: RequestInit): Promise<Response>;
211
+ private createStandardX402Header;
212
+ private cacheX402Receipt;
213
+ private x402PayerAddress;
214
+ private withX402Wallet;
195
215
  /**
196
216
  * Execute a tool call by name and input.
197
217
  *
@@ -282,6 +302,7 @@ declare function verifySignature(hash: string, signature: string, expectedAddres
282
302
  *
283
303
  * Provides:
284
304
  * - parsePaymentRequired() — extract payment requirements from a 402 response
305
+ * - parsePaymentRequiredResponse() — async parser with JSON body fallback
285
306
  * - encodePaymentProof() — encode a receipt as a PAYMENT-SIGNATURE header
286
307
  *
287
308
  * The main authorizeX402() and fetchWithPayment() are methods on HavenClient
@@ -296,6 +317,15 @@ declare function verifySignature(hash: string, signature: string, expectedAddres
296
317
  * - v1 fallback: X-PAYMENT header or response body
297
318
  */
298
319
  declare function parsePaymentRequired(response: Response): X402PaymentRequired;
320
+ /**
321
+ * Parse an HTTP 402 response into x402 PaymentRequired data.
322
+ *
323
+ * Soundside and other Bazaar-style MCP endpoints return the PaymentRequired
324
+ * object in the JSON body, while older Haven demos and many x402 examples use
325
+ * base64 headers. This keeps the synchronous header parser intact and adds the
326
+ * body fallback needed for those endpoints.
327
+ */
328
+ declare function parsePaymentRequiredResponse(response: Response): Promise<X402PaymentRequired>;
299
329
  /**
300
330
  * Select the best payment option from the x402 accepts array.
301
331
  *
@@ -317,6 +347,10 @@ declare function encodePaymentProof(receipt: {
317
347
  token: string;
318
348
  amount: string;
319
349
  to: string;
350
+ resourceUrl?: string;
351
+ accepted?: X402PaymentOption;
352
+ payer?: string;
353
+ chainId?: number;
320
354
  }): string;
321
355
 
322
- export { type ClaudeTool, HavenApiError, HavenClient, type HavenClientConfig, HavenError, HavenSigningError, HavenTimeoutError, type OpenAITool, type PaymentIntent, type PaymentRequest, type PaymentResult, type PaymentStatus, type SignData, type X402PaymentOption, type X402PaymentRequired, type X402Receipt, addressFromKey, encodePaymentProof, havenTools, parsePaymentRequired, selectPaymentOption, signHash, verifySignature };
356
+ export { type ClaudeTool, HavenApiError, HavenClient, type HavenClientConfig, HavenError, HavenSigningError, HavenTimeoutError, type OpenAITool, type PaymentIntent, type PaymentRequest, type PaymentResult, type PaymentStatus, type SignData, type X402PaymentOption, type X402PaymentRequired, type X402Receipt, addressFromKey, encodePaymentProof, havenTools, parsePaymentRequired, parsePaymentRequiredResponse, selectPaymentOption, signHash, verifySignature };
package/dist/index.d.ts CHANGED
@@ -5,6 +5,8 @@ interface HavenClientConfig {
5
5
  delegateKey?: string;
6
6
  /** Haven API base URL (default: http://localhost:3001) */
7
7
  baseUrl?: string;
8
+ /** Optional wallet identity to send as the x402-wallet header. */
9
+ x402Wallet?: string;
8
10
  /** Timeout in ms for individual HTTP requests (default: 30000) */
9
11
  requestTimeout?: number;
10
12
  /** Timeout in ms when polling for tx confirmation (default: 90000) */
@@ -87,6 +89,10 @@ interface X402PaymentOption {
87
89
  scheme: string;
88
90
  network: string;
89
91
  amount: string;
92
+ maxAmountRequired?: string;
93
+ resource?: string;
94
+ description?: string;
95
+ mimeType?: string;
90
96
  asset: string;
91
97
  payTo: string;
92
98
  maxTimeoutSeconds: number;
@@ -102,6 +108,11 @@ interface X402Receipt {
102
108
  to: string;
103
109
  resourceUrl: string;
104
110
  explorerUrl: string;
111
+ accepted?: X402PaymentOption;
112
+ paymentHeader?: string;
113
+ merchantTo?: string | null;
114
+ payer?: string;
115
+ chainId?: number;
105
116
  }
106
117
  declare class HavenError extends Error {
107
118
  readonly code: string;
@@ -124,9 +135,12 @@ declare class HavenClient {
124
135
  private readonly apiKey;
125
136
  private readonly delegateKey;
126
137
  private readonly baseUrl;
138
+ private readonly x402Wallet;
127
139
  private readonly requestTimeout;
128
140
  private readonly confirmationTimeout;
129
141
  private readonly pollingInterval;
142
+ private readonly inFlightX402;
143
+ private readonly x402ReceiptCache;
130
144
  /** Delegate address derived from the private key (if provided) */
131
145
  readonly delegateAddress: string | undefined;
132
146
  constructor(config: HavenClientConfig);
@@ -172,12 +186,14 @@ declare class HavenClient {
172
186
  /**
173
187
  * Authorize an x402 payment.
174
188
  *
175
- * Takes the parsed PaymentRequired from a 402 response, selects a
176
- * compatible payment option, signs and executes the payment through Haven.
189
+ * Takes the parsed PaymentRequired from a 402 response, selects a compatible
190
+ * option, funds the delegate wallet through Haven, and returns the standard
191
+ * x402 header that the merchant can verify and settle.
177
192
  *
178
193
  * Requires `delegateKey` to be set in the client config.
179
194
  */
180
195
  authorizeX402(paymentRequired: X402PaymentRequired): Promise<X402Receipt>;
196
+ private authorizeStandardX402;
181
197
  /**
182
198
  * Fetch wrapper that automatically handles HTTP 402 responses.
183
199
  *
@@ -192,6 +208,10 @@ declare class HavenClient {
192
208
  * Requires `delegateKey` to be set in the client config.
193
209
  */
194
210
  fetch(url: string, init?: RequestInit): Promise<Response>;
211
+ private createStandardX402Header;
212
+ private cacheX402Receipt;
213
+ private x402PayerAddress;
214
+ private withX402Wallet;
195
215
  /**
196
216
  * Execute a tool call by name and input.
197
217
  *
@@ -282,6 +302,7 @@ declare function verifySignature(hash: string, signature: string, expectedAddres
282
302
  *
283
303
  * Provides:
284
304
  * - parsePaymentRequired() — extract payment requirements from a 402 response
305
+ * - parsePaymentRequiredResponse() — async parser with JSON body fallback
285
306
  * - encodePaymentProof() — encode a receipt as a PAYMENT-SIGNATURE header
286
307
  *
287
308
  * The main authorizeX402() and fetchWithPayment() are methods on HavenClient
@@ -296,6 +317,15 @@ declare function verifySignature(hash: string, signature: string, expectedAddres
296
317
  * - v1 fallback: X-PAYMENT header or response body
297
318
  */
298
319
  declare function parsePaymentRequired(response: Response): X402PaymentRequired;
320
+ /**
321
+ * Parse an HTTP 402 response into x402 PaymentRequired data.
322
+ *
323
+ * Soundside and other Bazaar-style MCP endpoints return the PaymentRequired
324
+ * object in the JSON body, while older Haven demos and many x402 examples use
325
+ * base64 headers. This keeps the synchronous header parser intact and adds the
326
+ * body fallback needed for those endpoints.
327
+ */
328
+ declare function parsePaymentRequiredResponse(response: Response): Promise<X402PaymentRequired>;
299
329
  /**
300
330
  * Select the best payment option from the x402 accepts array.
301
331
  *
@@ -317,6 +347,10 @@ declare function encodePaymentProof(receipt: {
317
347
  token: string;
318
348
  amount: string;
319
349
  to: string;
350
+ resourceUrl?: string;
351
+ accepted?: X402PaymentOption;
352
+ payer?: string;
353
+ chainId?: number;
320
354
  }): string;
321
355
 
322
- export { type ClaudeTool, HavenApiError, HavenClient, type HavenClientConfig, HavenError, HavenSigningError, HavenTimeoutError, type OpenAITool, type PaymentIntent, type PaymentRequest, type PaymentResult, type PaymentStatus, type SignData, type X402PaymentOption, type X402PaymentRequired, type X402Receipt, addressFromKey, encodePaymentProof, havenTools, parsePaymentRequired, selectPaymentOption, signHash, verifySignature };
356
+ export { type ClaudeTool, HavenApiError, HavenClient, type HavenClientConfig, HavenError, HavenSigningError, HavenTimeoutError, type OpenAITool, type PaymentIntent, type PaymentRequest, type PaymentResult, type PaymentStatus, type SignData, type X402PaymentOption, type X402PaymentRequired, type X402Receipt, addressFromKey, encodePaymentProof, havenTools, parsePaymentRequired, parsePaymentRequiredResponse, selectPaymentOption, signHash, verifySignature };