@haven_ai/sdk 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts","../src/signer.ts","../src/x402.ts","../src/client.ts","../src/tools.ts"],"names":[],"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,SA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A,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;AACF,GACF;AACF;AAIO,IAAM,UAAA,GAAa;AAAA;AAAA,EAExB,MAAA,EAAQ,WAAA;AAAA;AAAA,EAGR,MAAA,EAAQ;AACV","file":"index.js","sourcesContent":["// ── Client Configuration ─────────────────────────────────────────\n\nexport interface HavenClientConfig {\n /** Haven API key (sk_agent_xxx) */\n apiKey: string\n\n /** Agent's delegate EOA private key. If provided, the SDK handles signing automatically. */\n delegateKey?: string\n\n /** Haven API base URL (default: http://localhost:3001) */\n baseUrl?: string\n\n /** 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/mpp.ts","../src/client.ts","../src/tools.ts"],"names":["decodeBase64Json","createHash","receipt"],"mappings":";;;;;;;;AAkbO,IAAM,UAAA,GAAN,cAAyB,KAAA,CAAM;AAAA,EACpC,WAAA,CACE,OAAA,EACgB,IAAA,EACA,UAAA,EACA,SAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAJG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AACA,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,YAAA;AAAA,EACd;AAAA,EANkB,IAAA;AAAA,EACA,UAAA;AAAA,EACA,SAAA;AAKpB;AAEO,IAAM,aAAA,GAAN,cAA4B,UAAA,CAAW;AAAA,EAC5C,WAAA,CACE,OAAA,EACA,UAAA,EACgB,IAAA,EAChB,SAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,WAAA,EAAa,UAAA,EAAY,SAAS,CAAA;AAHjC,IAAA,IAAA,CAAA,IAAA,GAAA,I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AAA;AAAA,MACb,YAAA,EAAc;AAAA,KAChB;AAAA,IACA;AAAA,MACE,IAAA,EAAM,wBAAA;AAAA,MACN,WAAA,EAAa,0BAAA;AAAA,MACb,YAAA,EAAc;AAAA,KAChB;AAAA,IACA;AAAA,MACE,IAAA,EAAM,2BAAA;AAAA,MACN,WAAA,EAAa,qCAAA;AAAA,MACb,YAAA,EAAc;AAAA;AAChB,GACF;AACF;AAiBA,SAAS,WAAA,GAA4B;AACnC,EAAA,OAAO;AAAA,IACL;AAAA,MACE,IAAA,EAAM,UAAA;AAAA,MACN,QAAA,EAAU;AAAA,QACR,IAAA,EAAM,cAAA;AAAA,QACN,WAAA,EAAa,wBAAA;AAAA,QACb,UAAA,EAAY;AAAA;AACd,KACF;AAAA,IACA;AAAA,MACE,IAAA,EAAM,UAAA;AAAA,MACN,QAAA,EAAU;AAAA,QACR,IAAA,EAAM,oBAAA;AAAA,QACN,WAAA,EAAa,sBAAA;AAAA,QACb,UAAA,EAAY;AAAA;AACd,KACF;AAAA,IACA;AAAA,MACE,IAAA,EAAM,UAAA;AAAA,MACN,QAAA,EAAU;AAAA,QACR,IAAA,EAAM,wBAAA;AAAA,QACN,WAAA,EAAa,0BAAA;AAAA,QACb,UAAA,EAAY;AAAA;AACd,KACF;AAAA,IACA;AAAA,MACE,IAAA,EAAM,UAAA;AAAA,MACN,QAAA,EAAU;AAAA,QACR,IAAA,EAAM,2BAAA;AAAA,QACN,WAAA,EAAa,qCAAA;AAAA,QACb,UAAA,EAAY;AAAA;AACd;AACF,GACF;AACF;AAIO,IAAM,UAAA,GAAa;AAAA;AAAA,EAExB,MAAA,EAAQ,WAAA;AAAA;AAAA,EAGR,MAAA,EAAQ;AACV","file":"index.js","sourcesContent":["// ── Client Configuration ─────────────────────────────────────────\n\nexport interface HavenClientConfig {\n /** Haven API key (sk_agent_xxx) */\n apiKey: string\n\n /** Agent's delegate EOA private key. If provided, the SDK handles signing automatically. */\n delegateKey?: string\n\n /** Haven API base URL (default: http://localhost:3001) */\n baseUrl?: string\n\n /** Optional wallet identity to send as the x402-wallet header. */\n x402Wallet?: string\n\n /** Timeout in ms for individual HTTP requests (default: 30000) */\n requestTimeout?: number\n\n /** Timeout in ms when polling for tx confirmation (default: 90000) */\n confirmationTimeout?: number\n\n /** Polling interval in ms when waiting for confirmation (default: 3000) */\n pollingInterval?: number\n}\n\n// ── Payment Types ────────────────────────────────────────────────\n\nexport interface PaymentRequest {\n /** Token symbol: \"EURe\", \"USDC.e\", or \"xDAI\" */\n token: string\n\n /** Amount as a decimal string, e.g. \"5.00\" */\n amount: string\n\n /** Recipient Ethereum address (0x...) */\n to: string\n}\n\nexport interface SignData {\n /** The hash to sign (keccak256, 0x-prefixed) */\n hash: string\n\n /** Breakdown of values that were hashed — useful for debugging */\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n\n /** Human-readable signing instructions */\n instructions: string\n}\n\nexport interface PaymentIntent {\n /** Unique payment ID */\n paymentId: string\n\n /** Current status */\n status: 'pending_signature'\n\n /** ISO 8601 expiry timestamp */\n expiresAt: string\n\n /** Data needed to sign the payment */\n signData: SignData\n}\n\nexport type PaymentStatus =\n | 'pending_signature'\n | 'submitted'\n | 'confirmed'\n | 'pending_approval'\n | 'approved'\n | 'proposed'\n | 'executed'\n | 'rejected'\n | 'expired'\n | 'failed'\n\nexport interface PaymentResult {\n /** Unique payment ID */\n paymentId: string\n\n /** Final status */\n status: PaymentStatus\n\n /** Token that was sent */\n token: string\n\n /** Amount that was sent (human-readable) */\n amount: string\n\n /** Recipient address */\n to: string\n\n /** On-chain transaction hash (present when confirmed) */\n txHash: string | null\n\n /** Error message (present when failed) */\n errorMessage: string | null\n\n /** Block explorer URL for the transaction (chain-dependent) */\n explorerUrl: string | null\n\n /** ISO 8601 timestamps */\n createdAt: string\n signedAt: string | null\n submittedAt: string | null\n confirmedAt: string | null\n expiresAt: string\n}\n\n// ── x402 Types ──────────────────────────────────────────────────\n\n/** Payment requirements from an HTTP 402 response (x402 protocol). */\nexport interface X402PaymentRequired {\n x402Version: number\n resource: {\n url: string\n description?: string\n mimeType?: string\n }\n accepts: X402PaymentOption[]\n error?: string\n}\n\n/** A single payment option from x402 PaymentRequired. */\nexport interface X402PaymentOption {\n scheme: string // \"exact\"\n network: string // CAIP-2 chain ID or x402 network, e.g. \"eip155:8453\" or \"base\"\n amount: string // Atomic units\n maxAmountRequired?: string // Atomic units (official x402 field)\n resource?: string\n description?: string\n mimeType?: string\n asset: string // Token contract address\n payTo: string // Recipient address\n maxTimeoutSeconds: number\n extra?: Record<string, unknown>\n}\n\n/** Receipt returned after a successful x402 payment. */\nexport interface X402Receipt {\n success: boolean\n paymentId: string\n txHash: string\n token: string\n amount: string\n to: string\n resourceUrl: string\n explorerUrl: string\n accepted?: X402PaymentOption\n paymentHeader?: string\n merchantTo?: string | null\n payer?: string\n chainId?: number\n}\n\n// ── Machine Payment Types ───────────────────────────────────────\n\nexport type MachinePaymentRail =\n | 'x402'\n | 'mpp_demo'\n | 'mpp_crypto'\n | 'stripe_deposit'\n | 'spt'\n\nexport interface MachinePaymentChallenge {\n rail: MachinePaymentRail\n version: string\n challengeId: string\n resource: string\n description: string\n network: {\n chainId: number\n name: 'base'\n }\n asset: {\n symbol: 'USDC'\n address: string\n decimals: 6\n }\n amount: {\n display: string\n atomic: string\n }\n recipient: string\n expiresAt: string\n metadata?: Record<string, unknown>\n}\n\nexport interface MachinePaymentReceipt {\n success: boolean\n rail: MachinePaymentRail\n paymentId: string\n challengeId: string\n txHash: string\n token: string\n amount: string\n to: string\n resourceUrl: string\n explorerUrl: string\n payer?: string\n chainId?: number\n proofHeader: string\n}\n\n// ── Agent Payment State Types ────────────────────────────────────\n\nexport type PaymentStateKind = 'payment_intent' | 'approval_request'\n\nexport type PaymentPhase =\n | 'agent_signature_required'\n | 'payment_submitted'\n | 'payment_confirmed'\n | 'user_approval_required'\n | 'user_execution_required'\n | 'waiting_for_additional_approvals'\n | 'funding_sent'\n | 'rejected'\n | 'expired'\n | 'failed'\n\nexport type PaymentNextAction =\n | 'sign_and_submit_payment'\n | 'check_status_later'\n | 'none'\n | 'wait_for_user_approval'\n | 'wait_for_user_to_complete_payment'\n | 'retry_original_x402_request'\n | 'stop_and_tell_user'\n | 'request_again_if_user_still_wants_it'\n\nexport interface PaymentStatusResult {\n paymentId: string\n kind: PaymentStateKind\n rail: string\n status: PaymentStatus | string\n phase: PaymentPhase\n nextAction: PaymentNextAction\n amount: string\n token: string\n resourceUrl: string | null\n merchantAddress: string | null\n txHash: string | null\n expiresAt: string\n chainId: number\n message: string\n}\n\nexport interface PendingApproval extends PaymentStatusResult {\n kind: 'approval_request'\n status: 'pending_approval' | 'pending' | string\n phase: 'user_approval_required'\n nextAction: 'wait_for_user_approval'\n requested?: string\n remaining?: string | null\n}\n\n/** @internal */\nexport interface RawMachinePaymentAuthorizeResponse {\n success?: boolean\n payment_id: string\n kind?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n tx_hash?: string\n chain_id?: number\n safe_address?: string\n payer?: string\n token?: string\n amount?: string\n to?: string\n merchant_to?: string | null\n resource_url?: string\n rail?: string\n challenge_id?: string\n explorer_url?: string\n expires_at?: string\n sign_data?: {\n hash: string\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n instructions: string\n }\n error?: string\n}\n\n/** @internal */\nexport interface RawX402AuthorizeResponse {\n success?: boolean\n payment_id: string\n kind?: string\n rail?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n tx_hash?: string\n chain_id?: number\n safe_address?: string\n payer?: string\n token?: string\n amount?: string\n to?: string\n merchant_to?: string | null\n resource_url?: string\n explorer_url?: string\n expires_at?: string\n sign_data?: {\n hash: string\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n instructions: string\n }\n error?: string\n}\n\n// ── API Response Shapes (raw, snake_case from server) ────────────\n\n/** @internal */\nexport interface RawCreateResponse {\n payment_id: string\n kind?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n expires_at: string\n sign_data: {\n hash: string\n components: {\n safe: string\n token: string\n to: string\n amount: string\n payment_token: string\n payment: string\n nonce: number\n }\n instructions: string\n }\n error?: string\n supported?: string[]\n}\n\n/** @internal */\nexport interface RawSignResponse {\n payment_id: string\n kind?: string\n status: string\n phase?: string\n next_action?: string\n message?: string\n remaining?: string | null\n requested?: string\n tx_hash?: string\n token?: string\n amount?: string\n to?: string\n merchant_to?: string | null\n resource_url?: string\n rail?: string\n explorer_url?: string\n chain_id?: number\n expires_at?: string\n error?: string\n details?: string\n}\n\n/** @internal */\nexport interface RawStatusResponse {\n payment_id: string\n status: string\n token: string\n amount: string\n to: string\n tx_hash: string | null\n explorer_url?: string | null\n chain_id?: number\n error_message: string | null\n created_at: string\n signed_at: string | null\n submitted_at: string | null\n confirmed_at: string | null\n expires_at: string\n}\n\n/** @internal */\nexport interface RawPaymentStatusResult {\n payment_id: string\n kind: PaymentStateKind\n rail: string\n status: string\n phase: PaymentPhase\n next_action: PaymentNextAction\n amount: string\n token: string\n resource_url: string | null\n merchant_address: string | null\n tx_hash: string | null\n expires_at: string\n chain_id: number\n message: string\n}\n\n// ── Error Types ──────────────────────────────────────────────────\n\nexport class HavenError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly statusCode?: number,\n public readonly paymentId?: string,\n ) {\n super(message)\n this.name = 'HavenError'\n }\n}\n\nexport class HavenApiError extends HavenError {\n constructor(\n message: string,\n statusCode: number,\n public readonly body?: unknown,\n paymentId?: string,\n ) {\n super(message, 'API_ERROR', statusCode, paymentId)\n this.name = 'HavenApiError'\n }\n}\n\nexport class HavenPaymentStateError extends HavenApiError {\n constructor(\n message: string,\n statusCode: number,\n public readonly state: PaymentStatusResult,\n body?: unknown,\n ) {\n super(message, statusCode, body, state.paymentId)\n this.name = 'HavenPaymentStateError'\n }\n\n get status(): string {\n return this.state.status\n }\n\n get phase(): PaymentPhase {\n return this.state.phase\n }\n\n get nextAction(): PaymentNextAction {\n return this.state.nextAction\n }\n}\n\nexport class HavenSigningError extends HavenError {\n constructor(message: string) {\n super(message, 'SIGNING_ERROR')\n this.name = 'HavenSigningError'\n }\n}\n\nexport class HavenTimeoutError extends HavenError {\n constructor(paymentId: string) {\n super(\n `Timed out waiting for payment ${paymentId} to confirm`,\n 'TIMEOUT',\n undefined,\n paymentId,\n )\n this.name = 'HavenTimeoutError'\n }\n}\n","import { ethers } from 'ethers'\nimport { HavenSigningError } from './types.js'\n\n/**\n * Sign a hash using raw ECDSA (no Ethereum message prefix).\n *\n * This matches what Safe's AllowanceModule `checkSignature` expects —\n * a direct ecrecover over the hash, NOT the \"\\x19Ethereum Signed Message\" variant.\n *\n * Uses ethers.SigningKey.sign() instead of wallet.signMessage() to avoid the prefix.\n */\nexport function signHash(privateKey: string, hash: string): string {\n try {\n const signingKey = new ethers.SigningKey(privateKey)\n const sig = signingKey.sign(hash)\n return sig.serialized // 0x + r(32) + s(32) + v(1)\n } catch (err) {\n throw new HavenSigningError(\n `Failed to sign hash: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Derive the Ethereum address from a private key.\n */\nexport function addressFromKey(privateKey: string): string {\n try {\n return new ethers.Wallet(privateKey).address\n } catch (err) {\n throw new HavenSigningError(\n `Invalid private key: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Verify that a signature over a hash recovers to the expected address.\n */\nexport function verifySignature(hash: string, signature: string, expectedAddress: string): boolean {\n try {\n const recovered = ethers.recoverAddress(hash, signature)\n return recovered.toLowerCase() === expectedAddress.toLowerCase()\n } catch {\n return false\n }\n}\n","/**\n * x402 protocol support for the Haven SDK.\n *\n * Provides:\n * - parsePaymentRequired() — extract payment requirements from a 402 response\n * - parsePaymentRequiredResponse() — async parser with JSON body fallback\n * - encodePaymentProof() — encode a receipt as a PAYMENT-SIGNATURE header\n *\n * The main authorizeX402() and fetchWithPayment() are methods on HavenClient\n * (see client.ts) since they need API access and signing.\n */\n\nimport { createHash } from 'node:crypto'\nimport type { X402PaymentRequired, X402PaymentOption } from './types.js'\nimport type { PaymentRequirements } from 'x402/types'\n\nconst BASE_USDC_ADDRESS = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'\nconst X402_IDEMPOTENCY_BUCKET_MS = 300_000\n\nfunction decodeBase64Json<T>(value: string, label: string): T {\n try {\n return JSON.parse(atob(value)) as T\n } catch {\n throw new Error(`Failed to decode ${label}`)\n }\n}\n\nfunction normalizePaymentOption(value: unknown): X402PaymentOption | null {\n const candidate = value as Partial<X402PaymentOption> | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n typeof candidate.scheme !== 'string' ||\n typeof candidate.network !== 'string' ||\n typeof candidate.asset !== 'string' ||\n typeof candidate.payTo !== 'string'\n ) {\n return null\n }\n\n const amount =\n typeof candidate.amount === 'string'\n ? candidate.amount\n : typeof candidate.maxAmountRequired === 'string'\n ? candidate.maxAmountRequired\n : null\n\n if (!amount) return null\n\n return {\n scheme: candidate.scheme,\n network: candidate.network,\n amount,\n maxAmountRequired: candidate.maxAmountRequired,\n resource: candidate.resource,\n description: candidate.description,\n mimeType: candidate.mimeType,\n asset: candidate.asset,\n payTo: candidate.payTo,\n maxTimeoutSeconds: candidate.maxTimeoutSeconds ?? 30,\n extra: candidate.extra,\n }\n}\n\nfunction normalizePaymentRequired(value: unknown): X402PaymentRequired | null {\n const candidate = value as Partial<X402PaymentRequired> | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n typeof candidate.x402Version !== 'number' ||\n !Array.isArray(candidate.accepts)\n ) {\n return null\n }\n\n const accepts = candidate.accepts\n .map((option) => normalizePaymentOption(option))\n .filter((option): option is X402PaymentOption => !!option)\n\n if (accepts.length === 0) return null\n\n const first = accepts[0]\n const resourceUrl = candidate.resource?.url ?? first.resource\n if (!resourceUrl) return null\n\n const resource = {\n url: resourceUrl,\n description: candidate.resource?.description ?? first.description,\n mimeType: candidate.resource?.mimeType ?? first.mimeType,\n }\n\n return {\n x402Version: candidate.x402Version,\n resource,\n accepts,\n error: candidate.error,\n }\n}\n\n// ── Supported networks ───────────────────────────────────────────\n\n/** Network identifiers that Haven can recognise in x402 payment requests. */\nexport const SUPPORTED_X402_NETWORKS: Record<string, string> = {\n 'eip155:100': 'Gnosis Chain',\n 'eip155:8453': 'Base',\n 'base': 'Base',\n}\n\n/** Networks supported by the official x402 EIP-3009 exact scheme. */\nconst STANDARD_X402_NETWORKS: Record<string, PaymentRequirements['network']> = {\n 'eip155:8453': 'base',\n 'base': 'base',\n}\n\n// ── Token address maps ────────────────────────────────────────────\n\n/** Known tokens on Gnosis Chain (chainId 100). */\nconst GNOSIS_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n '0x0000000000000000000000000000000000000000': { symbol: 'xDAI', decimals: 18 },\n '0xcb444e90d8198415266c6a2724b7900fb12fc56e': { symbol: 'EURe', decimals: 18 },\n '0x2a22f9c3b484c3629090feed35f17ff8f88f76f0': { symbol: 'USDC.e', decimals: 6 },\n}\n\n/** Known tokens on Base (chainId 8453). */\nconst BASE_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n '0x0000000000000000000000000000000000000000': { symbol: 'ETH', decimals: 18 },\n '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913': { symbol: 'USDC', decimals: 6 },\n}\n\n/** All known tokens across all supported chains (for display / resolution). */\nconst ALL_TOKENS: Record<string, { symbol: string; decimals: number }> = {\n ...GNOSIS_TOKENS,\n ...BASE_TOKENS,\n}\n\n/** Maps CAIP-2 network ID → token address map. */\nconst NETWORK_TOKENS: Record<string, Record<string, { symbol: string; decimals: number }>> = {\n 'eip155:100': GNOSIS_TOKENS,\n 'eip155:8453': BASE_TOKENS,\n 'base': BASE_TOKENS,\n}\n\n// ── Parser ───────────────────────────────────────────────────────\n\n/**\n * Parse an HTTP 402 response into x402 PaymentRequired data.\n *\n * Supports:\n * - v2: PAYMENT-REQUIRED header (base64 JSON)\n * - v1 fallback: X-PAYMENT header or response body\n */\nexport function parsePaymentRequired(response: Response): X402PaymentRequired {\n // v2: PAYMENT-REQUIRED header\n const v2Header = response.headers.get('PAYMENT-REQUIRED')\n if (v2Header) {\n const parsed = normalizePaymentRequired(\n decodeBase64Json<unknown>(v2Header, 'PAYMENT-REQUIRED header'),\n )\n if (parsed) return parsed\n }\n\n // v1: X-PAYMENT header\n const v1Header = response.headers.get('X-PAYMENT')\n if (v1Header) {\n const parsed = normalizePaymentRequired(\n decodeBase64Json<unknown>(v1Header, 'X-PAYMENT header'),\n )\n if (parsed) return parsed\n }\n\n throw new Error(\n 'No x402 payment headers found in 402 response. ' +\n 'Expected PAYMENT-REQUIRED (v2) or X-PAYMENT (v1) header.',\n )\n}\n\n/**\n * Parse an HTTP 402 response into x402 PaymentRequired data.\n *\n * Soundside and other Bazaar-style MCP endpoints return the PaymentRequired\n * object in the JSON body, while older Haven demos and many x402 examples use\n * base64 headers. This keeps the synchronous header parser intact and adds the\n * body fallback needed for those endpoints.\n */\nexport async function parsePaymentRequiredResponse(\n response: Response,\n): Promise<X402PaymentRequired> {\n try {\n return parsePaymentRequired(response)\n } catch (headerErr) {\n try {\n const body = await response.clone().json()\n const parsed = normalizePaymentRequired(body)\n if (parsed) return parsed\n } catch {\n // Fall through to the original, more specific header error below.\n }\n\n throw headerErr\n }\n}\n\n/**\n * Select the best payment option from the x402 accepts array.\n *\n * Preference order:\n * 1. Option on a Haven-supported network with a known token\n * 2. Any option on a Haven-supported network\n * 3. null — no compatible option\n */\nexport function selectPaymentOption(\n accepts: X402PaymentOption[],\n): X402PaymentOption | null {\n if (!accepts || accepts.length === 0) return null\n\n // First pass: find a supported network with a known token\n for (const opt of accepts) {\n if (opt.network in SUPPORTED_X402_NETWORKS) {\n const networkTokens = NETWORK_TOKENS[opt.network]\n if (networkTokens?.[opt.asset.toLowerCase()]) return opt\n }\n }\n\n // Second pass: any supported network\n for (const opt of accepts) {\n if (opt.network in SUPPORTED_X402_NETWORKS) {\n return opt\n }\n }\n\n // No compatible option found\n return null\n}\n\n/**\n * Select an option that can be paid with the official x402 EIP-3009 exact\n * scheme. Haven's older tx-hash proof path can describe more networks; the\n * merchant-verified path currently needs Base USDC.\n */\nexport function selectStandardPaymentOption(\n accepts: X402PaymentOption[],\n): X402PaymentOption | null {\n if (!accepts || accepts.length === 0) return null\n\n for (const opt of accepts) {\n if (\n opt.scheme === 'exact' &&\n opt.network in STANDARD_X402_NETWORKS &&\n opt.asset.toLowerCase() === BASE_USDC_ADDRESS\n ) {\n return opt\n }\n }\n\n return null\n}\n\nexport function toStandardPaymentRequirements(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n): PaymentRequirements {\n const network = STANDARD_X402_NETWORKS[option.network]\n if (!network) {\n throw new Error(`x402 exact payments are not supported on ${option.network}`)\n }\n\n if (option.scheme !== 'exact') {\n throw new Error(`Unsupported x402 scheme: ${option.scheme}`)\n }\n\n return {\n scheme: 'exact',\n network,\n maxAmountRequired: option.maxAmountRequired ?? option.amount,\n resource: option.resource ?? paymentRequired.resource.url,\n description:\n option.description ??\n paymentRequired.resource.description ??\n 'Haven x402 payment',\n mimeType:\n option.mimeType ??\n paymentRequired.resource.mimeType ??\n 'application/octet-stream',\n payTo: option.payTo,\n asset: option.asset,\n maxTimeoutSeconds: option.maxTimeoutSeconds,\n extra: option.extra,\n }\n}\n\nexport function buildX402IdempotencyKey(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n now = Date.now(),\n): string {\n const bucket = Math.floor(now / X402_IDEMPOTENCY_BUCKET_MS)\n const material = [\n paymentRequired.resource.url,\n paymentRequired.resource.description ?? '',\n option.payTo.toLowerCase(),\n option.asset.toLowerCase(),\n option.amount,\n option.network,\n bucket,\n ].join('|')\n\n return `x402:${createHash('sha256').update(material).digest('hex').slice(0, 16)}`\n}\n\n/**\n * Encode a payment receipt as a base64 PAYMENT-SIGNATURE header value.\n *\n * This follows the x402 v2 protocol — the server's facilitator will\n * verify the on-chain transaction referenced by tx_hash.\n */\nexport function encodePaymentProof(receipt: {\n txHash: string\n paymentId: string\n token: string\n amount: string\n to: string\n resourceUrl?: string\n accepted?: X402PaymentOption\n payer?: string\n chainId?: number\n}): string {\n const payload = {\n x402Version: 2,\n resource: receipt.resourceUrl ? { url: receipt.resourceUrl } : undefined,\n accepted: receipt.accepted,\n payload: {\n type: 'haven_tx_hash',\n txHash: receipt.txHash,\n paymentId: receipt.paymentId,\n settledVia: 'haven',\n payer: receipt.payer,\n chainId: receipt.chainId,\n },\n }\n return btoa(JSON.stringify(payload))\n}\n\n/**\n * Resolve a token symbol from a contract address.\n *\n * Checks all supported chains. For chain-specific resolution,\n * pass the optional `network` CAIP-2 string (e.g. \"eip155:100\").\n */\nexport function resolveTokenFromAddress(\n address: string,\n network?: string,\n): { symbol: string; decimals: number } | null {\n const lower = address.toLowerCase()\n\n if (network && network in NETWORK_TOKENS) {\n return NETWORK_TOKENS[network][lower] ?? null\n }\n\n return ALL_TOKENS[lower] ?? null\n}\n","import { createHash } from 'node:crypto'\nimport type {\n MachinePaymentChallenge,\n MachinePaymentReceipt,\n} from './types.js'\n\nfunction decodeBase64Json<T>(value: string, label: string): T {\n try {\n return JSON.parse(atob(value)) as T\n } catch {\n throw new Error(`Failed to decode ${label}`)\n }\n}\n\nfunction normalizeChallenge(value: unknown): MachinePaymentChallenge | null {\n const candidate = value as Partial<MachinePaymentChallenge> | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n candidate.rail !== 'mpp_demo' ||\n typeof candidate.version !== 'string' ||\n typeof candidate.challengeId !== 'string' ||\n typeof candidate.resource !== 'string' ||\n typeof candidate.description !== 'string' ||\n // TODO: relax these checks when non-demo machine payment rails are added.\n candidate.network?.chainId !== 8453 ||\n candidate.network?.name !== 'base' ||\n candidate.asset?.symbol !== 'USDC' ||\n typeof candidate.asset?.address !== 'string' ||\n candidate.asset.decimals !== 6 ||\n typeof candidate.amount?.display !== 'string' ||\n typeof candidate.amount?.atomic !== 'string' ||\n typeof candidate.recipient !== 'string' ||\n typeof candidate.expiresAt !== 'string'\n ) {\n return null\n }\n\n return {\n rail: candidate.rail,\n version: candidate.version,\n challengeId: candidate.challengeId,\n resource: candidate.resource,\n description: candidate.description,\n network: candidate.network,\n asset: candidate.asset,\n amount: candidate.amount,\n recipient: candidate.recipient,\n expiresAt: candidate.expiresAt,\n metadata: candidate.metadata,\n }\n}\n\nexport function parseMachinePaymentChallenge(response: Response): MachinePaymentChallenge {\n const header = response.headers.get('MACHINE-PAYMENT-CHALLENGE')\n if (!header) {\n throw new Error('No MACHINE-PAYMENT-CHALLENGE header found in 402 response.')\n }\n\n const parsed = normalizeChallenge(\n decodeBase64Json<unknown>(header, 'MACHINE-PAYMENT-CHALLENGE header'),\n )\n if (!parsed) throw new Error('Invalid machine payment challenge')\n return parsed\n}\n\nexport async function parseMachinePaymentChallengeResponse(\n response: Response,\n): Promise<MachinePaymentChallenge> {\n try {\n return parseMachinePaymentChallenge(response)\n } catch (headerErr) {\n try {\n const body = await response.clone().json() as { challenge?: unknown }\n const parsed = normalizeChallenge(body.challenge)\n if (parsed) return parsed\n } catch {\n // Fall through to the original, more specific header error.\n }\n\n throw headerErr\n }\n}\n\nexport function buildMachinePaymentIdempotencyKey(\n challenge: MachinePaymentChallenge,\n): string {\n const material = [\n challenge.rail,\n challenge.challengeId,\n challenge.resource,\n challenge.recipient.toLowerCase(),\n challenge.asset.address.toLowerCase(),\n challenge.amount.atomic,\n challenge.network.chainId,\n ].join('|')\n\n return `${challenge.rail}:${createHash('sha256').update(material).digest('hex').slice(0, 16)}`\n}\n\nexport function encodeMachinePaymentProof(receipt: Omit<MachinePaymentReceipt, 'proofHeader'>): string {\n return btoa(JSON.stringify({\n rail: receipt.rail,\n challengeId: receipt.challengeId,\n paymentId: receipt.paymentId,\n txHash: receipt.txHash,\n settledVia: 'haven',\n payer: receipt.payer,\n chainId: receipt.chainId,\n }))\n}\n","import { exact } from 'x402/schemes'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport { signHash, addressFromKey, verifySignature } from './signer.js'\nimport type {\n HavenClientConfig,\n PaymentRequest,\n PaymentIntent,\n PaymentResult,\n PaymentStatus,\n PaymentPhase,\n PaymentNextAction,\n PaymentStatusResult,\n SignData,\n RawCreateResponse,\n RawSignResponse,\n RawStatusResponse,\n RawPaymentStatusResult,\n X402PaymentRequired,\n X402PaymentOption,\n X402Receipt,\n RawX402AuthorizeResponse,\n MachinePaymentChallenge,\n MachinePaymentReceipt,\n RawMachinePaymentAuthorizeResponse,\n} from './types.js'\nimport {\n HavenApiError,\n HavenPaymentStateError,\n HavenSigningError,\n HavenTimeoutError,\n} from './types.js'\nimport {\n buildX402IdempotencyKey,\n parsePaymentRequiredResponse,\n selectStandardPaymentOption,\n toStandardPaymentRequirements,\n} from './x402.js'\nimport {\n buildMachinePaymentIdempotencyKey,\n encodeMachinePaymentProof,\n parseMachinePaymentChallengeResponse,\n} from './mpp.js'\n\nconst DEFAULT_BASE_URL = 'http://localhost:3001'\n\nconst CHAIN_EXPLORER_TX: Record<number, string> = {\n 100: 'https://gnosisscan.io/tx',\n 8453: 'https://basescan.org/tx',\n}\n\nfunction buildExplorerUrl(chainId: number | undefined, txHash: string): string {\n const base = CHAIN_EXPLORER_TX[chainId ?? 8453] ?? CHAIN_EXPLORER_TX[8453]\n return `${base}/${txHash}`\n}\nconst DEFAULT_REQUEST_TIMEOUT = 30_000\nconst DEFAULT_CONFIRMATION_TIMEOUT = 90_000\nconst DEFAULT_POLLING_INTERVAL = 3_000\n\nconst PAYMENT_STATE_STATUS_CODES: Record<string, number> = {\n pending: 202,\n pending_approval: 202,\n approved: 202,\n proposed: 202,\n executed: 200,\n pending_signature: 409,\n submitted: 409,\n expired: 410,\n failed: 502,\n rejected: 409,\n}\n\nfunction chainIdFromNetwork(network: string | undefined): number | undefined {\n if (network === 'base') return 8453\n if (!network?.startsWith('eip155:')) return undefined\n const chainId = Number(network.slice('eip155:'.length))\n return Number.isFinite(chainId) ? chainId : undefined\n}\n\nfunction phaseForStatus(status: string): PaymentPhase | null {\n if (status === 'pending_signature') return 'agent_signature_required'\n if (status === 'submitted') return 'payment_submitted'\n if (status === 'confirmed') return 'payment_confirmed'\n if (status === 'pending' || status === 'pending_approval') return 'user_approval_required'\n if (status === 'approved') return 'user_execution_required'\n if (status === 'proposed') return 'waiting_for_additional_approvals'\n if (status === 'executed') return 'funding_sent'\n if (status === 'rejected') return 'rejected'\n if (status === 'expired') return 'expired'\n if (status === 'failed') return 'failed'\n return null\n}\n\nfunction nextActionForStatus(status: string): PaymentNextAction | null {\n if (status === 'pending_signature') return 'sign_and_submit_payment'\n if (status === 'submitted') return 'check_status_later'\n if (status === 'confirmed') return 'none'\n if (status === 'pending' || status === 'pending_approval') return 'wait_for_user_approval'\n if (status === 'approved') return 'wait_for_user_to_complete_payment'\n if (status === 'proposed') return 'wait_for_user_approval'\n if (status === 'executed') return 'retry_original_x402_request'\n if (status === 'rejected') return 'stop_and_tell_user'\n if (status === 'expired') return 'request_again_if_user_still_wants_it'\n if (status === 'failed') return 'stop_and_tell_user'\n return null\n}\n\nfunction messageForState(\n label: string,\n status: string,\n paymentId: string,\n nextAction: PaymentNextAction,\n): string {\n if (status === 'pending' || status === 'pending_approval') {\n return `${label} is above the remaining agent budget and is waiting for user approval in Haven (payment_id: ${paymentId}).`\n }\n if (status === 'executed') {\n return 'The user completed the funding payment. Retry the original x402 request.'\n }\n if (status === 'rejected') {\n return `The user rejected this payment request (payment_id: ${paymentId}).`\n }\n if (status === 'expired') {\n return `This payment request expired (payment_id: ${paymentId}).`\n }\n return `${label} is ${status}; next_action=${nextAction} (payment_id: ${paymentId}).`\n}\n\nexport class HavenClient {\n private readonly apiKey: string\n private readonly delegateKey: string | undefined\n private readonly baseUrl: string\n private readonly x402Wallet: string | undefined\n private readonly requestTimeout: number\n private readonly confirmationTimeout: number\n private readonly pollingInterval: number\n private readonly inFlightX402 = new Map<string, Promise<X402Receipt>>()\n private readonly x402ReceiptCache = new Map<string, { expiresAt: number; receipt: X402Receipt }>()\n private readonly inFlightMachinePayments = new Map<string, Promise<MachinePaymentReceipt>>()\n\n /** Delegate address derived from the private key (if provided) */\n readonly delegateAddress: string | undefined\n\n constructor(config: HavenClientConfig) {\n this.apiKey = config.apiKey\n this.delegateKey = config.delegateKey\n this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n this.x402Wallet = config.x402Wallet\n this.requestTimeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT\n this.confirmationTimeout = config.confirmationTimeout ?? DEFAULT_CONFIRMATION_TIMEOUT\n this.pollingInterval = config.pollingInterval ?? DEFAULT_POLLING_INTERVAL\n\n if (this.delegateKey) {\n this.delegateAddress = addressFromKey(this.delegateKey)\n }\n }\n\n // ── High-Level API ───────────────────────────────────────────────\n\n /**\n * Send a payment in one call.\n *\n * Creates the intent, signs the hash, submits the signature,\n * and polls until confirmed (or throws on failure/timeout).\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async pay(request: PaymentRequest): Promise<PaymentResult> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot use pay() without a delegateKey. Use createIntent() + submitSignature() for manual signing.',\n )\n }\n\n // Step 1: Create intent\n const intent = await this.createIntent(request)\n\n // Step 2: Sign\n const signature = this.sign(intent.signData.hash)\n\n // Step 3: Submit\n await this.submitSignature(intent.paymentId, signature)\n\n // Step 4: Wait for confirmation\n return this.waitForConfirmation(intent.paymentId)\n }\n\n // ── Step-by-Step API ─────────────────────────────────────────────\n\n /**\n * Step 1: Create a payment intent.\n *\n * Returns the intent with the hash to sign.\n */\n async createIntent(request: PaymentRequest): Promise<PaymentIntent> {\n const raw = await this.post<RawCreateResponse>('/payments', {\n token: request.token,\n amount: request.amount,\n to: request.to,\n })\n\n // Haven returns HTTP 202 with this status when the requested amount\n // exceeds the on-chain allowance. The payment is parked for the owner\n // to approve in the dashboard — there's nothing to sign yet, so the SDK\n // surfaces it as an explicit error rather than returning a malformed\n // intent with no signData.\n if (raw.status === 'pending_approval') {\n this.throwPaymentStateError('Payment', raw)\n }\n\n return {\n paymentId: raw.payment_id,\n status: 'pending_signature',\n expiresAt: raw.expires_at,\n signData: raw.sign_data,\n }\n }\n\n /**\n * Step 2: Sign a hash with the delegate key.\n *\n * Returns the 65-byte signature (0x-prefixed).\n * Requires `delegateKey` to be set in the client config.\n */\n sign(hash: string): string {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'Cannot sign without a delegateKey. Pass the private key in HavenClient config, or sign externally.',\n )\n }\n\n const signature = signHash(this.delegateKey, hash)\n\n // Verify the signature locally before submitting\n if (!verifySignature(hash, signature, this.delegateAddress!)) {\n throw new HavenSigningError(\n 'Local signature verification failed — recovered address does not match delegate key.',\n )\n }\n\n return signature\n }\n\n /**\n * Step 3: Submit a signature to execute the payment.\n *\n * The signature can come from `client.sign()` or from external signing.\n */\n async submitSignature(\n paymentId: string,\n signature: string,\n ): Promise<{ status: string; txHash?: string }> {\n const raw = await this.post<RawSignResponse>(\n `/payments/${paymentId}/sign`,\n { signature },\n )\n\n return {\n status: raw.status,\n txHash: raw.tx_hash,\n }\n }\n\n /**\n * Get the current status of a payment.\n */\n async getPayment(paymentId: string): Promise<PaymentResult> {\n const raw = await this.get<RawStatusResponse>(`/payments/${paymentId}`)\n return this.mapPaymentResult(raw)\n }\n\n /**\n * Get agent-actionable status for a payment intent or approval request.\n *\n * Use this for IDs returned by agent tools and machine-payment/x402 flows.\n * `getPayment()` remains available for payment-intent-only integrations.\n */\n async getPaymentStatus(paymentId: string): Promise<PaymentStatusResult> {\n const raw = await this.get<RawPaymentStatusResult>(`/machine-payments/${paymentId}/status`)\n return this.mapPaymentStatusResult(raw)\n }\n\n /**\n * Poll until a payment reaches a terminal status (confirmed, failed, expired).\n */\n async waitForConfirmation(paymentId: string): Promise<PaymentResult> {\n const deadline = Date.now() + this.confirmationTimeout\n\n while (Date.now() < deadline) {\n const result = await this.getPayment(paymentId)\n\n if (result.status === 'confirmed' || result.status === 'failed' || result.status === 'expired') {\n return result\n }\n\n await sleep(this.pollingInterval)\n }\n\n throw new HavenTimeoutError(paymentId)\n }\n\n // ── x402 Protocol Support ────────────────────────────────────────\n\n /**\n * Authorize an x402 payment.\n *\n * Takes the parsed PaymentRequired from a 402 response, selects a compatible\n * option, funds the delegate wallet through Haven, and returns the standard\n * x402 header that the merchant can verify and settle.\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async authorizeX402(paymentRequired: X402PaymentRequired): Promise<X402Receipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for x402 payments. Pass it in the HavenClient config.',\n )\n }\n if (!this.delegateAddress) {\n throw new HavenSigningError('delegateAddress could not be derived from delegateKey.')\n }\n\n // 1. Select best payment option\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.',\n 400,\n )\n }\n\n const idempotencyKey = buildX402IdempotencyKey(paymentRequired, option)\n const cached = this.x402ReceiptCache.get(idempotencyKey)\n if (cached && cached.expiresAt > Date.now()) return cached.receipt\n\n const inFlight = this.inFlightX402.get(idempotencyKey)\n if (inFlight) return inFlight\n\n const promise = this.authorizeStandardX402(paymentRequired, option, idempotencyKey)\n this.inFlightX402.set(idempotencyKey, promise)\n\n try {\n return await promise\n } finally {\n this.inFlightX402.delete(idempotencyKey)\n }\n }\n\n private async authorizeStandardX402(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n idempotencyKey: string,\n ): Promise<X402Receipt> {\n // 2. Standard x402 settles from an EOA, so the SDK uses the agent-owned\n // delegate EOA for the merchant-facing EIP-3009 authorization. Haven does\n // not control this EOA or its private key.\n //\n // The only automated funding path is a separate Safe AllowanceModule\n // transfer signed by the agent key and constrained by the user's on-chain\n // allowance. Haven's backend relays that signed top-up; it is not the source\n // of payment authority.\n // Sign before funding so retries reuse one EIP-3009 nonce. If funding fails,\n // the unused authorization simply expires via validBefore.\n const paymentHeader = await this.createStandardX402Header(paymentRequired, option)\n const raw = await this.post<RawX402AuthorizeResponse>('/x402', {\n url: paymentRequired.resource.url,\n payTo: this.delegateAddress,\n merchantPayTo: option.payTo,\n amount: option.amount,\n asset: option.asset,\n network: option.network,\n description: paymentRequired.resource.description,\n idempotencyKey,\n })\n\n // If the backend already executed (shouldn't happen without sig), return\n if (raw.success && raw.tx_hash) {\n const receipt = {\n success: true,\n paymentId: raw.payment_id,\n txHash: raw.tx_hash,\n token: raw.token ?? '',\n amount: raw.amount ?? '',\n to: raw.to ?? '',\n resourceUrl: paymentRequired.resource.url,\n explorerUrl: raw.explorer_url ?? (raw.tx_hash ? buildExplorerUrl(raw.chain_id, raw.tx_hash) : ''),\n accepted: option,\n paymentHeader,\n merchantTo: raw.merchant_to ?? option.payTo,\n payer: raw.payer ?? raw.safe_address,\n chainId: raw.chain_id ?? chainIdFromNetwork(option.network),\n }\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n this.throwIfNonSignableAuthorizationState('x402 payment', raw)\n\n // 3. Sign the hash\n if (!raw.sign_data?.hash) {\n throw new HavenApiError('No sign_hash returned from x402/authorize', 500, raw)\n }\n const sig = signHash(this.delegateKey!, raw.sign_data.hash)\n\n // 4. Submit signature (reuse existing payments/:id/sign endpoint)\n const execResult = await this.post<RawSignResponse>(\n `/payments/${raw.payment_id}/sign`,\n { signature: sig },\n )\n\n if (execResult.status !== 'confirmed') {\n this.throwPaymentStateError('x402 payment', execResult)\n }\n\n const receipt = {\n success: true,\n paymentId: raw.payment_id,\n txHash: execResult.tx_hash ?? '',\n token: execResult.token ?? raw.token ?? '',\n amount: execResult.amount ?? raw.amount ?? '',\n to: execResult.to ?? raw.to ?? '',\n resourceUrl: paymentRequired.resource.url,\n explorerUrl: execResult.explorer_url ?? (execResult.tx_hash ? buildExplorerUrl(execResult.chain_id, execResult.tx_hash) : ''),\n accepted: option,\n paymentHeader,\n merchantTo: option.payTo,\n payer: raw.payer ?? raw.safe_address ?? raw.sign_data?.components.safe,\n chainId: execResult.chain_id ?? raw.chain_id ?? chainIdFromNetwork(option.network),\n }\n this.cacheX402Receipt(idempotencyKey, paymentHeader, receipt)\n return receipt\n }\n\n /**\n * Fetch wrapper that automatically handles HTTP 402 responses.\n *\n * Works like the standard `fetch()` but intercepts 402 responses,\n * pays via x402 through Haven, and retries the request.\n *\n * ```ts\n * const response = await haven.fetch('https://paid-api.com/data')\n * const data = await response.json()\n * ```\n *\n * Requires `delegateKey` to be set in the client config.\n */\n async fetch(url: string, init?: RequestInit): Promise<Response> {\n const initialInit = this.withX402Wallet(init, this.x402PayerAddress())\n\n // 1. Make the original request\n const response = await globalThis.fetch(url, initialInit)\n\n // 2. Not a 402 — return as-is\n if (response.status !== 402) return response\n\n const machineChallengeHeader = response.headers.get('MACHINE-PAYMENT-CHALLENGE')\n if (machineChallengeHeader) {\n const challenge = await parseMachinePaymentChallengeResponse(response)\n return this.fetchWithMachinePayment(url, initialInit, challenge)\n }\n\n // 3. Parse x402 payment requirements\n let paymentRequired: X402PaymentRequired\n try {\n paymentRequired = await parsePaymentRequiredResponse(response)\n } catch {\n let challenge: MachinePaymentChallenge\n try {\n challenge = await parseMachinePaymentChallengeResponse(response)\n } catch {\n // Not a Haven machine-payment 402 — return original response\n return response\n }\n return this.fetchWithMachinePayment(url, initialInit, challenge)\n }\n\n // 4. Pay through Haven\n const receipt = await this.authorizeX402(paymentRequired)\n if (!receipt.accepted) {\n throw new HavenApiError('No accepted x402 option was recorded for payment retry', 500)\n }\n if (!receipt.paymentHeader) {\n throw new HavenApiError('No x402 payment header was returned for payment retry', 500)\n }\n\n // 5. Retry with a merchant-verifiable x402 EIP-3009 payment header.\n const retryHeaders = new Headers(initialInit?.headers)\n retryHeaders.set('X-PAYMENT', receipt.paymentHeader)\n\n const retryResponse = await globalThis.fetch(url, {\n ...initialInit,\n headers: retryHeaders,\n })\n\n if (retryResponse.status === 402) {\n await this.recordMerchantRetryRejected({\n rail: 'x402',\n paymentId: receipt.paymentId,\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n retryResponse,\n details: {\n merchant_to: receipt.merchantTo,\n delegate_to: receipt.to,\n },\n })\n\n throw new HavenApiError(\n 'x402 retry was rejected after Haven funded the delegate wallet; reconciliation may be required.',\n 402,\n {\n marker: 'x402_retry_rejected_after_funding',\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n resource_url: receipt.resourceUrl,\n merchant_to: receipt.merchantTo,\n delegate_to: receipt.to,\n },\n )\n }\n\n await this.reportMachinePaymentEvidence({\n paymentId: receipt.paymentId,\n rail: 'x402',\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n merchantStatus: retryResponse.status,\n challengePayload: paymentRequired as unknown as Record<string, unknown>,\n selectedPayment: receipt.accepted as unknown as Record<string, unknown>,\n paymentProofHeaderName: 'X-PAYMENT',\n paymentProofHeader: receipt.paymentHeader,\n protocolReceiptHeaderName: 'PAYMENT-RESPONSE',\n protocolReceiptHeader: retryResponse.headers.get('PAYMENT-RESPONSE') ?? undefined,\n })\n\n return retryResponse\n }\n\n async authorizeMachinePayment(\n challenge: MachinePaymentChallenge,\n ): Promise<MachinePaymentReceipt> {\n if (!this.delegateKey) {\n throw new HavenSigningError(\n 'delegateKey is required for machine payments. Pass it in the HavenClient config.',\n )\n }\n\n if (challenge.rail !== 'mpp_demo') {\n throw new HavenApiError(`Unsupported machine payment rail: ${challenge.rail}`, 400)\n }\n\n const idempotencyKey = buildMachinePaymentIdempotencyKey(challenge)\n const inFlight = this.inFlightMachinePayments.get(idempotencyKey)\n if (inFlight) return inFlight\n\n const promise = this.authorizeMppDemoPayment(challenge, idempotencyKey)\n this.inFlightMachinePayments.set(idempotencyKey, promise)\n\n try {\n return await promise\n } finally {\n this.inFlightMachinePayments.delete(idempotencyKey)\n }\n }\n\n private async authorizeMppDemoPayment(\n challenge: MachinePaymentChallenge,\n idempotencyKey: string,\n ): Promise<MachinePaymentReceipt> {\n const raw = await this.post<RawMachinePaymentAuthorizeResponse>(\n '/machine-payments/authorize',\n { challenge, idempotencyKey },\n )\n\n if (raw.success && raw.tx_hash) {\n return this.mapMachinePaymentReceipt(challenge, raw, raw.tx_hash)\n }\n\n this.throwIfNonSignableAuthorizationState('Machine payment', raw)\n\n if (!raw.sign_data?.hash) {\n throw new HavenApiError('No sign_hash returned from machine payment authorization', 500, raw)\n }\n\n const sig = signHash(this.delegateKey!, raw.sign_data.hash)\n const execResult = await this.post<RawSignResponse>(\n `/payments/${raw.payment_id}/sign`,\n { signature: sig },\n )\n\n if (execResult.status !== 'confirmed' || !execResult.tx_hash) {\n this.throwPaymentStateError('Machine payment', execResult)\n }\n\n return this.mapMachinePaymentReceipt(challenge, raw, execResult.tx_hash, execResult)\n }\n\n private async fetchWithMachinePayment(\n url: string,\n initialInit: RequestInit | undefined,\n challenge: MachinePaymentChallenge,\n ): Promise<Response> {\n const receipt = await this.authorizeMachinePayment(challenge)\n\n const retryHeaders = new Headers(initialInit?.headers)\n retryHeaders.set('MACHINE-PAYMENT-PROOF', receipt.proofHeader)\n\n const retryResponse = await globalThis.fetch(url, {\n ...initialInit,\n headers: retryHeaders,\n })\n\n if (retryResponse.status === 402) {\n await this.recordMerchantRetryRejected({\n rail: receipt.rail,\n paymentId: receipt.paymentId,\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n retryResponse,\n details: {\n challenge_id: receipt.challengeId,\n },\n })\n\n throw new HavenApiError(\n 'Machine payment retry was rejected after Haven sent the payment.',\n 402,\n {\n marker: 'machine_payment_retry_rejected_after_payment',\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n resource_url: receipt.resourceUrl,\n rail: receipt.rail,\n },\n )\n }\n\n await this.reportMachinePaymentEvidence({\n paymentId: receipt.paymentId,\n rail: receipt.rail,\n txHash: receipt.txHash,\n resourceUrl: receipt.resourceUrl,\n merchantStatus: retryResponse.status,\n challengePayload: challenge as unknown as Record<string, unknown>,\n paymentProofHeaderName: 'MACHINE-PAYMENT-PROOF',\n paymentProofHeader: receipt.proofHeader,\n protocolReceiptHeaderName:\n retryResponse.headers.has('Payment-Receipt')\n ? 'Payment-Receipt'\n : retryResponse.headers.has('MACHINE-PAYMENT-RESPONSE')\n ? 'MACHINE-PAYMENT-RESPONSE'\n : undefined,\n protocolReceiptHeader:\n retryResponse.headers.get('Payment-Receipt') ??\n retryResponse.headers.get('MACHINE-PAYMENT-RESPONSE') ??\n undefined,\n })\n\n return retryResponse\n }\n\n private async createStandardX402Header(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n ): Promise<string> {\n if (!this.delegateKey) {\n throw new HavenSigningError('delegateKey is required to sign x402 payment headers.')\n }\n\n const account = privateKeyToAccount(this.delegateKey as `0x${string}`)\n const requirements = toStandardPaymentRequirements(paymentRequired, option)\n\n const header = await exact.evm.createPaymentHeader(\n account,\n paymentRequired.x402Version,\n requirements,\n )\n if (paymentRequired.x402Version < 2) return header\n\n const payment = decodeBase64Json<{ payload: unknown }>(header)\n return btoa(JSON.stringify({\n x402Version: paymentRequired.x402Version,\n accepted: option,\n payload: payment.payload,\n }))\n }\n\n private cacheX402Receipt(\n idempotencyKey: string,\n paymentHeader: string,\n receipt: X402Receipt,\n ): void {\n const expiresAt = getPaymentHeaderValidBefore(paymentHeader)\n if (expiresAt > Date.now()) {\n this.x402ReceiptCache.set(idempotencyKey, { expiresAt, receipt })\n }\n }\n\n private mapMachinePaymentReceipt(\n challenge: MachinePaymentChallenge,\n raw: RawMachinePaymentAuthorizeResponse,\n txHash: string,\n execResult?: RawSignResponse,\n ): MachinePaymentReceipt {\n const receiptWithoutHeader = {\n success: true,\n rail: challenge.rail,\n paymentId: raw.payment_id,\n challengeId: challenge.challengeId,\n txHash,\n token: execResult?.token ?? raw.token ?? challenge.asset.symbol,\n amount: execResult?.amount ?? raw.amount ?? challenge.amount.display,\n to: execResult?.to ?? raw.to ?? challenge.recipient,\n resourceUrl: raw.resource_url ?? challenge.resource,\n explorerUrl:\n execResult?.explorer_url ??\n raw.explorer_url ??\n buildExplorerUrl(execResult?.chain_id ?? raw.chain_id ?? challenge.network.chainId, txHash),\n payer: raw.payer ?? raw.safe_address,\n chainId: execResult?.chain_id ?? raw.chain_id ?? challenge.network.chainId,\n }\n\n return {\n ...receiptWithoutHeader,\n proofHeader: encodeMachinePaymentProof(receiptWithoutHeader),\n }\n }\n\n private async recordMerchantRetryRejected(input: {\n rail: string\n paymentId: string\n txHash: string\n resourceUrl: string\n retryResponse: Response\n details?: Record<string, unknown>\n }): Promise<void> {\n try {\n await this.post('/machine-payments/reconciliation-events', {\n paymentId: input.paymentId,\n rail: input.rail,\n eventType: 'merchant_retry_rejected_after_payment',\n txHash: input.txHash,\n reason: `Merchant returned HTTP ${input.retryResponse.status} after Haven payment confirmation`,\n details: {\n resource_url: input.resourceUrl,\n retry_status: input.retryResponse.status,\n retry_body: await responseSnippet(input.retryResponse),\n ...input.details,\n },\n })\n } catch {\n // Best-effort durability: preserve the original retry failure for callers.\n }\n }\n\n private async reportMachinePaymentEvidence(input: {\n paymentId: string\n rail: string\n txHash: string\n resourceUrl: string\n merchantStatus: number\n challengePayload?: Record<string, unknown>\n selectedPayment?: Record<string, unknown>\n paymentProofHeaderName?: string\n paymentProofHeader?: string\n protocolReceiptHeaderName?: string\n protocolReceiptHeader?: string\n }): Promise<void> {\n try {\n await this.post('/machine-payments/evidence', {\n paymentId: input.paymentId,\n rail: input.rail,\n txHash: input.txHash,\n resourceUrl: input.resourceUrl,\n merchantStatus: input.merchantStatus,\n challengePayload: input.challengePayload,\n selectedPayment: input.selectedPayment,\n paymentProofHeaderName: input.paymentProofHeaderName,\n paymentProofHeader: input.paymentProofHeader,\n protocolReceiptHeaderName: input.protocolReceiptHeaderName,\n protocolReceiptHeader: input.protocolReceiptHeader,\n protocolReceiptPayload: input.protocolReceiptHeader\n ? parseProtocolReceiptHeader(input.protocolReceiptHeader)\n : undefined,\n })\n } catch {\n // Evidence reporting is best-effort. The paid resource response remains\n // the caller-visible result when merchant retry succeeded.\n }\n }\n\n private throwIfNonSignableAuthorizationState(\n label: string,\n raw: RawMachinePaymentAuthorizeResponse | RawX402AuthorizeResponse,\n ): void {\n if (raw.status === 'pending_signature') return\n this.throwPaymentStateError(label, raw)\n }\n\n private throwPaymentStateError(\n label: string,\n raw: RawMachinePaymentAuthorizeResponse | RawX402AuthorizeResponse | RawSignResponse,\n ): never {\n const statusCode = PAYMENT_STATE_STATUS_CODES[raw.status] ?? 502\n const state = this.paymentStateFromRaw(label, raw)\n\n if (state) {\n throw new HavenPaymentStateError(state.message, statusCode, state, raw)\n }\n\n if (raw.status === 'pending_approval') {\n throw new HavenApiError(\n `${label} exceeds the on-chain allowance and was queued for owner approval (payment_id: ${raw.payment_id}).`,\n statusCode,\n raw,\n )\n }\n\n if (raw.status === 'expired') {\n throw new HavenApiError(\n `${label} expired before it could be completed (payment_id: ${raw.payment_id}).`,\n statusCode,\n raw,\n )\n }\n\n const paymentId = raw.payment_id ? ` (payment_id: ${raw.payment_id})` : ''\n const message = raw.error ?? `${label} ${raw.status}${paymentId}`\n throw new HavenApiError(message, statusCode, raw)\n }\n\n private paymentStateFromRaw(\n label: string,\n raw: RawMachinePaymentAuthorizeResponse | RawX402AuthorizeResponse | RawSignResponse,\n ): PaymentStatusResult | null {\n if (!raw.payment_id || !raw.status) return null\n\n const phase = (raw.phase as PaymentPhase | undefined) ?? phaseForStatus(raw.status)\n const nextAction = (raw.next_action as PaymentNextAction | undefined) ?? nextActionForStatus(raw.status)\n if (!phase || !nextAction) return null\n\n const amount = raw.amount ?? raw.requested ?? ''\n const token = raw.token ?? ''\n const message =\n raw.message ??\n raw.error ??\n messageForState(label, raw.status, raw.payment_id, nextAction)\n\n return {\n paymentId: raw.payment_id,\n kind: raw.kind === 'payment_intent' ? 'payment_intent' : 'approval_request',\n rail: raw.rail ?? 'direct',\n status: raw.status === 'pending' ? 'pending_approval' : raw.status,\n phase,\n nextAction,\n amount,\n token,\n resourceUrl: raw.resource_url ?? null,\n merchantAddress: raw.merchant_to ?? null,\n txHash: raw.tx_hash ?? null,\n expiresAt: raw.expires_at ?? '',\n chainId: raw.chain_id ?? 0,\n message,\n }\n }\n\n private x402PayerAddress(): string | undefined {\n return this.delegateAddress ?? this.x402Wallet\n }\n\n private withX402Wallet(init?: RequestInit, wallet = this.x402PayerAddress()): RequestInit | undefined {\n if (!wallet) return init\n\n const headers = new Headers(init?.headers)\n if (!headers.has('x402-wallet')) {\n headers.set('x402-wallet', wallet)\n }\n\n return {\n ...init,\n headers,\n }\n }\n\n // ── Tool Execution (for agent frameworks) ────────────────────────\n\n /**\n * Execute a tool call by name and input.\n *\n * Designed to plug directly into agent tool-call handlers:\n *\n * ```ts\n * if (block.type === 'tool_use') {\n * const result = await haven.executeTool(block.name, block.input)\n * // send result back to the model\n * }\n * ```\n */\n async executeTool(\n toolName: string,\n input: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n if (toolName === 'make_payment') {\n const { token, amount, to } = input as {\n token: string\n amount: string\n to: string\n }\n\n try {\n const result = await this.pay({ token, amount, to })\n return {\n success: result.status === 'confirmed',\n payment_id: result.paymentId,\n status: result.status,\n tx_hash: result.txHash,\n token: result.token,\n amount: result.amount,\n to: result.to,\n explorer_url: result.explorerUrl,\n error: result.errorMessage,\n }\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n if (toolName === 'authorize_x402_payment') {\n const { url, payTo, amount, asset, network, description } = input as {\n url: string\n payTo: string\n amount: string\n asset: string\n network: string\n description?: string\n }\n\n try {\n const receipt = await this.authorizeX402({\n x402Version: 2,\n resource: { url, description },\n accepts: [\n {\n scheme: 'exact',\n network,\n amount,\n asset,\n payTo,\n maxTimeoutSeconds: 30,\n },\n ],\n })\n return {\n success: true,\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n token: receipt.token,\n amount: receipt.amount,\n to: receipt.to,\n resource_url: receipt.resourceUrl,\n explorer_url: receipt.explorerUrl,\n payment_header: receipt.paymentHeader,\n merchant_to: receipt.merchantTo,\n payer: receipt.payer,\n chain_id: receipt.chainId,\n }\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n if (toolName === 'authorize_machine_payment') {\n const { challenge } = input as { challenge: MachinePaymentChallenge }\n\n try {\n const receipt = await this.authorizeMachinePayment(challenge)\n return {\n success: true,\n payment_id: receipt.paymentId,\n tx_hash: receipt.txHash,\n token: receipt.token,\n amount: receipt.amount,\n to: receipt.to,\n resource_url: receipt.resourceUrl,\n explorer_url: receipt.explorerUrl,\n proof_header: receipt.proofHeader,\n rail: receipt.rail,\n challenge_id: receipt.challengeId,\n payer: receipt.payer,\n chain_id: receipt.chainId,\n }\n } catch (err) {\n return this.toolError(err)\n }\n }\n\n if (toolName === 'get_payment_status') {\n const { payment_id } = input as { payment_id: string }\n const result = await this.getPaymentStatus(payment_id)\n return {\n payment_id: result.paymentId,\n kind: result.kind,\n rail: result.rail,\n status: result.status,\n phase: result.phase,\n next_action: result.nextAction,\n tx_hash: result.txHash,\n token: result.token,\n amount: result.amount,\n resource_url: result.resourceUrl,\n merchant_address: result.merchantAddress,\n expires_at: result.expiresAt,\n chain_id: result.chainId,\n message: result.message,\n }\n }\n\n throw new Error(`Unknown tool: ${toolName}`)\n }\n\n private toolError(err: unknown): Record<string, unknown> {\n if (err instanceof HavenPaymentStateError) {\n return {\n success: false,\n payment_id: err.state.paymentId,\n kind: err.state.kind,\n rail: err.state.rail,\n status: err.state.status,\n phase: err.state.phase,\n next_action: err.state.nextAction,\n tx_hash: err.state.txHash,\n token: err.state.token,\n amount: err.state.amount,\n resource_url: err.state.resourceUrl,\n merchant_address: err.state.merchantAddress,\n expires_at: err.state.expiresAt,\n chain_id: err.state.chainId,\n message: err.state.message,\n error: err.message,\n }\n }\n\n if (err instanceof HavenApiError) {\n return {\n success: false,\n status_code: err.statusCode,\n error: err.message,\n body: err.body,\n }\n }\n\n return {\n success: false,\n error: err instanceof Error ? err.message : String(err),\n }\n }\n\n // ── HTTP Helpers ─────────────────────────────────────────────────\n\n private async post<T>(path: string, body: Record<string, unknown>): Promise<T> {\n return this.request<T>('POST', path, body)\n }\n\n private async get<T>(path: string): Promise<T> {\n return this.request<T>('GET', path)\n }\n\n private async request<T>(\n method: 'GET' | 'POST',\n path: string,\n body?: Record<string, unknown>,\n ): Promise<T> {\n const url = `${this.baseUrl}${path}`\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), this.requestTimeout)\n\n try {\n const res = await fetch(url, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`,\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n })\n\n const data = await res.json()\n\n if (!res.ok) {\n const message =\n (data as Record<string, unknown>).error as string\n ?? (data as Record<string, unknown>).details as string\n ?? `API request failed`\n throw new HavenApiError(message, res.status, data)\n }\n\n return data as T\n } catch (err) {\n if (err instanceof HavenApiError) throw err\n if (err instanceof Error && err.name === 'AbortError') {\n throw new HavenApiError(`Request to ${path} timed out`, 408)\n }\n throw new HavenApiError(\n `Request to ${path} failed: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n )\n } finally {\n clearTimeout(timeout)\n }\n }\n\n // ── Mapping Helpers ──────────────────────────────────────────────\n\n private mapPaymentResult(raw: RawStatusResponse): PaymentResult {\n return {\n paymentId: raw.payment_id,\n status: raw.status as PaymentStatus,\n token: raw.token,\n amount: raw.amount,\n to: raw.to,\n txHash: raw.tx_hash,\n errorMessage: raw.error_message,\n explorerUrl: raw.explorer_url ?? (raw.tx_hash ? buildExplorerUrl(raw.chain_id, raw.tx_hash) : null),\n createdAt: raw.created_at,\n signedAt: raw.signed_at,\n submittedAt: raw.submitted_at,\n confirmedAt: raw.confirmed_at,\n expiresAt: raw.expires_at,\n }\n }\n\n private mapPaymentStatusResult(raw: RawPaymentStatusResult): PaymentStatusResult {\n return {\n paymentId: raw.payment_id,\n kind: raw.kind,\n rail: raw.rail,\n status: raw.status,\n phase: raw.phase,\n nextAction: raw.next_action,\n amount: raw.amount,\n token: raw.token,\n resourceUrl: raw.resource_url,\n merchantAddress: raw.merchant_address,\n txHash: raw.tx_hash,\n expiresAt: raw.expires_at,\n chainId: raw.chain_id,\n message: raw.message,\n }\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction getPaymentHeaderValidBefore(paymentHeader: string): number {\n try {\n const payment = decodeBase64Json<{ payload?: { authorization?: { validBefore?: string } } }>(\n paymentHeader,\n )\n const payload = payment.payload as { authorization?: { validBefore?: string } }\n const validBeforeSeconds = Number(payload.authorization?.validBefore)\n if (Number.isFinite(validBeforeSeconds)) return validBeforeSeconds * 1000\n } catch {\n // If the header cannot be decoded, skip caching rather than hiding errors.\n }\n\n return 0\n}\n\nfunction decodeBase64Json<T>(value: string): T {\n return JSON.parse(atob(value)) as T\n}\n\nfunction parseProtocolReceiptHeader(value: string): Record<string, unknown> | undefined {\n try {\n return JSON.parse(atob(value)) as Record<string, unknown>\n } catch {\n try {\n return JSON.parse(value) as Record<string, unknown>\n } catch {\n return undefined\n }\n }\n}\n\nasync function responseSnippet(response: Response): Promise<string | null> {\n try {\n const text = await response.clone().text()\n return text.slice(0, 1000) || null\n } catch {\n return null\n }\n}\n","/**\n * Pre-built tool definitions for AI agent frameworks.\n *\n * These definitions describe the `make_payment` and `get_payment_status` tools\n * in the formats expected by Claude (Anthropic) and OpenAI.\n *\n * Usage with Claude:\n * const response = await anthropic.messages.create({\n * tools: havenTools.claude(),\n * ...\n * })\n *\n * Usage with OpenAI:\n * const response = await openai.chat.completions.create({\n * tools: havenTools.openai(),\n * ...\n * })\n */\n\n// ── JSON Schema (shared across formats) ──────────────────────────\n\nconst makePaymentSchema = {\n type: 'object' as const,\n properties: {\n token: {\n type: 'string' as const,\n description: 'Token to send. Gnosis Chain: EURe, USDC.e, xDAI. Base: USDC, ETH.',\n },\n amount: {\n type: 'string' as const,\n description: 'Amount to send as a decimal string, e.g. \"5.00\"',\n },\n to: {\n type: 'string' as const,\n description: 'Recipient Ethereum address (0x...)',\n },\n reason: {\n type: 'string' as const,\n description: 'Brief reason for this payment (for audit trail)',\n },\n },\n required: ['token', 'amount', 'to', 'reason'] as const,\n}\n\nconst getPaymentStatusSchema = {\n type: 'object' as const,\n properties: {\n payment_id: {\n type: 'string' as const,\n description: 'The payment ID returned from make_payment',\n },\n },\n required: ['payment_id'] as const,\n}\n\nconst authorizeX402Schema = {\n type: 'object' as const,\n properties: {\n url: {\n type: 'string' as const,\n description: 'The URL that returned HTTP 402',\n },\n payTo: {\n type: 'string' as const,\n description: 'Payment recipient address from the 402 response',\n },\n amount: {\n type: 'string' as const,\n description: 'Payment amount in atomic units (e.g. \"1000000\" for 1 USDC)',\n },\n asset: {\n type: 'string' as const,\n description: 'Token contract address from the 402 response',\n },\n network: {\n type: 'string' as const,\n description: 'CAIP-2 chain ID. \"eip155:100\" for Gnosis Chain, \"eip155:8453\" for Base.',\n },\n description: {\n type: 'string' as const,\n description: 'Description of the resource being paid for',\n },\n },\n required: ['url', 'payTo', 'amount', 'asset', 'network'] as const,\n}\n\nconst authorizeMachinePaymentSchema = {\n type: 'object' as const,\n properties: {\n challenge: {\n type: 'object' as const,\n description: 'Machine payment challenge returned by a Haven demo endpoint',\n },\n },\n required: ['challenge'] as const,\n}\n\nconst MAKE_PAYMENT_DESCRIPTION =\n 'Request and sign a payment from the user-controlled Safe within approved on-chain limits. ' +\n 'Haven authenticates the agent, validates the signed intent, and relays the Safe AllowanceModule transaction; it does not hold keys or control funds. ' +\n 'Gnosis Chain tokens: EURe, USDC.e, xDAI. Base tokens: USDC, ETH.'\n\nconst GET_STATUS_DESCRIPTION =\n 'Check the status of a previously initiated payment. ' +\n 'Accepts payment intent IDs and approval request IDs. Returns the current status, phase, next_action, transaction hash if available, and payment details.'\n\nconst AUTHORIZE_X402_DESCRIPTION =\n 'Authorize payment for an HTTP 402 (Payment Required) response. ' +\n 'When a paid API returns x402 payment requirements, use this tool to sign with the agent-owned delegate key and request a policy-limited Safe AllowanceModule top-up when needed. ' +\n 'Haven relays signed transactions only; the agent key authorizes payment and on-chain limits enforce spend. ' +\n 'If this returns pending_approval, tell the user it is waiting in Haven, call get_payment_status later, and retry the original x402 request only when next_action is retry_original_x402_request. Do not rewrite the SDK or loop retries while approval is pending. ' +\n 'Use the returned payment_header as the X-PAYMENT header on the retry request.'\n\nconst AUTHORIZE_MACHINE_PAYMENT_DESCRIPTION =\n 'Authorize a Haven machine-payment challenge, currently for the internal MPP demo rail. ' +\n 'The agent signs the payment, Haven relays it within the on-chain allowance, and the tool returns a proof header for the retry request.'\n\n// ── Claude (Anthropic) format ────────────────────────────────────\n\nexport interface ClaudeTool {\n name: string\n description: string\n input_schema: {\n type: 'object'\n properties: Record<string, unknown>\n required: readonly string[]\n }\n}\n\nfunction claudeTools(): ClaudeTool[] {\n return [\n {\n name: 'make_payment',\n description: MAKE_PAYMENT_DESCRIPTION,\n input_schema: makePaymentSchema,\n },\n {\n name: 'get_payment_status',\n description: GET_STATUS_DESCRIPTION,\n input_schema: getPaymentStatusSchema,\n },\n {\n name: 'authorize_x402_payment',\n description: AUTHORIZE_X402_DESCRIPTION,\n input_schema: authorizeX402Schema,\n },\n {\n name: 'authorize_machine_payment',\n description: AUTHORIZE_MACHINE_PAYMENT_DESCRIPTION,\n input_schema: authorizeMachinePaymentSchema,\n },\n ]\n}\n\n// ── OpenAI format ────────────────────────────────────────────────\n\nexport interface OpenAITool {\n type: 'function'\n function: {\n name: string\n description: string\n parameters: {\n type: 'object'\n properties: Record<string, unknown>\n required: readonly string[]\n }\n }\n}\n\nfunction openaiTools(): OpenAITool[] {\n return [\n {\n type: 'function',\n function: {\n name: 'make_payment',\n description: MAKE_PAYMENT_DESCRIPTION,\n parameters: makePaymentSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'get_payment_status',\n description: GET_STATUS_DESCRIPTION,\n parameters: getPaymentStatusSchema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'authorize_x402_payment',\n description: AUTHORIZE_X402_DESCRIPTION,\n parameters: authorizeX402Schema,\n },\n },\n {\n type: 'function',\n function: {\n name: 'authorize_machine_payment',\n description: AUTHORIZE_MACHINE_PAYMENT_DESCRIPTION,\n parameters: authorizeMachinePaymentSchema,\n },\n },\n ]\n}\n\n// ── Public API ───────────────────────────────────────────────────\n\nexport const havenTools = {\n /** Tool definitions in Anthropic/Claude format */\n claude: claudeTools,\n\n /** Tool definitions in OpenAI function-calling format */\n openai: openaiTools,\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@haven_ai/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "TypeScript SDK for Haven — agent wallet infrastructure",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -25,6 +25,7 @@
25
25
  "scripts": {
26
26
  "build": "tsup",
27
27
  "dev": "tsup --watch",
28
+ "test": "vitest run",
28
29
  "typecheck": "tsc --noEmit"
29
30
  },
30
31
  "keywords": [
@@ -39,10 +40,13 @@
39
40
  ],
40
41
  "license": "MIT",
41
42
  "dependencies": {
42
- "ethers": "^6.13.0"
43
+ "ethers": "^6.13.0",
44
+ "viem": "^2.48.11",
45
+ "x402": "^1.2.0"
43
46
  },
44
47
  "devDependencies": {
45
48
  "tsup": "^8.0.0",
46
- "typescript": "^5.7.0"
49
+ "typescript": "^5.7.0",
50
+ "vitest": "^3.2.4"
47
51
  }
48
52
  }