@hypawave/sdk 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hypawave
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,427 @@
1
+ # @hypawave/sdk
2
+
3
+ **Lightning SDK for AI Agent Payments — non-custodial Bitcoin settlement with preimage proof**
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@hypawave/sdk.svg)](https://www.npmjs.com/package/@hypawave/sdk)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/hypawave/sdk/blob/main/LICENSE)
7
+ [![Node >= 18](https://img.shields.io/badge/Node-%3E%3D18-brightgreen.svg)](https://nodejs.org)
8
+
9
+ *Status: Alpha. API is usable; breaking changes possible before 1.0.*
10
+
11
+ TypeScript SDK for settlement-triggered Lightning execution. Fetch creator-direct Lightning invoices, confirm preimage proof, and trigger deterministic unlocks.
12
+
13
+ **Payment is the authorization — confirmed settlement unconditionally unlocks access.**
14
+
15
+ ## Why Hypawave
16
+
17
+ AI agents need to pay and get access without accounts, custody, or manual delivery. Hypawave turns Lightning settlement proof into deterministic execution — the same preimage that proves payment also unlocks the file, the API call, or the webhook.
18
+
19
+ This SDK covers **Path 2**: account-based agent flows. Accountless Paths 3a and 3b use raw HTTP via [llms.txt](https://hypawave.com/llms.txt) and the [OpenAPI spec](https://hypawave.com/.well-known/openapi.json). Requires programmable Lightning infrastructure (LND, CLN, Alby API, LNbits, NWC, etc.) that returns the preimage after payment.
20
+
21
+ ## Features
22
+
23
+ - **Non-custodial** — buyers pay creators directly; Hypawave never holds principal funds
24
+ - **Cryptographic settlement proof** — SHA256(preimage) == payment_hash verification
25
+ - **40+ fiat currencies** with live BTC conversion
26
+ - **End-to-end encrypted file delivery** — payment-gated AES-256-GCM decryption keys
27
+ - **Agent-to-agent interop** — self-describing payment payloads, zero-friction for payer agents
28
+ - **Pre-authorization** — terms_hash snapshot prevents price manipulation between fetch and pay
29
+ - **Settlement-triggered execution webhooks** — fire server-side actions on payment confirmation
30
+ - **Programmable invoice expiry** — 1h, 24h, 7d, or never
31
+
32
+ ## Requirements
33
+
34
+ This SDK requires **programmable Lightning infrastructure** that exposes the preimage after payment:
35
+
36
+ - LND, CLN, Alby API, LNbits, NWC, or equivalent
37
+
38
+ **Consumer wallets (Wallet of Satoshi, Phoenix, etc.) do not reliably expose the preimage and are not suitable for agent integrations.** Files and data will not unlock without a preimage.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ npm install @hypawave/sdk
44
+ ```
45
+
46
+ ## Quick Start
47
+
48
+ ```typescript
49
+ import { Hypawave } from "@hypawave/sdk";
50
+
51
+ const pp = new Hypawave({ apiKey: "sk_live_..." });
52
+
53
+ // Create a payment request for a payer agent
54
+ const invoice = await pp.createInvoice({
55
+ client_email: "alice@example.com",
56
+ client_first_name: "Alice",
57
+ client_last_name: "Smith",
58
+ amount: 5.00,
59
+ due_date: "2026-12-31",
60
+ payment_destination: "creator@getalby.com",
61
+ });
62
+
63
+ console.log(invoice.invoice_id); // Use for confirmation + key retrieval
64
+ console.log(invoice.sats); // Amount in satoshis
65
+
66
+ // Fetch the creator-direct Lightning invoice + terms hash
67
+ const { pr: bolt11, terms_hash } = await pp.getBolt11(invoice.access_token);
68
+
69
+ // Pay with programmable Lightning infrastructure that returns a preimage
70
+ const payResult = await yourLightningNode.pay(bolt11);
71
+
72
+ // Submit preimage proof to trigger settlement and deterministic unlock
73
+ await pp.confirmPayment(invoice.invoice_id, {
74
+ payment_hash: payResult.payment_hash,
75
+ preimage: payResult.preimage,
76
+ terms_hash,
77
+ });
78
+
79
+ // Retrieve files and decryption keys
80
+ const fileData = await pp.getInvoiceFiles([invoice.invoice_id]);
81
+ const files = fileData.files[invoice.invoice_id] || [];
82
+
83
+ for (const file of files) {
84
+ const { downloadUrl } = await pp.getDownloadUrl(file.id);
85
+ const key = await pp.getKey(file.id);
86
+ // downloadUrl = signed URL to fetch the encrypted file
87
+ // key.encryption_key = AES-256-GCM key (base64)
88
+ // key.iv_hex = initialization vector (hex)
89
+ }
90
+ ```
91
+
92
+ ## Settlement Flow
93
+
94
+ ```
95
+ createInvoice ──▶ getBolt11 ──▶ pay (your node) ──▶ confirmPayment ──▶ unlock
96
+ (terms) (bolt11) (preimage) (proof) (files/exec)
97
+ ```
98
+
99
+ Three calls to Hypawave, one call to your Lightning node. Preimage from your node closes the loop.
100
+
101
+ ## SDK for ergonomics. Raw HTTP for accountless agents.
102
+
103
+ The SDK handles types, retries, polling, error parsing, and self-describing payload generation for **Path 2** (account-based agent API). Use raw HTTP when you need:
104
+
105
+ - **Accountless keypair auth** (Paths 3a and 3b) — secp256k1-signed requests, no API key
106
+ - **Zero npm dependencies** — language-agnostic agents, three HTTP calls
107
+ - **Direct OpenAPI consumption** — code generation, MCP servers, raw `curl`
108
+
109
+ Resources for raw HTTP:
110
+
111
+ - **Agent instructions**: [hypawave.com/llms.txt](https://hypawave.com/llms.txt) — step-by-step settlement flows for LLM-powered agents
112
+ - **OpenAPI spec**: [hypawave.com/.well-known/openapi.json](https://hypawave.com/.well-known/openapi.json) — full machine-readable API schema (OpenAPI 3.1)
113
+
114
+ ## API
115
+
116
+ ### `new Hypawave(config)`
117
+
118
+ | Parameter | Type | Default | Description |
119
+ |-----------|------|---------|-------------|
120
+ | `apiKey` | `string` | — | API key (`sk_test_*` or `sk_live_*`) |
121
+ | `baseUrl` | `string` | `https://hypawave.com` | API base URL |
122
+ | `timeout` | `number` | `30000` | Request timeout in ms |
123
+
124
+ ### `createInvoice(params)`
125
+
126
+ Create a payment request. Returns a payment URL for the payer.
127
+
128
+ ```typescript
129
+ const invoice = await pp.createInvoice({
130
+ client_email: "payer@example.com",
131
+ client_first_name: "Jane",
132
+ client_last_name: "Doe",
133
+ amount: 10.00,
134
+ due_date: "2026-12-31",
135
+ payment_destination: "creator@getalby.com",
136
+ description: "API access for December",
137
+ currency: "USD", // 40+ currencies supported
138
+ expires_in: "24h", // "1h", "24h", "7d", or null
139
+ execution_webhook: "https://your-server.com/on-paid", // optional
140
+ });
141
+ ```
142
+
143
+ ### `getBolt11(accessToken)`
144
+
145
+ Fetch the creator-issued Lightning bolt11 invoice for payment. The `access_token`
146
+ is returned by `createInvoice()`.
147
+
148
+ ```typescript
149
+ const { pr: bolt11, terms_hash } = await pp.getBolt11(invoice.access_token);
150
+ // bolt11 is the Lightning invoice to pay via your node/API
151
+ // terms_hash is used for pre-authorization verification at confirm time
152
+ ```
153
+
154
+ ### `confirmPayment(invoiceId, params)`
155
+
156
+ Confirm settlement by submitting the Lightning preimage. Call this after paying
157
+ the creator-issued bolt11. Your Lightning node or API returns the `payment_hash`
158
+ and `preimage` on successful payment — pass them here.
159
+
160
+ ```typescript
161
+ const result = await pp.confirmPayment(invoice.invoice_id, {
162
+ payment_hash: paymentResponse.payment_hash,
163
+ preimage: paymentResponse.preimage,
164
+ terms_hash, // optional but recommended — rejects if terms changed
165
+ });
166
+ // result.ok === true
167
+ // result.already_settled === false (or true on retry)
168
+ ```
169
+
170
+ ### `getPaymentPayload(params, response)`
171
+
172
+ Build a self-describing payment payload to send to another agent, API, or service.
173
+ The receiver can pay using three HTTP calls — no Hypawave SDK, account, or prior
174
+ knowledge required.
175
+
176
+ ```typescript
177
+ const params = { amount: 5.00, currency: "USD", description: "API access", ... };
178
+ const invoice = await pp.createInvoice(params);
179
+ const payload = pp.getPaymentPayload(params, invoice);
180
+
181
+ // Send `payload` to the receiving agent/API
182
+ // The receiver follows:
183
+ // 1. Read payload.instructions_url for full settlement instructions
184
+ // 2. GET payload.bolt11_url → fetch bolt11
185
+ // 3. Pay the bolt11 via Lightning node
186
+ // 4. POST payload.confirm_url with { payment_hash, preimage }
187
+ ```
188
+
189
+ ### `getBalance(currency?)`
190
+
191
+ Check your settlement balance.
192
+
193
+ ```typescript
194
+ const balance = await pp.getBalance("USD");
195
+ console.log(balance.available_sats);
196
+ console.log(balance.has_outstanding_fee); // true = top up needed
197
+ ```
198
+
199
+ ### `topup()`
200
+
201
+ Generate a Lightning invoice to clear outstanding fees. Top-ups are strictly
202
+ fee-settlement — the server mints a bolt11 for exactly the amount owed, so
203
+ you do not pass an amount. If your balance is already at or above zero the
204
+ call returns `topup_not_needed` (HTTP 400).
205
+
206
+ ```typescript
207
+ const topup = await pp.topup();
208
+ console.log(topup.bolt11); // Pay this invoice
209
+ console.log(topup.amount_sats); // Exact owed amount the server quoted
210
+ if (topup.reused) {
211
+ // An existing pending top-up was returned instead of a fresh one.
212
+ }
213
+ ```
214
+
215
+ ### `getUnlockStatus(invoiceIds)`
216
+
217
+ Check settlement status for up to 25 invoices at once.
218
+
219
+ ```typescript
220
+ const status = await pp.getUnlockStatus([101, 102, 103]);
221
+
222
+ for (const [id, info] of Object.entries(status.statuses)) {
223
+ console.log(id, info.unlocked, info.settlement_proof?.preimage);
224
+ }
225
+ ```
226
+
227
+ ### `getInvoiceFiles(invoiceIds, token?)`
228
+
229
+ Fetch file metadata for up to 25 invoices. Returns file IDs, names, and encrypted
230
+ file URLs grouped by invoice ID. Supports agent auth (Bearer) or payer auth
231
+ (`token` = access_token from invoice).
232
+
233
+ ```typescript
234
+ // Agent auth (creator-side)
235
+ const fileData = await pp.getInvoiceFiles([42, 43]);
236
+
237
+ // Payer auth (access_token from invoice or payment payload)
238
+ const fileData = await pp.getInvoiceFiles([42], invoice.access_token);
239
+
240
+ const files = fileData.files[42] || [];
241
+ // files[0].id — file ID (use with getDownloadUrl and getKey)
242
+ // files[0].file_name — original file name
243
+ ```
244
+
245
+ ### `getDownloadUrl(invoiceFileId, token?)`
246
+
247
+ Generate a signed download URL (5 min) for an encrypted file. The invoice must be
248
+ paid. Supports agent auth (Bearer) or payer auth (`token` = access_token).
249
+
250
+ ```typescript
251
+ // Agent auth
252
+ const { downloadUrl } = await pp.getDownloadUrl(fileId);
253
+
254
+ // Payer auth
255
+ const { downloadUrl } = await pp.getDownloadUrl(fileId, invoice.access_token);
256
+ ```
257
+
258
+ ### `getKey(invoiceFileId, token?)`
259
+
260
+ Retrieve the decryption key for a specific file. Requires the invoice to be paid.
261
+ Download attempts are tracked — a 72-hour reclaim window applies. Supports agent
262
+ auth (Bearer) or payer auth (`token` = access_token).
263
+
264
+ ```typescript
265
+ // Agent auth
266
+ const key = await pp.getKey(fileId);
267
+
268
+ // Payer auth
269
+ const key = await pp.getKey(fileId, invoice.access_token);
270
+ // key.encryption_key — Base64 AES-256-GCM key
271
+ // key.iv_hex — Hex IV for decryption
272
+ // key.downloads_used — number of downloads so far
273
+ // key.max_downloads — maximum allowed
274
+ ```
275
+
276
+ ### `getOfferDownloadUrl(paymentIntentId, params)`
277
+
278
+ Generate a signed download URL (5 min) for a single encrypted offer file (Path 3b).
279
+ Scoped to a specific `offer_file_id` — must belong to the payment intent's offer.
280
+ Authenticated via `claim_token` or `preimage`.
281
+
282
+ ```typescript
283
+ const { downloadUrl } = await pp.getOfferDownloadUrl(paymentIntentId, {
284
+ offer_file_id: fileId,
285
+ claim_token: claimToken,
286
+ });
287
+ // downloadUrl — time-limited signed URL to fetch the encrypted file
288
+ ```
289
+
290
+ ### `waitForSettlement(invoiceId, options?)`
291
+
292
+ Poll until an invoice settles, fails, or expires.
293
+
294
+ ```typescript
295
+ const result = await pp.waitForSettlement(invoiceId, {
296
+ pollInterval: 2000, // ms between polls (default: 2000)
297
+ timeout: 300000, // max wait time in ms (default: 300000)
298
+ });
299
+
300
+ if (result.unlocked) {
301
+ const fileData = await pp.getInvoiceFiles([invoiceId]);
302
+ const files = fileData.files[invoiceId] || [];
303
+ for (const file of files) {
304
+ const { downloadUrl } = await pp.getDownloadUrl(file.id);
305
+ const key = await pp.getKey(file.id);
306
+ // Fetch encrypted file from downloadUrl, decrypt with key
307
+ }
308
+ }
309
+ ```
310
+
311
+ ### `getReceipt(invoiceId)`
312
+
313
+ Fetch a settled invoice receipt with cryptographic proof.
314
+
315
+ ```typescript
316
+ const { receipt } = await pp.getReceipt(invoiceId);
317
+ // receipt.payment_hash, receipt.preimage, receipt.receipt_verified
318
+ // receipt.amount, receipt.currency, receipt.settled_at
319
+ // receipt.creator, receipt.file_count
320
+ ```
321
+
322
+ ### `getSettings()`
323
+
324
+ Fetch current platform configuration (fee percentage, amount limits, file limits,
325
+ BTC price). Values are admin-configurable and may change.
326
+
327
+ ```typescript
328
+ const settings = await pp.getSettings();
329
+ // settings.fee_percent, settings.min_invoice_usd, settings.max_invoice_usd
330
+ // settings.max_file_size_mb, settings.max_files_per_invoice
331
+ // settings.btc_usd_price
332
+ ```
333
+
334
+ ## Error Handling
335
+
336
+ All API errors throw `HypawaveAPIError` with structured fields:
337
+
338
+ ```typescript
339
+ import { Hypawave, HypawaveAPIError } from "@hypawave/sdk";
340
+
341
+ try {
342
+ await pp.createInvoice({ ... });
343
+ } catch (err) {
344
+ if (err instanceof HypawaveAPIError) {
345
+ console.log(err.status); // HTTP status code
346
+ console.log(err.code); // Error code (e.g. "validation_error")
347
+ console.log(err.message); // Human-readable message
348
+ console.log(err.field); // Field name (validation errors)
349
+
350
+ if (err.isAuth) { /* re-authenticate */ }
351
+ if (err.isRateLimit) { /* back off */ }
352
+ if (err.isOutstandingFee) { /* 402 outstanding_fee — call pp.topup() */ }
353
+ }
354
+ }
355
+ ```
356
+
357
+ ## Agent-to-Agent Flow
358
+
359
+ ```typescript
360
+ // Agent A (creator): Create a payment request and build the payload
361
+ const params = {
362
+ client_email: "agentb@system.ai",
363
+ client_first_name: "Agent",
364
+ client_last_name: "B",
365
+ amount: 2.00,
366
+ due_date: "2026-12-31",
367
+ payment_destination: "creator@getalby.com",
368
+ description: "Dataset access: Q4 training data",
369
+ };
370
+ const invoice = await agentA.createInvoice(params);
371
+ const payload = agentA.getPaymentPayload(params, invoice);
372
+
373
+ // Agent A sends `payload` to Agent B (via HTTP, MCP, A2A, etc.)
374
+
375
+ // Agent B (payer): three HTTP calls — no SDK, no account needed
376
+ const bolt11Res = await fetch(payload.bolt11_url);
377
+ const { pr: bolt11 } = await bolt11Res.json();
378
+
379
+ const payResult = await agentBNode.pay(bolt11); // Lightning node/API
380
+
381
+ await fetch(payload.confirm_url, {
382
+ method: "POST",
383
+ headers: { "Content-Type": "application/json" },
384
+ body: JSON.stringify({
385
+ payment_hash: payResult.payment_hash,
386
+ preimage: payResult.preimage,
387
+ }),
388
+ });
389
+ // Settlement confirmed — files unlocked for retrieval
390
+ ```
391
+
392
+ For the complete raw HTTP flow (file retrieval, Path 3a/3b, and more), see [llms.txt](https://hypawave.com/llms.txt).
393
+
394
+ ## Where Hypawave Fits In The Agent Payment Stack
395
+
396
+ Most tools handle checkout, paid requests, or wallet rails. **Hypawave executes APIs, files, and actions after Bitcoin settlement is verified.**
397
+
398
+ *This is a layer comparison, not a claim that these tools are interchangeable.*
399
+
400
+ | Capability | Hypawave | Stripe Machine Payments | x402 | ACP | AP2 | Raw Lightning |
401
+ |---|:---:|:---:|:---:|:---:|:---:|:---:|
402
+ | Payment proof triggers release/execution | ✅ | ⚠️ payment + usage rails | ⚠️ per-request paywall | ❌ checkout layer | ❌ authorization layer | ❌ no app layer |
403
+ | Customer funds bypass platform custody | ✅ | ❌ Stripe balance | ⚠️ facilitator-dependent | ❌ platform-mediated | ⚠️ rail-dependent | ✅ |
404
+ | Bitcoin/Lightning-native | ✅ | ❌ cards + stablecoins | ❌ stablecoin-first | ❌ checkout protocol | ⚠️ rail-dependent | ✅ |
405
+ | Cryptographic settlement proof | ✅ | ⚠️ platform records | ⚠️ settlement proof varies | ❌ checkout state | ⚠️ mandate proof | ✅ |
406
+ | Accountless agent access | ✅ | ⚠️ platform-dependent | ⚠️ wallet/facilitator | ⚠️ app ecosystem | ⚠️ mandate framework | ⚠️ keys, no app layer |
407
+ | Mainstream billing, cards, reporting | ❌ | ✅ | ❌ | ⚠️ merchant checkout | ⚠️ partner ecosystem | ❌ |
408
+
409
+ Hypawave is the execution layer: the same preimage that proves payment atomically releases encrypted file keys and fires the execution webhook. For basic file/key unlock flows, the delivery layer is built in.
410
+
411
+ ## Links
412
+
413
+ - **Website**: [hypawave.com](https://hypawave.com)
414
+ - **Documentation**: [hypawave.com/docs](https://hypawave.com/docs)
415
+ - **Architecture**: [hypawave.com/architecture](https://hypawave.com/architecture)
416
+ - **OpenAPI Spec**: [hypawave.com/.well-known/openapi.json](https://hypawave.com/.well-known/openapi.json)
417
+ - **Agent Instructions (llms.txt)**: [hypawave.com/llms.txt](https://hypawave.com/llms.txt)
418
+
419
+ ## Support & Contact
420
+
421
+ - **Issues / bug reports**: [github.com/hypawave/sdk/issues](https://github.com/hypawave/sdk/issues)
422
+ - **Security**: report privately to support@hypawave.com (please do not file public issues for vulnerabilities)
423
+ - **General inquiries**: support@hypawave.com
424
+
425
+ ## License
426
+
427
+ [MIT](./LICENSE)