@cosmosapp/pay_sdk 2.3.2 → 2.4.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 +19 -0
- package/README.md +97 -61
- package/dist/{chunk-U3WDM2FJ.js → chunk-6FIALX2E.js} +3 -3
- package/dist/{chunk-U3WDM2FJ.js.map → chunk-6FIALX2E.js.map} +1 -1
- package/dist/chunk-ALFITFBN.js +105 -0
- package/dist/chunk-ALFITFBN.js.map +1 -0
- package/dist/chunk-PAQHOXQ6.js +392 -0
- package/dist/chunk-PAQHOXQ6.js.map +1 -0
- package/dist/errors-CZu5mmz1.d.cts +293 -0
- package/dist/errors-Cqh7UdUO.d.ts +293 -0
- package/dist/index.cjs +18 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +12 -7
- package/dist/index.d.ts +12 -7
- package/dist/index.js +19 -6
- package/dist/index.js.map +1 -1
- package/dist/intent-input-BybnwL83.d.ts +126 -0
- package/dist/intent-input-C2PTr2XH.d.cts +126 -0
- package/dist/swk/index.js +1 -103
- package/dist/swk/index.js.map +1 -1
- package/dist/wallets/index.cjs +1043 -0
- package/dist/wallets/index.cjs.map +1 -0
- package/dist/wallets/index.d.cts +384 -0
- package/dist/wallets/index.d.ts +384 -0
- package/dist/wallets/index.js +629 -0
- package/dist/wallets/index.js.map +1 -0
- package/dist/{intent-input-CP5bkBYI.d.cts → wallets-CeIjESt5.d.cts} +39 -126
- package/dist/{intent-input-CP5bkBYI.d.ts → wallets-CeIjESt5.d.ts} +39 -126
- package/dist/web/index.cjs +1 -1
- package/dist/web/index.cjs.map +1 -1
- package/dist/web/index.d.cts +7 -292
- package/dist/web/index.d.ts +7 -292
- package/dist/web/index.js +5 -391
- package/dist/web/index.js.map +1 -1
- package/llms/07-webhooks.md +2 -0
- package/llms/15-swaps.md +2 -0
- package/llms/18-wallets.md +94 -0
- package/llms/llms-full.txt +101 -0
- package/llms/llms.txt +1 -0
- package/package.json +22 -8
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,25 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to @cosmosapp/pay_sdk are documented here.
|
|
4
4
|
Generated from [Conventional Commits](https://www.conventionalcommits.org) by [git-cliff](https://git-cliff.org).
|
|
5
|
+
## [2.4.0] - 2026-11-08
|
|
6
|
+
|
|
7
|
+
### Features
|
|
8
|
+
- Every Stellar, EVM and Solana wallet behind one shape, and Monad submit by txHash (a61f570)
|
|
9
|
+
- Stellar Wallets Kit v2 (static class, fetchAddress), Freighter listed as Varial (41b5e9b)
|
|
10
|
+
- ParseEip681 turns an EVM deposit link into the wallet's transaction (e1043c3)
|
|
11
|
+
- Hana, Klever, OneKey, Bitget, Cactus Link, D'CENT and Scopuly without the kit (d32d876)
|
|
12
|
+
|
|
13
|
+
### Bug Fixes
|
|
14
|
+
- EVM amounts are bounded to uint256 (d03c441)
|
|
15
|
+
- An adapter that never answers its availability probe counts as absent (1b64f04)
|
|
16
|
+
- The server's current spec, protected payment events, unwrapped routes listed (f8c1287)
|
|
17
|
+
|
|
18
|
+
### Miscellaneous
|
|
19
|
+
- Bump the minor-and-patch group across 1 directory with 3 updates (f8f9107)
|
|
20
|
+
|
|
21
|
+
### Documentation
|
|
22
|
+
- Brand banner and no emojis (#36) (a7622af)
|
|
23
|
+
|
|
5
24
|
## [2.3.2] - 2026-11-02
|
|
6
25
|
|
|
7
26
|
### Bug Fixes
|
package/README.md
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://www.npmjs.com/package/@cosmosapp/pay_sdk"><img src=".github/assets/banner.png" width="100%" alt="Cosmos Pay JavaScript and TypeScript SDK: @cosmosapp/pay_sdk, for the server and the browser."></a>
|
|
3
|
+
</p>
|
|
4
|
+
|
|
1
5
|
<div align="center">
|
|
2
6
|
|
|
3
|
-
#
|
|
7
|
+
# @cosmosapp/pay_sdk
|
|
4
8
|
|
|
5
9
|
**The official JavaScript / TypeScript SDK for [Cosmos Pay](https://cosmospay.lat), the stablecoin payments API for Stellar, Solana and Monad**
|
|
6
10
|
|
|
@@ -50,51 +54,52 @@ const { txHash, account, wallet } = await webClient.pay(intent);
|
|
|
50
54
|
console.log(`Paid via ${wallet} from ${account}: ${txHash}`);
|
|
51
55
|
```
|
|
52
56
|
|
|
53
|
-
>
|
|
57
|
+
> **Runnable examples** for every feature live in [`examples/`](./examples)
|
|
54
58
|
> (one file per area — payment intents, web client, webhooks, products, customers,
|
|
55
59
|
> analytics, errors, …). See [`examples/README.md`](./examples/README.md).
|
|
56
60
|
>
|
|
57
|
-
>
|
|
61
|
+
> **Using an AI assistant?** Atomic, AI-readable docs live in the isolated
|
|
58
62
|
> [`llms/`](./llms) folder ([`llms.txt`](./llms/llms.txt) index + per-topic files +
|
|
59
63
|
> a combined [`llms-full.txt`](./llms/llms-full.txt)) — point your tool at them to
|
|
60
64
|
> make integrating the SDK much easier. After install they're at
|
|
61
65
|
> `node_modules/@cosmosapp/pay_sdk/llms/`.
|
|
62
66
|
|
|
63
|
-
##
|
|
67
|
+
## Features
|
|
64
68
|
|
|
65
|
-
-
|
|
66
|
-
-
|
|
67
|
-
-
|
|
68
|
-
-
|
|
69
|
-
-
|
|
70
|
-
-
|
|
71
|
-
-
|
|
69
|
+
- **TypeScript & JavaScript** — full typings, works in both **CJS** and **ESM**.
|
|
70
|
+
- **Zero runtime dependencies** — native `fetch` + `node:crypto`, nothing else.
|
|
71
|
+
- **Atomic API** — one client, one manager per resource: `client.paymentIntents`, `client.webhooks`, …
|
|
72
|
+
- **Self-acting structures** — `intent.validate()`, `endpoint.rotateSecret()`, `product.deactivate()`.
|
|
73
|
+
- **Built-in webhook signature verification** + ready-made `http` / Express handlers.
|
|
74
|
+
- **Resilient by default** — automatic retries, timeouts and structured errors.
|
|
75
|
+
- **Browser web client** — auto-detects Freighter, xBull, Rabet, LOBSTR & Albedo, builds the
|
|
72
76
|
transaction from the SEP-7 response and signs it. Agnostic — you never pass a provider.
|
|
73
77
|
|
|
74
|
-
##
|
|
75
|
-
|
|
76
|
-
- [Installation](
|
|
77
|
-
- [Authentication](
|
|
78
|
-
- [Quick start](
|
|
79
|
-
- [The client at a glance](
|
|
80
|
-
- [Web client (browser wallets)](
|
|
81
|
-
- [
|
|
82
|
-
- [
|
|
83
|
-
- [
|
|
84
|
-
- [
|
|
85
|
-
- [
|
|
86
|
-
- [
|
|
87
|
-
- [
|
|
88
|
-
- [
|
|
89
|
-
- [
|
|
90
|
-
- [
|
|
91
|
-
- [
|
|
92
|
-
- [
|
|
93
|
-
- [
|
|
94
|
-
- [
|
|
95
|
-
- [
|
|
96
|
-
|
|
97
|
-
|
|
78
|
+
## Table of contents
|
|
79
|
+
|
|
80
|
+
- [Installation](#installation)
|
|
81
|
+
- [Authentication](#authentication)
|
|
82
|
+
- [Quick start](#quick-start)
|
|
83
|
+
- [The client at a glance](#the-client-at-a-glance)
|
|
84
|
+
- [Web client (browser wallets)](#web-client-browser-wallets)
|
|
85
|
+
- [Wallets: Stellar, EVM and Solana](#wallets-stellar-evm-and-solana)
|
|
86
|
+
- [Payment intents](#payment-intents)
|
|
87
|
+
- [Typed assets, wallets & addresses](#typed-assets-wallets--addresses)
|
|
88
|
+
- [Swaps](#swaps)
|
|
89
|
+
- [USDT0 (Stellar to EVM networks)](#usdt0-stellar-to-evm-networks)
|
|
90
|
+
- [Private payments](#private-payments)
|
|
91
|
+
- [Webhooks](#webhooks)
|
|
92
|
+
- [Products & customers](#products--customers)
|
|
93
|
+
- [Analytics & health](#analytics--health)
|
|
94
|
+
- [Error handling](#error-handling)
|
|
95
|
+
- [Observability](#observability)
|
|
96
|
+
- [Configuration reference](#configuration-reference)
|
|
97
|
+
- [TypeScript](#typescript)
|
|
98
|
+
- [Running the tests locally](#running-the-tests-locally)
|
|
99
|
+
- [CI/CD & publishing](#cicd--publishing)
|
|
100
|
+
- [License](#license)
|
|
101
|
+
|
|
102
|
+
## Installation
|
|
98
103
|
|
|
99
104
|
```bash
|
|
100
105
|
npm install @cosmosapp/pay_sdk
|
|
@@ -106,7 +111,7 @@ yarn add @cosmosapp/pay_sdk
|
|
|
106
111
|
|
|
107
112
|
Requires **Node.js ≥ 18** (for the global `fetch`). On older runtimes pass a `fetch` polyfill via the `fetch` option.
|
|
108
113
|
|
|
109
|
-
##
|
|
114
|
+
## Authentication
|
|
110
115
|
|
|
111
116
|
**You only need your API key.** Everything else — the gateway URL, the API version, and other
|
|
112
117
|
infrastructure details — is part of the SDK's **shared configuration**, maintained by Cosmos Pay
|
|
@@ -152,7 +157,7 @@ normal integration never sets them.
|
|
|
152
157
|
|
|
153
158
|
</details>
|
|
154
159
|
|
|
155
|
-
##
|
|
160
|
+
## Quick start
|
|
156
161
|
|
|
157
162
|
```ts
|
|
158
163
|
import { Client } from '@cosmosapp/pay_sdk';
|
|
@@ -183,7 +188,7 @@ const outcome = await pay.validate('3389e9f0d6b3e3f1c2a1...');
|
|
|
183
188
|
if (outcome.valid) console.log('Settled!', outcome.status);
|
|
184
189
|
```
|
|
185
190
|
|
|
186
|
-
##
|
|
191
|
+
## The client at a glance
|
|
187
192
|
|
|
188
193
|
| Manager | Resource | Key methods |
|
|
189
194
|
| ------------------------ | --------------------------------- | ----------- |
|
|
@@ -201,7 +206,7 @@ if (outcome.valid) console.log('Settled!', outcome.status);
|
|
|
201
206
|
| `client.analytics` | Read-only metrics & logs | `summary` · `series` · `balances` · `apiLogs` · `webhookLogs` |
|
|
202
207
|
| `client.health` | Liveness / readiness probes | `liveness` · `readiness` |
|
|
203
208
|
|
|
204
|
-
##
|
|
209
|
+
## Web client (browser wallets)
|
|
205
210
|
|
|
206
211
|
The server SDK *creates* intents. The **web client** *completes* them in the user's browser.
|
|
207
212
|
|
|
@@ -336,7 +341,7 @@ The web client can **also call the Cosmos Pay API directly** — creating and va
|
|
|
336
341
|
the browser — by passing an `apiKey`. This is handy for prototypes, internal tools and other
|
|
337
342
|
**trusted environments**.
|
|
338
343
|
|
|
339
|
-
>
|
|
344
|
+
> **Not recommended for public/production frontends.** Doing this ships your API key to the
|
|
340
345
|
> browser, where anyone can read it. Only enable it when the environment is trusted and the key is
|
|
341
346
|
> safe to expose (e.g. a scoped testnet `dv_` key). For production, **create and validate intents on
|
|
342
347
|
> your server** and let the web client only sign/submit.
|
|
@@ -360,7 +365,36 @@ import freighter from '@stellar/freighter-api';
|
|
|
360
365
|
const webClient = new WebClient({ stellarSdk: StellarSdk, freighter });
|
|
361
366
|
```
|
|
362
367
|
|
|
363
|
-
##
|
|
368
|
+
## Wallets: Stellar, EVM and Solana
|
|
369
|
+
|
|
370
|
+
`@cosmosapp/pay_sdk/wallets` finds every wallet a person can sign with in the browser and gives
|
|
371
|
+
each the same small shape, whatever its ecosystem. It bundles no wallet library: Stellar wallets
|
|
372
|
+
come through the SDK's adapters and the providers wallets inject (Hana, OneKey, Bitget,
|
|
373
|
+
D'CENT...), plus a Stellar Wallets Kit when you pass one; EVM wallets
|
|
374
|
+
through EIP-6963 (MetaMask, Rabby, Coinbase Wallet...), Solana wallets through Wallet Standard
|
|
375
|
+
(Phantom, Solflare, Backpack...).
|
|
376
|
+
|
|
377
|
+
```ts
|
|
378
|
+
import { discoverWallets, EvmChains, isUserRejection } from '@cosmosapp/pay_sdk/wallets';
|
|
379
|
+
|
|
380
|
+
const { stellar, evm, solana } = await discoverWallets(); // { stellar: { kit } } adds a kit's wallets
|
|
381
|
+
|
|
382
|
+
// Stellar: sign the swap's XDR
|
|
383
|
+
const signedXdr = await stellar[0].signTransaction(swap.xdr, { network: 'public', address });
|
|
384
|
+
|
|
385
|
+
// Solana: sign the base64 transaction, the API relays it
|
|
386
|
+
const signedTransaction = await solana[0].signTransaction(sol.transaction.data);
|
|
387
|
+
|
|
388
|
+
// Monad: EVM wallets sign and broadcast, and answer the hash. The chain is switched (or added) first.
|
|
389
|
+
const from = await evm[0].connect();
|
|
390
|
+
const txHash = await evm[0].sendTransaction({ from, ...mon.transaction }, EvmChains.monad);
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
Each wallet has `id` (`stellar:freighter`, `evm:io.metamask`, `solana:phantom`), `name`, `icon`
|
|
394
|
+
and `ecosystem`. Failures are `WalletError`s; `isUserRejection(error)` tells a declined prompt
|
|
395
|
+
from a real failure. Full guide: [`llms/18-wallets.md`](./llms/18-wallets.md).
|
|
396
|
+
|
|
397
|
+
## Payment intents
|
|
364
398
|
|
|
365
399
|
```ts
|
|
366
400
|
// tx intent (source known → unsigned XDR + tx URI + QR)
|
|
@@ -402,7 +436,7 @@ const outcome = await intent.validate('<txHash>');
|
|
|
402
436
|
Each `PaymentIntent` exposes typed helpers: `isTx`, `isPay`, `isSucceeded`, `isPending`, `assetLabel`,
|
|
403
437
|
and the action methods `fetch()`, `edit()`, `validate()`, `cancel()`, `delete()`.
|
|
404
438
|
|
|
405
|
-
##
|
|
439
|
+
## Typed assets, wallets & addresses
|
|
406
440
|
|
|
407
441
|
So you never paste the wrong issuer or a magic string, the SDK ships small **typed, extensible
|
|
408
442
|
catalogs** — and a plain string still works everywhere. These are exported from **both** entry points
|
|
@@ -428,7 +462,7 @@ await client.paymentIntents.createPay({ destination: 'G...', amount: '5', assetC
|
|
|
428
462
|
// Testnet issuers live in TestnetAssets.* (e.g. TestnetAssets.USDC).
|
|
429
463
|
```
|
|
430
464
|
|
|
431
|
-
>
|
|
465
|
+
> **Note:** Issuers are network-specific. `Assets.*` targets **mainnet**; use `TestnetAssets.*` for testnet.
|
|
432
466
|
|
|
433
467
|
**Wallets** — typed ids instead of magic strings:
|
|
434
468
|
|
|
@@ -454,7 +488,7 @@ import { isStellarAddress } from '@cosmosapp/pay_sdk';
|
|
|
454
488
|
isStellarAddress('GC...'); // true
|
|
455
489
|
```
|
|
456
490
|
|
|
457
|
-
##
|
|
491
|
+
## Swaps
|
|
458
492
|
|
|
459
493
|
Two managers, split by whether the swap leaves its chain.
|
|
460
494
|
|
|
@@ -485,6 +519,8 @@ await sol.submit({ signedTransaction });
|
|
|
485
519
|
const mon = await client.swaps.create({ chain: 'monad', amount: '10', sourceAssetCode: 'MON',
|
|
486
520
|
destAssetCode: '0x754704bc059f8c67012fed69bc8a327a5aafb603', source: evmWallet });
|
|
487
521
|
if (mon.approval) await wallet.sendTransaction(mon.approval);
|
|
522
|
+
// A browser wallet (MetaMask...) sends the swap itself: report its hash instead.
|
|
523
|
+
// await mon.submit({ txHash }); see @cosmosapp/pay_sdk/wallets
|
|
488
524
|
|
|
489
525
|
const page = await client.swaps.list({ chain: 'solana' }); // ChainSwap[]
|
|
490
526
|
```
|
|
@@ -513,7 +549,7 @@ Keep `x.quoteSignature`: it is NEAR Intents' signature over the quote, what
|
|
|
513
549
|
settles a dispute. Webhooks: `SWAP_*` for both same-chain managers,
|
|
514
550
|
`CROSS_CHAIN_SWAP_*` here — `client.webhooks.on('crossChainSwapSucceeded', …)`.
|
|
515
551
|
|
|
516
|
-
##
|
|
552
|
+
## USDT0 (Stellar to EVM networks)
|
|
517
553
|
|
|
518
554
|
`client.usdt0` sends USDT0, Tether's omnichain USDT, from Stellar to an EVM network
|
|
519
555
|
through LayerZero's OFT: Ethereum (`eth`) receives native USDT, every other network
|
|
@@ -541,7 +577,7 @@ The OFT carries 6 decimals, so a 7th decimal of `amount` is `dust` that stays in
|
|
|
541
577
|
account. See [`llms/17-usdt0.md`](./llms/17-usdt0.md) for the fees, the shared public
|
|
542
578
|
key's `publicToken` and every field.
|
|
543
579
|
|
|
544
|
-
##
|
|
580
|
+
## Private payments
|
|
545
581
|
|
|
546
582
|
`client.privatePayments` creates and reads payments whose amount is hidden on-chain:
|
|
547
583
|
priced in XLM and paid with confidential transfers on Cosmos Pay's confidential token.
|
|
@@ -564,7 +600,7 @@ const config = await client.privatePayments.config(); // the token, registries,
|
|
|
564
600
|
See [`llms/16-private-payments.md`](./llms/16-private-payments.md) for merchant fees,
|
|
565
601
|
expiry and every field.
|
|
566
602
|
|
|
567
|
-
##
|
|
603
|
+
## Webhooks
|
|
568
604
|
|
|
569
605
|
```ts
|
|
570
606
|
// register an endpoint — the secret is returned ONCE
|
|
@@ -663,7 +699,7 @@ const event = Webhooks.constructEvent(
|
|
|
663
699
|
`client.webhooks.process(rawBody, header, { secret })` does the same and emits the event to your
|
|
664
700
|
`on(...)` listeners.
|
|
665
701
|
|
|
666
|
-
##
|
|
702
|
+
## Products & customers
|
|
667
703
|
|
|
668
704
|
```ts
|
|
669
705
|
const product = await client.products.create({
|
|
@@ -685,7 +721,7 @@ await customer.removeWallet(wallet); // or client.customers.removeWallet(custome
|
|
|
685
721
|
const customers = await client.customers.list(); // includes payment stats
|
|
686
722
|
```
|
|
687
723
|
|
|
688
|
-
##
|
|
724
|
+
## Analytics & health
|
|
689
725
|
|
|
690
726
|
```ts
|
|
691
727
|
const summary = await client.analytics.summary(); // totals, volume, webhook health, 30-day series
|
|
@@ -698,7 +734,7 @@ await client.health.liveness(); // true
|
|
|
698
734
|
const ready = await client.health.readiness(); // { status, info, details }
|
|
699
735
|
```
|
|
700
736
|
|
|
701
|
-
##
|
|
737
|
+
## Error handling
|
|
702
738
|
|
|
703
739
|
```ts
|
|
704
740
|
import { CosmosPayAPIError, CosmosPayRequestError } from '@cosmosapp/pay_sdk';
|
|
@@ -717,7 +753,7 @@ try {
|
|
|
717
753
|
Transient failures (network errors, `408`, `429`, `5xx`) are retried automatically
|
|
718
754
|
(default 2 retries, honoring `Retry-After`).
|
|
719
755
|
|
|
720
|
-
##
|
|
756
|
+
## Observability
|
|
721
757
|
|
|
722
758
|
The client re-emits REST telemetry:
|
|
723
759
|
|
|
@@ -727,7 +763,7 @@ client.on('response', ({ status, url }) => {});
|
|
|
727
763
|
client.on('rateLimited', ({ url }) => {});
|
|
728
764
|
```
|
|
729
765
|
|
|
730
|
-
##
|
|
766
|
+
## Configuration reference
|
|
731
767
|
|
|
732
768
|
```ts
|
|
733
769
|
new Client({
|
|
@@ -746,7 +782,7 @@ new Client({
|
|
|
746
782
|
});
|
|
747
783
|
```
|
|
748
784
|
|
|
749
|
-
##
|
|
785
|
+
## TypeScript
|
|
750
786
|
|
|
751
787
|
Everything is fully typed. Import option/entity types and enums directly:
|
|
752
788
|
|
|
@@ -760,7 +796,7 @@ import {
|
|
|
760
796
|
} from '@cosmosapp/pay_sdk';
|
|
761
797
|
```
|
|
762
798
|
|
|
763
|
-
##
|
|
799
|
+
## Running the tests locally
|
|
764
800
|
|
|
765
801
|
The test suite runs **entirely offline** with the built-in Node test runner (`node:test`) — no network,
|
|
766
802
|
no API key and no extra dependencies. Every HTTP call is served by an injected fake `fetch`, and the
|
|
@@ -789,7 +825,7 @@ node --test test/webhooks.test.mjs
|
|
|
789
825
|
|
|
790
826
|
> The `pretest` hook builds `dist/` first, so the tests exercise the exact artifact that gets published to npm.
|
|
791
827
|
|
|
792
|
-
##
|
|
828
|
+
## CI/CD & publishing
|
|
793
829
|
|
|
794
830
|
This repo ships two GitHub Actions workflows under [`.github/workflows/`](./.github/workflows):
|
|
795
831
|
|
|
@@ -800,7 +836,7 @@ This repo ships two GitHub Actions workflows under [`.github/workflows/`](./.git
|
|
|
800
836
|
|
|
801
837
|
Publishing is **fully automatic**: there's no Release to create and no tag to push. `release.yml`
|
|
802
838
|
runs on every push to `main`, compares `package.json`'s version against what's already on npm, and
|
|
803
|
-
publishes only when it's new. Unchanged version → the job skips cleanly (no
|
|
839
|
+
publishes only when it's new. Unchanged version → the job skips cleanly (no failed run).
|
|
804
840
|
|
|
805
841
|
### One-time setup (the GitHub environment variable)
|
|
806
842
|
|
|
@@ -837,14 +873,14 @@ pushing unrelated commits is always safe. Packages ship with
|
|
|
837
873
|
> Only `dist/`, `README.md` and `LICENSE` are published (`package.json#files`) — source, tests and
|
|
838
874
|
> workflows never ship in the tarball. Verify locally with `npm pack --dry-run`.
|
|
839
875
|
|
|
840
|
-
##
|
|
876
|
+
## License
|
|
841
877
|
|
|
842
878
|
**[Apache License 2.0](./LICENSE)** — a permissive, OSI-approved open-source license. In short:
|
|
843
879
|
|
|
844
|
-
-
|
|
845
|
-
-
|
|
846
|
-
-
|
|
847
|
-
-
|
|
880
|
+
- **Free to use**, including in **commercial** products and services.
|
|
881
|
+
- **Modify, distribute and sublicense** — you may even sell it.
|
|
882
|
+
- **Explicit patent grant** from contributors, with patent-retaliation protection.
|
|
883
|
+
- When you redistribute, keep the [`LICENSE`](./LICENSE) + [`NOTICE`](./NOTICE) and note any
|
|
848
884
|
significant changes you made.
|
|
849
885
|
|
|
850
886
|
> This is not legal advice.
|
|
@@ -145,7 +145,7 @@ function resolveIntentBody(options, book = addresses) {
|
|
|
145
145
|
}
|
|
146
146
|
|
|
147
147
|
// src/util/Constants.ts
|
|
148
|
-
var version = "2.
|
|
148
|
+
var version = "2.4.0";
|
|
149
149
|
var DEFAULT_BASE_URL = "https://api.cosmospay.lat/cosmos-api";
|
|
150
150
|
var DEFAULT_VERSION = "v1";
|
|
151
151
|
var DEFAULT_TIMEOUT = 3e4;
|
|
@@ -214,5 +214,5 @@ var Wallets = {
|
|
|
214
214
|
};
|
|
215
215
|
|
|
216
216
|
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 };
|
|
217
|
-
//# sourceMappingURL=chunk-
|
|
218
|
-
//# sourceMappingURL=chunk-
|
|
217
|
+
//# sourceMappingURL=chunk-6FIALX2E.js.map
|
|
218
|
+
//# sourceMappingURL=chunk-6FIALX2E.js.map
|
|
@@ -1 +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":";AAWA,IAAM,SAAA,GAAY,iBAAA;AAClB,IAAM,SAAA,GAAY,i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A,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;AAAA,EAErB,MAAA,EAAQ,QAAA;AAAA,EACR,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-U3WDM2FJ.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 = '2.3.2';\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 /** Cosmos Pay's own wallet — extension, or the hosted build (see CosmosWalletAdapter). */\n COSMOS: 'cosmos',\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"]}
|
|
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":";AAWA,IAAM,SAAA,GAAY,iBAAA;AAClB,IAAM,SAAA,GAAY,iBAAA;AAClB,IAAM,SAAA,GAAY,iBAAA;AAGX,SAAS,iBAAiB,KAAA,EAAiC;AAChE,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,SAAA,CAAU,KAAK,KAAK,CAAA;AAC1D;AAGO,SAAS,eAAe,KAAA,EAAiC;AAC9D,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,SAAA,CAAU,KAAK,KAAK,CAAA;AAC1D;AAGO,SAAS,kBAAkB,KAAA,EAAiC;AACjE,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,SAAA,CAAU,KAAK,KAAK,CAAA;AAC1D;AAGO,SAAS,UAAU,KAAA,EAAiC;AACzD,EAAA,OAAO,iBAAiB,KAAK,CAAA,IAAK,eAAe,KAAK,CAAA,IAAK,kBAAkB,KAAK,CAAA;AACpF;AAGO,SAAS,aAAA,CAAc,KAAA,EAAgB,KAAA,GAAQ,SAAA,EAAmB;AACvE,EAAA,IAAI,CAAC,SAAA,CAAU,KAAK,CAAA,EAAG;AACrB,IAAA,MAAM,IAAI,UAAU,CAAA,gBAAA,EAAmB,KAAK,KAAK,MAAA,CAAO,KAAK,CAAC,CAAA,CAAE,CAAA;AAAA,EAClE;AACA,EAAA,OAAO,KAAA;AACT;AAWO,IAAM,cAAN,MAAkB;AAAA,EAGvB,WAAA,CAAY,OAAA,GAAkC,EAAC,EAAG;AAFlD,IAAA,IAAA,CAAiB,OAAA,uBAAc,GAAA,EAAoB;AAGjD,IAAA,KAAA,MAAW,CAAC,I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MAAM,sBAAA,SAA8B,KAAA,CAAM;AAAA,EAK/C,YAAY,OAAA,EAA0D;AACpE,IAAA,MAAM,MAAA,GACJ,QAAQ,KAAA,YAAiB,KAAA,GAAQ,QAAQ,KAAA,CAAM,OAAA,GAAU,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA;AAC/E,IAAA,KAAA,CAAM,CAAA,WAAA,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;AAAA,EAErB,MAAA,EAAQ,QAAA;AAAA,EACR,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-6FIALX2E.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 = '2.4.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 /** Cosmos Pay's own wallet — extension, or the hosted build (see CosmosWalletAdapter). */\n COSMOS: 'cosmos',\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"]}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { injectedProvider, resolveProvider } from './chunk-6PHQBYQ4.js';
|
|
2
|
+
|
|
3
|
+
// src/swk/types.ts
|
|
4
|
+
var SwkModuleType = {
|
|
5
|
+
HW_WALLET: "HW_WALLET",
|
|
6
|
+
HOT_WALLET: "HOT_WALLET",
|
|
7
|
+
BRIDGE_WALLET: "BRIDGE_WALLET",
|
|
8
|
+
AIR_GAPED_WALLET: "AIR_GAPED_WALLET"
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
// src/swk/CosmosWalletModule.ts
|
|
12
|
+
var COSMOS_WALLET_ID = "cosmos-wallet";
|
|
13
|
+
var PRODUCT_NAME = "Cosmos Pay Wallet";
|
|
14
|
+
var PRODUCT_URL = "https://github.com/CosmosPay/CosmosPay-Wallet";
|
|
15
|
+
var PRODUCT_ICON = "https://raw.githubusercontent.com/CosmosPay/CosmosPay-Wallet/main/public/logo-512.png";
|
|
16
|
+
var NOT_SUPPORTED = -3;
|
|
17
|
+
var CosmosWalletModule = class {
|
|
18
|
+
constructor(options = {}) {
|
|
19
|
+
this.productId = COSMOS_WALLET_ID;
|
|
20
|
+
this.moduleType = options.moduleType ?? SwkModuleType.HOT_WALLET;
|
|
21
|
+
this.productName = options.productName ?? PRODUCT_NAME;
|
|
22
|
+
this.productUrl = options.productUrl ?? PRODUCT_URL;
|
|
23
|
+
this.productIcon = options.productIcon ?? PRODUCT_ICON;
|
|
24
|
+
this.options = {
|
|
25
|
+
provider: options.provider,
|
|
26
|
+
walletUrl: options.walletUrl,
|
|
27
|
+
loadTimeoutMs: options.loadTimeoutMs
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The kit allows 1000ms for this and shows the wallet as unavailable otherwise,
|
|
32
|
+
* so it answers from what is already in the page: an injected provider, or a
|
|
33
|
+
* configured hosted wallet — which needs no install and is therefore always
|
|
34
|
+
* usable. The hosted script itself is fetched on the first real call.
|
|
35
|
+
*/
|
|
36
|
+
async isAvailable() {
|
|
37
|
+
if (this.options.provider) return true;
|
|
38
|
+
if (injectedProvider()) return true;
|
|
39
|
+
return !!this.options.walletUrl;
|
|
40
|
+
}
|
|
41
|
+
async provider() {
|
|
42
|
+
const provider = await resolveProvider(this.options);
|
|
43
|
+
if (!provider) throw kitError(`${this.productName} is not available.`, -1);
|
|
44
|
+
return provider;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* `skipRequestAccess` is accepted and ignored on purpose: the wallet decides
|
|
48
|
+
* whether an origin it already knows needs to be asked again, and a dapp asking
|
|
49
|
+
* to skip the prompt is not the party that gets to decide that.
|
|
50
|
+
*/
|
|
51
|
+
async getAddress(_params) {
|
|
52
|
+
const provider = await this.provider();
|
|
53
|
+
const { address } = await provider.getAddress();
|
|
54
|
+
if (!address) throw kitError("The wallet returned no address.", -1);
|
|
55
|
+
return { address };
|
|
56
|
+
}
|
|
57
|
+
async signTransaction(xdr, opts) {
|
|
58
|
+
const provider = await this.provider();
|
|
59
|
+
const result = await provider.signTransaction(xdr, {
|
|
60
|
+
networkPassphrase: opts?.networkPassphrase,
|
|
61
|
+
address: opts?.address
|
|
62
|
+
});
|
|
63
|
+
if (!result?.signedTxXdr) throw kitError("The wallet returned no signed transaction.", -1);
|
|
64
|
+
return { signedTxXdr: result.signedTxXdr, signerAddress: result.signerAddress };
|
|
65
|
+
}
|
|
66
|
+
async signMessage(message, opts) {
|
|
67
|
+
const provider = await this.provider();
|
|
68
|
+
const result = await provider.signMessage(message, {
|
|
69
|
+
networkPassphrase: opts?.networkPassphrase,
|
|
70
|
+
address: opts?.address
|
|
71
|
+
});
|
|
72
|
+
if (!result?.signedMessage) throw kitError("The wallet returned no signature.", -1);
|
|
73
|
+
return { signedMessage: result.signedMessage, signerAddress: result.signerAddress };
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Not supported, and reported as such in the kit's own vocabulary.
|
|
77
|
+
*
|
|
78
|
+
* Cosmos Pay Wallet has no Soroban authorization-entry signing. Anything this could
|
|
79
|
+
* return instead of an error would be a signature the network rejects, discovered
|
|
80
|
+
* by the user rather than by the dapp.
|
|
81
|
+
*/
|
|
82
|
+
signAuthEntry() {
|
|
83
|
+
return Promise.reject(
|
|
84
|
+
kitError(`${this.productName} does not support the "signAuthEntry" function`, NOT_SUPPORTED)
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The network the WALLET is on, which is the only one it will sign for. A dapp
|
|
89
|
+
* that wants another network has to ask the user to switch, not ask the wallet to
|
|
90
|
+
* pretend.
|
|
91
|
+
*/
|
|
92
|
+
async getNetwork() {
|
|
93
|
+
const provider = await this.provider();
|
|
94
|
+
const { network, networkPassphrase } = await provider.getNetwork();
|
|
95
|
+
if (!networkPassphrase) throw kitError("The wallet returned no network.", -1);
|
|
96
|
+
return { network, networkPassphrase };
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
function kitError(message, code) {
|
|
100
|
+
return Object.assign(new Error(message), { code, message });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export { COSMOS_WALLET_ID, CosmosWalletModule, SwkModuleType };
|
|
104
|
+
//# sourceMappingURL=chunk-ALFITFBN.js.map
|
|
105
|
+
//# sourceMappingURL=chunk-ALFITFBN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+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CAAA;AACD,IAAA,IAAI,CAAC,MAAA,EAAQ,aAAA,EAAe,MAAM,QAAA,CAAS,qCAAqC,EAAE,CAAA;AAClF,IAAA,OAAO,EAAE,aAAA,EAAe,MAAA,CAAO,aAAA,EAAe,aAAA,EAAe,OAAO,aAAA,EAAc;AAAA,EACpF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,aAAA,GAA8E;AACnF,IAAA,OAAO,OAAA,CAAQ,MAAA;AAAA,MACb,QAAA,CAAS,CAAA,EAAG,IAAA,CAAK,WAAW,kDAAkD,aAAa;AAAA,KAC7F;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAa,UAAA,GAAsE;AACjF,IAAA,MAAM,QAAA,GAAW,MAAM,IAAA,CAAK,QAAA,EAAS;AACrC,IAAA,MAAM,EAAE,OAAA,EAAS,iBAAA,EAAkB,GAAI,MAAM,SAAS,UAAA,EAAW;AACjE,IAAA,IAAI,CAAC,iBAAA,EAAmB,MAAM,QAAA,CAAS,mCAAmC,EAAE,CAAA;AAC5E,IAAA,OAAO,EAAE,SAAS,iBAAA,EAAkB;AAAA,EACtC;AACF;AAQA,SAAS,QAAA,CAAS,SAAiB,IAAA,EAAiC;AAClE,EAAA,OAAO,MAAA,CAAO,OAAO,IAAI,KAAA,CAAM,OAAO,CAAA,EAAG,EAAE,IAAA,EAAM,OAAA,EAAS,CAAA;AAC5D","file":"chunk-ALFITFBN.js","sourcesContent":["/**\n * The Stellar Wallets Kit module contract, transcribed.\n *\n * WHY A COPY INSTEAD OF AN IMPORT. A module is one small class; depending on the\n * whole kit to describe it would put a UI library (and, when this was measured, 22\n * dev advisories) into an SDK whose own dependency list is empty. The kit is what a\n * CONSUMER installs — this package only has to produce something that fits it.\n *\n * The shapes below are transcribed from `@creit.tech/stellar-wallets-kit@2.6`\n * (`esm/types/mod.d.ts`) and are structural, so a module written against them is\n * assignable to the kit's `ModuleInterface` without either side knowing about the\n * other. The one place structural typing does not reach is `moduleType`: the kit\n * declares it as a string ENUM, and TypeScript does not accept a plain string\n * literal for one. `CosmosWalletModule` is therefore generic in that property —\n * pass the kit's own `ModuleType.HOT_WALLET` and it type-checks exactly; pass\n * nothing and you get the same string at runtime.\n *\n * Keep this file in step with the kit when it moves. `signAndSubmitTransaction` and\n * `isPlatformWrapper` are deliberately absent below: they are optional in the kit\n * and Cosmos Pay Wallet implements neither.\n */\n\n/** `moduleType` values the kit filters and groups by. */\nexport const SwkModuleType = {\n HW_WALLET: 'HW_WALLET',\n HOT_WALLET: 'HOT_WALLET',\n BRIDGE_WALLET: 'BRIDGE_WALLET',\n AIR_GAPED_WALLET: 'AIR_GAPED_WALLET',\n} as const;\n\nexport type SwkModuleTypeValue = (typeof SwkModuleType)[keyof typeof SwkModuleType];\n\n/**\n * What a module rejects with. The kit's `parseError` reads `code`, `message` and\n * `ext` off whatever it catches, so a plain object is the native shape — and `-3`\n * is the code its own modules use for \"this wallet cannot do that\".\n */\nexport interface IKitError {\n code: number;\n message: string;\n ext?: string;\n}\n\n/** Payload of the optional `onChange` subscription. */\nexport interface IOnChangeEvent {\n address: string;\n /** Human-readable network name, as the wallet calls it. */\n network: string;\n networkPassphrase: string;\n error?: IKitError;\n}\n\n/** Options every signing method accepts. `path` is for hardware wallets. */\nexport interface SwkSignOptions {\n networkPassphrase?: string;\n address?: string;\n path?: string;\n}\n\n/**\n * The kit's `ModuleInterface`, minus the optional members Cosmos Pay Wallet does not\n * implement. `TModuleType` exists only so the kit's enum can flow through — see\n * the header.\n */\nexport interface SwkModule<TModuleType extends string = SwkModuleTypeValue> {\n moduleType: TModuleType;\n productId: string;\n productName: string;\n productUrl: string;\n productIcon: string;\n /** Must answer in under 1000ms or the kit renders the wallet as unavailable. */\n isAvailable(): Promise<boolean>;\n getAddress(params?: { path?: string; skipRequestAccess?: boolean }): Promise<{ address: string }>;\n signTransaction(\n xdr: string,\n opts?: SwkSignOptions,\n ): Promise<{ signedTxXdr: string; signerAddress?: string }>;\n signAuthEntry(\n authEntry: string,\n opts?: SwkSignOptions,\n ): Promise<{ signedAuthEntry: string; signerAddress?: string }>;\n signMessage(\n message: string,\n opts?: SwkSignOptions,\n ): Promise<{ signedMessage: string; signerAddress?: string }>;\n getNetwork(): Promise<{ network: string; networkPassphrase: string }>;\n onChange?(callback: (event: IOnChangeEvent) => void): void;\n disconnect?(): Promise<void>;\n}\n","/**\n * Cosmos Pay Wallet as a Stellar Wallets Kit module.\n *\n * The kit is how most Stellar dapps ask for a signature: they register a list of\n * modules and it renders one button per wallet. A wallet that is not a module is a\n * wallet those dapps cannot see, however good its provider is — which is the whole\n * reason this file exists. Registering it:\n *\n * ```ts\n * import { StellarWalletsKit, WalletNetwork, ModuleType } from '@creit.tech/stellar-wallets-kit';\n * import { CosmosWalletModule, COSMOS_WALLET_ID } from '@cosmosapp/pay_sdk/swk';\n *\n * const kit = new StellarWalletsKit({\n * network: WalletNetwork.PUBLIC,\n * selectedWalletId: COSMOS_WALLET_ID,\n * modules: [\n * // `moduleType` is the kit's own enum — passing it here keeps the module\n * // exactly assignable to `ModuleInterface` with no cast anywhere.\n * new CosmosWalletModule({ moduleType: ModuleType.HOT_WALLET }),\n * ],\n * });\n * ```\n *\n * TWO TRANSPORTS, ONE MODULE. With the extension installed the provider is already\n * on the page. Without it, pass `walletUrl` and the hosted wallet's provider script\n * is fetched from that origin on first use, so a dapp can offer Cosmos Pay Wallet to\n * users who have installed nothing:\n *\n * ```ts\n * new CosmosWalletModule({ walletUrl: 'https://wallet.cosmospay.lat' })\n * ```\n *\n * WHAT IT REFUSES, AND WHY THAT IS THE POINT. `signAuthEntry` rejects with the\n * kit's own `-3` \"not supported\" shape rather than returning something. Cosmos\n * Wallet signs transactions and domain-separated messages; it does not sign Soroban\n * authorization entries, and a module that faked one would hand a dapp a signature\n * that fails on chain instead of an error it can render.\n */\n\nimport {\n injectedProvider,\n resolveProvider,\n type CosmosProviderOptions,\n type CosmosWalletProvider,\n} from '@/web/cosmosProvider';\nimport { SwkModuleType, type IKitError, type SwkModule, type SwkSignOptions } from '@/swk/types';\n\n/** The id a dapp filters or preselects this wallet by. */\nexport const COSMOS_WALLET_ID = 'cosmos-wallet';\n\nconst PRODUCT_NAME = 'Cosmos Pay Wallet';\nconst PRODUCT_URL = 'https://github.com/CosmosPay/CosmosPay-Wallet';\n/**\n * Served from the wallet's repository so the module has nothing to host. When this\n * module is upstreamed the kit serves its own copy from `stellar.creit.tech`, which\n * is why the URL is an option rather than a constant baked into every call site.\n */\nconst PRODUCT_ICON =\n 'https://raw.githubusercontent.com/CosmosPay/CosmosPay-Wallet/main/public/logo-512.png';\n\n/** The kit's code for \"this wallet cannot do that\" (see its own modules). */\nconst NOT_SUPPORTED = -3;\n\nexport interface CosmosWalletModuleOptions<TModuleType extends string = string>\n extends CosmosProviderOptions {\n /**\n * Pass the kit's `ModuleType.HOT_WALLET` for exact typing. Defaults to the same\n * string, which is what the enum holds at runtime.\n */\n moduleType?: TModuleType;\n /** Override the name shown in the kit's modal. */\n productName?: string;\n /** Override the \"get this wallet\" link. */\n productUrl?: string;\n /** Override the icon shown in the modal. */\n productIcon?: string;\n}\n\nexport class CosmosWalletModule<TModuleType extends string = string>\n implements SwkModule<TModuleType>\n{\n public readonly moduleType: TModuleType;\n public readonly productId: string = COSMOS_WALLET_ID;\n public readonly productName: string;\n public readonly productUrl: string;\n public readonly productIcon: string;\n\n private readonly options: CosmosProviderOptions;\n\n constructor(options: CosmosWalletModuleOptions<TModuleType> = {}) {\n this.moduleType = (options.moduleType ?? SwkModuleType.HOT_WALLET) as TModuleType;\n this.productName = options.productName ?? PRODUCT_NAME;\n this.productUrl = options.productUrl ?? PRODUCT_URL;\n this.productIcon = options.productIcon ?? PRODUCT_ICON;\n this.options = {\n provider: options.provider,\n walletUrl: options.walletUrl,\n loadTimeoutMs: options.loadTimeoutMs,\n };\n }\n\n /**\n * The kit allows 1000ms for this and shows the wallet as unavailable otherwise,\n * so it answers from what is already in the page: an injected provider, or a\n * configured hosted wallet — which needs no install and is therefore always\n * usable. The hosted script itself is fetched on the first real call.\n */\n public async isAvailable(): Promise<boolean> {\n if (this.options.provider) return true;\n if (injectedProvider()) return true;\n return !!this.options.walletUrl;\n }\n\n private async provider(): Promise<CosmosWalletProvider> {\n const provider = await resolveProvider(this.options);\n if (!provider) throw kitError(`${this.productName} is not available.`, -1);\n return provider;\n }\n\n /**\n * `skipRequestAccess` is accepted and ignored on purpose: the wallet decides\n * whether an origin it already knows needs to be asked again, and a dapp asking\n * to skip the prompt is not the party that gets to decide that.\n */\n public async getAddress(_params?: { path?: string; skipRequestAccess?: boolean }): Promise<{\n address: string;\n }> {\n const provider = await this.provider();\n const { address } = await provider.getAddress();\n if (!address) throw kitError('The wallet returned no address.', -1);\n return { address };\n }\n\n public async signTransaction(\n xdr: string,\n opts?: SwkSignOptions,\n ): Promise<{ signedTxXdr: string; signerAddress?: string }> {\n const provider = await this.provider();\n // The passphrase is forwarded, not authoritative: Cosmos Pay Wallet parses with its\n // own network configuration and REFUSES a mismatch, so a caller cannot redirect\n // a signature to another network by naming one. Forwarding it is what turns a\n // wrong-network request into an error the dapp can show.\n const result = await provider.signTransaction(xdr, {\n networkPassphrase: opts?.networkPassphrase,\n address: opts?.address,\n });\n if (!result?.signedTxXdr) throw kitError('The wallet returned no signed transaction.', -1);\n return { signedTxXdr: result.signedTxXdr, signerAddress: result.signerAddress };\n }\n\n public async signMessage(\n message: string,\n opts?: SwkSignOptions,\n ): Promise<{ signedMessage: string; signerAddress?: string }> {\n const provider = await this.provider();\n const result = await provider.signMessage(message, {\n networkPassphrase: opts?.networkPassphrase,\n address: opts?.address,\n });\n if (!result?.signedMessage) throw kitError('The wallet returned no signature.', -1);\n return { signedMessage: result.signedMessage, signerAddress: result.signerAddress };\n }\n\n /**\n * Not supported, and reported as such in the kit's own vocabulary.\n *\n * Cosmos Pay Wallet has no Soroban authorization-entry signing. Anything this could\n * return instead of an error would be a signature the network rejects, discovered\n * by the user rather than by the dapp.\n */\n public signAuthEntry(): Promise<{ signedAuthEntry: string; signerAddress?: string }> {\n return Promise.reject(\n kitError(`${this.productName} does not support the \"signAuthEntry\" function`, NOT_SUPPORTED),\n );\n }\n\n /**\n * The network the WALLET is on, which is the only one it will sign for. A dapp\n * that wants another network has to ask the user to switch, not ask the wallet to\n * pretend.\n */\n public async getNetwork(): Promise<{ network: string; networkPassphrase: string }> {\n const provider = await this.provider();\n const { network, networkPassphrase } = await provider.getNetwork();\n if (!networkPassphrase) throw kitError('The wallet returned no network.', -1);\n return { network, networkPassphrase };\n }\n}\n\n/**\n * The kit reads `code`, `message` and `ext` off whatever a module rejects with, and\n * its own modules reject with a plain object. This keeps the `Error` prototype (so\n * a stack survives and `instanceof Error` holds for anyone else who catches it)\n * while carrying the fields the kit looks for.\n */\nfunction kitError(message: string, code: number): Error & IKitError {\n return Object.assign(new Error(message), { code, message });\n}\n"]}
|