@cosmosapp/pay_sdk 1.0.1 → 1.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/CHANGELOG.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  All notable changes to this project are documented here. This file is updated automatically on each release.
4
4
 
5
+ ## [v1.1.0](https://github.com/CosmosPay/CosmosJS_SDK/compare/v1.0.1...v1.1.0) - 2026-06-26
6
+
7
+ - Maintenance release (no notable changes).
8
+
5
9
  ## [v1.0.1](https://github.com/CosmosPay/CosmosJS_SDK/releases/tag/v1.0.1) - 2026-06-25
6
10
 
7
11
  - Update package-lock.json and package.json to reflect package name change to "@cosmosapp/pay_sdk" and add "semver" as a dev dependency. Enhance GitHub Actions workflow for automated versioning and publishing, including a new script for version resolution. ([`ec09229`](https://github.com/CosmosPay/CosmosJS_SDK/commit/ec09229))
package/README.md CHANGED
@@ -17,10 +17,18 @@ Stellar **SEP-7 payment intents** · **webhooks** · **products** · **customers
17
17
 
18
18
  ---
19
19
 
20
- Designed in the style of **discord.js**: one atomic `Client`, every resource split into its own
21
- manager, and rich structure classes that can act on themselves.
20
+ Designed to be **atomic**: one `Client`, every resource split into its own manager, and rich
21
+ structure classes that can act on themselves.
22
+
23
+ The SDK ships **two entry points** for the two halves of a payment:
24
+
25
+ | Import | Where it runs | What it does |
26
+ | ------ | ------------- | ------------ |
27
+ | `@cosmosapp/pay_sdk` | **server** (Node ≥ 18) | Create & manage SEP-7 payment intents, webhooks, products, customers, analytics — everything that needs your secret API key. |
28
+ | `@cosmosapp/pay_sdk/web` | **browser** | *Complete* an intent: auto-detect the user's Stellar wallet (Freighter, xBull, Rabet, LOBSTR, Albedo…), adapt the response into a transaction, request a signature and submit — **provider-agnostic, no provider argument**. |
22
29
 
23
30
  ```ts
31
+ // ── server ──────────────────────────────────────────────────────────
24
32
  import { Client } from '@cosmosapp/pay_sdk';
25
33
 
26
34
  // You only bring your API key — the gateway URL and other internals are pre-configured for you.
@@ -30,14 +38,26 @@ const intent = await client.paymentIntents.createPay({ destination: 'G...', amou
30
38
  console.log(intent.uri); // web+stellar:pay?destination=...
31
39
  ```
32
40
 
41
+ ```ts
42
+ // ── browser ─────────────────────────────────────────────────────────
43
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
44
+
45
+ // `intent` is the payload your server returned above. No wallet/provider to choose.
46
+ const webClient = new WebClient();
47
+ const { txHash, account, wallet } = await webClient.pay(intent);
48
+ console.log(`Paid via ${wallet} from ${account}: ${txHash}`);
49
+ ```
50
+
33
51
  ## ✨ Features
34
52
 
35
53
  - ✅ **TypeScript & JavaScript** — full typings, works in both **CJS** and **ESM**.
36
54
  - ✅ **Zero runtime dependencies** — native `fetch` + `node:crypto`, nothing else.
37
- - ✅ **Atomic, discord.js-style API** — `client.paymentIntents`, `client.webhooks`, …
55
+ - ✅ **Atomic API** — one client, one manager per resource: `client.paymentIntents`, `client.webhooks`, …
38
56
  - ✅ **Self-acting structures** — `intent.validate()`, `endpoint.rotateSecret()`, `product.deactivate()`.
39
57
  - ✅ **Built-in webhook signature verification** + ready-made `http` / Express handlers.
40
58
  - ✅ **Resilient by default** — automatic retries, timeouts and structured errors.
59
+ - ✅ **Browser web client** — auto-detects Freighter, xBull, Rabet, LOBSTR & Albedo, builds the
60
+ transaction from the SEP-7 response and signs it. Agnostic — you never pass a provider.
41
61
 
42
62
  ## 📑 Table of contents
43
63
 
@@ -45,7 +65,9 @@ console.log(intent.uri); // web+stellar:pay?destination=...
45
65
  - [Authentication](#-authentication)
46
66
  - [Quick start](#-quick-start)
47
67
  - [The client at a glance](#-the-client-at-a-glance)
68
+ - [Web client (browser wallets)](#-web-client-browser-wallets)
48
69
  - [Payment intents](#-payment-intents)
70
+ - [Typed assets, wallets & addresses](#-typed-assets-wallets--addresses)
49
71
  - [Webhooks](#-webhooks)
50
72
  - [Products & customers](#-products--customers)
51
73
  - [Analytics & health](#-analytics--health)
@@ -150,6 +172,165 @@ if (outcome.valid) console.log('Settled!', outcome.status);
150
172
  | `client.analytics` | Read-only metrics & logs | `summary` · `balances` · `apiLogs` · `webhookLogs` |
151
173
  | `client.health` | Liveness / readiness probes | `liveness` · `readiness` |
152
174
 
175
+ ## 🌐 Web client (browser wallets)
176
+
177
+ The server SDK *creates* intents. The **web client** *completes* them in the user's browser.
178
+
179
+ Stellar browser wallets (Freighter, xBull, Rabet, LOBSTR, Albedo…) **don't ingest SEP-7
180
+ `web+stellar:` URIs from a dapp** — each exposes its own JS API. The web client bridges that gap: it
181
+ **auto-detects** whichever wallet the user has, **adapts** the Cosmos Pay response into a concrete
182
+ Stellar transaction (building the payment for `pay` intents, reusing the XDR for `tx` intents), asks
183
+ the wallet to **sign**, and **submits** to Horizon (or POSTs to the SEP-7 `callback`). You never
184
+ *have to* pass a provider — it's fully agnostic — but you **can** pin one when you want (see
185
+ [Inspecting & choosing wallets](#inspecting--choosing-wallets)).
186
+
187
+ ```bash
188
+ # the web client builds/submits transactions, so it needs the Stellar SDK (optional peer dep)
189
+ npm install @cosmosapp/pay_sdk @stellar/stellar-sdk
190
+ ```
191
+
192
+ ### The typical flow
193
+
194
+ 1. **Server** creates the intent (with your secret key) and sends the payload to your frontend.
195
+ 2. **Browser** completes it — one call:
196
+
197
+ ```ts
198
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
199
+
200
+ const webClient = new WebClient(); // auto-detects the wallet
201
+
202
+ // `intent` may be the PaymentIntent payload from your server, a PaymentIntent
203
+ // instance, or even the raw `web+stellar:` URI string.
204
+ const result = await webClient.pay(intent);
205
+
206
+ console.log(result.wallet); // 'freighter' | 'xbull' | 'rabet' | 'lobstr' | 'albedo' | ...
207
+ console.log(result.account); // the G... account that signed
208
+ console.log(result.txHash); // the on-chain transaction hash
209
+ console.log(result.submitted); // true
210
+ ```
211
+
212
+ 3. Report `result.txHash` back to your server and finalize with `intent.validate(txHash)` (or call
213
+ `webClient.validate(...)`, see below).
214
+
215
+ ### Supported wallets
216
+
217
+ Auto-detected with **zero config** (they inject a browser global):
218
+
219
+ | Wallet | id | Detection |
220
+ | ------ | -- | --------- |
221
+ | **Freighter** | `freighter` | `window.freighterApi` (extension) |
222
+ | **xBull** | `xbull` | `window.xBullSDK` (extension) |
223
+ | **Rabet** | `rabet` | `window.rabet` (extension) |
224
+
225
+ Enabled by **passing their library** (no reliable global to sniff):
226
+
227
+ | Wallet | id | How to enable |
228
+ | ------ | -- | ------------- |
229
+ | **Albedo** | `albedo` | `new WebClient({ albedo })` — `import albedo from '@albedo-link/intent'` |
230
+ | **LOBSTR** | `lobstr` | `new WebClient({ lobstr })` — `import * as lobstr from '@lobstrco/signer-extension-api'` |
231
+
232
+ Bring **any other** wallet (WalletConnect, Ledger, a custom signer) by implementing the small
233
+ `WalletAdapter` interface and registering it — see [Custom wallets](#custom-wallets).
234
+
235
+ ### Inspecting & choosing wallets
236
+
237
+ Detection is automatic by default, **but the provider can also be defined** — per call, or as the
238
+ client's preferred order:
239
+
240
+ ```ts
241
+ import { Wallets } from '@cosmosapp/pay_sdk/web';
242
+
243
+ const wallets = await webClient.getAvailableWallets();
244
+ // [{ id: 'freighter', name: 'Freighter', available: true }, { id: 'xbull', … }, …]
245
+
246
+ // Just connect (e.g. to show the address) without paying:
247
+ const { wallet, address, network } = await webClient.connect();
248
+
249
+ // Pin a specific provider for one call:
250
+ await webClient.pay(intent, { wallet: Wallets.XBULL });
251
+
252
+ // …or set the default order for this client:
253
+ const pinned = new WebClient({ preferredWallets: [Wallets.XBULL, Wallets.FREIGHTER] });
254
+ ```
255
+
256
+ ### `tx` vs `pay` intents
257
+
258
+ - **`pay` intent** (no source): the client builds a payment transaction from the **connected account**
259
+ as source — loading its sequence from Horizon, adding the payment op + memo, fee and timebounds.
260
+ For an open-amount intent (e.g. a donation) pass the amount: `webClient.pay(intent, { amount: '5' })`.
261
+ - **`tx` intent** (source known, XDR present): the client signs the **returned XDR** as-is. If the
262
+ connected wallet isn't the intent's `source`, it throws a clear error so you can prompt an account
263
+ switch.
264
+
265
+ Want to show the user the transaction before signing? Build without prompting:
266
+
267
+ ```ts
268
+ const { xdr, source, network } = await webClient.buildTransaction(intent);
269
+ // …render a confirmation…
270
+ const result = await webClient.pay(intent); // or sign the xdr yourself
271
+ ```
272
+
273
+ `webClient.pay(intent, { sign: true })` signs **without** submitting (returns `signedXdr`); `{ submit: false }`
274
+ also skips submission.
275
+
276
+ ### Network detection
277
+
278
+ The network (mainnet/testnet), passphrase and Horizon endpoint are **inferred from the intent**
279
+ (its `network` field / the SEP-7 `network_passphrase`). Override if you self-host Horizon:
280
+
281
+ ```ts
282
+ new WebClient({ network: 'testnet', horizonUrl: 'https://horizon-testnet.stellar.org' });
283
+ ```
284
+
285
+ ### Custom wallets
286
+
287
+ ```ts
288
+ import { WebClient, type WalletAdapter } from '@cosmosapp/pay_sdk/web';
289
+
290
+ const myWallet: WalletAdapter = {
291
+ id: 'my-wallet',
292
+ name: 'My Wallet',
293
+ async isAvailable() { return Boolean(globalThis.myWallet); },
294
+ async getPublicKey() { return globalThis.myWallet.getAddress(); },
295
+ async signTransaction(xdr, { networkPassphrase }) {
296
+ return globalThis.myWallet.sign(xdr, networkPassphrase);
297
+ },
298
+ };
299
+
300
+ const webClient = new WebClient();
301
+ webClient.registerWallet(myWallet, /* prepend (win auto-detection) */ true);
302
+ ```
303
+
304
+ ### Talking to the API directly (optional — trusted environments only)
305
+
306
+ The web client can **also call the Cosmos Pay API directly** — creating and validating intents from
307
+ the browser — by passing an `apiKey`. This is handy for prototypes, internal tools and other
308
+ **trusted environments**.
309
+
310
+ > ⚠️ **Not recommended for public/production frontends.** Doing this ships your API key to the
311
+ > browser, where anyone can read it. Only enable it when the environment is trusted and the key is
312
+ > safe to expose (e.g. a scoped testnet `dv_` key). For production, **create and validate intents on
313
+ > your server** and let the web client only sign/submit.
314
+
315
+ ```ts
316
+ const webClient = new WebClient({ apiKey: 'dv_test_only' }); // trusted env only
317
+ const intent = await webClient.createPay({ destination: 'G...', amount: '10' });
318
+ const result = await webClient.pay(intent);
319
+ const outcome = await webClient.validate(intent.id, result.txHash);
320
+ ```
321
+
322
+ ### Inject everything (advanced / SSR / bundle control)
323
+
324
+ Nothing is imported eagerly. You can inject the Stellar SDK and any wallet library so the bundler
325
+ sees explicit imports:
326
+
327
+ ```ts
328
+ import * as StellarSdk from '@stellar/stellar-sdk';
329
+ import freighter from '@stellar/freighter-api';
330
+
331
+ const webClient = new WebClient({ stellarSdk: StellarSdk, freighter });
332
+ ```
333
+
153
334
  ## 💳 Payment intents
154
335
 
155
336
  ```ts
@@ -162,8 +343,13 @@ const tx = await client.paymentIntents.createTx({
162
343
  });
163
344
  console.log(tx.xdr, tx.uri, tx.qr);
164
345
 
165
- // pay intent (no source)
166
- const pay = await client.paymentIntents.createPay({ destination: 'G...', amount: '10' });
346
+ // pay intent (no source) — typed asset, no issuer to look up
347
+ import { Assets } from '@cosmosapp/pay_sdk';
348
+ const pay = await client.paymentIntents.createPay({
349
+ destination: 'G...',
350
+ amount: '10',
351
+ asset: Assets.USDC, // fills assetCode + the verified issuer for you
352
+ });
167
353
 
168
354
  // fetch one
169
355
  const intent = await client.paymentIntents.fetch('pi_123');
@@ -184,6 +370,58 @@ const outcome = await intent.validate('<txHash>');
184
370
  Each `PaymentIntent` exposes typed helpers: `isTx`, `isPay`, `isSucceeded`, `isPending`, `assetLabel`,
185
371
  and the action methods `fetch()`, `edit()`, `validate()`, `cancel()`, `delete()`.
186
372
 
373
+ ## 🎨 Typed assets, wallets & addresses
374
+
375
+ So you never paste the wrong issuer or a magic string, the SDK ships small **typed, extensible
376
+ catalogs** — and a plain string still works everywhere. These are exported from **both** entry points
377
+ (`@cosmosapp/pay_sdk` and `@cosmosapp/pay_sdk/web`).
378
+
379
+ **Assets** — common assets with their **verified issuers** baked in (no contract/issuer hunting):
380
+
381
+ ```ts
382
+ import { Assets, defineAsset, TestnetAssets } from '@cosmosapp/pay_sdk';
383
+
384
+ Assets.XLM; // native lumens
385
+ Assets.USDC; // { code: 'USDC', issuer: 'GA5Z…' } (Circle, mainnet — verified)
386
+ Assets.EURC; // { code: 'EURC', issuer: 'GDHU…' }
387
+
388
+ // Need another asset? Define it once (issuer/contract are validated):
389
+ const AQUA = defineAsset({ code: 'AQUA', issuer: 'GBNZ…ILCT', name: 'Aquarius' });
390
+
391
+ await client.paymentIntents.createPay({ destination: 'G...', amount: '5', asset: AQUA });
392
+
393
+ // Plain code strings still work (treated as code-only):
394
+ await client.paymentIntents.createPay({ destination: 'G...', amount: '5', assetCode: 'USDC', assetIssuer: 'G...' });
395
+
396
+ // Testnet issuers live in TestnetAssets.* (e.g. TestnetAssets.USDC).
397
+ ```
398
+
399
+ > ⚠️ Issuers are network-specific. `Assets.*` targets **mainnet**; use `TestnetAssets.*` for testnet.
400
+
401
+ **Wallets** — typed ids instead of magic strings:
402
+
403
+ ```ts
404
+ import { WebClient, Wallets } from '@cosmosapp/pay_sdk/web';
405
+
406
+ const webClient = new WebClient({ preferredWallets: [Wallets.XBULL, Wallets.FREIGHTER] });
407
+ await webClient.pay(intent, { wallet: Wallets.FREIGHTER }); // pin a provider for one call
408
+ ```
409
+
410
+ **Addresses** — name the accounts you use a lot and reference them by name; values are validated, and
411
+ anything unknown passes through unchanged (so raw `G…`, muxed `M…` and federation addresses keep
412
+ working):
413
+
414
+ ```ts
415
+ import { addresses } from '@cosmosapp/pay_sdk';
416
+
417
+ addresses.define('merchant', 'GC...PAYOUT');
418
+ await client.paymentIntents.createPay({ destination: 'merchant', amount: '10' });
419
+
420
+ // validation helpers, too:
421
+ import { isStellarAddress } from '@cosmosapp/pay_sdk';
422
+ isStellarAddress('GC...'); // true
423
+ ```
424
+
187
425
  ## 🔔 Webhooks
188
426
 
189
427
  ```ts
@@ -210,7 +448,7 @@ await endpoint.delete();
210
448
 
211
449
  ### Receiving events — `client.webhooks.on(...)`
212
450
 
213
- Subscribe to events the discord.js way. You can listen with the raw type, its camelCase alias, or
451
+ Subscribe to events with the atomic event API. You can listen with the raw type, its camelCase alias, or
214
452
  `event` for everything:
215
453
 
216
454
  ```ts
@@ -0,0 +1,216 @@
1
+ // src/common/addresses.ts
2
+ var G_ADDRESS = /^G[A-Z2-7]{55}$/;
3
+ var M_ADDRESS = /^M[A-Z2-7]{68}$/;
4
+ var C_ADDRESS = /^C[A-Z2-7]{55}$/;
5
+ function isStellarAddress(value) {
6
+ return typeof value === "string" && G_ADDRESS.test(value);
7
+ }
8
+ function isMuxedAddress(value) {
9
+ return typeof value === "string" && M_ADDRESS.test(value);
10
+ }
11
+ function isContractAddress(value) {
12
+ return typeof value === "string" && C_ADDRESS.test(value);
13
+ }
14
+ function isAddress(value) {
15
+ return isStellarAddress(value) || isMuxedAddress(value) || isContractAddress(value);
16
+ }
17
+ function assertAddress(value, label = "address") {
18
+ if (!isAddress(value)) {
19
+ throw new TypeError(`Invalid Stellar ${label}: ${String(value)}`);
20
+ }
21
+ return value;
22
+ }
23
+ var AddressBook = class {
24
+ constructor(initial = {}) {
25
+ this.entries = /* @__PURE__ */ new Map();
26
+ for (const [name, address] of Object.entries(initial)) {
27
+ this.define(name, address);
28
+ }
29
+ }
30
+ /** Register (or overwrite) a named address. The address is validated. */
31
+ define(name, address) {
32
+ this.entries.set(name, assertAddress(address, `address for "${name}"`));
33
+ return this;
34
+ }
35
+ /** Whether a name is registered. */
36
+ has(name) {
37
+ return this.entries.has(name);
38
+ }
39
+ /** Look up a registered address by name. */
40
+ get(name) {
41
+ return this.entries.get(name);
42
+ }
43
+ /** Remove a named address. */
44
+ delete(name) {
45
+ return this.entries.delete(name);
46
+ }
47
+ /** All registered names. */
48
+ names() {
49
+ return [...this.entries.keys()];
50
+ }
51
+ /**
52
+ * Resolve a reference to a concrete address: a registered name is substituted,
53
+ * any other string is returned unchanged (so raw `G…`, muxed `M…`, federation
54
+ * `name*domain`, etc. all keep working).
55
+ */
56
+ resolve(ref) {
57
+ return this.entries.get(ref) ?? ref;
58
+ }
59
+ };
60
+ var addresses = new AddressBook();
61
+ function resolveAddress(ref, book = addresses) {
62
+ return book.resolve(ref);
63
+ }
64
+
65
+ // src/common/assets.ts
66
+ var NATIVE = { code: "XLM", issuer: null, name: "Stellar Lumens" };
67
+ var Assets = {
68
+ /** Native lumens. */
69
+ XLM: NATIVE,
70
+ /** USD Coin by Circle (mainnet). */
71
+ USDC: {
72
+ code: "USDC",
73
+ issuer: "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN",
74
+ name: "USD Coin",
75
+ network: "public"
76
+ },
77
+ /** Euro Coin by Circle (mainnet). */
78
+ EURC: {
79
+ code: "EURC",
80
+ issuer: "GDHU6WRG4IEQXM5NZ4BMPKOXHW76MZM4Y2IEMFDVXBSDP6SJY4ITNPP2",
81
+ name: "Euro Coin",
82
+ network: "public"
83
+ }
84
+ };
85
+ var TestnetAssets = {
86
+ XLM: NATIVE,
87
+ USDC: {
88
+ code: "USDC",
89
+ issuer: "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5",
90
+ name: "USD Coin",
91
+ network: "testnet"
92
+ },
93
+ EURC: {
94
+ code: "EURC",
95
+ issuer: "GB3Q6QDZYTHWT7E5PVS3W7FUT5GVAFC5KSZFFLPU25GO7VTC3NM2ZTVO",
96
+ name: "Euro Coin",
97
+ network: "testnet"
98
+ }
99
+ };
100
+ function isNativeAsset(ref) {
101
+ if (typeof ref === "string") {
102
+ const code = ref.trim().toLowerCase();
103
+ return code === "" || code === "xlm" || code === "native";
104
+ }
105
+ return !ref.issuer || isNativeAsset(ref.code);
106
+ }
107
+ function defineAsset(def) {
108
+ if (!def.code) throw new TypeError("defineAsset requires a `code`.");
109
+ if (def.issuer != null && !isStellarAddress(def.issuer)) {
110
+ throw new TypeError(`defineAsset: invalid issuer for ${def.code}: ${def.issuer}`);
111
+ }
112
+ if (def.contract != null && !/^C[A-Z2-7]{55}$/.test(def.contract)) {
113
+ throw new TypeError(`defineAsset: invalid contract for ${def.code}: ${def.contract}`);
114
+ }
115
+ return Object.freeze({ ...def });
116
+ }
117
+ function resolveAsset(ref) {
118
+ if (isNativeAsset(ref)) return { code: "XLM", issuer: null };
119
+ if (typeof ref === "string") return { code: ref, issuer: null };
120
+ return {
121
+ code: ref.code,
122
+ issuer: ref.issuer ?? null,
123
+ ...ref.contract ? { contract: ref.contract } : {}
124
+ };
125
+ }
126
+
127
+ // src/common/intent-input.ts
128
+ function resolveIntentBody(options, book = addresses) {
129
+ const out = { ...options };
130
+ if (typeof out["destination"] === "string") {
131
+ out["destination"] = resolveAddress(out["destination"], book);
132
+ }
133
+ if (typeof out["source"] === "string") {
134
+ out["source"] = resolveAddress(out["source"], book);
135
+ }
136
+ if (out["asset"] != null) {
137
+ const { code, issuer } = resolveAsset(out["asset"]);
138
+ delete out["asset"];
139
+ if (issuer) {
140
+ out["assetCode"] ??= code;
141
+ out["assetIssuer"] ??= issuer;
142
+ }
143
+ }
144
+ return out;
145
+ }
146
+
147
+ // src/util/Constants.ts
148
+ var version = "1.1.0";
149
+ var DEFAULT_BASE_URL = "https://api.cosmospay.lat/cosmos-api";
150
+ var DEFAULT_VERSION = "v1";
151
+ var DEFAULT_TIMEOUT = 3e4;
152
+ var DEFAULT_RETRIES = 2;
153
+ var SIGNATURE_HEADER = "x-cosmos-signature";
154
+ var Events = {
155
+ Debug: "debug",
156
+ Request: "request",
157
+ Response: "response",
158
+ RateLimited: "rateLimited"
159
+ };
160
+
161
+ // src/errors/CosmosPayError.ts
162
+ var CosmosPayAPIError = class _CosmosPayAPIError extends Error {
163
+ constructor(options) {
164
+ const message = _CosmosPayAPIError.resolveMessage(options.status, options.body);
165
+ super(message);
166
+ this.name = "CosmosPayAPIError";
167
+ this.status = options.status;
168
+ this.method = options.method;
169
+ this.url = options.url;
170
+ this.body = options.body;
171
+ this.code = _CosmosPayAPIError.resolveCode(options.body);
172
+ Error.captureStackTrace?.(this, _CosmosPayAPIError);
173
+ }
174
+ static resolveMessage(status, body) {
175
+ if (body && typeof body === "object") {
176
+ const maybe = body;
177
+ const msg = maybe.message ?? maybe.error;
178
+ if (Array.isArray(msg)) return `[${status}] ${msg.join(", ")}`;
179
+ if (typeof msg === "string") return `[${status}] ${msg}`;
180
+ }
181
+ if (typeof body === "string" && body.length) return `[${status}] ${body}`;
182
+ return `[${status}] Request failed`;
183
+ }
184
+ static resolveCode(body) {
185
+ if (body && typeof body === "object") {
186
+ const maybe = body;
187
+ if (typeof maybe.code === "string") return maybe.code;
188
+ if (typeof maybe.error === "string") return maybe.error;
189
+ }
190
+ return void 0;
191
+ }
192
+ };
193
+ var CosmosPayRequestError = class _CosmosPayRequestError extends Error {
194
+ constructor(options) {
195
+ const reason = options.cause instanceof Error ? options.cause.message : String(options.cause);
196
+ super(`Request to ${options.method} ${options.url} failed: ${reason}`);
197
+ this.name = "CosmosPayRequestError";
198
+ this.method = options.method;
199
+ this.url = options.url;
200
+ this.cause = options.cause;
201
+ Error.captureStackTrace?.(this, _CosmosPayRequestError);
202
+ }
203
+ };
204
+
205
+ // src/common/wallets.ts
206
+ var Wallets = {
207
+ FREIGHTER: "freighter",
208
+ XBULL: "xbull",
209
+ RABET: "rabet",
210
+ LOBSTR: "lobstr",
211
+ ALBEDO: "albedo"
212
+ };
213
+
214
+ export { AddressBook, Assets, CosmosPayAPIError, CosmosPayRequestError, DEFAULT_BASE_URL, DEFAULT_RETRIES, DEFAULT_TIMEOUT, DEFAULT_VERSION, Events, SIGNATURE_HEADER, TestnetAssets, Wallets, addresses, assertAddress, defineAsset, isAddress, isContractAddress, isMuxedAddress, isNativeAsset, isStellarAddress, resolveAddress, resolveAsset, resolveIntentBody, version };
215
+ //# sourceMappingURL=chunk-RCLT7E4Y.js.map
216
+ //# sourceMappingURL=chunk-RCLT7E4Y.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/common/addresses.ts","../src/common/assets.ts","../src/common/intent-input.ts","../src/util/Constants.ts","../src/errors/CosmosPayError.ts","../src/common/wallets.ts"],"names":[],"mappings":";A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,EAAc,QAAQ,MAAM,CAAA,CAAA,EAAI,QAAQ,GAAG,CAAA,SAAA,EAAY,MAAM,CAAA,CAAE,CAAA;AACrE,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AACZ,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,MAAA;AACtB,IAAA,IAAA,CAAK,MAAM,OAAA,CAAQ,GAAA;AACnB,IAAA,IAAA,CAAK,QAAQ,OAAA,CAAQ,KAAA;AACrB,IAAA,KAAA,CAAM,iBAAA,GAAoB,MAAM,sBAAqB,CAAA;AAAA,EACvD;AACF;;;ACpEO,IAAM,OAAA,GAAU;AAAA,EACrB,SAAA,EAAW,WAAA;AAAA,EACX,KAAA,EAAO,OAAA;AAAA,EACP,KAAA,EAAO,OAAA;AAAA,EACP,MAAA,EAAQ,QAAA;AAAA,EACR,MAAA,EAAQ;AACV","file":"chunk-RCLT7E4Y.js","sourcesContent":["/**\n * Stellar address helpers + a tiny named-address book.\n *\n * So integrators don't have to sprinkle raw `G...` strings everywhere (and risk\n * typos), they can name the accounts they care about once and reference them by\n * name. A plain address string always keeps working — `resolveAddress` only\n * substitutes registered names and otherwise passes the value straight through.\n */\n\n// Stellar strkeys are base32 (RFC 4648 alphabet, no padding). These checks are\n// length/prefix sanity checks, not full checksum validation.\nconst G_ADDRESS = /^G[A-Z2-7]{55}$/; // ed25519 public key (account)\nconst M_ADDRESS = /^M[A-Z2-7]{68}$/; // muxed account\nconst C_ADDRESS = /^C[A-Z2-7]{55}$/; // contract id\n\n/** Whether a value looks like a Stellar account address (`G…`). */\nexport function isStellarAddress(value: unknown): value is string {\n return typeof value === 'string' && G_ADDRESS.test(value);\n}\n\n/** Whether a value looks like a muxed account address (`M…`). */\nexport function isMuxedAddress(value: unknown): value is string {\n return typeof value === 'string' && M_ADDRESS.test(value);\n}\n\n/** Whether a value looks like a Soroban contract id (`C…`). */\nexport function isContractAddress(value: unknown): value is string {\n return typeof value === 'string' && C_ADDRESS.test(value);\n}\n\n/** Whether a value is any kind of Stellar address (account, muxed or contract). */\nexport function isAddress(value: unknown): value is string {\n return isStellarAddress(value) || isMuxedAddress(value) || isContractAddress(value);\n}\n\n/** Throw unless `value` is a valid Stellar account/muxed/contract address. */\nexport function assertAddress(value: unknown, label = 'address'): string {\n if (!isAddress(value)) {\n throw new TypeError(`Invalid Stellar ${label}: ${String(value)}`);\n }\n return value;\n}\n\n/**\n * A registry of named Stellar addresses. Register the accounts you use a lot —\n * your merchant payout account, a treasury, frequent counterparties — and refer\n * to them by name anywhere an address is accepted.\n *\n * @example\n * addresses.define('merchant', 'GC...');\n * await client.paymentIntents.createPay({ destination: 'merchant', amount: '10' });\n */\nexport class AddressBook {\n private readonly entries = new Map<string, string>();\n\n constructor(initial: Record<string, string> = {}) {\n for (const [name, address] of Object.entries(initial)) {\n this.define(name, address);\n }\n }\n\n /** Register (or overwrite) a named address. The address is validated. */\n public define(name: string, address: string): this {\n this.entries.set(name, assertAddress(address, `address for \"${name}\"`));\n return this;\n }\n\n /** Whether a name is registered. */\n public has(name: string): boolean {\n return this.entries.has(name);\n }\n\n /** Look up a registered address by name. */\n public get(name: string): string | undefined {\n return this.entries.get(name);\n }\n\n /** Remove a named address. */\n public delete(name: string): boolean {\n return this.entries.delete(name);\n }\n\n /** All registered names. */\n public names(): string[] {\n return [...this.entries.keys()];\n }\n\n /**\n * Resolve a reference to a concrete address: a registered name is substituted,\n * any other string is returned unchanged (so raw `G…`, muxed `M…`, federation\n * `name*domain`, etc. all keep working).\n */\n public resolve(ref: string): string {\n return this.entries.get(ref) ?? ref;\n }\n}\n\n/** Process-wide default address book. Use `addresses.define(...)` to populate it. */\nexport const addresses = new AddressBook();\n\n/** Anything accepted where an address is expected: a raw address or a name in a book. */\nexport type AddressRef = string;\n\n/**\n * Resolve an {@link AddressRef} using the given book (the shared {@link addresses}\n * by default). Lenient: unknown strings pass through unchanged.\n */\nexport function resolveAddress(ref: AddressRef, book: AddressBook = addresses): string {\n return book.resolve(ref);\n}\n","/**\n * A typed, extensible catalog of Stellar assets.\n *\n * Instead of hunting down an asset's issuer (or pasting the wrong one), use the\n * built-in catalog — `Assets.USDC`, `Assets.EURC`, `Assets.XLM` — which carries\n * the verified issuer for you. Need something else? `defineAsset(...)` makes a\n * typed asset you can reuse. And a plain code string still works everywhere.\n *\n * ⚠️ Issuers are network-specific. The {@link Assets} catalog targets **mainnet**;\n * {@link TestnetAssets} carries the testnet issuers. Bare code strings (e.g.\n * `'USDC'`) are treated as *code only* (no issuer) for backwards compatibility —\n * use the catalog object or `defineAsset` when you want the issuer filled in.\n */\n\nimport { isStellarAddress } from '@/common/addresses';\n\n/** A fully-described Stellar asset. */\nexport interface AssetDefinition {\n /** Asset code, e.g. `USDC`. Use `XLM` (or omit the issuer) for native lumens. */\n code: string;\n /** Issuer account (`G…`). `null`/omitted means the native asset (XLM). */\n issuer?: string | null;\n /** Optional Soroban contract id (`C…`) for the SAC / token contract. */\n contract?: string;\n /** Human-readable name. */\n name?: string;\n /** Network the `issuer` is valid on. */\n network?: 'public' | 'testnet';\n}\n\n/** Anything accepted where an asset is expected: a code string or a definition. */\nexport type AssetRef = string | AssetDefinition;\n\n/** Normalized asset: a code plus a concrete issuer (or `null` for native). */\nexport interface ResolvedAsset {\n /** `XLM` for the native asset, otherwise the asset code. */\n code: string;\n /** Issuer `G…`, or `null` for the native asset. */\n issuer: string | null;\n /** Optional Soroban contract id. */\n contract?: string;\n}\n\nconst NATIVE: AssetDefinition = { code: 'XLM', issuer: null, name: 'Stellar Lumens' };\n\n/**\n * Built-in **mainnet** assets with verified issuers. Extend with your own via\n * {@link defineAsset}. Issuers sourced from the official issuers (Circle for\n * USDC/EURC).\n */\nexport const Assets = {\n /** Native lumens. */\n XLM: NATIVE,\n /** USD Coin by Circle (mainnet). */\n USDC: {\n code: 'USDC',\n issuer: 'GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN',\n name: 'USD Coin',\n network: 'public',\n },\n /** Euro Coin by Circle (mainnet). */\n EURC: {\n code: 'EURC',\n issuer: 'GDHU6WRG4IEQXM5NZ4BMPKOXHW76MZM4Y2IEMFDVXBSDP6SJY4ITNPP2',\n name: 'Euro Coin',\n network: 'public',\n },\n} as const satisfies Record<string, AssetDefinition>;\n\n/** Built-in **testnet** assets (Circle's Test SDF Network issuers). */\nexport const TestnetAssets = {\n XLM: NATIVE,\n USDC: {\n code: 'USDC',\n issuer: 'GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5',\n name: 'USD Coin',\n network: 'testnet',\n },\n EURC: {\n code: 'EURC',\n issuer: 'GB3Q6QDZYTHWT7E5PVS3W7FUT5GVAFC5KSZFFLPU25GO7VTC3NM2ZTVO',\n name: 'Euro Coin',\n network: 'testnet',\n },\n} as const satisfies Record<string, AssetDefinition>;\n\n/** Whether a reference denotes the native asset (XLM). */\nexport function isNativeAsset(ref: AssetRef): boolean {\n if (typeof ref === 'string') {\n const code = ref.trim().toLowerCase();\n return code === '' || code === 'xlm' || code === 'native';\n }\n return !ref.issuer || isNativeAsset(ref.code);\n}\n\n/**\n * Create a reusable, typed custom asset. Validates the issuer/contract format so\n * a typo surfaces immediately rather than on-chain.\n *\n * @example\n * const AQUA = defineAsset({ code: 'AQUA', issuer: 'GBNZ...', name: 'Aquarius' });\n * await client.paymentIntents.createPay({ destination, amount: '5', asset: AQUA });\n */\nexport function defineAsset(def: AssetDefinition): AssetDefinition {\n if (!def.code) throw new TypeError('defineAsset requires a `code`.');\n if (def.issuer != null && !isStellarAddress(def.issuer)) {\n throw new TypeError(`defineAsset: invalid issuer for ${def.code}: ${def.issuer}`);\n }\n if (def.contract != null && !/^C[A-Z2-7]{55}$/.test(def.contract)) {\n throw new TypeError(`defineAsset: invalid contract for ${def.code}: ${def.contract}`);\n }\n return Object.freeze({ ...def });\n}\n\n/**\n * Normalize an {@link AssetRef} into `{ code, issuer, contract }`.\n *\n * - A bare string is treated as *code only* (`issuer: null`) — pass a catalog\n * object or `defineAsset(...)` result when you want the issuer included.\n * - The native asset normalizes to `{ code: 'XLM', issuer: null }`.\n */\nexport function resolveAsset(ref: AssetRef): ResolvedAsset {\n if (isNativeAsset(ref)) return { code: 'XLM', issuer: null };\n if (typeof ref === 'string') return { code: ref, issuer: null };\n return {\n code: ref.code,\n issuer: ref.issuer ?? null,\n ...(ref.contract ? { contract: ref.contract } : {}),\n };\n}\n","/**\n * Shared resolution of \"create intent\" input, used by both the server SDK and\n * the web client so the convenience layers behave identically: a typed\n * {@link AssetRef} (e.g. `Assets.USDC`) is expanded into `assetCode`/`assetIssuer`,\n * and named addresses are substituted via an {@link AddressBook}.\n */\n\nimport { addresses as defaultBook, AddressBook, resolveAddress } from '@/common/addresses';\nimport { resolveAsset, type AssetRef } from '@/common/assets';\n\n/** Fields the resolver understands (everything else passes through untouched). */\nexport interface ResolvableIntentInput {\n destination?: string;\n source?: string;\n /** Typed asset (`Assets.USDC`, `defineAsset(...)`) — fills code + issuer. */\n asset?: AssetRef;\n assetCode?: string;\n assetIssuer?: string;\n}\n\n/**\n * Expand `asset` into `assetCode`/`assetIssuer` and resolve named\n * `destination`/`source` addresses. Existing `assetCode`/`assetIssuer` win over a\n * provided `asset`; native assets leave the code unset (the API treats an omitted\n * asset as native XLM). Returns a new object — the input is not mutated.\n */\nexport function resolveIntentBody<T extends ResolvableIntentInput>(\n options: T,\n book: AddressBook = defaultBook,\n): Omit<T, 'asset'> {\n const out: Record<string, unknown> = { ...(options as Record<string, unknown>) };\n\n if (typeof out['destination'] === 'string') {\n out['destination'] = resolveAddress(out['destination'], book);\n }\n if (typeof out['source'] === 'string') {\n out['source'] = resolveAddress(out['source'], book);\n }\n\n if (out['asset'] != null) {\n const { code, issuer } = resolveAsset(out['asset'] as AssetRef);\n delete out['asset'];\n if (issuer) {\n // Non-native: fill code + issuer unless the caller set them explicitly.\n out['assetCode'] ??= code;\n out['assetIssuer'] ??= issuer;\n }\n // Native (issuer == null) → leave assetCode/assetIssuer omitted = native XLM.\n }\n\n return out as Omit<T, 'asset'>;\n}\n","/** Library version, kept in sync with package.json. */\nexport const version = '1.1.0';\n\n/**\n * Default base URL of the Cosmos Pay gateway. Maintained by Cosmos Pay — users\n * never need to set this; it's part of the {@link shared} configuration. Override\n * only when self-hosting or pointing at a staging gateway.\n *\n * This is the public APISIX gateway: requests under `/cosmos-api/*` are\n * authenticated (API key) and proxied to the Payments API. The version segment\n * (`/v1`, see {@link DEFAULT_VERSION}) is appended by the REST layer, producing\n * e.g. `https://api.cosmospay.lat/cosmos-api/v1/payment-intents/pay`.\n */\nexport const DEFAULT_BASE_URL = 'https://api.cosmospay.lat/cosmos-api';\n\n/** Default API version segment prefixed to every route (`/v1/...`). */\nexport const DEFAULT_VERSION = 'v1';\n\n/** Default request timeout in milliseconds. */\nexport const DEFAULT_TIMEOUT = 30_000;\n\n/** Default number of retries for transient failures (network / 429 / 5xx). */\nexport const DEFAULT_RETRIES = 2;\n\n/** Default HMAC signature header sent by the Cosmos Pay webhook dispatcher. */\nexport const SIGNATURE_HEADER = 'x-cosmos-signature';\n\n/**\n * Client debug/telemetry events. The {@link Client} extends EventEmitter and\n * emits these for observability (`debug`/`rateLimit`-style events).\n */\nexport const Events = {\n Debug: 'debug',\n Request: 'request',\n Response: 'response',\n RateLimited: 'rateLimited',\n} as const;\nexport type ClientEvent = (typeof Events)[keyof typeof Events];\n","/**\n * Error thrown when the Cosmos Pay API responds with a non-2xx status.\n *\n * Carries the HTTP status, the parsed response body and the request context so\n * callers can branch on `error.status` (e.g. 404 → not found, 403 → gateway).\n */\nexport class CosmosPayAPIError extends Error {\n /** HTTP status code returned by the API. */\n public readonly status: number;\n /** HTTP method of the failed request. */\n public readonly method: string;\n /** Absolute URL of the failed request. */\n public readonly url: string;\n /** Parsed response body (object when JSON, string otherwise, or null). */\n public readonly body: unknown;\n /** Machine-readable error code extracted from the body when present. */\n public readonly code: string | undefined;\n\n constructor(options: {\n status: number;\n method: string;\n url: string;\n body: unknown;\n }) {\n const message = CosmosPayAPIError.resolveMessage(options.status, options.body);\n super(message);\n this.name = 'CosmosPayAPIError';\n this.status = options.status;\n this.method = options.method;\n this.url = options.url;\n this.body = options.body;\n this.code = CosmosPayAPIError.resolveCode(options.body);\n Error.captureStackTrace?.(this, CosmosPayAPIError);\n }\n\n private static resolveMessage(status: number, body: unknown): string {\n if (body && typeof body === 'object') {\n const maybe = body as { message?: unknown; error?: unknown };\n const msg = maybe.message ?? maybe.error;\n if (Array.isArray(msg)) return `[${status}] ${msg.join(', ')}`;\n if (typeof msg === 'string') return `[${status}] ${msg}`;\n }\n if (typeof body === 'string' && body.length) return `[${status}] ${body}`;\n return `[${status}] Request failed`;\n }\n\n private static resolveCode(body: unknown): string | undefined {\n if (body && typeof body === 'object') {\n const maybe = body as { code?: unknown; error?: unknown };\n if (typeof maybe.code === 'string') return maybe.code;\n if (typeof maybe.error === 'string') return maybe.error;\n }\n return undefined;\n }\n}\n\n/**\n * Error thrown when a request never reaches the API: network failure, abort or\n * timeout. Distinct from {@link CosmosPayAPIError}, which always has a status.\n */\nexport class CosmosPayRequestError extends Error {\n public readonly method: string;\n public readonly url: string;\n public readonly cause: unknown;\n\n constructor(options: { method: string; url: string; cause: unknown }) {\n const reason =\n options.cause instanceof Error ? options.cause.message : String(options.cause);\n super(`Request to ${options.method} ${options.url} failed: ${reason}`);\n this.name = 'CosmosPayRequestError';\n this.method = options.method;\n this.url = options.url;\n this.cause = options.cause;\n Error.captureStackTrace?.(this, CosmosPayRequestError);\n }\n}\n","/**\n * Typed identifiers for the wallets the web client knows about, so you can write\n * `Wallets.FREIGHTER` instead of remembering the `'freighter'` magic string —\n * while any custom adapter id still works.\n */\n\n/** Built-in wallet ids (matches each adapter's `id`). */\nexport const Wallets = {\n FREIGHTER: 'freighter',\n XBULL: 'xbull',\n RABET: 'rabet',\n LOBSTR: 'lobstr',\n ALBEDO: 'albedo',\n} as const;\n\n/** A known wallet id, or any custom adapter id (autocomplete for the built-ins). */\nexport type WalletId = (typeof Wallets)[keyof typeof Wallets] | (string & {});\n"]}