@cosmosapp/pay_sdk 2.3.1 → 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.
Files changed (49) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +97 -61
  3. package/dist/{chunk-B3HT6MCO.js → chunk-6FIALX2E.js} +3 -3
  4. package/dist/{chunk-B3HT6MCO.js.map → chunk-6FIALX2E.js.map} +1 -1
  5. package/dist/{chunk-AYVWYEOK.js → chunk-6PHQBYQ4.js} +2 -2
  6. package/dist/chunk-6PHQBYQ4.js.map +1 -0
  7. package/dist/chunk-ALFITFBN.js +105 -0
  8. package/dist/chunk-ALFITFBN.js.map +1 -0
  9. package/dist/chunk-PAQHOXQ6.js +392 -0
  10. package/dist/chunk-PAQHOXQ6.js.map +1 -0
  11. package/dist/{cosmosProvider-DTz0Y8xZ.d.cts → cosmosProvider-BrpOdL_b.d.cts} +3 -3
  12. package/dist/{cosmosProvider-DTz0Y8xZ.d.ts → cosmosProvider-BrpOdL_b.d.ts} +3 -3
  13. package/dist/errors-CZu5mmz1.d.cts +293 -0
  14. package/dist/errors-Cqh7UdUO.d.ts +293 -0
  15. package/dist/index.cjs +18 -5
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +12 -7
  18. package/dist/index.d.ts +12 -7
  19. package/dist/index.js +19 -6
  20. package/dist/index.js.map +1 -1
  21. package/dist/intent-input-BybnwL83.d.ts +126 -0
  22. package/dist/intent-input-C2PTr2XH.d.cts +126 -0
  23. package/dist/swk/index.cjs +2 -2
  24. package/dist/swk/index.cjs.map +1 -1
  25. package/dist/swk/index.d.cts +7 -7
  26. package/dist/swk/index.d.ts +7 -7
  27. package/dist/swk/index.js +2 -104
  28. package/dist/swk/index.js.map +1 -1
  29. package/dist/wallets/index.cjs +1043 -0
  30. package/dist/wallets/index.cjs.map +1 -0
  31. package/dist/wallets/index.d.cts +384 -0
  32. package/dist/wallets/index.d.ts +384 -0
  33. package/dist/wallets/index.js +629 -0
  34. package/dist/wallets/index.js.map +1 -0
  35. package/dist/{intent-input-CP5bkBYI.d.cts → wallets-CeIjESt5.d.cts} +39 -126
  36. package/dist/{intent-input-CP5bkBYI.d.ts → wallets-CeIjESt5.d.ts} +39 -126
  37. package/dist/web/index.cjs +4 -4
  38. package/dist/web/index.cjs.map +1 -1
  39. package/dist/web/index.d.cts +11 -296
  40. package/dist/web/index.d.ts +11 -296
  41. package/dist/web/index.js +6 -392
  42. package/dist/web/index.js.map +1 -1
  43. package/llms/07-webhooks.md +2 -0
  44. package/llms/15-swaps.md +2 -0
  45. package/llms/18-wallets.md +94 -0
  46. package/llms/llms-full.txt +101 -0
  47. package/llms/llms.txt +1 -0
  48. package/package.json +22 -8
  49. package/dist/chunk-AYVWYEOK.js.map +0 -1
@@ -596,6 +596,8 @@ Event types (`WebhookEventType`, the same list the API accepts in `eventTypes`):
596
596
  `LIQUIDITY_FAILED`, `LIQUIDITY_EXPIRED`.
597
597
  - Fiat ramps: `RECEIVER_UPDATED`, `PAYIN_CREATED`, `PAYIN_UPDATED`, `PAYIN_COMPLETED`,
598
598
  `PAYOUT_CREATED`, `PAYOUT_UPDATED`, `PAYOUT_COMPLETED`.
599
+ - Protected payments (held in a contract until delivery; `data` untyped for now):
600
+ `PROTECTED_PAYMENT_CREATED`, `PROTECTED_PAYMENT_FUNDED`, `PROTECTED_PAYMENT_SHIPPED`, `PROTECTED_PAYMENT_APPROVED`, `PROTECTED_PAYMENT_RELEASED`, `PROTECTED_PAYMENT_DISPUTED`, `PROTECTED_PAYMENT_RESOLVED`, `PROTECTED_PAYMENT_DEADLINE_PASSED`, `PROTECTED_PAYMENT_EXPIRED`, `PROTECTED_PAYMENT_CANCELLED`.
599
601
 
600
602
  A same-chain swap (`SWAP_EXPIRED`) or a liquidity operation (`LIQUIDITY_EXPIRED`) can
601
603
  still settle if its transaction lands late: the API then sends `SWAP_SUCCEEDED` or
@@ -1131,6 +1133,8 @@ await sol.submit({ signedTransaction });
1131
1133
  const mon = await client.swaps.create({ chain: 'monad', amount: '10', sourceAssetCode: 'MON',
1132
1134
  destAssetCode: '0x754704bc059f8c67012fed69bc8a327a5aafb603', source: evmWallet });
1133
1135
  if (mon.approval) await wallet.sendTransaction(mon.approval);
1136
+ // A browser wallet (MetaMask...) sends the swap itself: report its hash instead.
1137
+ // await mon.submit({ txHash }); see @cosmosapp/pay_sdk/wallets
1134
1138
 
1135
1139
  const page = await client.swaps.list({ chain: 'solana' }); // ChainSwap[]
1136
1140
  ```
@@ -1323,3 +1327,100 @@ shared public key. Any other key ignores the token.
1323
1327
  `guid`, `destinationTxHash`, `scanStatus`, `scanUrl`, `failureReason`,
1324
1328
  `merchantFee`, `idempotencyKey`, `expiresAt`, `submittedAt`, `createdAt`,
1325
1329
  `updatedAt`, `publicToken`, plus `isPending`, `isDelivered`, `isFinal`.
1330
+
1331
+ ---
1332
+
1333
+ # Wallets: Stellar, EVM and Solana
1334
+
1335
+ `@cosmosapp/pay_sdk/wallets` finds every wallet a person can sign with in their browser and
1336
+ gives each the same small shape, whatever its ecosystem. It bundles no wallet library: each
1337
+ ecosystem is reached through its own open standard.
1338
+
1339
+ | Ecosystem | Reached through | Wallets |
1340
+ | --- | --- | --- |
1341
+ | `stellar` | the SDK's adapters, the providers wallets inject, plus a Stellar Wallets Kit when passed | Freighter (now Varial), xBull, Rabet, LOBSTR, Albedo, Cosmos Pay Wallet, Hana, Klever, OneKey, Bitget, Cactus Link, D'CENT, Scopuly; with a kit also MetaMask (Stellar Snap), Ledger, Trezor, WalletConnect... |
1342
+ | `evm` | EIP-6963 announcements, else `window.ethereum` | MetaMask, Rabby, Coinbase Wallet, OKX, Trust, Brave... |
1343
+ | `solana` | Wallet Standard (`wallet-standard:register-wallet` / `app-ready`) | Phantom, Solflare, Backpack... |
1344
+
1345
+ ```ts
1346
+ import { discoverWallets, EvmChains, isUserRejection } from '@cosmosapp/pay_sdk/wallets';
1347
+
1348
+ const { stellar, evm, solana } = await discoverWallets(); // each an array, possibly empty
1349
+ ```
1350
+
1351
+ Every wallet has `id` (`stellar:freighter`, `evm:io.metamask`, `solana:phantom`), `name`,
1352
+ `icon` (the wallet's own, when it gives one) and `ecosystem`. Outside a browser every list is
1353
+ empty. Pass `{ ecosystems: ['evm'] }` to look in one ecosystem only.
1354
+
1355
+ ## Stellar
1356
+
1357
+ ```ts
1358
+ const wallet = stellar[0];
1359
+ const address = await wallet.connect('public'); // or 'testnet'
1360
+ const signedXdr = await wallet.signTransaction(xdr, { network: 'public', address });
1361
+ await swap.submit({ signedXdr });
1362
+ ```
1363
+
1364
+ Hana, Klever, OneKey, Bitget, Cactus Link, D'CENT and Scopuly inject a provider into the page and
1365
+ are found with no library. With a Stellar Wallets Kit, its wallets join the list too (a wallet
1366
+ reached several ways is listed once, with the kit's name and icon). Kit v2's static class and a v1
1367
+ instance both work:
1368
+
1369
+ ```ts
1370
+ import { StellarWalletsKit } from '@creit.tech/stellar-wallets-kit/sdk';
1371
+ import { defaultModules } from '@creit.tech/stellar-wallets-kit/modules/utils';
1372
+
1373
+ StellarWalletsKit.init({ modules: defaultModules() });
1374
+ const { stellar } = await discoverWallets({ stellar: { kit: StellarWalletsKit } });
1375
+ ```
1376
+
1377
+ `stellar.injected` passes wallet libraries that have no global (LOBSTR, Albedo, a hosted Cosmos
1378
+ Pay Wallet), as in `WebClient`.
1379
+
1380
+ ## EVM (Monad)
1381
+
1382
+ EVM wallets cannot hand a signed transaction back: they sign and broadcast it themselves, so
1383
+ `sendTransaction` answers the transaction hash. It switches the wallet to the transaction's chain
1384
+ first, adding the chain when the wallet does not know it (`EvmChains.monad`,
1385
+ `EvmChains.monadTestnet`).
1386
+
1387
+ ```ts
1388
+ const wallet = evm.find((w) => w.rdns === 'io.metamask') ?? evm[0];
1389
+ const from = await wallet.connect();
1390
+ if (swap.approval) {
1391
+ const approval = await wallet.sendTransaction({ from, ...swap.approval }, EvmChains.monad);
1392
+ await wallet.waitForTransaction(approval); // the swap needs the allowance mined
1393
+ }
1394
+ const txHash = await wallet.sendTransaction({ from, ...swap.transaction }, EvmChains.monad);
1395
+ await swap.submit({ txHash });
1396
+ ```
1397
+
1398
+ The node may not know a just-sent transaction yet: `submit({ txHash })` then fails with
1399
+ `400 transaction_not_found` and records nothing, so retry it after a few seconds.
1400
+
1401
+ A cross-chain swap's EVM `depositUri` is an EIP-681 link: `parseEip681(uri)` turns it into the
1402
+ transaction (`{ chainId, to, value }` or an ERC-20 `transfer`), so
1403
+ `wallet.sendTransaction({ from, ...parseEip681(swap.depositUri) })` pays the deposit.
1404
+
1405
+ `wallet.provider` is the wallet's EIP-1193 provider for anything else. `erc20TransferData(to,
1406
+ amount)` builds a token transfer's call data; `toQuantity` turns a decimal amount of wei into the
1407
+ hex a wallet takes.
1408
+
1409
+ ## Solana
1410
+
1411
+ ```ts
1412
+ const wallet = solana[0];
1413
+ const address = await wallet.connect();
1414
+ const signedTransaction = await wallet.signTransaction(swap.transaction.data); // base64 in and out
1415
+ await swap.submit({ signedTransaction });
1416
+ ```
1417
+
1418
+ `signTransaction` signs without broadcasting, so the API can check the transaction and relay it.
1419
+ `signAndSendTransaction` (when `canSignAndSend`) broadcasts too and answers the signature.
1420
+ Chains are `solana:mainnet` (the default), `solana:devnet` and `solana:testnet`.
1421
+
1422
+ ## Errors
1423
+
1424
+ A wallet's failure is a `WalletError` (`error.wallet` is the wallet id, `error.cause` the
1425
+ wallet's own error). `isUserRejection(error)` tells the person declining (closing the prompt,
1426
+ pressing reject, EIP-1193 code 4001) from a failure worth reporting.
package/llms/llms.txt CHANGED
@@ -38,6 +38,7 @@ The files below are atomic and self-contained — read the ones relevant to the
38
38
  - [Swaps](./15-swaps.md): same-chain swaps (Stellar DEX, Jupiter on Solana, Kuru Flow on Monad) and cross-chain swaps (NEAR Intents)
39
39
  - [Private payments](./16-private-payments.md): payments whose amount is hidden on-chain (Stellar Testnet for now, 0.18% commission)
40
40
  - [USDT0](./17-usdt0.md): send USDT0 from Stellar to EVM networks through LayerZero (mainnet only)
41
+ - [Wallets](./18-wallets.md): `@cosmosapp/pay_sdk/wallets`, every Stellar, EVM and Solana wallet in the browser behind one shape (connect, sign, send)
41
42
 
42
43
  ## Optional
43
44
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cosmosapp/pay_sdk",
3
- "version": "2.3.1",
4
- "description": "Official SDK for Cosmos Pay, the stablecoin payments API for Stellar, Solana and Monad: payment intents and checkout, webhooks, swaps (same-chain and cross-chain), fiat ramps, products and customers. Payment links on all three (SEP-7, Solana Pay, EIP-681). Includes a browser client for Stellar wallets.",
3
+ "version": "2.4.0",
4
+ "description": "Official SDK for Cosmos Pay, the stablecoin payments API for Stellar, Solana and Monad: payment intents and checkout, webhooks, swaps (same-chain and cross-chain), fiat ramps, products and customers. Payment links on all three (SEP-7, Solana Pay, EIP-681). Includes a browser client for Stellar wallets and a wallets module that reaches every Stellar, EVM (EIP-6963) and Solana (Wallet Standard) wallet.",
5
5
  "keywords": [
6
6
  "cosmos-pay",
7
7
  "cosmos",
@@ -27,7 +27,11 @@
27
27
  "xbull",
28
28
  "albedo",
29
29
  "rabet",
30
- "lobstr"
30
+ "lobstr",
31
+ "metamask",
32
+ "phantom",
33
+ "eip-6963",
34
+ "wallet-standard"
31
35
  ],
32
36
  "license": "Apache-2.0",
33
37
  "author": "Cosmos Pay",
@@ -74,6 +78,16 @@
74
78
  "default": "./dist/swk/index.cjs"
75
79
  }
76
80
  },
81
+ "./wallets": {
82
+ "import": {
83
+ "types": "./dist/wallets/index.d.ts",
84
+ "default": "./dist/wallets/index.js"
85
+ },
86
+ "require": {
87
+ "types": "./dist/wallets/index.d.cts",
88
+ "default": "./dist/wallets/index.cjs"
89
+ }
90
+ },
77
91
  "./package.json": "./package.json"
78
92
  },
79
93
  "files": [
@@ -92,8 +106,8 @@
92
106
  "dev": "tsup --watch",
93
107
  "typecheck": "tsc --noEmit",
94
108
  "pretest": "npm run build",
95
- "test": "node --test test/client.test.mjs test/rest.test.mjs test/payment-intents.test.mjs test/swaps.test.mjs test/webhooks.test.mjs test/structures.test.mjs test/web.test.mjs test/catalogs.test.mjs test/cosmos-wallet.test.mjs test/liquidity.test.mjs test/ramps.test.mjs test/kyc.test.mjs test/aliases-assets.test.mjs test/cross-chain-swaps.test.mjs test/extensions.test.mjs test/customers-analytics.test.mjs test/private-payments.test.mjs test/usdt0.test.mjs test/openapi.test.mjs",
96
- "test:watch": "node --test --watch test/client.test.mjs test/rest.test.mjs test/payment-intents.test.mjs test/swaps.test.mjs test/webhooks.test.mjs test/structures.test.mjs test/web.test.mjs test/catalogs.test.mjs test/cosmos-wallet.test.mjs test/liquidity.test.mjs test/ramps.test.mjs test/kyc.test.mjs test/aliases-assets.test.mjs test/cross-chain-swaps.test.mjs test/extensions.test.mjs test/customers-analytics.test.mjs test/private-payments.test.mjs test/usdt0.test.mjs test/openapi.test.mjs",
109
+ "test": "node --test test/client.test.mjs test/rest.test.mjs test/payment-intents.test.mjs test/swaps.test.mjs test/webhooks.test.mjs test/structures.test.mjs test/web.test.mjs test/catalogs.test.mjs test/cosmos-wallet.test.mjs test/liquidity.test.mjs test/ramps.test.mjs test/kyc.test.mjs test/aliases-assets.test.mjs test/cross-chain-swaps.test.mjs test/extensions.test.mjs test/customers-analytics.test.mjs test/private-payments.test.mjs test/usdt0.test.mjs test/wallets.test.mjs test/openapi.test.mjs",
110
+ "test:watch": "node --test --watch test/client.test.mjs test/rest.test.mjs test/payment-intents.test.mjs test/swaps.test.mjs test/webhooks.test.mjs test/structures.test.mjs test/web.test.mjs test/catalogs.test.mjs test/cosmos-wallet.test.mjs test/liquidity.test.mjs test/ramps.test.mjs test/kyc.test.mjs test/aliases-assets.test.mjs test/cross-chain-swaps.test.mjs test/extensions.test.mjs test/customers-analytics.test.mjs test/private-payments.test.mjs test/usdt0.test.mjs test/wallets.test.mjs test/openapi.test.mjs",
97
111
  "prepublishOnly": "npm run build",
98
112
  "changelog": "npx --yes git-cliff@2 -o CHANGELOG.md",
99
113
  "llms": "node scripts/build-llms.mjs",
@@ -102,9 +116,9 @@
102
116
  "openapi:check": "node scripts/sync-openapi.mjs --check"
103
117
  },
104
118
  "devDependencies": {
105
- "@types/node": "^26.6.5",
106
- "rimraf": "^6.1.3",
107
- "semver": "^7.8.5",
119
+ "@types/node": "^26.6.6",
120
+ "rimraf": "^6.1.4",
121
+ "semver": "^7.8.6",
108
122
  "tsup": "^9.0.0",
109
123
  "typescript": "^5.9.3"
110
124
  },
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/web/cosmosProvider.ts"],"names":[],"mappings":"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","file":"chunk-AYVWYEOK.js","sourcesContent":["/**\n * Reaching Cosmos Wallet, over either of the two transports it ships.\n *\n * Cosmos Pay's own wallet exposes a SEP-43-shaped provider on `window.cosmosWallet`,\n * and it gets there two different ways:\n *\n * extension the browser extension's content script injects it at document start,\n * so the global is simply there — nothing to configure.\n * hosted the wallet also runs as a plain web page, and a site opts in by\n * loading `<wallet origin>/cosmos-wallet.js`. Each call then opens the\n * wallet's own approval window. Nothing is installed.\n *\n * One module for both, because everything above the provider — the SDK's wallet\n * adapter and the Stellar Wallets Kit module — cares about the same five methods\n * and not at all about how they arrived.\n *\n * WHY THE SCRIPT IS LOADED ONCE AND MEMOISED AS A PROMISE: `isAvailable()` and\n * `getAddress()` can be called in the same tick (a kit rendering its modal does\n * exactly that), and two `<script>` tags for one provider is a race whose loser\n * silently wins — the second load finds `window.cosmosWallet` already defined and\n * bails, and whichever promise settles last is the one the caller reads.\n */\n\n/** The provider surface this SDK uses. A superset lives on the real object. */\nexport interface CosmosWalletProvider {\n /** Marker the wallet sets on its own provider. */\n isCosmosWallet?: boolean;\n /** `'web'` on the hosted build; absent on the extension's provider. */\n transport?: string;\n isConnected?(): Promise<boolean>;\n getAddress(): Promise<{\n address: string;\n network?: string;\n networkPassphrase?: string;\n networkUrl?: string;\n }>;\n getNetwork(): Promise<{ network: string; networkPassphrase: string; networkUrl?: string }>;\n signTransaction(\n xdr: string,\n opts?: { networkPassphrase?: string; address?: string },\n ): Promise<{ signedTxXdr: string; signerAddress?: string }>;\n signMessage(\n message: string,\n opts?: { networkPassphrase?: string; address?: string },\n ): Promise<{ signedMessage: string; signerAddress?: string; domain?: string }>;\n /** SEP-7 `web+stellar:pay…` — the wallet builds, signs and submits it. */\n requestPayment?(uri: string): Promise<{ hash: string; signerAddress?: string }>;\n}\n\n/** How to find the provider. Everything is optional: an extension needs nothing. */\nexport interface CosmosProviderOptions {\n /**\n * A provider object supplied by the host (tests, or an app that already holds\n * one). Wins over everything else and is never probed for.\n */\n provider?: CosmosWalletProvider;\n /**\n * Origin of a hosted Cosmos Wallet — e.g. `https://wallet.cosmospay.lat`. Set it\n * to support users who have not installed the extension: the provider script is\n * pulled from that origin on first use, and signing happens in the wallet's own\n * window on its own origin. Leave it unset to require the extension.\n */\n walletUrl?: string;\n /**\n * How long to wait for that script, in ms. The kit gives a module 1000ms to answer\n * `isAvailable()`, which is why availability never waits for this — see\n * `CosmosWalletModule`.\n */\n loadTimeoutMs?: number;\n}\n\n/** File the hosted wallet serves its provider from, relative to the wallet origin. */\nconst PROVIDER_FILE = 'cosmos-wallet.js';\nconst DEFAULT_LOAD_TIMEOUT_MS = 15_000;\n\n/** The window, or undefined outside a browser (SSR-safe). */\nfunction browserWindow(): (Window & typeof globalThis) | undefined {\n return typeof window !== 'undefined' ? window : undefined;\n}\n\n/** The provider the extension injected, if any. Never throws, never loads. */\nexport function injectedProvider(): CosmosWalletProvider | undefined {\n const win = browserWindow() as unknown as Record<string, unknown> | undefined;\n const provider = win?.['cosmosWallet'];\n return provider && typeof provider === 'object' ? (provider as CosmosWalletProvider) : undefined;\n}\n\n/** One in-flight load per wallet origin, shared by every caller. */\nconst loads = new Map<string, Promise<CosmosWalletProvider | undefined>>();\n\n/**\n * Load the hosted wallet's provider script from `walletUrl` and resolve with the\n * provider it defines. Resolves `undefined` rather than throwing when there is no\n * document, no URL, or the script never arrives: \"no wallet\" is an answer every\n * caller here already has to handle.\n */\nexport function loadHostedProvider(\n walletUrl: string,\n timeoutMs: number = DEFAULT_LOAD_TIMEOUT_MS,\n): Promise<CosmosWalletProvider | undefined> {\n const existing = injectedProvider();\n if (existing) return Promise.resolve(existing);\n\n const win = browserWindow();\n if (!win || typeof document === 'undefined') return Promise.resolve(undefined);\n\n const origin = walletUrl.replace(/\\/+$/, '');\n const cached = loads.get(origin);\n if (cached) return cached;\n\n const pending = new Promise<CosmosWalletProvider | undefined>((resolve) => {\n const src = `${origin}/${PROVIDER_FILE}`;\n const done = (value: CosmosWalletProvider | undefined) => {\n clearTimeout(timer);\n resolve(value);\n };\n const timer = setTimeout(() => done(injectedProvider()), timeoutMs);\n\n // A tag for this exact src may already be on the page — the site can ship it\n // itself, which is the documented integration. Reuse it instead of adding a\n // second one; `onload` on an already-loaded script never fires, so the\n // provider is read directly in that case.\n const existingTag = document.querySelector<HTMLScriptElement>(`script[src=\"${src}\"]`);\n if (existingTag) {\n const found = injectedProvider();\n if (found) return done(found);\n existingTag.addEventListener('load', () => done(injectedProvider()), { once: true });\n existingTag.addEventListener('error', () => done(undefined), { once: true });\n return;\n }\n\n const tag = document.createElement('script');\n tag.src = src;\n tag.async = true;\n tag.addEventListener('load', () => done(injectedProvider()), { once: true });\n tag.addEventListener('error', () => done(undefined), { once: true });\n (document.head ?? document.documentElement).appendChild(tag);\n });\n\n // Not cached on failure: a wallet origin that was down once should be retried,\n // and a memoised `undefined` would make the wallet permanently unavailable for\n // the life of the page.\n loads.set(origin, pending);\n void pending.then((provider) => {\n if (!provider) loads.delete(origin);\n });\n return pending;\n}\n\n/**\n * The provider to act on: the injected one, the host's, or the hosted build's —\n * in that order. `undefined` when Cosmos Wallet cannot be reached at all.\n */\nexport async function resolveProvider(\n options: CosmosProviderOptions = {},\n): Promise<CosmosWalletProvider | undefined> {\n if (options.provider) return options.provider;\n const injected = injectedProvider();\n if (injected) return injected;\n if (!options.walletUrl) return undefined;\n return loadHostedProvider(options.walletUrl, options.loadTimeoutMs);\n}\n\n/** Forget memoised loads. Exposed for tests; harmless in an app. */\nexport function resetProviderCache(): void {\n loads.clear();\n}\n"]}