@cosmosapp/pay_sdk 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1015 @@
1
+ import { version, CosmosPayAPIError, CosmosPayRequestError, DEFAULT_BASE_URL, resolveIntentBody } from '../chunk-TZDZBVFS.js';
2
+ export { AddressBook, Assets, CosmosPayAPIError, CosmosPayRequestError, TestnetAssets, Wallets, addresses, assertAddress, defineAsset, isAddress, isContractAddress, isMuxedAddress, isNativeAsset, isStellarAddress, resolveAddress, resolveAsset, resolveIntentBody } from '../chunk-TZDZBVFS.js';
3
+
4
+ // src/web/errors.ts
5
+ var CosmosPayWebError = class _CosmosPayWebError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = "CosmosPayWebError";
9
+ Error.captureStackTrace?.(this, _CosmosPayWebError);
10
+ }
11
+ };
12
+ var WalletNotFoundError = class extends CosmosPayWebError {
13
+ constructor(searched) {
14
+ super(
15
+ searched.length ? `No compatible Stellar wallet detected. Looked for: ${searched.join(", ")}. Install one (e.g. Freighter, xBull, Rabet) or pass a wallet adapter explicitly.` : "No wallet adapters are registered on this client."
16
+ );
17
+ this.name = "WalletNotFoundError";
18
+ this.searched = searched;
19
+ }
20
+ };
21
+ var WalletError = class extends CosmosPayWebError {
22
+ constructor(wallet, message, cause) {
23
+ super(`[${wallet}] ${message}`);
24
+ this.name = "WalletError";
25
+ this.wallet = wallet;
26
+ this.cause = cause;
27
+ }
28
+ };
29
+ var StellarSdkRequiredError = class extends CosmosPayWebError {
30
+ constructor(detail) {
31
+ super(
32
+ "The Stellar SDK is required to build/submit this transaction but was not found. Install it with `npm i @stellar/stellar-sdk`, or pass it via `new WebClient({ stellarSdk })`." + (detail ? ` (${detail})` : "")
33
+ );
34
+ this.name = "StellarSdkRequiredError";
35
+ }
36
+ };
37
+ var IntentError = class extends CosmosPayWebError {
38
+ constructor(message) {
39
+ super(message);
40
+ this.name = "IntentError";
41
+ }
42
+ };
43
+
44
+ // src/web/adapters/util.ts
45
+ function getWindow() {
46
+ return typeof window !== "undefined" ? window : void 0;
47
+ }
48
+ function globalRef(name) {
49
+ const win = getWindow();
50
+ if (!win) return void 0;
51
+ return win[name];
52
+ }
53
+ function unwrap(result, key) {
54
+ if (result && typeof result === "object") {
55
+ const obj = result;
56
+ if (obj["error"]) {
57
+ const err = obj["error"];
58
+ const message = typeof err === "string" ? err : err?.message ?? JSON.stringify(err);
59
+ throw new Error(message);
60
+ }
61
+ if (key in obj) return obj[key];
62
+ }
63
+ return result;
64
+ }
65
+ function errorMessage(error) {
66
+ if (error instanceof Error) return error.message;
67
+ if (typeof error === "string") return error;
68
+ try {
69
+ return JSON.stringify(error);
70
+ } catch {
71
+ return String(error);
72
+ }
73
+ }
74
+
75
+ // src/web/adapters/FreighterAdapter.ts
76
+ var FreighterAdapter = class {
77
+ constructor(injected) {
78
+ this.injected = injected;
79
+ this.id = "freighter";
80
+ this.name = "Freighter";
81
+ }
82
+ api() {
83
+ return this.injected ?? globalRef("freighterApi");
84
+ }
85
+ async isAvailable() {
86
+ const api = this.api();
87
+ if (!api) return false;
88
+ try {
89
+ const result = await api.isConnected();
90
+ return unwrap(result, "isConnected") !== false;
91
+ } catch {
92
+ return true;
93
+ }
94
+ }
95
+ async getPublicKey(_network) {
96
+ const api = this.api();
97
+ if (!api) throw new WalletError(this.id, "Freighter is not available.");
98
+ try {
99
+ if (api.requestAccess) {
100
+ const result = await api.requestAccess();
101
+ const address = unwrap(result, "address");
102
+ if (address) return address;
103
+ }
104
+ if (api.getAddress) {
105
+ return unwrap(await api.getAddress(), "address");
106
+ }
107
+ if (api.getPublicKey) {
108
+ return unwrap(await api.getPublicKey(), "address");
109
+ }
110
+ throw new Error("No address method exposed by Freighter.");
111
+ } catch (error) {
112
+ throw new WalletError(this.id, errorMessage(error), error);
113
+ }
114
+ }
115
+ async signTransaction(xdr, params) {
116
+ const api = this.api();
117
+ if (!api) throw new WalletError(this.id, "Freighter is not available.");
118
+ try {
119
+ const result = await api.signTransaction(xdr, {
120
+ networkPassphrase: params.networkPassphrase,
121
+ network: params.network,
122
+ address: params.address,
123
+ accountToSign: params.address
124
+ });
125
+ return unwrap(result, "signedTxXdr");
126
+ } catch (error) {
127
+ throw new WalletError(this.id, errorMessage(error), error);
128
+ }
129
+ }
130
+ };
131
+
132
+ // src/web/adapters/XBullAdapter.ts
133
+ var XBullAdapter = class {
134
+ constructor(injected) {
135
+ this.injected = injected;
136
+ this.id = "xbull";
137
+ this.name = "xBull";
138
+ }
139
+ sdk() {
140
+ return this.injected ?? globalRef("xBullSDK");
141
+ }
142
+ async isAvailable() {
143
+ return Boolean(this.sdk());
144
+ }
145
+ async getPublicKey(_network) {
146
+ const sdk = this.sdk();
147
+ if (!sdk) throw new WalletError(this.id, "xBull is not available.");
148
+ try {
149
+ await sdk.connect({ canRequestPublicKey: true, canRequestSign: true });
150
+ return await sdk.getPublicKey();
151
+ } catch (error) {
152
+ throw new WalletError(this.id, errorMessage(error), error);
153
+ }
154
+ }
155
+ async signTransaction(xdr, params) {
156
+ const sdk = this.sdk();
157
+ if (!sdk) throw new WalletError(this.id, "xBull is not available.");
158
+ try {
159
+ return await sdk.signXDR(xdr, {
160
+ network: params.networkPassphrase,
161
+ publicKey: params.address
162
+ });
163
+ } catch (error) {
164
+ throw new WalletError(this.id, errorMessage(error), error);
165
+ }
166
+ }
167
+ async disconnect() {
168
+ this.sdk()?.closeConnections?.();
169
+ }
170
+ };
171
+
172
+ // src/web/network.ts
173
+ var PASSPHRASES = {
174
+ public: "Public Global Stellar Network ; September 2015",
175
+ testnet: "Test SDF Network ; September 2015"
176
+ };
177
+ var HORIZON_URLS = {
178
+ public: "https://horizon.stellar.org",
179
+ testnet: "https://horizon-testnet.stellar.org"
180
+ };
181
+ var RABET_NETWORK = {
182
+ public: "mainnet",
183
+ testnet: "testnet"
184
+ };
185
+ function classifyNetwork(hint) {
186
+ if (!hint) return "public";
187
+ const value = hint.trim().toLowerCase();
188
+ if (value === PASSPHRASES.testnet.toLowerCase()) return "testnet";
189
+ if (value === PASSPHRASES.public.toLowerCase()) return "public";
190
+ if (value.includes("test")) return "testnet";
191
+ if (value.includes("public") || value.includes("main") || value.includes("pubnet")) {
192
+ return "public";
193
+ }
194
+ return "public";
195
+ }
196
+ function isPassphrase(value) {
197
+ return value === PASSPHRASES.public || value === PASSPHRASES.testnet;
198
+ }
199
+ function resolveNetwork(input = {}) {
200
+ const network = input.network ?? classifyNetwork(input.passphrase ?? input.hint);
201
+ return {
202
+ network,
203
+ passphrase: input.passphrase ?? PASSPHRASES[network],
204
+ horizonUrl: (input.horizonUrl ?? HORIZON_URLS[network]).replace(/\/+$/, "")
205
+ };
206
+ }
207
+
208
+ // src/web/adapters/RabetAdapter.ts
209
+ var RabetAdapter = class {
210
+ constructor(injected) {
211
+ this.injected = injected;
212
+ this.id = "rabet";
213
+ this.name = "Rabet";
214
+ }
215
+ api() {
216
+ return this.injected ?? globalRef("rabet");
217
+ }
218
+ async isAvailable() {
219
+ return Boolean(this.api());
220
+ }
221
+ async getPublicKey(_network) {
222
+ const api = this.api();
223
+ if (!api) throw new WalletError(this.id, "Rabet is not available.");
224
+ try {
225
+ return unwrap(await api.connect(), "publicKey");
226
+ } catch (error) {
227
+ throw new WalletError(this.id, errorMessage(error), error);
228
+ }
229
+ }
230
+ async signTransaction(xdr, params) {
231
+ const api = this.api();
232
+ if (!api) throw new WalletError(this.id, "Rabet is not available.");
233
+ try {
234
+ const result = await api.sign(xdr, RABET_NETWORK[params.network]);
235
+ return unwrap(result, "xdr");
236
+ } catch (error) {
237
+ throw new WalletError(this.id, errorMessage(error), error);
238
+ }
239
+ }
240
+ async disconnect() {
241
+ await this.api()?.disconnect?.();
242
+ }
243
+ };
244
+
245
+ // src/web/adapters/LobstrAdapter.ts
246
+ var LobstrAdapter = class {
247
+ constructor(api) {
248
+ this.api = api;
249
+ this.id = "lobstr";
250
+ this.name = "LOBSTR";
251
+ }
252
+ async isAvailable() {
253
+ if (!this.api) return false;
254
+ try {
255
+ return await this.api.isConnected();
256
+ } catch {
257
+ return false;
258
+ }
259
+ }
260
+ async getPublicKey(_network) {
261
+ if (!this.api) throw new WalletError(this.id, "LOBSTR signer API not provided.");
262
+ try {
263
+ return await this.api.getPublicKey();
264
+ } catch (error) {
265
+ throw new WalletError(this.id, errorMessage(error), error);
266
+ }
267
+ }
268
+ async signTransaction(xdr, _params) {
269
+ if (!this.api) throw new WalletError(this.id, "LOBSTR signer API not provided.");
270
+ try {
271
+ return await this.api.signTransaction(xdr);
272
+ } catch (error) {
273
+ throw new WalletError(this.id, errorMessage(error), error);
274
+ }
275
+ }
276
+ };
277
+
278
+ // src/web/adapters/AlbedoAdapter.ts
279
+ var AlbedoAdapter = class {
280
+ constructor(injected) {
281
+ this.injected = injected;
282
+ this.id = "albedo";
283
+ this.name = "Albedo";
284
+ }
285
+ intent() {
286
+ return this.injected ?? globalRef("albedo");
287
+ }
288
+ async isAvailable() {
289
+ return Boolean(this.intent());
290
+ }
291
+ async getPublicKey(_network) {
292
+ const albedo = this.intent();
293
+ if (!albedo) throw new WalletError(this.id, "Albedo is not available.");
294
+ try {
295
+ const result = await albedo.publicKey();
296
+ return result.pubkey;
297
+ } catch (error) {
298
+ throw new WalletError(this.id, errorMessage(error), error);
299
+ }
300
+ }
301
+ async signTransaction(xdr, params) {
302
+ const albedo = this.intent();
303
+ if (!albedo) throw new WalletError(this.id, "Albedo is not available.");
304
+ try {
305
+ const result = await albedo.tx({
306
+ xdr,
307
+ // Albedo expects the `public` / `testnet` label, not a passphrase.
308
+ network: params.network,
309
+ pubkey: params.address,
310
+ submit: false
311
+ });
312
+ return result.signed_envelope_xdr;
313
+ } catch (error) {
314
+ throw new WalletError(this.id, errorMessage(error), error);
315
+ }
316
+ }
317
+ };
318
+
319
+ // src/web/adapters/index.ts
320
+ function defaultAdapters(injected = {}) {
321
+ return [
322
+ new FreighterAdapter(injected.freighter),
323
+ new XBullAdapter(injected.xBull),
324
+ new RabetAdapter(injected.rabet),
325
+ new LobstrAdapter(injected.lobstr),
326
+ new AlbedoAdapter(injected.albedo)
327
+ ];
328
+ }
329
+
330
+ // src/web/sep7.ts
331
+ var SCHEME = "web+stellar:";
332
+ function isSep7Uri(value) {
333
+ return typeof value === "string" && value.trim().toLowerCase().startsWith(SCHEME);
334
+ }
335
+ function parseSep7(uri) {
336
+ const trimmed = uri.trim();
337
+ const withoutScheme = trimmed.slice(SCHEME.length);
338
+ const queryStart = withoutScheme.indexOf("?");
339
+ const operation = (queryStart === -1 ? withoutScheme : withoutScheme.slice(0, queryStart)).toLowerCase();
340
+ if (operation !== "tx" && operation !== "pay") {
341
+ throw new IntentError(`Unsupported SEP-7 operation: "${operation}".`);
342
+ }
343
+ const params = new URLSearchParams(
344
+ queryStart === -1 ? "" : withoutScheme.slice(queryStart + 1)
345
+ );
346
+ const get = (key) => params.get(key) ?? void 0;
347
+ return {
348
+ operation,
349
+ xdr: get("xdr"),
350
+ destination: get("destination"),
351
+ amount: get("amount"),
352
+ assetCode: get("asset_code"),
353
+ assetIssuer: get("asset_issuer"),
354
+ memo: get("memo"),
355
+ memoType: get("memo_type"),
356
+ msg: get("msg"),
357
+ callback: get("callback"),
358
+ networkPassphrase: get("network_passphrase"),
359
+ originDomain: get("origin_domain"),
360
+ signature: get("signature")
361
+ };
362
+ }
363
+ function fromSep7(req) {
364
+ const isTx = req.operation === "tx";
365
+ if (isTx && !req.xdr) {
366
+ throw new IntentError("SEP-7 `tx` request is missing its `xdr`.");
367
+ }
368
+ if (!isTx && !req.destination) {
369
+ throw new IntentError("SEP-7 `pay` request is missing its `destination`.");
370
+ }
371
+ return {
372
+ kind: isTx ? "tx" : "pay",
373
+ network: req.networkPassphrase ?? null,
374
+ source: null,
375
+ destination: req.destination ?? "",
376
+ amount: req.amount ?? null,
377
+ asset: req.assetCode || "native",
378
+ assetIssuer: req.assetIssuer ?? null,
379
+ memo: req.memo ?? null,
380
+ memoType: req.memoType ?? (req.memo ? "MEMO_ID" : null),
381
+ msg: req.msg ?? null,
382
+ callback: req.callback ?? null,
383
+ xdr: req.xdr ?? null,
384
+ uri: null
385
+ };
386
+ }
387
+ function fromPaymentIntent(data) {
388
+ return {
389
+ kind: data.kind === "TX" ? "tx" : "pay",
390
+ id: data.id,
391
+ network: data.network ?? null,
392
+ source: data.source ?? null,
393
+ destination: data.destination,
394
+ amount: data.amount ?? null,
395
+ asset: data.asset || "native",
396
+ assetIssuer: data.assetIssuer ?? null,
397
+ memo: data.memo ?? null,
398
+ memoType: data.memo ? "MEMO_ID" : null,
399
+ msg: data.msg ?? null,
400
+ callback: data.callback ?? null,
401
+ xdr: data.xdr ?? null,
402
+ uri: data.uri ?? null
403
+ };
404
+ }
405
+ function looksLikePaymentIntent(value) {
406
+ return "kind" in value && "destination" in value && "asset" in value;
407
+ }
408
+ function looksLikeSep7(value) {
409
+ return "operation" in value;
410
+ }
411
+ function normalizeIntent(input) {
412
+ if (isSep7Uri(input)) {
413
+ return fromSep7(parseSep7(input));
414
+ }
415
+ if (typeof input === "string") {
416
+ throw new IntentError(
417
+ "Expected a payment intent or a `web+stellar:` URI string."
418
+ );
419
+ }
420
+ if (typeof input !== "object" || input === null) {
421
+ throw new IntentError("Cannot normalize a non-object intent.");
422
+ }
423
+ if ("toJSON" in input && typeof input.toJSON === "function") {
424
+ return fromPaymentIntent(input.toJSON());
425
+ }
426
+ if (looksLikePaymentIntent(input)) {
427
+ const normalized = fromPaymentIntent(input);
428
+ if (normalized.uri && isSep7Uri(normalized.uri)) {
429
+ const sep7 = parseSep7(normalized.uri);
430
+ normalized.callback = normalized.callback ?? sep7.callback ?? null;
431
+ normalized.memoType = normalized.memoType ?? sep7.memoType ?? null;
432
+ if (!normalized.network && sep7.networkPassphrase) {
433
+ normalized.network = sep7.networkPassphrase;
434
+ }
435
+ }
436
+ return normalized;
437
+ }
438
+ if (looksLikeSep7(input)) {
439
+ return fromSep7(input);
440
+ }
441
+ throw new IntentError(
442
+ "Unrecognized intent shape. Pass a Cosmos Pay payment intent, a `web+stellar:` URI, or a parsed SEP-7 request."
443
+ );
444
+ }
445
+
446
+ // src/web/stellar.ts
447
+ var cachedSdk;
448
+ async function loadStellarSdk(injected) {
449
+ if (injected) return injected;
450
+ if (cachedSdk) return cachedSdk;
451
+ try {
452
+ const specifier = ["@stellar", "stellar-sdk"].join("/");
453
+ const mod = await import(
454
+ /* @vite-ignore */
455
+ specifier
456
+ );
457
+ const resolved = mod["TransactionBuilder"] ? mod : mod["default"];
458
+ if (!resolved?.TransactionBuilder) {
459
+ throw new Error("module did not expose TransactionBuilder");
460
+ }
461
+ cachedSdk = resolved;
462
+ return resolved;
463
+ } catch (error) {
464
+ throw new StellarSdkRequiredError(
465
+ error instanceof Error ? error.message : void 0
466
+ );
467
+ }
468
+ }
469
+ function getServerCtor(sdk) {
470
+ const ctor = sdk.Horizon?.Server ?? sdk.Server;
471
+ if (!ctor) {
472
+ throw new StellarSdkRequiredError("no Horizon Server export found");
473
+ }
474
+ return ctor;
475
+ }
476
+ function buildMemo(sdk, intent) {
477
+ if (!intent.memo) return sdk.Memo.none();
478
+ switch ((intent.memoType ?? "MEMO_ID").toUpperCase()) {
479
+ case "MEMO_TEXT":
480
+ return sdk.Memo.text(intent.memo);
481
+ case "MEMO_HASH":
482
+ return sdk.Memo.hash(intent.memo);
483
+ case "MEMO_RETURN":
484
+ return sdk.Memo.return(intent.memo);
485
+ case "MEMO_ID":
486
+ default:
487
+ return sdk.Memo.id(intent.memo);
488
+ }
489
+ }
490
+ function buildAsset(sdk, intent) {
491
+ const code = intent.asset;
492
+ if (!code || code === "native" || code.toUpperCase() === "XLM") {
493
+ return sdk.Asset.native();
494
+ }
495
+ if (!intent.assetIssuer) {
496
+ throw new Error(`Asset ${code} requires an issuer to build the payment.`);
497
+ }
498
+ return new sdk.Asset(code, intent.assetIssuer);
499
+ }
500
+ async function buildPaymentXdr(sdk, network, input) {
501
+ const { intent, source } = input;
502
+ const amount = input.amount ?? intent.amount;
503
+ if (!amount) {
504
+ throw new Error(
505
+ "This intent has no fixed amount \u2014 pass `{ amount }` so the payment can be built."
506
+ );
507
+ }
508
+ const Server = getServerCtor(sdk);
509
+ const server = new Server(network.horizonUrl);
510
+ const account = await server.loadAccount(source);
511
+ let fee = input.baseFee ?? sdk.BASE_FEE ?? "100";
512
+ if (!input.baseFee && server.fetchBaseFee) {
513
+ try {
514
+ fee = String(await server.fetchBaseFee());
515
+ } catch {
516
+ }
517
+ }
518
+ const builder = new sdk.TransactionBuilder(account, {
519
+ fee,
520
+ networkPassphrase: network.passphrase
521
+ });
522
+ builder.addOperation(
523
+ sdk.Operation.payment({
524
+ destination: intent.destination,
525
+ asset: buildAsset(sdk, intent),
526
+ amount: String(amount)
527
+ })
528
+ );
529
+ builder.addMemo(buildMemo(sdk, intent));
530
+ builder.setTimeout(input.timeoutSeconds ?? 300);
531
+ return builder.build().toXDR();
532
+ }
533
+ function transactionHash(sdk, signedXdr, passphrase) {
534
+ const tx = sdk.TransactionBuilder.fromXDR(signedXdr, passphrase);
535
+ const hash = tx.hash();
536
+ return typeof hash === "string" ? hash : toHex(hash);
537
+ }
538
+ async function submitToHorizon(sdk, network, signedXdr) {
539
+ const Server = getServerCtor(sdk);
540
+ const server = new Server(network.horizonUrl);
541
+ const tx = sdk.TransactionBuilder.fromXDR(signedXdr, network.passphrase);
542
+ return server.submitTransaction(tx);
543
+ }
544
+ async function postToCallback(callback, signedXdr, fetchFn = globalThis.fetch) {
545
+ const url = callback.startsWith("url:") ? callback.slice(4) : callback;
546
+ const response = await fetchFn(url, {
547
+ method: "POST",
548
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
549
+ body: new URLSearchParams({ xdr: signedXdr }).toString()
550
+ });
551
+ const text = await response.text();
552
+ if (!response.ok) {
553
+ throw new Error(`Callback ${url} responded ${response.status}: ${text}`);
554
+ }
555
+ try {
556
+ return JSON.parse(text);
557
+ } catch {
558
+ return text || null;
559
+ }
560
+ }
561
+ function toHex(bytes) {
562
+ if (typeof bytes.toString === "function") {
563
+ try {
564
+ const hex = bytes.toString("hex");
565
+ if (/^[0-9a-f]+$/i.test(hex)) return hex;
566
+ } catch {
567
+ }
568
+ }
569
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
570
+ }
571
+
572
+ // src/web/WalletRegistry.ts
573
+ var WalletRegistry = class {
574
+ constructor(adapters = []) {
575
+ this.adapters = [];
576
+ for (const adapter of adapters) this.register(adapter);
577
+ }
578
+ /**
579
+ * Register (or replace, by id) a wallet adapter. By default it's appended at
580
+ * the lowest priority; pass `prepend` to make it win auto-detection.
581
+ */
582
+ register(adapter, prepend = false) {
583
+ const existing = this.adapters.findIndex((a) => a.id === adapter.id);
584
+ if (existing !== -1) this.adapters.splice(existing, 1);
585
+ if (prepend) this.adapters.unshift(adapter);
586
+ else this.adapters.push(adapter);
587
+ return this;
588
+ }
589
+ /** Remove an adapter by id. */
590
+ unregister(id) {
591
+ const index = this.adapters.findIndex((a) => a.id === id);
592
+ if (index !== -1) this.adapters.splice(index, 1);
593
+ return this;
594
+ }
595
+ /** Get a registered adapter by id. */
596
+ get(id) {
597
+ return this.adapters.find((a) => a.id === id);
598
+ }
599
+ /** All registered adapter ids, in priority order. */
600
+ ids() {
601
+ return this.adapters.map((a) => a.id);
602
+ }
603
+ /** Probe every adapter and report which are available. */
604
+ async list() {
605
+ return Promise.all(
606
+ this.adapters.map(async (adapter) => ({
607
+ id: adapter.id,
608
+ name: adapter.name,
609
+ icon: adapter.icon,
610
+ available: await safeAvailable(adapter)
611
+ }))
612
+ );
613
+ }
614
+ /** The available adapters, in priority order. */
615
+ async available() {
616
+ const flags = await Promise.all(this.adapters.map(safeAvailable));
617
+ return this.adapters.filter((_, i) => flags[i]);
618
+ }
619
+ /**
620
+ * Pick a wallet automatically. If `preferred` is given and available it wins;
621
+ * otherwise the first available adapter (in priority order) is returned.
622
+ * Throws {@link WalletNotFoundError} when nothing is available.
623
+ */
624
+ async detect(preferred) {
625
+ if (preferred) {
626
+ const adapter = this.get(preferred);
627
+ if (adapter && await safeAvailable(adapter)) return adapter;
628
+ }
629
+ const available = await this.available();
630
+ if (available[0]) return available[0];
631
+ throw new WalletNotFoundError(this.ids());
632
+ }
633
+ };
634
+ async function safeAvailable(adapter) {
635
+ try {
636
+ return await adapter.isAvailable();
637
+ } catch {
638
+ return false;
639
+ }
640
+ }
641
+
642
+ // src/web/rest.ts
643
+ var RETRYABLE_STATUS = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
644
+ var WebREST = class {
645
+ constructor(options) {
646
+ if (!options.baseURL) throw new TypeError("WebREST requires a `baseURL`.");
647
+ this.baseURL = options.baseURL.replace(/\/+$/, "");
648
+ this.version = options.version ?? "v1";
649
+ this.timeout = options.timeout ?? 3e4;
650
+ this.retries = options.retries ?? 2;
651
+ this.extraHeaders = options.headers ?? {};
652
+ this.apiKey = options.apiKey;
653
+ const fetchFn = options.fetch ?? globalThis.fetch;
654
+ if (typeof fetchFn !== "function") {
655
+ throw new TypeError(
656
+ "No global `fetch` found. Pass a `fetch` implementation in the client options."
657
+ );
658
+ }
659
+ this.fetchFn = fetchFn.bind(globalThis);
660
+ }
661
+ setApiKey(apiKey) {
662
+ this.apiKey = apiKey;
663
+ return this;
664
+ }
665
+ get(path, options = {}) {
666
+ return this.request("GET", path, options);
667
+ }
668
+ post(path, options = {}) {
669
+ return this.request("POST", path, options);
670
+ }
671
+ patch(path, options = {}) {
672
+ return this.request("PATCH", path, options);
673
+ }
674
+ buildURL(path, query) {
675
+ const clean = path.startsWith("/") ? path : `/${path}`;
676
+ const prefix = this.version ? `/${this.version}` : "";
677
+ const url = new URL(`${this.baseURL}${prefix}${clean}`);
678
+ if (query) {
679
+ for (const [key, value] of Object.entries(query)) {
680
+ if (value === void 0 || value === null) continue;
681
+ url.searchParams.set(key, String(value));
682
+ }
683
+ }
684
+ return url.toString();
685
+ }
686
+ buildHeaders(extra) {
687
+ const headers = {
688
+ Accept: "application/json",
689
+ "User-Agent": `@cosmosapp/pay_sdk/${version} (web)`,
690
+ ...this.extraHeaders
691
+ };
692
+ if (this.apiKey) {
693
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
694
+ headers["apikey"] = this.apiKey;
695
+ }
696
+ return { ...headers, ...extra };
697
+ }
698
+ async request(method, path, options = {}) {
699
+ const url = this.buildURL(path, options.query);
700
+ const headers = this.buildHeaders(options.headers);
701
+ let serializedBody;
702
+ if (options.body !== void 0) {
703
+ serializedBody = JSON.stringify(options.body);
704
+ headers["Content-Type"] = "application/json";
705
+ }
706
+ let attempt = 0;
707
+ let lastError;
708
+ while (attempt <= this.retries) {
709
+ const controller = new AbortController();
710
+ const timer = setTimeout(() => controller.abort(), this.timeout);
711
+ const signal = mergeSignals(options.signal, controller.signal);
712
+ try {
713
+ const response = await this.fetchFn(url, {
714
+ method,
715
+ headers,
716
+ body: serializedBody,
717
+ signal
718
+ });
719
+ clearTimeout(timer);
720
+ if (!response.ok) {
721
+ const body = await safeParse(response);
722
+ if (RETRYABLE_STATUS.has(response.status) && attempt < this.retries) {
723
+ await sleep(backoff(response, attempt));
724
+ attempt++;
725
+ continue;
726
+ }
727
+ throw new CosmosPayAPIError({ status: response.status, method, url, body });
728
+ }
729
+ return await safeParse(response);
730
+ } catch (error) {
731
+ clearTimeout(timer);
732
+ if (error instanceof CosmosPayAPIError) throw error;
733
+ lastError = error;
734
+ if (attempt < this.retries) {
735
+ await sleep(backoffDelay(attempt));
736
+ attempt++;
737
+ continue;
738
+ }
739
+ throw new CosmosPayRequestError({ method, url, cause: error });
740
+ }
741
+ }
742
+ throw new CosmosPayRequestError({ method, url, cause: lastError });
743
+ }
744
+ };
745
+ function backoffDelay(attempt) {
746
+ return Math.min(1e3 * 2 ** attempt, 8e3);
747
+ }
748
+ function backoff(response, attempt) {
749
+ const retryAfter = response.headers.get("retry-after");
750
+ const ms = retryAfter ? Number(retryAfter) * 1e3 : backoffDelay(attempt);
751
+ return Number.isFinite(ms) ? ms : backoffDelay(attempt);
752
+ }
753
+ function sleep(ms) {
754
+ return new Promise((resolve) => setTimeout(resolve, ms));
755
+ }
756
+ async function safeParse(response) {
757
+ const text = await response.text();
758
+ if (!text) return null;
759
+ const contentType = response.headers.get("content-type") ?? "";
760
+ if (contentType.includes("application/json")) {
761
+ try {
762
+ return JSON.parse(text);
763
+ } catch {
764
+ return text;
765
+ }
766
+ }
767
+ return text;
768
+ }
769
+ function mergeSignals(external, internal) {
770
+ if (!external) return internal;
771
+ const controller = new AbortController();
772
+ const onAbort = (signal) => () => controller.abort(signal.reason);
773
+ for (const signal of [external, internal]) {
774
+ if (signal.aborted) {
775
+ controller.abort(signal.reason);
776
+ break;
777
+ }
778
+ signal.addEventListener("abort", onAbort(signal), { once: true });
779
+ }
780
+ return controller.signal;
781
+ }
782
+
783
+ // src/web/WebClient.ts
784
+ var WebClient = class {
785
+ constructor(options = {}) {
786
+ /** The most recent successful connection (wallet + address + network). */
787
+ this.connection = null;
788
+ this.options = options;
789
+ this.injectedSdk = options.stellarSdk;
790
+ const fetchFn = options.fetch ?? globalThis.fetch;
791
+ this.fetchFn = typeof fetchFn === "function" ? fetchFn.bind(globalThis) : fetchFn;
792
+ const adapters = options.wallets ?? defaultAdapters({
793
+ freighter: options.freighter,
794
+ xBull: options.xBull,
795
+ rabet: options.rabet,
796
+ albedo: options.albedo,
797
+ lobstr: options.lobstr
798
+ });
799
+ this.wallets = new WalletRegistry(reorder(adapters, options.preferredWallets));
800
+ if (options.apiKey) {
801
+ this.rest = new WebREST({
802
+ baseURL: options.baseURL ?? DEFAULT_BASE_URL,
803
+ apiKey: options.apiKey,
804
+ version: options.version,
805
+ timeout: options.timeout,
806
+ retries: options.retries,
807
+ headers: options.headers,
808
+ fetch: options.fetch
809
+ });
810
+ }
811
+ }
812
+ // ── Wallet discovery & connection ──────────────────────────────────────────
813
+ /** Probe and list wallets, flagging which are currently available. */
814
+ getAvailableWallets() {
815
+ return this.wallets.list();
816
+ }
817
+ /** Register a custom wallet adapter (WalletConnect, Ledger, …). */
818
+ registerWallet(adapter, prepend = false) {
819
+ this.wallets.register(adapter, prepend);
820
+ return this;
821
+ }
822
+ /**
823
+ * Auto-detect a wallet and connect, returning the account + network. You can
824
+ * skip this and call {@link pay} directly — it connects on demand.
825
+ */
826
+ async connect(options = {}) {
827
+ const adapter = await this.wallets.detect(options.wallet);
828
+ const network = resolveNetwork({
829
+ network: options.network ?? this.options.network,
830
+ passphrase: this.options.passphrase,
831
+ horizonUrl: this.options.horizonUrl
832
+ });
833
+ const address = await adapter.getPublicKey(network);
834
+ this.connection = { wallet: adapter.id, address, network: network.network };
835
+ return this.connection;
836
+ }
837
+ /** Forget the current connection (and disconnect the adapter if it supports it). */
838
+ async disconnect() {
839
+ if (this.connection) {
840
+ const adapter = this.wallets.get(this.connection.wallet);
841
+ await adapter?.disconnect?.();
842
+ }
843
+ this.connection = null;
844
+ }
845
+ // ── The full flow ──────────────────────────────────────────────────────────
846
+ /**
847
+ * The one-call happy path: detect a wallet, adapt the intent into a
848
+ * transaction, sign it, and (unless told otherwise) broadcast it. Works for
849
+ * both `tx` intents (signs the returned XDR) and `pay` intents (builds the
850
+ * payment from the connected account).
851
+ */
852
+ async pay(input, options = {}) {
853
+ const intent = normalizeIntent(input);
854
+ const network = this.networkFor(intent);
855
+ const adapter = await this.wallets.detect(options.wallet);
856
+ const account = await adapter.getPublicKey(network);
857
+ this.connection = {
858
+ wallet: adapter.id,
859
+ address: account,
860
+ network: network.network
861
+ };
862
+ const { xdr, source } = await this.prepare(intent, network, account, options);
863
+ const signedXdr = await adapter.signTransaction(xdr, {
864
+ networkPassphrase: network.passphrase,
865
+ network: network.network,
866
+ address: source
867
+ });
868
+ const result = {
869
+ intentId: intent.id,
870
+ wallet: adapter.id,
871
+ account: source,
872
+ network: network.network,
873
+ signedXdr,
874
+ txHash: "",
875
+ submitted: false
876
+ };
877
+ if (options.sign === true) {
878
+ result.txHash = await this.hashOf(signedXdr, network);
879
+ return result;
880
+ }
881
+ const useCallback = Boolean(intent.callback) && options.submit !== false;
882
+ const shouldSubmit = options.submit !== false;
883
+ if (useCallback) {
884
+ result.response = await postToCallback(
885
+ intent.callback,
886
+ signedXdr,
887
+ this.fetchFn
888
+ );
889
+ result.submitted = true;
890
+ } else if (shouldSubmit) {
891
+ const sdk = await this.sdk();
892
+ result.response = await submitToHorizon(sdk, network, signedXdr);
893
+ result.submitted = true;
894
+ }
895
+ result.txHash = extractHash(result.response) || await this.hashOf(signedXdr, network);
896
+ return result;
897
+ }
898
+ /**
899
+ * Adapt an intent into an unsigned transaction without signing it. Useful when
900
+ * you want to inspect/confirm the XDR before prompting the wallet.
901
+ */
902
+ async buildTransaction(input, options = {}) {
903
+ const intent = normalizeIntent(input);
904
+ const network = this.networkFor(intent);
905
+ const account = options.source ?? this.connection?.address ?? await (await this.wallets.detect(options.wallet)).getPublicKey(network);
906
+ const { xdr, source } = await this.prepare(intent, network, account, options);
907
+ return { xdr, source, intent, network };
908
+ }
909
+ // ── Optional REST convenience (requires an apiKey) ──────────────────────────
910
+ /**
911
+ * Create a `pay` intent directly from the browser. Requires a browser-safe
912
+ * `apiKey` (trusted environments only). Accepts typed assets (`Assets.USDC`)
913
+ * and named addresses.
914
+ */
915
+ createPay(options) {
916
+ return this.api().post("/payment-intents/pay", {
917
+ body: resolveIntentBody(options)
918
+ });
919
+ }
920
+ /**
921
+ * Create a `tx` intent directly from the browser. Requires a browser-safe
922
+ * `apiKey` (trusted environments only). Accepts typed assets (`Assets.USDC`)
923
+ * and named addresses.
924
+ */
925
+ createTx(options) {
926
+ return this.api().post("/payment-intents/tx", {
927
+ body: resolveIntentBody(options)
928
+ });
929
+ }
930
+ /** Validate a submitted transaction against an intent. Requires an `apiKey`. */
931
+ validate(intentId, txHash) {
932
+ return this.api().post(
933
+ `/payment-intents/${intentId}/validate`,
934
+ { body: { txHash } }
935
+ );
936
+ }
937
+ // ── internals ───────────────────────────────────────────────────────────────
938
+ /** Resolve the SDK (injected wins, else lazy-import). */
939
+ sdk() {
940
+ return loadStellarSdk(this.injectedSdk);
941
+ }
942
+ /** REST accessor that fails clearly when no apiKey was configured. */
943
+ api() {
944
+ if (!this.rest) {
945
+ throw new IntentError(
946
+ "This method needs an `apiKey`. Construct the WebClient with `{ apiKey }`, or (recommended) create/validate intents on your server."
947
+ );
948
+ }
949
+ return this.rest;
950
+ }
951
+ /** Combine the intent's network hint with the client's overrides. */
952
+ networkFor(intent) {
953
+ return resolveNetwork({
954
+ hint: intent.network,
955
+ network: this.options.network,
956
+ passphrase: this.options.passphrase,
957
+ horizonUrl: this.options.horizonUrl
958
+ });
959
+ }
960
+ /** Turn a normalized intent into an unsigned XDR + the signing source. */
961
+ async prepare(intent, network, account, options) {
962
+ if (intent.kind === "tx") {
963
+ if (!intent.xdr) {
964
+ throw new IntentError("This `tx` intent has no XDR to sign.");
965
+ }
966
+ if (intent.source && account && intent.source !== account) {
967
+ throw new IntentError(
968
+ `This transaction must be signed by ${intent.source}, but the connected wallet is ${account}. Switch accounts in your wallet and try again.`
969
+ );
970
+ }
971
+ return { xdr: intent.xdr, source: intent.source ?? account };
972
+ }
973
+ const source = options.source ?? account;
974
+ const sdk = await this.sdk();
975
+ const xdr = await buildPaymentXdr(sdk, network, {
976
+ intent,
977
+ source,
978
+ amount: options.amount,
979
+ baseFee: this.options.baseFee,
980
+ timeoutSeconds: this.options.timeoutSeconds
981
+ });
982
+ return { xdr, source };
983
+ }
984
+ /** Best-effort transaction hash via the SDK (empty string if unavailable). */
985
+ async hashOf(signedXdr, network) {
986
+ try {
987
+ const sdk = await this.sdk();
988
+ return transactionHash(sdk, signedXdr, network.passphrase);
989
+ } catch {
990
+ return "";
991
+ }
992
+ }
993
+ };
994
+ function reorder(adapters, preferred) {
995
+ if (!preferred?.length) return adapters;
996
+ const rank = new Map(preferred.map((id, i) => [id, i]));
997
+ return [...adapters].sort((a, b) => {
998
+ const ra = rank.has(a.id) ? rank.get(a.id) : Number.MAX_SAFE_INTEGER;
999
+ const rb = rank.has(b.id) ? rank.get(b.id) : Number.MAX_SAFE_INTEGER;
1000
+ return ra - rb;
1001
+ });
1002
+ }
1003
+ function extractHash(response) {
1004
+ if (response && typeof response === "object") {
1005
+ const obj = response;
1006
+ if (typeof obj["hash"] === "string") return obj["hash"];
1007
+ if (typeof obj["txHash"] === "string") return obj["txHash"];
1008
+ if (typeof obj["tx_hash"] === "string") return obj["tx_hash"];
1009
+ }
1010
+ return "";
1011
+ }
1012
+
1013
+ export { AlbedoAdapter, CosmosPayWebError, FreighterAdapter, HORIZON_URLS, IntentError, LobstrAdapter, PASSPHRASES, RabetAdapter, StellarSdkRequiredError, WalletError, WalletNotFoundError, WalletRegistry, WebClient, WebREST, XBullAdapter, buildPaymentXdr, classifyNetwork, defaultAdapters, isPassphrase, isSep7Uri, loadStellarSdk, normalizeIntent, parseSep7, postToCallback, resolveNetwork, submitToHorizon, transactionHash };
1014
+ //# sourceMappingURL=index.js.map
1015
+ //# sourceMappingURL=index.js.map