@haven_ai/sdk 0.1.3 → 0.1.5

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.d.ts DELETED
@@ -1,499 +0,0 @@
1
- interface HavenClientConfig {
2
- /** Haven API key (sk_agent_xxx) */
3
- apiKey: string;
4
- /** Agent's delegate EOA private key. If provided, the SDK handles signing automatically. */
5
- delegateKey?: string;
6
- /** Haven API base URL (default: http://localhost:3001) */
7
- baseUrl?: string;
8
- /** Optional wallet identity to send as the x402-wallet header. */
9
- x402Wallet?: string;
10
- /** Timeout in ms for individual HTTP requests (default: 30000) */
11
- requestTimeout?: number;
12
- /** Timeout in ms when polling for tx confirmation (default: 90000) */
13
- confirmationTimeout?: number;
14
- /** Polling interval in ms when waiting for confirmation (default: 3000) */
15
- pollingInterval?: number;
16
- }
17
- interface PaymentRequest {
18
- /** Token symbol: "EURe", "USDC.e", or "xDAI" */
19
- token: string;
20
- /** Amount as a decimal string, e.g. "5.00" */
21
- amount: string;
22
- /** Recipient Ethereum address (0x...) */
23
- to: string;
24
- }
25
- interface SignData {
26
- /** The hash to sign (keccak256, 0x-prefixed) */
27
- hash: string;
28
- /** Breakdown of values that were hashed — useful for debugging */
29
- components: {
30
- safe: string;
31
- token: string;
32
- to: string;
33
- amount: string;
34
- payment_token: string;
35
- payment: string;
36
- nonce: number;
37
- };
38
- /** Human-readable signing instructions */
39
- instructions: string;
40
- }
41
- interface PaymentIntent {
42
- /** Unique payment ID */
43
- paymentId: string;
44
- /** Current status */
45
- status: 'pending_signature';
46
- /** ISO 8601 expiry timestamp */
47
- expiresAt: string;
48
- /** Data needed to sign the payment */
49
- signData: SignData;
50
- }
51
- type PaymentStatus = 'pending_signature' | 'submitted' | 'confirmed' | 'pending_approval' | 'approved' | 'proposed' | 'executed' | 'rejected' | 'expired' | 'failed';
52
- interface PaymentResult {
53
- /** Unique payment ID */
54
- paymentId: string;
55
- /** Final status */
56
- status: PaymentStatus;
57
- /** Token that was sent */
58
- token: string;
59
- /** Amount that was sent (human-readable) */
60
- amount: string;
61
- /** Recipient address */
62
- to: string;
63
- /** On-chain transaction hash (present when confirmed) */
64
- txHash: string | null;
65
- /** Error message (present when failed) */
66
- errorMessage: string | null;
67
- /** Block explorer URL for the transaction (chain-dependent) */
68
- explorerUrl: string | null;
69
- /** ISO 8601 timestamps */
70
- createdAt: string;
71
- signedAt: string | null;
72
- submittedAt: string | null;
73
- confirmedAt: string | null;
74
- expiresAt: string;
75
- }
76
- /** Payment requirements from an HTTP 402 response (x402 protocol). */
77
- interface X402PaymentRequired {
78
- x402Version: number;
79
- resource: {
80
- url: string;
81
- description?: string;
82
- mimeType?: string;
83
- };
84
- accepts: X402PaymentOption[];
85
- error?: string;
86
- }
87
- /** A single payment option from x402 PaymentRequired. */
88
- interface X402PaymentOption {
89
- scheme: string;
90
- network: string;
91
- amount: string;
92
- maxAmountRequired?: string;
93
- resource?: string;
94
- description?: string;
95
- mimeType?: string;
96
- asset: string;
97
- payTo: string;
98
- maxTimeoutSeconds: number;
99
- extra?: Record<string, unknown>;
100
- }
101
- /** Receipt returned after a successful x402 payment. */
102
- interface X402Receipt {
103
- success: boolean;
104
- paymentId: string;
105
- txHash: string;
106
- token: string;
107
- amount: string;
108
- to: string;
109
- resourceUrl: string;
110
- explorerUrl: string;
111
- accepted?: X402PaymentOption;
112
- paymentHeader?: string;
113
- merchantTo?: string | null;
114
- payer?: string;
115
- chainId?: number;
116
- haven?: {
117
- paymentId: string;
118
- fundingTxHash: string;
119
- fundingExplorerUrl: string;
120
- };
121
- merchant?: {
122
- payTo: string | null;
123
- settlementTxHash?: string | null;
124
- settlementExplorerUrl?: string | null;
125
- };
126
- x402?: {
127
- amount: string;
128
- token: string;
129
- network: string;
130
- asset: string;
131
- resource: string;
132
- };
133
- }
134
- interface X402AuthorizationOptions {
135
- /** Stable caller-supplied key for this user intent. Prevents duplicate approvals across fresh 402 quotes. */
136
- idempotencyKey?: string;
137
- }
138
- interface ResumeAuthorizedX402Input extends X402AuthorizationOptions {
139
- /** Payment or approval request ID returned by authorizeX402 / haven.fetch. */
140
- paymentId: string;
141
- /** Original or freshly parsed x402 requirements for the merchant retry. */
142
- paymentRequired: X402PaymentRequired;
143
- }
144
- interface ResumeX402PaymentInput extends X402AuthorizationOptions {
145
- /** Payment or approval request ID returned by authorizeX402 / haven.fetch. */
146
- paymentId: string;
147
- /** Original paid URL. If paymentRequired is omitted, Haven will call it once to re-read the 402 challenge. */
148
- url: string;
149
- /** Original fetch options. Reused for the 402 probe and final merchant retry. */
150
- init?: RequestInit;
151
- /** Original or freshly parsed x402 requirements. Supplying this avoids an extra merchant 402 probe. */
152
- paymentRequired?: X402PaymentRequired;
153
- }
154
- type MachinePaymentRail = 'x402' | 'mpp_demo' | 'mpp_crypto' | 'stripe_deposit' | 'spt';
155
- interface MachinePaymentChallenge {
156
- rail: MachinePaymentRail;
157
- version: string;
158
- challengeId: string;
159
- resource: string;
160
- description: string;
161
- network: {
162
- chainId: number;
163
- name: 'base';
164
- };
165
- asset: {
166
- symbol: 'USDC';
167
- address: string;
168
- decimals: 6;
169
- };
170
- amount: {
171
- display: string;
172
- atomic: string;
173
- };
174
- recipient: string;
175
- expiresAt: string;
176
- metadata?: Record<string, unknown>;
177
- }
178
- interface MachinePaymentReceipt {
179
- success: boolean;
180
- rail: MachinePaymentRail;
181
- paymentId: string;
182
- challengeId: string;
183
- txHash: string;
184
- token: string;
185
- amount: string;
186
- to: string;
187
- resourceUrl: string;
188
- explorerUrl: string;
189
- payer?: string;
190
- chainId?: number;
191
- proofHeader: string;
192
- }
193
- type PaymentStateKind = 'payment_intent' | 'approval_request';
194
- type PaymentPhase = 'agent_signature_required' | 'payment_submitted' | 'payment_confirmed' | 'user_approval_required' | 'user_execution_required' | 'waiting_for_additional_approvals' | 'funding_sent' | 'rejected' | 'expired' | 'failed';
195
- type PaymentNextAction = 'sign_and_submit_payment' | 'check_status_later' | 'none' | 'wait_for_user_approval' | 'wait_for_user_to_complete_payment' | 'retry_original_x402_request' | 'stop_and_tell_user' | 'request_again_if_user_still_wants_it';
196
- interface PaymentStatusResult {
197
- paymentId: string;
198
- kind: PaymentStateKind;
199
- rail: string;
200
- status: PaymentStatus | string;
201
- phase: PaymentPhase;
202
- nextAction: PaymentNextAction;
203
- amount: string;
204
- token: string;
205
- resourceUrl: string | null;
206
- merchantAddress: string | null;
207
- txHash: string | null;
208
- expiresAt: string;
209
- chainId: number;
210
- message: string;
211
- }
212
- interface PendingApproval extends PaymentStatusResult {
213
- kind: 'approval_request';
214
- status: 'pending_approval' | 'pending' | string;
215
- phase: 'user_approval_required';
216
- nextAction: 'wait_for_user_approval';
217
- requested?: string;
218
- remaining?: string | null;
219
- }
220
- declare class HavenError extends Error {
221
- readonly code: string;
222
- readonly statusCode?: number | undefined;
223
- readonly paymentId?: string | undefined;
224
- constructor(message: string, code: string, statusCode?: number | undefined, paymentId?: string | undefined);
225
- }
226
- declare class HavenApiError extends HavenError {
227
- readonly body?: unknown | undefined;
228
- constructor(message: string, statusCode: number, body?: unknown | undefined, paymentId?: string);
229
- }
230
- declare class HavenPaymentStateError extends HavenApiError {
231
- readonly state: PaymentStatusResult;
232
- constructor(message: string, statusCode: number, state: PaymentStatusResult, body?: unknown);
233
- get status(): string;
234
- get phase(): PaymentPhase;
235
- get nextAction(): PaymentNextAction;
236
- }
237
- declare class HavenSigningError extends HavenError {
238
- constructor(message: string);
239
- }
240
- declare class HavenTimeoutError extends HavenError {
241
- constructor(paymentId: string);
242
- }
243
-
244
- declare class HavenClient {
245
- private readonly apiKey;
246
- private readonly delegateKey;
247
- private readonly baseUrl;
248
- private readonly x402Wallet;
249
- private readonly requestTimeout;
250
- private readonly confirmationTimeout;
251
- private readonly pollingInterval;
252
- private readonly inFlightX402;
253
- private readonly x402ReceiptCache;
254
- private readonly inFlightMachinePayments;
255
- /** Delegate address derived from the private key (if provided) */
256
- readonly delegateAddress: string | undefined;
257
- constructor(config: HavenClientConfig);
258
- /**
259
- * Send a payment in one call.
260
- *
261
- * Creates the intent, signs the hash, submits the signature,
262
- * and polls until confirmed (or throws on failure/timeout).
263
- *
264
- * Requires `delegateKey` to be set in the client config.
265
- */
266
- pay(request: PaymentRequest): Promise<PaymentResult>;
267
- /**
268
- * Step 1: Create a payment intent.
269
- *
270
- * Returns the intent with the hash to sign.
271
- */
272
- createIntent(request: PaymentRequest): Promise<PaymentIntent>;
273
- /**
274
- * Step 2: Sign a hash with the delegate key.
275
- *
276
- * Returns the 65-byte signature (0x-prefixed).
277
- * Requires `delegateKey` to be set in the client config.
278
- */
279
- sign(hash: string): string;
280
- /**
281
- * Step 3: Submit a signature to execute the payment.
282
- *
283
- * The signature can come from `client.sign()` or from external signing.
284
- */
285
- submitSignature(paymentId: string, signature: string): Promise<{
286
- status: string;
287
- txHash?: string;
288
- }>;
289
- /**
290
- * Get the current status of a payment.
291
- */
292
- getPayment(paymentId: string): Promise<PaymentResult>;
293
- /**
294
- * Get agent-actionable status for a payment intent or approval request.
295
- *
296
- * Use this for IDs returned by agent tools and machine-payment/x402 flows.
297
- * `getPayment()` remains available for payment-intent-only integrations.
298
- */
299
- getPaymentStatus(paymentId: string): Promise<PaymentStatusResult>;
300
- /**
301
- * Poll until a payment reaches a terminal status (confirmed, failed, expired).
302
- */
303
- waitForConfirmation(paymentId: string): Promise<PaymentResult>;
304
- /**
305
- * Authorize an x402 payment.
306
- *
307
- * Takes the parsed PaymentRequired from a 402 response, selects a compatible
308
- * option, funds the delegate wallet through Haven, and returns the standard
309
- * x402 header that the merchant can verify and settle.
310
- *
311
- * Requires `delegateKey` to be set in the client config.
312
- */
313
- authorizeX402(paymentRequired: X402PaymentRequired, options?: X402AuthorizationOptions): Promise<X402Receipt>;
314
- private authorizeStandardX402;
315
- resumeAuthorizedX402(input: ResumeAuthorizedX402Input): Promise<X402Receipt>;
316
- resumeX402Payment(input: ResumeX402PaymentInput): Promise<Response>;
317
- /**
318
- * Fetch wrapper that automatically handles HTTP 402 responses.
319
- *
320
- * Works like the standard `fetch()` but intercepts 402 responses,
321
- * pays via x402 through Haven, and retries the request.
322
- *
323
- * ```ts
324
- * const response = await haven.fetch('https://paid-api.com/data')
325
- * const data = await response.json()
326
- * ```
327
- *
328
- * Requires `delegateKey` to be set in the client config.
329
- */
330
- fetch(url: string, init?: RequestInit, options?: X402AuthorizationOptions): Promise<Response>;
331
- private retryX402Request;
332
- authorizeMachinePayment(challenge: MachinePaymentChallenge): Promise<MachinePaymentReceipt>;
333
- private authorizeMppDemoPayment;
334
- private fetchWithMachinePayment;
335
- private assertCanResumeX402;
336
- private mapX402ReceiptFromAuthorization;
337
- private mapX402ReceiptFromStatus;
338
- private buildX402Receipt;
339
- private createStandardX402Header;
340
- private cacheX402Receipt;
341
- private mapMachinePaymentReceipt;
342
- private recordMerchantRetryRejected;
343
- private reportMachinePaymentEvidence;
344
- private throwIfNonSignableAuthorizationState;
345
- private throwPaymentStateError;
346
- private paymentStateFromRaw;
347
- private x402PayerAddress;
348
- private withX402Wallet;
349
- /**
350
- * Execute a tool call by name and input.
351
- *
352
- * Designed to plug directly into agent tool-call handlers:
353
- *
354
- * ```ts
355
- * if (block.type === 'tool_use') {
356
- * const result = await haven.executeTool(block.name, block.input)
357
- * // send result back to the model
358
- * }
359
- * ```
360
- */
361
- executeTool(toolName: string, input: Record<string, unknown>): Promise<Record<string, unknown>>;
362
- private toolX402PaymentRequired;
363
- private x402ToolReceipt;
364
- private toolError;
365
- private post;
366
- private get;
367
- private request;
368
- private mapPaymentResult;
369
- private mapPaymentStatusResult;
370
- }
371
-
372
- /**
373
- * Pre-built tool definitions for AI agent frameworks.
374
- *
375
- * These definitions describe the `make_payment` and `get_payment_status` tools
376
- * in the formats expected by Claude (Anthropic) and OpenAI.
377
- *
378
- * Usage with Claude:
379
- * const response = await anthropic.messages.create({
380
- * tools: havenTools.claude(),
381
- * ...
382
- * })
383
- *
384
- * Usage with OpenAI:
385
- * const response = await openai.chat.completions.create({
386
- * tools: havenTools.openai(),
387
- * ...
388
- * })
389
- */
390
- interface ClaudeTool {
391
- name: string;
392
- description: string;
393
- input_schema: {
394
- type: 'object';
395
- properties: Record<string, unknown>;
396
- required: readonly string[];
397
- };
398
- }
399
- declare function claudeTools(): ClaudeTool[];
400
- interface OpenAITool {
401
- type: 'function';
402
- function: {
403
- name: string;
404
- description: string;
405
- parameters: {
406
- type: 'object';
407
- properties: Record<string, unknown>;
408
- required: readonly string[];
409
- };
410
- };
411
- }
412
- declare function openaiTools(): OpenAITool[];
413
- declare const havenTools: {
414
- /** Tool definitions in Anthropic/Claude format */
415
- claude: typeof claudeTools;
416
- /** Tool definitions in OpenAI function-calling format */
417
- openai: typeof openaiTools;
418
- };
419
-
420
- /**
421
- * Sign a hash using raw ECDSA (no Ethereum message prefix).
422
- *
423
- * This matches what Safe's AllowanceModule `checkSignature` expects —
424
- * a direct ecrecover over the hash, NOT the "\x19Ethereum Signed Message" variant.
425
- *
426
- * Uses ethers.SigningKey.sign() instead of wallet.signMessage() to avoid the prefix.
427
- */
428
- declare function signHash(privateKey: string, hash: string): string;
429
- /**
430
- * Derive the Ethereum address from a private key.
431
- */
432
- declare function addressFromKey(privateKey: string): string;
433
- /**
434
- * Verify that a signature over a hash recovers to the expected address.
435
- */
436
- declare function verifySignature(hash: string, signature: string, expectedAddress: string): boolean;
437
-
438
- /**
439
- * x402 protocol support for the Haven SDK.
440
- *
441
- * Provides:
442
- * - parsePaymentRequired() — extract payment requirements from a 402 response
443
- * - parsePaymentRequiredResponse() — async parser with JSON body fallback
444
- * - encodePaymentProof() — encode a receipt as a PAYMENT-SIGNATURE header
445
- *
446
- * The main authorizeX402() and fetchWithPayment() are methods on HavenClient
447
- * (see client.ts) since they need API access and signing.
448
- */
449
-
450
- /**
451
- * Parse an HTTP 402 response into x402 PaymentRequired data.
452
- *
453
- * Supports:
454
- * - v2: PAYMENT-REQUIRED header (base64 JSON)
455
- * - v1 fallback: X-PAYMENT header or response body
456
- */
457
- declare function parsePaymentRequired(response: Response): X402PaymentRequired;
458
- /**
459
- * Parse an HTTP 402 response into x402 PaymentRequired data.
460
- *
461
- * Soundside and other Bazaar-style MCP endpoints return the PaymentRequired
462
- * object in the JSON body, while older Haven demos and many x402 examples use
463
- * base64 headers. This keeps the synchronous header parser intact and adds the
464
- * body fallback needed for those endpoints.
465
- */
466
- declare function parsePaymentRequiredResponse(response: Response): Promise<X402PaymentRequired>;
467
- /**
468
- * Select the best payment option from the x402 accepts array.
469
- *
470
- * Preference order:
471
- * 1. Option on a Haven-supported network with a known token
472
- * 2. Any option on a Haven-supported network
473
- * 3. null — no compatible option
474
- */
475
- declare function selectPaymentOption(accepts: X402PaymentOption[]): X402PaymentOption | null;
476
- /**
477
- * Encode a payment receipt as a base64 PAYMENT-SIGNATURE header value.
478
- *
479
- * This follows the x402 v2 protocol — the server's facilitator will
480
- * verify the on-chain transaction referenced by tx_hash.
481
- */
482
- declare function encodePaymentProof(receipt: {
483
- txHash: string;
484
- paymentId: string;
485
- token: string;
486
- amount: string;
487
- to: string;
488
- resourceUrl?: string;
489
- accepted?: X402PaymentOption;
490
- payer?: string;
491
- chainId?: number;
492
- }): string;
493
-
494
- declare function parseMachinePaymentChallenge(response: Response): MachinePaymentChallenge;
495
- declare function parseMachinePaymentChallengeResponse(response: Response): Promise<MachinePaymentChallenge>;
496
- declare function buildMachinePaymentIdempotencyKey(challenge: MachinePaymentChallenge): string;
497
- declare function encodeMachinePaymentProof(receipt: Omit<MachinePaymentReceipt, 'proofHeader'>): string;
498
-
499
- export { type ClaudeTool, HavenApiError, HavenClient, type HavenClientConfig, HavenError, HavenPaymentStateError, HavenSigningError, HavenTimeoutError, type MachinePaymentChallenge, type MachinePaymentRail, type MachinePaymentReceipt, type OpenAITool, type PaymentIntent, type PaymentNextAction, type PaymentPhase, type PaymentRequest, type PaymentResult, type PaymentStatus, type PaymentStatusResult, type PendingApproval, type ResumeAuthorizedX402Input, type ResumeX402PaymentInput, type SignData, type X402AuthorizationOptions, type X402PaymentOption, type X402PaymentRequired, type X402Receipt, addressFromKey, buildMachinePaymentIdempotencyKey, encodeMachinePaymentProof, encodePaymentProof, havenTools, parseMachinePaymentChallenge, parseMachinePaymentChallengeResponse, parsePaymentRequired, parsePaymentRequiredResponse, selectPaymentOption, signHash, verifySignature };