@cosmosapp/pay_sdk 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,93 @@
1
+ # Recipes
2
+
3
+ Copy-paste end-to-end patterns. All server snippets assume:
4
+
5
+ ```ts
6
+ import { Assets, Client, TestnetAssets } from '@cosmosapp/pay_sdk';
7
+
8
+ const apiKey = process.env.COSMOS_PAY_API_KEY;
9
+ const merchantAccount = process.env.MERCHANT_ACCOUNT;
10
+ if (!apiKey || !merchantAccount) throw new Error('Missing Cosmos Pay configuration');
11
+
12
+ const client = new Client({ apiKey });
13
+ const usdc = apiKey.startsWith('prod_') ? Assets.USDC : TestnetAssets.USDC;
14
+ ```
15
+
16
+ ## 1. Checkout (server creates, browser pays, webhook confirms)
17
+
18
+ ```ts
19
+ // server: create the intent for an order
20
+ export async function startCheckout(orderId: string, total: string) {
21
+ const intent = await client.paymentIntents.createPay({
22
+ destination: merchantAccount,
23
+ amount: total,
24
+ asset: usdc,
25
+ msg: `Order ${orderId}`,
26
+ });
27
+ await intent.edit({ reference: orderId }); // reference is set through PATCH
28
+ return intent.toJSON(); // → send to the browser
29
+ }
30
+ ```
31
+
32
+ ```ts
33
+ // browser: complete it with the user's wallet
34
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
35
+ const { txHash } = await new WebClient().pay(intentPayload);
36
+ await fetch('/api/confirm', { method: 'POST', body: JSON.stringify({ id: intentPayload.id, txHash }) });
37
+ ```
38
+
39
+ ```ts
40
+ // server: fulfill on the webhook (don't trust the browser alone)
41
+ client.webhooks.on('paymentIntentSucceeded', async (event) => {
42
+ await markOrderPaid(event.data.reference, event.data.id);
43
+ });
44
+ ```
45
+
46
+ ## 2. Donation / tip jar (open amount)
47
+
48
+ ```ts
49
+ const intent = await client.paymentIntents.createPay({
50
+ destination: merchantAccount,
51
+ asset: usdc, // no amount → the wallet asks the user
52
+ msg: 'Support us 💜',
53
+ });
54
+ // browser: await new WebClient().pay(intent, { amount: enteredAmount });
55
+ ```
56
+
57
+ ## 3. Idempotent webhook handling
58
+
59
+ ```ts
60
+ const processed = new Set<string>(); // use your DB in production
61
+ client.webhooks.on('event', (event) => {
62
+ if (processed.has(event.id)) return; // event.id is stable — dedupe on it
63
+ processed.add(event.id);
64
+ handle(event);
65
+ });
66
+ ```
67
+
68
+ ## 4. Reconcile a payment server-side
69
+
70
+ ```ts
71
+ // You received a txHash out-of-band (e.g. polled the browser). Finalize it:
72
+ const outcome = await client.paymentIntents.validate(intentId, { txHash });
73
+ if (!outcome.valid) {
74
+ console.warn('payment not valid:', outcome.reason); // amount/destination/memo mismatch
75
+ }
76
+ ```
77
+
78
+ ## 5. Testnet vs mainnet
79
+
80
+ ```ts
81
+ import { Assets, TestnetAssets } from '@cosmosapp/pay_sdk';
82
+ // dv_ key → testnet → use TestnetAssets.USDC
83
+ // prod_ key → mainnet → use Assets.USDC
84
+ const asset = apiKey.startsWith('prod_') ? Assets.USDC : TestnetAssets.USDC;
85
+ ```
86
+
87
+ ## 6. Catalog: products + customers
88
+
89
+ ```ts
90
+ const product = await client.products.create({ name: 'Pro', amount: '49.00', assetCode: 'USDC', kind: 'recurring' });
91
+ const customer = await client.customers.create({ name: 'Acme', email: 'billing@acme.com', account: 'G...' });
92
+ // then create intents referencing the customer's account as destination/source.
93
+ ```
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`).