@cosmosapp/pay_sdk 1.0.1 → 1.2.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.
@@ -0,0 +1,113 @@
1
+ # Web client (browser wallets)
2
+
3
+ `@cosmosapp/pay_sdk/web` *completes* an intent in the user's browser. Stellar
4
+ wallets don't ingest SEP-7 `web+stellar:` URIs from a dapp, so the web client
5
+ auto-detects the wallet, adapts the intent into a transaction, signs and submits.
6
+
7
+ ```bash
8
+ npm install @cosmosapp/pay_sdk @stellar/stellar-sdk
9
+ ```
10
+
11
+ ## One-call happy path
12
+
13
+ ```ts
14
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
15
+
16
+ const webClient = new WebClient(); // auto-detects the wallet
17
+ const result = await webClient.pay(intent); // intent = payload/instance/URI string
18
+
19
+ result.wallet; // 'freighter' | 'xbull' | 'rabet' | 'lobstr' | 'albedo' | …
20
+ result.account; // the G... account that signed
21
+ result.txHash; // on-chain transaction hash
22
+ result.submitted; // true
23
+ ```
24
+
25
+ Report `result.txHash` to your server and finalize with `intent.validate(txHash)`.
26
+
27
+ ## Supported wallets
28
+
29
+ Auto-detected (inject a browser global, zero config):
30
+
31
+ | Wallet | id | Detection |
32
+ | ------ | -- | --------- |
33
+ | Freighter | `freighter` | `window.freighterApi` |
34
+ | xBull | `xbull` | `window.xBullSDK` |
35
+ | Rabet | `rabet` | `window.rabet` |
36
+
37
+ Enabled by passing their library (no reliable global):
38
+
39
+ | Wallet | id | Enable |
40
+ | ------ | -- | ------ |
41
+ | Albedo | `albedo` | `new WebClient({ albedo })` — `import albedo from '@albedo-link/intent'` |
42
+ | LOBSTR | `lobstr` | `new WebClient({ lobstr })` — `import * as lobstr from '@lobstrco/signer-extension-api'` |
43
+
44
+ ## Inspect & choose
45
+
46
+ ```ts
47
+ import { Wallets } from '@cosmosapp/pay_sdk/web';
48
+
49
+ const wallets = await webClient.getAvailableWallets(); // [{ id, name, available }]
50
+ const { wallet, address, network } = await webClient.connect(); // just connect
51
+ await webClient.pay(intent, { wallet: Wallets.XBULL }); // pin for one call
52
+ const pinned = new WebClient({ preferredWallets: [Wallets.XBULL, Wallets.FREIGHTER] });
53
+ ```
54
+
55
+ ## `pay()` options & variations
56
+
57
+ ```ts
58
+ await webClient.pay(intent, { amount: '5' }); // open-amount intent
59
+ await webClient.pay(intent, { sign: true }); // sign WITHOUT submitting → { signedXdr }
60
+ await webClient.pay(intent, { submit: false }); // also skips submission
61
+ await webClient.pay(intent, { wallet: 'xbull' });
62
+
63
+ // Inspect the tx before prompting the wallet:
64
+ const { xdr, source, network } = await webClient.buildTransaction(intent);
65
+ ```
66
+
67
+ `pay` vs `tx`: for **pay** intents the client builds a payment from the connected
68
+ account (loads sequence from Horizon, adds op + memo, fee, timebounds). For **tx**
69
+ intents it signs the returned XDR as-is (throws if the connected wallet isn't the
70
+ intent's `source`).
71
+
72
+ ## Network
73
+
74
+ Inferred from the intent (`network` / SEP-7 `network_passphrase`). Override if you
75
+ self-host Horizon: `new WebClient({ network: 'testnet', horizonUrl: '...' })`.
76
+
77
+ ## Custom wallet adapter
78
+
79
+ ```ts
80
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
81
+
82
+ const myWallet = {
83
+ id: 'my-wallet',
84
+ name: 'My Wallet',
85
+ async isAvailable() { return Boolean(globalThis.myWallet); },
86
+ async getPublicKey() { return globalThis.myWallet.getAddress(); },
87
+ async signTransaction(xdr, { networkPassphrase }) {
88
+ return globalThis.myWallet.sign(xdr, networkPassphrase);
89
+ },
90
+ };
91
+ const wc = new WebClient();
92
+ wc.registerWallet(myWallet, /* prepend */ true);
93
+ ```
94
+
95
+ ## Dependency injection (SSR / bundle control)
96
+
97
+ ```ts
98
+ import * as StellarSdk from '@stellar/stellar-sdk';
99
+ import freighter from '@stellar/freighter-api';
100
+ const wc = new WebClient({ stellarSdk: StellarSdk, freighter });
101
+ ```
102
+
103
+ ## Direct API (trusted environments only)
104
+
105
+ > ⚠️ Ships your API key to the browser. Only for prototypes/internal tools with a
106
+ > scoped testnet `dv_` key. For production, create/validate on your server.
107
+
108
+ ```ts
109
+ const wc = new WebClient({ apiKey: 'dv_test_only' });
110
+ const intent = await wc.createPay({ destination: 'G...', amount: '10' });
111
+ const result = await wc.pay(intent);
112
+ const outcome = await wc.validate(intent.id, result.txHash);
113
+ ```
@@ -0,0 +1,109 @@
1
+ # Webhooks
2
+
3
+ Two halves: **registering** endpoints (server CRUD) and **receiving** events
4
+ (the listener + handlers). `client.webhooks` does both.
5
+
6
+ ## Register & manage endpoints
7
+
8
+ ```ts
9
+ import { WebhookEventType } from '@cosmosapp/pay_sdk';
10
+
11
+ const endpoint = await client.webhooks.create({
12
+ url: 'https://me.example.com/hooks/cosmos',
13
+ description: 'Production events',
14
+ eventTypes: [
15
+ WebhookEventType.PaymentIntentSucceeded,
16
+ WebhookEventType.PaymentIntentFailed,
17
+ ], // omit/empty → receive ALL events
18
+ });
19
+ console.log(endpoint.secret); // whsec_… — returned ONCE, store it now!
20
+
21
+ await endpoint.disable(); // pause
22
+ await endpoint.enable(); // resume
23
+ await endpoint.edit({ url: 'https://new...' });
24
+ await endpoint.ping(); // send a test event
25
+ const rotated = await endpoint.rotateSecret(); // new instance carries new secret
26
+ await endpoint.delete();
27
+
28
+ // audit trail + manual redelivery
29
+ const deliveries = await endpoint.fetchDeliveries({ status: 'FAILED', take: 50 });
30
+ for (const d of deliveries.items) await d.redeliver();
31
+ ```
32
+
33
+ Manager forms exist too: `client.webhooks.list()`, `.fetch(id)`,
34
+ `.update(id, {...})`, `.delete(id)`, `.rotateSecret(id)`, `.ping(id)`,
35
+ `.fetchDeliveries(id, {...})`, `.redeliver(id, deliveryId)`.
36
+
37
+ ## Receive events — `client.webhooks.on(...)`
38
+
39
+ Subscribe with the raw type, the camelCase alias, or `event` for all:
40
+
41
+ ```ts
42
+ client.webhooks.on('paymentIntentSucceeded', (event) => {
43
+ console.log('Paid!', event.data.id, event.data.amount);
44
+ });
45
+ client.webhooks.on('PAYMENT_INTENT_FAILED', (event) => { /* ... */ });
46
+ client.webhooks.on('event', (event) => console.log(event.type));
47
+ ```
48
+
49
+ Set the signing secret on the client (or pass `{ secret }` to the handler):
50
+
51
+ ```ts
52
+ const client = new Client({
53
+ apiKey: process.env.COSMOS_PAY_API_KEY,
54
+ webhookSecret: process.env.COSMOS_WEBHOOK_SECRET, // whsec_…
55
+ });
56
+ ```
57
+
58
+ ### Node.js `http` (zero deps)
59
+
60
+ ```ts
61
+ import { createServer } from 'node:http';
62
+ createServer(client.webhooks.createHandler()).listen(4242);
63
+ // verifies signature → emits event → replies 200 (or 400 on bad signature)
64
+ ```
65
+
66
+ ### Express
67
+
68
+ ```ts
69
+ import express from 'express';
70
+ const app = express();
71
+ app.post(
72
+ '/hooks/cosmos',
73
+ express.raw({ type: '*/*' }), // MUST be the RAW body
74
+ client.webhooks.middleware(),
75
+ (req, res) => res.sendStatus(200), // req.cosmosEvent is the verified event
76
+ );
77
+ ```
78
+
79
+ ## Verify signatures manually
80
+
81
+ The dispatcher signs each POST with `X-Cosmos-Signature: t=<unixSeconds>,v1=<hmacSha256>`.
82
+
83
+ ```ts
84
+ import { Webhooks } from '@cosmosapp/pay_sdk';
85
+
86
+ Webhooks.verify(rawBody, header, secret); // → true or throws
87
+ const event = Webhooks.constructEvent(rawBody, header, secret); // verify + parse
88
+ // both accept { toleranceSeconds } (default 300s replay window; 0 disables)
89
+
90
+ // or on a client (also emits to your on(...) listeners):
91
+ client.webhooks.process(rawBody, header, { secret });
92
+ ```
93
+
94
+ Bad signatures throw `WebhookSignatureError`.
95
+
96
+ ## Event payload shape
97
+
98
+ ```ts
99
+ interface WebhookEvent {
100
+ id: string; // stable — use for idempotency
101
+ type: WebhookEventType;
102
+ createdAt: string;
103
+ data: PaymentIntentData;
104
+ }
105
+ ```
106
+
107
+ Event types: `PAYMENT_INTENT_CREATED`, `PAYMENT_INTENT_UPDATED`,
108
+ `PAYMENT_INTENT_SUCCEEDED`, `PAYMENT_INTENT_FAILED`, `PAYMENT_INTENT_CANCELLED`,
109
+ `PAYMENT_INTENT_DELETED`.
@@ -0,0 +1,52 @@
1
+ # Products & customers
2
+
3
+ ## Products / prices — `client.products`
4
+
5
+ ```ts
6
+ import { ProductKind } from '@cosmosapp/pay_sdk';
7
+
8
+ const product = await client.products.create({
9
+ name: 'Pro plan — monthly',
10
+ description: 'Priority support included.', // optional
11
+ amount: '49.00', // optional — omit for customer-set amount
12
+ assetCode: 'USDC', // optional — omit for native XLM
13
+ kind: ProductKind.Recurring, // 'recurring' | 'one_time' | 'link'
14
+ reference: 'sku_pro_monthly', // optional
15
+ });
16
+
17
+ await client.products.list();
18
+ await client.products.fetch(product.id);
19
+ await product.edit({ amount: '59.00' });
20
+ await product.deactivate(); // active = false
21
+ await product.activate(); // active = true
22
+ await product.delete();
23
+ ```
24
+
25
+ `Product` accessors: `id`, `name`, `description`, `amount`, `asset`, `assetLabel`,
26
+ `kind`, `active`, `reference`, `createdAt`, `updatedAt`.
27
+
28
+ ## Customers — `client.customers`
29
+
30
+ ```ts
31
+ const customer = await client.customers.create({
32
+ name: 'Acme Inc.',
33
+ email: 'billing@acme.com', // optional
34
+ alias: 'acme', // optional
35
+ account: 'G...', // optional Stellar account to associate
36
+ reference: 'crm_4821', // optional
37
+ });
38
+
39
+ await customer.edit({ note: 'VIP, net-30' });
40
+ await client.customers.fetch(customer.id);
41
+ await customer.delete();
42
+
43
+ // list() includes payment stats per customer:
44
+ const customers = await client.customers.list();
45
+ for (const c of customers) {
46
+ console.log(c.name, c.payments, c.succeeded, c.total);
47
+ }
48
+ ```
49
+
50
+ `Customer` accessors: `id`, `consumerId`, `name`, `alias`, `note`, `email`,
51
+ `account`, `reference`, `createdAt`, `updatedAt`, plus list-only stats
52
+ `payments`, `succeeded`, `total` (null outside `list()`).
@@ -0,0 +1,25 @@
1
+ # Analytics & health
2
+
3
+ ## Analytics (read-only) — `client.analytics`
4
+
5
+ ```ts
6
+ const summary = await client.analytics.summary(); // totals, volume, webhook health, 30-day series
7
+ const balances = await client.analytics.balances(); // settled + pending per asset
8
+ const apiLogs = await client.analytics.apiLogs(); // recent API requests
9
+ const hookLogs = await client.analytics.webhookLogs(); // recent webhook deliveries
10
+ ```
11
+
12
+ `summary()` → `{ totals: { all, succeeded, pending, submitted, failed, cancelled,
13
+ expired, successRate }, volume: [...], webhooks: { endpoints, deliveries, ... } }`.
14
+
15
+ `balances()` → `{ data: [{ asset, amount, pending, count }], total }`
16
+ where `amount`/`pending` are decimal strings and `count` is the number of payments.
17
+
18
+ ## Health (public probes) — `client.health`
19
+
20
+ ```ts
21
+ await client.health.liveness(); // → true when the service is up
22
+ const ready = await client.health.readiness(); // → { status, info, details } (checks the DB)
23
+ ```
24
+
25
+ These routes don't require an authenticated consumer.
@@ -0,0 +1,57 @@
1
+ # Typed assets, wallets & addresses
2
+
3
+ Small typed catalogs so you never paste the wrong issuer or a magic string. Plain
4
+ strings still work everywhere. Exported from **both** entry points
5
+ (`@cosmosapp/pay_sdk` and `@cosmosapp/pay_sdk/web`).
6
+
7
+ ## Assets
8
+
9
+ ```ts
10
+ import { Assets, TestnetAssets, defineAsset, resolveAsset, isNativeAsset } from '@cosmosapp/pay_sdk';
11
+
12
+ Assets.XLM; // native lumens
13
+ Assets.USDC; // { code: 'USDC', issuer: 'GA5Z…' } (Circle, mainnet — verified)
14
+ Assets.EURC; // { code: 'EURC', issuer: 'GDHU…' }
15
+
16
+ // Custom asset (issuer/contract validated):
17
+ const AQUA = defineAsset({ code: 'AQUA', issuer: 'GBNZ…', name: 'Aquarius' });
18
+
19
+ await client.paymentIntents.createPay({ destination: 'G...', amount: '5', asset: AQUA });
20
+
21
+ // Plain code + issuer also works:
22
+ await client.paymentIntents.createPay({ destination: 'G...', amount: '5', assetCode: 'USDC', assetIssuer: 'G...' });
23
+ ```
24
+
25
+ > ⚠️ Issuers are **network-specific**. `Assets.*` = mainnet; use `TestnetAssets.*`
26
+ > (e.g. `TestnetAssets.USDC`) for testnet, matched to your `dv_` key.
27
+
28
+ Helpers: `resolveAsset(ref)` → `{ code, issuer? }`; `isNativeAsset(ref)` → boolean.
29
+
30
+ ## Wallets
31
+
32
+ ```ts
33
+ import { Wallets } from '@cosmosapp/pay_sdk/web';
34
+ Wallets.FREIGHTER; Wallets.XBULL; Wallets.RABET; Wallets.LOBSTR; Wallets.ALBEDO;
35
+
36
+ const wc = new WebClient({ preferredWallets: [Wallets.XBULL, Wallets.FREIGHTER] });
37
+ await wc.pay(intent, { wallet: Wallets.FREIGHTER });
38
+ ```
39
+
40
+ ## Address book
41
+
42
+ ```ts
43
+ import { addresses, resolveAddress, isStellarAddress, isMuxedAddress, isContractAddress, isAddress, assertAddress } from '@cosmosapp/pay_sdk';
44
+
45
+ addresses.define('merchant', 'GC...PAYOUT');
46
+ await client.paymentIntents.createPay({ destination: 'merchant', amount: '10' });
47
+
48
+ resolveAddress('merchant'); // → 'GC...PAYOUT' (unknown values pass through unchanged)
49
+ isStellarAddress('GC...'); // true
50
+ isMuxedAddress('MA...'); // true
51
+ isContractAddress('CA...'); // true
52
+ isAddress('merchant'); // true
53
+ assertAddress(value); // throws on an invalid value
54
+ ```
55
+
56
+ Raw `G…`, muxed `M…`, contract `C…` and federation addresses keep working as
57
+ plain strings.
@@ -0,0 +1,47 @@
1
+ # Error handling & observability
2
+
3
+ ## Errors
4
+
5
+ ```ts
6
+ import { CosmosPayAPIError, CosmosPayRequestError } from '@cosmosapp/pay_sdk';
7
+
8
+ try {
9
+ await client.paymentIntents.fetch('missing');
10
+ } catch (err) {
11
+ if (err instanceof CosmosPayAPIError) {
12
+ // server responded with an error status
13
+ console.error(err.status, err.code, err.body); // e.g. 404
14
+ } else if (err instanceof CosmosPayRequestError) {
15
+ // no usable response — network / TLS / timeout / offline
16
+ console.error('Network/timeout:', err.cause);
17
+ } else {
18
+ throw err;
19
+ }
20
+ }
21
+ ```
22
+
23
+ - `CosmosPayAPIError` — the API replied with 4xx/5xx. Fields: `status`, `code`, `body`.
24
+ - `CosmosPayRequestError` — the request never completed. Field: `cause`.
25
+ - Web client adds: `CosmosPayWebError`, `WalletNotFoundError`, `WalletError`
26
+ (user rejected / locked), `StellarSdkRequiredError`, `IntentError`. The API
27
+ error classes are re-exported from `/web` too, so `catch` works across entries.
28
+ - Webhook signature failures throw `WebhookSignatureError`.
29
+
30
+ ### Retries
31
+
32
+ Transient failures (network errors, `408`, `429`, `5xx`) are retried
33
+ automatically — default **2** retries, honoring `Retry-After`. Tune via
34
+ `new Client({ retries, timeout })`.
35
+
36
+ ## Observability
37
+
38
+ The client re-emits REST telemetry:
39
+
40
+ ```ts
41
+ client.on('request', ({ method, url, attempt }) => {});
42
+ client.on('response', ({ method, url, status, attempt }) => {});
43
+ client.on('rateLimited', ({ method, url, attempt }) => {});
44
+ client.on('debug', (message) => {});
45
+ ```
46
+
47
+ Wire these into your logger/APM to trace or meter every request.
@@ -0,0 +1,43 @@
1
+ # Configuration reference
2
+
3
+ ```ts
4
+ new Client({
5
+ apiKey: 'prod_xxx', // required — the only thing you normally set
6
+ webhookSecret: 'whsec_...', // default secret for the webhook listener
7
+ timeout: 30_000, // ms (default 30000)
8
+ retries: 2, // network errors / 429 / 5xx (default 2)
9
+ headers: { 'X-Trace': 'abc' }, // extra headers on every request
10
+ fetch: customFetch, // custom fetch implementation
11
+
12
+ // Advanced / internal — pre-filled from Client.shared, rarely overridden:
13
+ baseURL: 'https://api.cosmospay.lat/cosmos-api', // gateway URL (default)
14
+ version: 'v1', // route prefix
15
+ gatewaySecret: '...', // direct access (X-Gateway-Secret), local dev
16
+ consumerUsername: '...', // direct access (X-Consumer-Username), local dev
17
+ });
18
+ ```
19
+
20
+ ## Environment variables (convention)
21
+
22
+ The SDK reads nothing from the environment itself — you pass values in. Common
23
+ convention used across the docs/examples:
24
+
25
+ | Var | Used for |
26
+ | --- | -------- |
27
+ | `COSMOS_PAY_API_KEY` | `new Client({ apiKey })` |
28
+ | `COSMOS_WEBHOOK_SECRET` | `new Client({ webhookSecret })` / handler `{ secret }` |
29
+
30
+ ## Self-hosting / staging
31
+
32
+ ```ts
33
+ // Once at startup, for every client:
34
+ Client.shared.baseURL = 'https://gateway.your-domain.com';
35
+
36
+ // Or per-client, bypassing the gateway in local dev:
37
+ new Client({
38
+ apiKey: 'x',
39
+ baseURL: 'http://localhost:3000',
40
+ gatewaySecret: process.env.APISIX_GATEWAY_SECRET,
41
+ consumerUsername: 'cosmos_demo',
42
+ });
43
+ ```
@@ -0,0 +1,78 @@
1
+ # Types & enums reference
2
+
3
+ Everything is fully typed. Import option/entity types and the const-enums directly
4
+ from `@cosmosapp/pay_sdk` (or `/web`).
5
+
6
+ ```ts
7
+ import {
8
+ Client,
9
+ PaymentIntentStatus,
10
+ PaymentIntentKind,
11
+ WebhookEventType,
12
+ WebhookDeliveryStatus,
13
+ ProductKind,
14
+ type CreatePayPaymentIntentOptions,
15
+ type CreateTxPaymentIntentOptions,
16
+ type PaymentIntentData,
17
+ } from '@cosmosapp/pay_sdk';
18
+ ```
19
+
20
+ ## Enums (const objects — usable as values and types)
21
+
22
+ ```ts
23
+ PaymentIntentStatus = { Pending:'PENDING', Submitted:'SUBMITTED', Succeeded:'SUCCEEDED',
24
+ Failed:'FAILED', Cancelled:'CANCELLED', Expired:'EXPIRED' }
25
+ PaymentIntentKind = { Tx:'TX', Pay:'PAY' }
26
+ WebhookEventType = { PaymentIntentCreated:'PAYMENT_INTENT_CREATED',
27
+ PaymentIntentUpdated:'PAYMENT_INTENT_UPDATED',
28
+ PaymentIntentSucceeded:'PAYMENT_INTENT_SUCCEEDED',
29
+ PaymentIntentFailed:'PAYMENT_INTENT_FAILED',
30
+ PaymentIntentCancelled:'PAYMENT_INTENT_CANCELLED',
31
+ PaymentIntentDeleted:'PAYMENT_INTENT_DELETED' }
32
+ WebhookDeliveryStatus = { Pending:'PENDING', Succeeded:'SUCCEEDED', Failed:'FAILED' }
33
+ ProductKind = { Recurring:'recurring', OneTime:'one_time', Link:'link' }
34
+ ```
35
+
36
+ ## Option types (inputs)
37
+
38
+ ```ts
39
+ interface CreatePayPaymentIntentOptions {
40
+ destination: string; amount?: string; asset?: AssetRef;
41
+ assetCode?: string; assetIssuer?: string; memo?: string; msg?: string; callback?: string;
42
+ }
43
+ interface CreateTxPaymentIntentOptions {
44
+ source: string; destination: string; amount: string; asset?: AssetRef;
45
+ assetCode?: string; assetIssuer?: string; memo?: string; msg?: string; callback?: string;
46
+ }
47
+ interface UpdatePaymentIntentOptions { status?: PaymentIntentStatus; txHash?: string; reference?: string; }
48
+ interface ListPaymentIntentsOptions { status?: PaymentIntentStatus; take?: number; skip?: number; }
49
+ interface ValidatePaymentIntentOptions { txHash: string; }
50
+
51
+ interface CreateWebhookEndpointOptions { url: string; description?: string; eventTypes?: WebhookEventType[]; }
52
+ interface UpdateWebhookEndpointOptions { url?: string; description?: string; enabled?: boolean; eventTypes?: WebhookEventType[]; }
53
+ interface ListWebhookDeliveriesOptions { status?: WebhookDeliveryStatus; take?: number; skip?: number; }
54
+
55
+ interface CreateProductOptions { name: string; description?: string; amount?: string; assetCode?: string; kind?: ProductKind; active?: boolean; reference?: string; }
56
+ type UpdateProductOptions = Partial<CreateProductOptions>;
57
+
58
+ interface CreateCustomerOptions { name: string; alias?: string; note?: string; email?: string; account?: string; reference?: string; }
59
+ type UpdateCustomerOptions = Partial<CreateCustomerOptions>;
60
+ ```
61
+
62
+ ## Entity payloads (outputs)
63
+
64
+ - `PaymentIntentData` — `id, kind, status, network, source, destination, amount,
65
+ asset, assetIssuer, memo, msg, callback, xdr, uri, qr, txHash, reference,
66
+ createdAt, updatedAt`.
67
+ - `WebhookEndpointData` — `id, url, description, enabled, eventTypes, createdAt,
68
+ updatedAt` (+ `secret` on create/rotate only).
69
+ - `WebhookEvent<T = PaymentIntentData>` — `{ id, type, createdAt, data }`.
70
+ - `ProductData` — `id, name, description, amount, asset, kind, active, reference,
71
+ createdAt, updatedAt`.
72
+ - `CustomerData` — `id, consumerId, name, alias, note, email, account, reference,
73
+ createdAt, updatedAt` (+ list-only `payments, succeeded, total`).
74
+ - `AnalyticsBalancesData` — `{ data: { asset, amount, pending, count }[], total }`.
75
+ - `ValidationOutcomeData` — `{ valid, status, reason?, paymentIntent? }`.
76
+
77
+ Pagination wrappers (`list` / `fetchDeliveries`) return
78
+ `{ items, total, take, skip }`.
@@ -0,0 +1,87 @@
1
+ # Recipes
2
+
3
+ Copy-paste end-to-end patterns. All server snippets assume:
4
+
5
+ ```ts
6
+ import { Client, Assets } from '@cosmosapp/pay_sdk';
7
+ const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });
8
+ ```
9
+
10
+ ## 1. Checkout (server creates, browser pays, webhook confirms)
11
+
12
+ ```ts
13
+ // server: create the intent for an order
14
+ export async function startCheckout(orderId: string, total: string) {
15
+ const intent = await client.paymentIntents.createPay({
16
+ destination: process.env.MERCHANT_ACCOUNT,
17
+ amount: total,
18
+ asset: Assets.USDC,
19
+ reference: orderId, // ties the intent to your order
20
+ msg: `Order ${orderId}`,
21
+ });
22
+ return intent.toJSON(); // → send to the browser
23
+ }
24
+ ```
25
+
26
+ ```ts
27
+ // browser: complete it with the user's wallet
28
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
29
+ const { txHash } = await new WebClient().pay(intentPayload);
30
+ await fetch('/api/confirm', { method: 'POST', body: JSON.stringify({ id: intentPayload.id, txHash }) });
31
+ ```
32
+
33
+ ```ts
34
+ // server: fulfill on the webhook (don't trust the browser alone)
35
+ client.webhooks.on('paymentIntentSucceeded', async (event) => {
36
+ await markOrderPaid(event.data.reference, event.data.id);
37
+ });
38
+ ```
39
+
40
+ ## 2. Donation / tip jar (open amount)
41
+
42
+ ```ts
43
+ const intent = await client.paymentIntents.createPay({
44
+ destination: process.env.MERCHANT_ACCOUNT,
45
+ asset: Assets.USDC, // no amount → the wallet asks the user
46
+ msg: 'Support us 💜',
47
+ });
48
+ // browser: await new WebClient().pay(intent, { amount: enteredAmount });
49
+ ```
50
+
51
+ ## 3. Idempotent webhook handling
52
+
53
+ ```ts
54
+ const processed = new Set<string>(); // use your DB in production
55
+ client.webhooks.on('event', (event) => {
56
+ if (processed.has(event.id)) return; // event.id is stable — dedupe on it
57
+ processed.add(event.id);
58
+ handle(event);
59
+ });
60
+ ```
61
+
62
+ ## 4. Reconcile a payment server-side
63
+
64
+ ```ts
65
+ // You received a txHash out-of-band (e.g. polled the browser). Finalize it:
66
+ const outcome = await client.paymentIntents.validate(intentId, { txHash });
67
+ if (!outcome.valid) {
68
+ console.warn('payment not valid:', outcome.reason); // amount/destination/memo mismatch
69
+ }
70
+ ```
71
+
72
+ ## 5. Testnet vs mainnet
73
+
74
+ ```ts
75
+ import { Assets, TestnetAssets } from '@cosmosapp/pay_sdk';
76
+ // dv_ key → testnet → use TestnetAssets.USDC
77
+ // prod_ key → mainnet → use Assets.USDC
78
+ const asset = process.env.COSMOS_PAY_API_KEY.startsWith('prod_') ? Assets.USDC : TestnetAssets.USDC;
79
+ ```
80
+
81
+ ## 6. Catalog: products + customers
82
+
83
+ ```ts
84
+ const product = await client.products.create({ name: 'Pro', amount: '49.00', assetCode: 'USDC', kind: 'recurring' });
85
+ const customer = await client.customers.create({ name: 'Acme', email: 'billing@acme.com', account: 'G...' });
86
+ // then create intents referencing the customer's account as destination/source.
87
+ ```
package/llms/README.md ADDED
@@ -0,0 +1,40 @@
1
+ # `llms/` — AI-readable docs for `@cosmosapp/pay_sdk`
2
+
3
+ This is an **isolated, atomic** documentation set designed to make integrating the
4
+ SDK much easier — both for developers and for the AI assistants they use (Cursor,
5
+ Copilot, Claude, ChatGPT, …). It is **not** part of the library's source code; it
6
+ ships alongside it purely as reference material.
7
+
8
+ ## What's here
9
+
10
+ - **[`llms.txt`](./llms.txt)** — a concise, link-first index following the
11
+ [llmstxt.org](https://llmstxt.org) convention. Point your AI tool at this first.
12
+ - **`00…14-*.md`** — atomic, self-contained topic files (overview, installation,
13
+ payment intents, web client, webhooks, products/customers, analytics, assets,
14
+ errors, configuration, types, recipes). Read only the ones a task needs.
15
+ - **[`llms-full.txt`](./llms-full.txt)** — every topic file concatenated into one
16
+ document, for tools that prefer a single-file ingest. Generated from the `.md`
17
+ files (do not edit by hand).
18
+
19
+ ## How to use it
20
+
21
+ **As a developer:** open the topic file you need, or paste `llms.txt` /
22
+ `llms-full.txt` into your AI chat as context before asking it to write the
23
+ integration.
24
+
25
+ **With AI coding tools:** after `npm install @cosmosapp/pay_sdk`, this folder is
26
+ available at `node_modules/@cosmosapp/pay_sdk/llms/`. Add it to your tool's context
27
+ (e.g. Cursor "@Docs", a custom rule, or by copying `llms-full.txt`).
28
+
29
+ **Hosting:** you may also serve `llms.txt` at the root of your own site
30
+ (`/llms.txt`) so crawlers and assistants can discover how to use the SDK.
31
+
32
+ ## Regenerating `llms-full.txt`
33
+
34
+ The `.md` files are the single source of truth. Rebuild the combined file with:
35
+
36
+ ```bash
37
+ npm run llms
38
+ ```
39
+
40
+ (runs `scripts/build-llms.mjs`).