@tuwaio/orbit-core 0.1.1 → 0.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.
package/dist/index.d.ts CHANGED
@@ -100,12 +100,14 @@ type BaseAdapter = {
100
100
  getName?: (address: string) => Promise<string | null>;
101
101
  /** Optional method to get avatar for resolved names */
102
102
  getAvatar?: (name: string) => Promise<string | null>;
103
+ /** Optional method to resolve names to addresses */
104
+ getAddress?: (name: string) => Promise<string | null>;
103
105
  };
104
106
  /**
105
- * Type representing a wallet identifier in format "OrbitAdapter:wallet"
107
+ * Type representing a connector identifier in format "OrbitAdapter:connector"
106
108
  * @example "evm:metamask" | "solana:phantom"
107
109
  */
108
- type WalletType = `${OrbitAdapter}:${string}`;
110
+ type ConnectorType = `${OrbitAdapter}:${string}`;
109
111
 
110
112
  /**
111
113
  * @name delay
@@ -152,69 +154,70 @@ declare const delay: <T>(value: T, ms: number) => Promise<T>;
152
154
  */
153
155
  declare function filterUniqueByKey<T>(array: T[], key: keyof T): T[];
154
156
 
155
- declare function formatWalletChainId(chainId: string | number, connectedAdapter: OrbitAdapter): string | number;
157
+ declare function formatConnectorChainId(chainId: string | number, connectedAdapter: OrbitAdapter): string | number;
156
158
 
157
- declare const formatWalletName: (walletName: string) => string;
159
+ declare const formatConnectorName: (connectorName: string) => string;
158
160
 
159
161
  /**
160
- * Extracts the adapter type from a wallet type string
162
+ * Extracts the adapter type from a connector type string
161
163
  *
162
164
  * @example
163
165
  * ```typescript
164
166
  * // Returns OrbitAdapter.EVM
165
- * getAdapterFromWalletType('evm:metamask');
167
+ * getAdapterFromConnectorType('evm:metamask');
166
168
  *
167
169
  * // Returns OrbitAdapter.SOLANA
168
- * getAdapterFromWalletType('solana:phantom');
170
+ * getAdapterFromConnectorType('solana:phantom');
169
171
  *
170
172
  * // Returns OrbitAdapter.EVM (default)
171
- * getAdapterFromWalletType('unknown');
173
+ * getAdapterFromConnectorType('unknown');
172
174
  * ```
173
175
  *
174
- * @param walletType - Wallet type in format "chain:wallet" (e.g. "evm:metamask", "solana:phantom")
176
+ * @param connectorType - Connector type in format "orbit-adapter:connector" (e.g. "evm:metamask", "solana:phantom")
175
177
  * @returns The corresponding {@link OrbitAdapter} type or EVM as default
176
178
  *
177
179
  * @remarks
178
- * The function splits the wallet type string by ":" and takes the first part as the adapter type.
180
+ * The function splits the connector type string by ":" and takes the first part as the adapter type.
179
181
  * If the split fails or the first part is empty, it defaults to EVM adapter.
180
182
  */
181
- declare function getAdapterFromWalletType(walletType: WalletType): OrbitAdapter;
183
+ declare function getAdapterFromConnectorType(connectorType: ConnectorType): OrbitAdapter;
182
184
 
183
185
  /**
184
- * Internal function for safely retrieving and parsing data from localStorage.
185
- *
186
- * @param key - The key for localStorage
187
- * @returns The parsed LastConnectedWallet object or undefined if data is not found/invalid
188
- */
189
- declare function getParsedStorageItem<ReturnType>(key: string): ReturnType | undefined;
190
-
191
- /**
192
- * Generates a standardized wallet type identifier from adapter type and connector name
186
+ * Generates a standardized connector type identifier from adapter type and connector name
193
187
  *
194
188
  * @example
195
189
  * ```typescript
196
190
  * // Returns "evm:metamask"
197
- * getWalletTypeFromConnectorName(OrbitAdapter.EVM, "MetaMask");
191
+ * getConnectorTypeFromName(OrbitAdapter.EVM, "MetaMask");
198
192
  *
199
193
  * // Returns "solana:phantom"
200
- * getWalletTypeFromConnectorName(OrbitAdapter.SOLANA, "Phantom");
194
+ * getConnectorTypeFromName(OrbitAdapter.SOLANA, "Phantom");
201
195
  *
202
196
  * // Returns "evm:coinbasewallet" (removes spaces)
203
- * getWalletTypeFromConnectorName(OrbitAdapter.EVM, "Coinbase Wallet");
197
+ * getConnectorTypeFromName(OrbitAdapter.EVM, "Coinbase Wallet");
204
198
  * ```
205
199
  *
206
200
  * @param adapter - The blockchain adapter type (e.g. EVM, SOLANA)
207
- * @param name - The wallet connector name (e.g. "MetaMask", "Phantom")
208
- * @returns A formatted wallet type string in format "chain:wallet"
201
+ * @param name - The connector name (e.g. "MetaMask", "Phantom")
202
+ * @returns A formatted connector type string in format "orbit-adapter:connector"
209
203
  *
210
204
  * @remarks
211
205
  * The function:
212
206
  * 1. Combines adapter type with connector name using ":" as separator
213
207
  * 2. Removes all whitespace from connector name
214
208
  * 3. Converts connector name to lowercase
215
- * This ensures consistent wallet type identifiers across the application
209
+ * This ensures consistent connector type identifiers across the application
210
+ * and normalizes connector names for better UX/consistency.
216
211
  */
217
- declare function getWalletTypeFromConnectorName(adapter: OrbitAdapter, name: string): string;
212
+ declare function getConnectorTypeFromName(adapter: OrbitAdapter, name: string): string;
213
+
214
+ /**
215
+ * Internal function for safely retrieving and parsing data from localStorage.
216
+ *
217
+ * @param key - The key for localStorage
218
+ * @returns The parsed LastConnectedConnector object or undefined if data is not found/invalid
219
+ */
220
+ declare function getParsedStorageItem<ReturnType>(key: string): ReturnType | undefined;
218
221
 
219
222
  /**
220
223
  * Helper utilities for managing impersonated wallet addresses
@@ -263,8 +266,8 @@ declare const impersonatedHelpers: {
263
266
 
264
267
  declare const isSafeApp: boolean;
265
268
 
266
- type LastConnectedWallet = {
267
- walletType: WalletType;
269
+ type LastConnectedConnector = {
270
+ connectorType: ConnectorType;
268
271
  chainId: number | string;
269
272
  address?: string;
270
273
  };
@@ -272,71 +275,269 @@ type LastConnectedWallet = {
272
275
  * Helper utilities for managing the last connected wallet state
273
276
  *
274
277
  * @remarks
275
- * All data is stored in localStorage with the 'orbit-core:lastConnectedWallet' key.
278
+ * All data is stored in localStorage with the 'orbit-core:lastConnectedConnector' key.
276
279
  * Functions are safe to use in both browser and SSR environments.
277
280
  */
278
- declare const lastConnectedWalletHelpers: {
281
+ declare const lastConnectedConnectorHelpers: {
279
282
  STORAGE_KEY: string;
280
283
  /**
281
284
  * The value of the last connected wallet, initialized when the module loads.
282
285
  * Returns undefined if not set, invalid, or in an SSR context.
283
286
  */
284
- lastConnectedWallet: LastConnectedWallet | undefined;
287
+ lastConnectedConnector: LastConnectedConnector | undefined;
285
288
  /**
286
289
  * Stores the last connected wallet data in localStorage.
287
290
  *
288
291
  * @param data - Object containing the wallet type and chain ID.
289
292
  * @returns undefined in SSR context, void in browser
290
293
  */
291
- setLastConnectedWallet: ({ walletType, chainId, address }: LastConnectedWallet) => void;
294
+ setLastConnectedConnector: ({ connectorType, chainId, address }: LastConnectedConnector) => void;
292
295
  /**
293
296
  * Retrieves the current last connected wallet data from localStorage.
294
297
  *
295
- * @returns The LastConnectedWallet object or undefined if not set or in SSR context
298
+ * @returns The LastConnectedConnector object or undefined if not set or in SSR context
296
299
  */
297
- getLastConnectedWallet: () => LastConnectedWallet | undefined;
300
+ getLastConnectedConnector: () => LastConnectedConnector | undefined;
298
301
  /**
299
302
  * Removes the last connected wallet data from localStorage.
300
303
  *
301
304
  * @returns undefined in SSR context, void in browser
302
305
  */
303
- removeLastConnectedWallet: () => void;
306
+ removeLastConnectedConnector: () => void;
304
307
  };
305
308
 
306
- type RecentConnectedWallet = Record<OrbitAdapter, Record<string, boolean>>;
307
309
  /**
308
- * Helper utilities for managing the last connected wallet state
310
+ * Data structure for a recently connected connector
311
+ *
312
+ * @interface RecentlyConnectedConnectorData
313
+ * @property {string} address - The wallet address that was connected
314
+ * @property {number} disconnectedTimestamp - Unix timestamp in milliseconds when the connector was disconnected
315
+ * @property {string} [icon] - Optional icon URL or identifier for the connector
316
+ */
317
+ type RecentlyConnectedConnectorData = {
318
+ address: string;
319
+ disconnectedTimestamp: number;
320
+ icon?: string;
321
+ };
322
+ /**
323
+ * Record mapping connector types to their recently connected data
324
+ *
325
+ * @type RecentlyConnectedConnectorsList
326
+ */
327
+ type RecentlyConnectedConnectorsList = Record<ConnectorType, RecentlyConnectedConnectorData>;
328
+ /**
329
+ * Helper utilities for managing recently connected connectors list with disconnect timestamps
309
330
  *
310
331
  * @remarks
311
- * All data is stored in localStorage with the 'orbit-core:lastConnectedWallet' key.
332
+ * All data is stored in localStorage with the 'orbit-core:recentlyConnectedConnectorsListHelpers' key.
312
333
  * Functions are safe to use in both browser and SSR environments.
334
+ *
335
+ * The storage contains a record where each key is a ConnectorType and value contains
336
+ * address, disconnectedTimestamp (Unix timestamp in milliseconds), and optional icon for that connector.
337
+ * This allows tracking when each connector was last disconnected for cleanup and sorting purposes.
338
+ *
339
+ * @example
340
+ * ```typescript
341
+ * // Set entire list
342
+ * recentlyConnectedConnectorsListHelpers.setRecentlyConnectedConnectorsList({
343
+ * 'evm:metamask': {
344
+ * address: '0x123...',
345
+ * disconnectedTimestamp: Date.now(),
346
+ * icon: 'metamask-icon.png'
347
+ * },
348
+ * 'solana:phantom': {
349
+ * address: 'ABC123...',
350
+ * disconnectedTimestamp: Date.now() - 3600000, // 1 hour ago
351
+ * icon: 'phantom-icon.png'
352
+ * }
353
+ * });
354
+ *
355
+ * // Add single connector
356
+ * recentlyConnectedConnectorsListHelpers.addConnector('evm:walletconnect', {
357
+ * address: '0x456...',
358
+ * disconnectedTimestamp: Date.now(),
359
+ * icon: 'walletconnect-icon.png'
360
+ * });
361
+ *
362
+ * // Remove single connector
363
+ * recentlyConnectedConnectorsListHelpers.removeConnector('evm:metamask');
364
+ * ```
313
365
  */
314
- declare const recentConnectedWalletHelpers: {
366
+ declare const recentlyConnectedConnectorsListHelpers: {
367
+ /** Key used for localStorage storage */
315
368
  STORAGE_KEY: string;
316
369
  /**
317
- * The value of the last connected wallet, initialized when the module loads.
370
+ * The current recently connected connectors list, initialized when the module loads.
318
371
  * Returns undefined if not set, invalid, or in an SSR context.
372
+ *
373
+ * @readonly
319
374
  */
320
- recentConnectedWallet: RecentConnectedWallet | undefined;
375
+ recentlyConnectedConnectorsList: RecentlyConnectedConnectorsList | undefined;
321
376
  /**
322
- * Stores the last connected wallet data in localStorage.
377
+ * Stores the complete recently connected connectors list in localStorage.
378
+ * This will overwrite the entire existing list.
323
379
  *
324
- * @param wallets - RecentConnectedWallet
380
+ * @param connectors - Complete RecentlyConnectedConnectorsList object
325
381
  * @returns undefined in SSR context, void in browser
382
+ *
383
+ * @example
384
+ * ```typescript
385
+ * recentlyConnectedConnectorsListHelpers.setRecentlyConnectedConnectorsList({
386
+ * 'evm:metamask': {
387
+ * address: '0x123...',
388
+ * disconnectedTimestamp: Date.now(),
389
+ * icon: 'metamask.png'
390
+ * },
391
+ * 'solana:phantom': {
392
+ * address: 'ABC123...',
393
+ * disconnectedTimestamp: Date.now() - 1800000 // 30 minutes ago
394
+ * }
395
+ * });
396
+ * ```
326
397
  */
327
- setRecentConnectedWallet: (wallets: RecentConnectedWallet) => void;
398
+ setRecentlyConnectedConnectorsList: (connectors: RecentlyConnectedConnectorsList) => void;
328
399
  /**
329
- * Retrieves the current last connected wallet data from localStorage.
400
+ * Retrieves the current recently connected connectors list from localStorage.
330
401
  *
331
- * @returns The LastConnectedWallet object or undefined if not set or in SSR context
402
+ * @returns The RecentlyConnectedConnectorsList object or undefined if not set or in SSR context
403
+ *
404
+ * @example
405
+ * ```typescript
406
+ * const connectors = recentlyConnectedConnectorsListHelpers.getRecentlyConnectedConnectorsList();
407
+ * if (connectors) {
408
+ * console.log('Available connectors:', Object.keys(connectors));
409
+ * // Sort by most recently disconnected
410
+ * const sorted = Object.entries(connectors)
411
+ * .sort(([,a], [,b]) => b.disconnectedTimestamp - a.disconnectedTimestamp);
412
+ * }
413
+ * ```
332
414
  */
333
- getRecentConnectedWallet: () => RecentConnectedWallet | undefined;
415
+ getRecentlyConnectedConnectorsList: () => RecentlyConnectedConnectorsList | undefined;
334
416
  /**
335
- * Removes the last connected wallet data from localStorage.
417
+ * Adds or updates a single connector in the recently connected connectors list.
418
+ * Preserves existing connectors and only adds/updates the specified one.
336
419
  *
420
+ * @param connectorType - The connector type to add/update
421
+ * @param connectorData - The connector data (address, disconnectedTimestamp, and optional icon)
337
422
  * @returns undefined in SSR context, void in browser
423
+ *
424
+ * @example
425
+ * ```typescript
426
+ * // Add new connector with current timestamp
427
+ * recentlyConnectedConnectorsListHelpers.addConnector('evm:metamask', {
428
+ * address: '0x123...',
429
+ * disconnectedTimestamp: Date.now(),
430
+ * icon: 'metamask.png'
431
+ * });
432
+ *
433
+ * // Update existing connector with new disconnect time
434
+ * recentlyConnectedConnectorsListHelpers.addConnector('evm:metamask', {
435
+ * address: '0x456...',
436
+ * disconnectedTimestamp: Date.now(),
437
+ * icon: 'new-metamask.png'
438
+ * });
439
+ * ```
440
+ */
441
+ addConnector: (connectorType: ConnectorType, connectorData: RecentlyConnectedConnectorData) => undefined;
442
+ /**
443
+ * Removes a single connector from the recently connected connectors list.
444
+ * Preserves all other connectors in the list.
445
+ *
446
+ * @param connectorType - The connector type to remove
447
+ * @returns undefined in SSR context, void in browser
448
+ *
449
+ * @example
450
+ * ```typescript
451
+ * // Remove specific connector
452
+ * recentlyConnectedConnectorsListHelpers.removeConnector('evm:metamask');
453
+ * ```
454
+ */
455
+ removeConnector: (connectorType: ConnectorType) => undefined;
456
+ /**
457
+ * Checks if a specific connector exists in the recently connected connectors list.
458
+ *
459
+ * @param connectorType - The connector type to check
460
+ * @returns true if the connector exists, false otherwise, undefined in SSR context
461
+ *
462
+ * @example
463
+ * ```typescript
464
+ * if (recentlyConnectedConnectorsListHelpers.hasConnector('evm:metamask')) {
465
+ * console.log('MetaMask was recently connected');
466
+ * }
467
+ * ```
468
+ */
469
+ hasConnector: (connectorType: ConnectorType) => boolean | undefined;
470
+ /**
471
+ * Gets data for a specific connector from the recently connected connectors list.
472
+ *
473
+ * @param connectorType - The connector type to get data for
474
+ * @returns The connector data (including address, disconnectedTimestamp, and optional icon) or undefined if not found or in SSR context
475
+ *
476
+ * @example
477
+ * ```typescript
478
+ * const metamaskData = recentlyConnectedConnectorsListHelpers.getConnector('evm:metamask');
479
+ * if (metamaskData) {
480
+ * console.log('MetaMask address:', metamaskData.address);
481
+ * console.log('Disconnected at:', new Date(metamaskData.disconnectedTimestamp));
482
+ * console.log('MetaMask icon:', metamaskData.icon);
483
+ * }
484
+ * ```
485
+ */
486
+ getConnector: (connectorType: ConnectorType) => RecentlyConnectedConnectorData | undefined;
487
+ /**
488
+ * Gets the count of recently connected connectors.
489
+ *
490
+ * @returns Number of connectors in the list, 0 in SSR context or if list is empty
491
+ *
492
+ * @example
493
+ * ```typescript
494
+ * const count = recentlyConnectedConnectorsListHelpers.getConnectorCount();
495
+ * console.log(`${count} connectors recently connected`);
496
+ * ```
497
+ */
498
+ getConnectorCount: () => number;
499
+ /**
500
+ * Gets recently connected connectors sorted by disconnect time (most recent first).
501
+ * Useful for showing connectors in order of recent usage.
502
+ *
503
+ * @returns Array of [ConnectorType, RecentlyConnectedConnectorData] tuples sorted by disconnectedTimestamp (descending), empty array in SSR context
504
+ *
505
+ * @example
506
+ * ```typescript
507
+ * const sortedConnectors = recentlyConnectedConnectorsListHelpers.getConnectorsSortedByTime();
508
+ * sortedConnectors.forEach(([connectorType, data]) => {
509
+ * console.log(`${connectorType}: disconnected ${new Date(data.disconnectedTimestamp)}`);
510
+ * });
511
+ * ```
512
+ */
513
+ getConnectorsSortedByTime: () => [ConnectorType, RecentlyConnectedConnectorData][];
514
+ /**
515
+ * Removes connectors that were disconnected before the specified timestamp.
516
+ * Useful for cleaning up old connector entries.
517
+ *
518
+ * @param beforeTimestamp - Unix timestamp in milliseconds; connectors disconnected before this time will be removed
519
+ * @returns undefined in SSR context, void in browser
520
+ *
521
+ * @example
522
+ * ```typescript
523
+ * // Remove connectors disconnected more than 7 days ago
524
+ * const weekAgo = Date.now() - (7 * 24 * 60 * 60 * 1000);
525
+ * recentlyConnectedConnectorsListHelpers.removeConnectorsOlderThan(weekAgo);
526
+ * ```
527
+ */
528
+ removeConnectorsOlderThan: (beforeTimestamp: number) => undefined;
529
+ /**
530
+ * Removes all recently connected connectors from localStorage.
531
+ *
532
+ * @returns undefined in SSR context, void in browser
533
+ *
534
+ * @example
535
+ * ```typescript
536
+ * // Clear all recently connected connectors
537
+ * recentlyConnectedConnectorsListHelpers.removeRecentlyConnectedConnectorsList();
538
+ * ```
338
539
  */
339
- removeRecentConnectedWallet: () => void;
540
+ removeRecentlyConnectedConnectorsList: () => void;
340
541
  };
341
542
 
342
543
  /**
@@ -406,4 +607,4 @@ declare function isSolanaChain(chainId: number | string): boolean;
406
607
  */
407
608
  declare function setChainId(chainId: number | string): string | number;
408
609
 
409
- export { type BaseAdapter, OrbitAdapter, type OrbitGenericAdapter, type RecentConnectedWallet, type WalletType, delay, filterUniqueByKey, formatWalletChainId, formatWalletName, getAdapterFromWalletType, getParsedStorageItem, getWalletTypeFromConnectorName, impersonatedHelpers, isSafeApp, isSolanaChain, lastConnectedWalletHelpers, recentConnectedWalletHelpers, selectAdapterByKey, setChainId, waitFor };
610
+ export { type BaseAdapter, type ConnectorType, OrbitAdapter, type OrbitGenericAdapter, type RecentlyConnectedConnectorData, type RecentlyConnectedConnectorsList, delay, filterUniqueByKey, formatConnectorChainId, formatConnectorName, getAdapterFromConnectorType, getConnectorTypeFromName, getParsedStorageItem, impersonatedHelpers, isSafeApp, isSolanaChain, lastConnectedConnectorHelpers, recentlyConnectedConnectorsListHelpers, selectAdapterByKey, setChainId, waitFor };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var l=(n=>(n.EVM="evm",n.SOLANA="solana",n.Starknet="starknet",n))(l||{});var c=(e,t)=>new Promise(r=>{let n=()=>{setTimeout(()=>r(e),t);};typeof window<"u"?n():setTimeout(n,0);});function u(e,t){let r=new Set;return e.filter(n=>{let a=n[t];return r.has(a)?false:(r.add(a),true)})}function g(e,t){return typeof e=="string"?`${t}:${e}`:e}var s=new Map([["Impersonated Connector","impersonatedwallet"],["Safe","safewallet"],["Trust","trustwallet"],["Trust Wallet","trustwallet"],["Brave \u041A\u043E\u0448\u0435\u043B\u0435\u043A","bravewallet"],["Brave Wallet","bravewallet"]]),A=e=>s.get(e)??e.replace(/\s+/g,"").toLowerCase();function W(e){return e?.split(":")[0]??"evm"}function o(e){if(typeof window>"u")return;let t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(r){console.error(`Error parsing ${e} from localStorage:`,r);return}}function O(e,t){return `${e}:${t.replace(/\s+/g,"").toLowerCase()}`}var R={impersonatedAddress:typeof window<"u"?window.localStorage.getItem("satellite-connect:impersonatedAddress")??"":"",setImpersonated:e=>typeof window<"u"?window.localStorage.setItem("satellite-connect:impersonatedAddress",e):void 0,getImpersonated:()=>typeof window<"u"?window.localStorage.getItem("satellite-connect:impersonatedAddress"):void 0,removeImpersonated:()=>typeof window<"u"?window.localStorage.removeItem("satellite-connect:impersonatedAddress"):void 0};var v=typeof window<"u"&&window!==window.parent;var i={STORAGE_KEY:"orbit-core:lastConnectedWallet",lastConnectedWallet:o("orbit-core:lastConnectedWallet"),setLastConnectedWallet:({walletType:e,chainId:t,address:r})=>typeof window<"u"?window.localStorage.setItem(i.STORAGE_KEY,JSON.stringify({walletType:e,chainId:t,address:r})):void 0,getLastConnectedWallet:()=>o(i.STORAGE_KEY),removeLastConnectedWallet:()=>typeof window<"u"?window.localStorage.removeItem(i.STORAGE_KEY):void 0};var d={STORAGE_KEY:"orbit-core:recentConnectedWallet",recentConnectedWallet:o("orbit-core:recentConnectedWallets"),setRecentConnectedWallet:e=>typeof window<"u"?window.localStorage.setItem(d.STORAGE_KEY,JSON.stringify(e)):void 0,getRecentConnectedWallet:()=>o(d.STORAGE_KEY),removeRecentConnectedWallet:()=>typeof window<"u"?window.localStorage.removeItem(d.STORAGE_KEY):void 0};var $=({adapterKey:e,adapter:t})=>{if(Array.isArray(t)){if(t.length===0){console.error("Adapter selection failed: The provided adapters array is empty.");return}let r=t.find(n=>n.key===e);return r||(console.warn(`No adapter found for key: "${e}". Falling back to the first available adapter: "${t[0].key}".`),t[0])}return t};async function N(e,t=50,r=200){for(let n=0;n<t;n++){if(e())return;await new Promise(a=>setTimeout(a,r));}throw new Error("Predicate not fulfilled in time")}function p(e){return typeof e=="string"?["devnet","testnet","mainnet-beta","mainnet"].includes(e):false}function h(e){return p(e)?`solana:${e}`:e}exports.OrbitAdapter=l;exports.delay=c;exports.filterUniqueByKey=u;exports.formatWalletChainId=g;exports.formatWalletName=A;exports.getAdapterFromWalletType=W;exports.getParsedStorageItem=o;exports.getWalletTypeFromConnectorName=O;exports.impersonatedHelpers=R;exports.isSafeApp=v;exports.isSolanaChain=p;exports.lastConnectedWalletHelpers=i;exports.recentConnectedWalletHelpers=d;exports.selectAdapterByKey=$;exports.setChainId=h;exports.waitFor=N;//# sourceMappingURL=index.js.map
1
+ 'use strict';var c=(r=>(r.EVM="evm",r.SOLANA="solana",r.Starknet="starknet",r))(c||{});var p=(e,t)=>new Promise(n=>{let r=()=>{setTimeout(()=>n(e),t);};typeof window<"u"?r():setTimeout(r,0);});function m(e,t){let n=new Set;return e.filter(r=>{let s=r[t];return n.has(s)?false:(n.add(s),true)})}function y(e,t){return typeof e=="string"?`${t}:${e}`:e}var a=new Map([["Impersonated Connector","impersonatedwallet"],["Safe","safewallet"],["Trust","trustwallet"],["Trust Wallet","trustwallet"],["Brave \u041A\u043E\u0448\u0435\u043B\u0435\u043A","bravewallet"],["Brave Wallet","bravewallet"],["Base Account","coinbasewallet"]]),g=e=>a.get(e)??e.replace(/\s+/g,"").toLowerCase();function S(e){return e?.split(":")[0]??"evm"}function x(e,t){return `${e}:${t.replace(/\s+/g,"").toLowerCase()}`}function i(e){if(typeof window>"u")return;let t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(n){console.error(`Error parsing ${e} from localStorage:`,n);return}}var E={impersonatedAddress:typeof window<"u"?window.localStorage.getItem("satellite-connect:impersonatedAddress")??"":"",setImpersonated:e=>typeof window<"u"?window.localStorage.setItem("satellite-connect:impersonatedAddress",e):void 0,getImpersonated:()=>typeof window<"u"?window.localStorage.getItem("satellite-connect:impersonatedAddress"):void 0,removeImpersonated:()=>typeof window<"u"?window.localStorage.removeItem("satellite-connect:impersonatedAddress"):void 0};var v=typeof window<"u"&&window!==window.parent;var d={STORAGE_KEY:"orbit-core:lastConnectedConnector",lastConnectedConnector:i("orbit-core:lastConnectedConnector"),setLastConnectedConnector:({connectorType:e,chainId:t,address:n})=>typeof window<"u"?window.localStorage.setItem(d.STORAGE_KEY,JSON.stringify({connectorType:e,chainId:t,address:n})):void 0,getLastConnectedConnector:()=>i(d.STORAGE_KEY),removeLastConnectedConnector:()=>typeof window<"u"?window.localStorage.removeItem(d.STORAGE_KEY):void 0};var o={STORAGE_KEY:"orbit-core:recentlyConnectedConnectorsListHelpers",recentlyConnectedConnectorsList:i("orbit-core:recentlyConnectedConnectorsListHelpers"),setRecentlyConnectedConnectorsList:e=>typeof window<"u"?window.localStorage.setItem(o.STORAGE_KEY,JSON.stringify(e)):void 0,getRecentlyConnectedConnectorsList:()=>i(o.STORAGE_KEY),addConnector:(e,t)=>{if(typeof window>"u")return;let r={...o.getRecentlyConnectedConnectorsList()||{},[e]:t};window.localStorage.setItem(o.STORAGE_KEY,JSON.stringify(r));},removeConnector:e=>{if(typeof window>"u")return;let t=o.getRecentlyConnectedConnectorsList();if(!t||!(e in t))return;let{[e]:n,...r}=t;window.localStorage.setItem(o.STORAGE_KEY,JSON.stringify(r));},hasConnector:e=>{if(typeof window>"u")return;let t=o.getRecentlyConnectedConnectorsList();return t?e in t:false},getConnector:e=>typeof window>"u"?void 0:o.getRecentlyConnectedConnectorsList()?.[e],getConnectorCount:()=>{if(typeof window>"u")return 0;let e=o.getRecentlyConnectedConnectorsList();return e?Object.keys(e).length:0},getConnectorsSortedByTime:()=>{if(typeof window>"u")return [];let e=o.getRecentlyConnectedConnectorsList();return e?Object.entries(e).sort(([,t],[,n])=>n.disconnectedTimestamp-t.disconnectedTimestamp):[]},removeConnectorsOlderThan:e=>{if(typeof window>"u")return;let t=o.getRecentlyConnectedConnectorsList();if(!t)return;let n=Object.fromEntries(Object.entries(t).filter(([,r])=>r.disconnectedTimestamp>=e));window.localStorage.setItem(o.STORAGE_KEY,JSON.stringify(n));},removeRecentlyConnectedConnectorsList:()=>typeof window<"u"?window.localStorage.removeItem(o.STORAGE_KEY):void 0};var k=({adapterKey:e,adapter:t})=>{if(Array.isArray(t)){if(t.length===0){console.error("Adapter selection failed: The provided adapters array is empty.");return}let n=t.find(r=>r.key===e);return n||(console.warn(`No adapter found for key: "${e}". Falling back to the first available adapter: "${t[0].key}".`),t[0])}return t};async function $(e,t=50,n=200){for(let r=0;r<t;r++){if(e())return;await new Promise(s=>setTimeout(s,n));}throw new Error("Predicate not fulfilled in time")}function f(e){return typeof e=="string"?["devnet","testnet","mainnet-beta","mainnet"].includes(e):false}function B(e){return f(e)?`solana:${e}`:e}exports.OrbitAdapter=c;exports.delay=p;exports.filterUniqueByKey=m;exports.formatConnectorChainId=y;exports.formatConnectorName=g;exports.getAdapterFromConnectorType=S;exports.getConnectorTypeFromName=x;exports.getParsedStorageItem=i;exports.impersonatedHelpers=E;exports.isSafeApp=v;exports.isSolanaChain=f;exports.lastConnectedConnectorHelpers=d;exports.recentlyConnectedConnectorsListHelpers=o;exports.selectAdapterByKey=k;exports.setChainId=B;exports.waitFor=$;//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts","../src/utils/delay.ts","../src/utils/filterUniqueByKey.ts","../src/utils/formatWalletChainId.ts","../src/utils/formatWalletName.ts","../src/utils/getAdapterFromWalletType.ts","../src/utils/getParsedStorageItem.ts","../src/utils/getWalletTypeFromConnectorName.ts","../src/utils/impersonatedHelpers.ts","../src/utils/isSafeApp.ts","../src/utils/lastConnectedWalletHelpers.ts","../src/utils/recentConnectedWalletHelpers.ts","../src/utils/selectAdapterByKey.ts","../src/utils/waitFor.ts","../src/utils/%D1%81hainHelpers.ts"],"names":["OrbitAdapter","delay","value","ms","resolve","runTimeout","filterUniqueByKey","array","key","seenValues","item","keyValue","formatWalletChainId","chainId","connectedAdapter","WALLET_MAPPINGS","formatWalletName","walletName","getAdapterFromWalletType","walletType","getParsedStorageItem","error","getWalletTypeFromConnectorName","adapter","name","impersonatedHelpers","address","isSafeApp","lastConnectedWalletHelpers","recentConnectedWalletHelpers","wallets","selectAdapterByKey","adapterKey","foundAdapter","a","waitFor","predicate","maxChecks","checkIntervalMs","i","isSolanaChain","setChainId"],"mappings":"aAgCO,IAAKA,CAAAA,CAAAA,CAAAA,CAAAA,GAUVA,CAAAA,CAAA,GAAA,CAAM,KAAA,CASNA,CAAAA,CAAA,MAAA,CAAS,QAAA,CASTA,CAAAA,CAAA,QAAA,CAAW,UAAA,CA5BDA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAAA,ECHL,IAAMC,EAAQ,CAAIC,CAAAA,CAAUC,CAAAA,GAC1B,IAAI,OAAA,CAASC,CAAAA,EAAY,CAC9B,IAAMC,CAAAA,CAAa,IAAM,CACvB,UAAA,CAAW,IAAMD,CAAAA,CAAQF,CAAK,CAAA,CAAGC,CAAE,EACrC,CAAA,CAEI,OAAO,MAAA,CAAW,GAAA,CACpBE,CAAAA,EAAW,CAEX,UAAA,CAAWA,CAAAA,CAAY,CAAC,EAE5B,CAAC,EC5BI,SAASC,CAAAA,CAAqBC,CAAAA,CAAYC,CAAAA,CAAmB,CAGlE,IAAMC,CAAAA,CAAa,IAAI,GAAA,CAGvB,OAAOF,CAAAA,CAAM,MAAA,CAAQG,CAAAA,EAAS,CAE5B,IAAMC,EAAWD,CAAAA,CAAKF,CAAG,CAAA,CAGzB,OAAIC,CAAAA,CAAW,GAAA,CAAIE,CAAQ,CAAA,CAGlB,KAAA,EAGPF,CAAAA,CAAW,GAAA,CAAIE,CAAQ,CAAA,CAEhB,IAAA,CAEX,CAAC,CACH,CChCO,SAASC,CAAAA,CAAoBC,CAAAA,CAA0BC,CAAAA,CAAgC,CAC5F,OAAI,OAAOD,CAAAA,EAAY,QAAA,CACd,CAAA,EAAGC,CAAgB,CAAA,CAAA,EAAID,CAAO,CAAA,CAAA,CAE9BA,CAEX,CCRA,IAAME,CAAAA,CAAkB,IAAI,GAAA,CAAI,CAC9B,CAAC,wBAAA,CAA0B,oBAAoB,CAAA,CAC/C,CAAC,MAAA,CAA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D,CCLO,SAASE,EAAc3B,CAAAA,CAAmC,CAC/D,OAAI,OAAOA,CAAAA,EAAY,QAAA,CACd,CAAC,QAAA,CAAU,SAAA,CAAW,cAAA,CAAgB,SAAS,CAAA,CAAE,QAAA,CAASA,CAAO,CAAA,CAEnE,KACT,CAQO,SAAS4B,CAAAA,CAAW5B,CAAAA,CAA2C,CACpE,OAAI2B,CAAAA,CAAc3B,CAAO,CAAA,CAChB,CAAA,OAAA,EAAUA,CAAO,CAAA,CAAA,CAEjBA,CAEX","file":"index.js","sourcesContent":["/**\n * @file\n * Core type definitions for the Orbit blockchain adapter system.\n * This file contains fundamental enums and types that define the supported blockchain architectures\n * and their adapter interfaces.\n */\n\n// =================================================================================================\n// 1. ENUMS AND CORE TRANSACTION TYPES\n// =================================================================================================\n\n/**\n * Defines the supported blockchain adapters in the Orbit system.\n * Each adapter corresponds to a specific blockchain architecture and implements\n * the necessary interfaces for that chain's functionality.\n *\n * @enum {string}\n *\n * @example\n * ```typescript\n * // Using adapter types in configuration\n * const config = {\n * chainType: OrbitAdapter.EVM,\n * // other configuration...\n * };\n *\n * // Checking adapter compatibility\n * if (chainType === OrbitAdapter.SOLANA) {\n * // Solana-specific logic\n * }\n * ```\n */\nexport enum OrbitAdapter {\n /**\n * For Ethereum Virtual Machine (EVM) compatible chains.\n * Supports networks like:\n * - Ethereum Mainnet\n * - Polygon\n * - Binance Smart Chain\n * - Avalanche\n * - Other EVM-compatible L1/L2 chains\n */\n EVM = 'evm',\n\n /**\n * For the Solana blockchain.\n * Supports:\n * - Solana Mainnet\n * - Devnet\n * - Testnet\n */\n SOLANA = 'solana',\n\n /**\n * For the Starknet L2 network.\n * Supports:\n * - Starknet Mainnet\n * - Testnet (Goerli)\n * - Other Starknet deployments\n */\n Starknet = 'starknet',\n}\n\n/**\n * Generic type for creating blockchain adapters with type safety.\n * This type ensures that all adapters implement the required interface\n * and are properly keyed by their blockchain type.\n *\n * @typeParam A - Type that extends the base adapter interface with a key property\n *\n * @property {A | A[]} adapter - Single adapter instance or array of adapters\n *\n * @example\n * ```typescript\n * // Single adapter implementation\n * interface EVMAdapter extends BaseAdapter {\n * key: OrbitAdapter.EVM;\n * // EVM-specific methods...\n * }\n * const evmConfig: OrbitGenericAdapter<EVMAdapter> = {\n * adapter: {\n * key: OrbitAdapter.EVM,\n * // implementation...\n * }\n * };\n *\n * // Multiple adapters\n * const multiChainConfig: OrbitGenericAdapter<EVMAdapter> = {\n * adapter: [\n * { key: OrbitAdapter.EVM, ... },\n * { key: OrbitAdapter.SOLANA, ... }\n * ]\n * };\n * ```\n */\nexport type OrbitGenericAdapter<A extends { key: OrbitAdapter }> = {\n adapter: A | A[];\n};\n\nexport type BaseAdapter = {\n /**\n * Generates blockchain explorer URL\n * @returns Explorer URL or undefined if not available\n */\n getExplorerUrl: (url?: string, chainId?: string | number) => string | undefined;\n\n /** Optional method to resolve ENS-like names */\n getName?: (address: string) => Promise<string | null>;\n\n /** Optional method to get avatar for resolved names */\n getAvatar?: (name: string) => Promise<string | null>;\n};\n\n/**\n * Type representing a wallet identifier in format \"OrbitAdapter:wallet\"\n * @example \"evm:metamask\" | \"solana:phantom\"\n */\nexport type WalletType = `${OrbitAdapter}:${string}`;\n","/**\n * @name delay\n *\n * Ensures the global 'window' object is available (if running in a browser-like environment),\n * then pauses execution for a specified duration, and finally resolves the Promise with the given value.\n *\n * This utility function is designed to be safe for use in Server-Side Rendering (SSR) environments.\n * It asynchronously waits for the 'window' object to be defined before starting the actual timer,\n * helping to prevent errors during the initial server render while still providing a time delay on the client.\n *\n * @template T - The type of the value being resolved.\n *\n * @param {T} value - The value to resolve the Promise with after the delay.\n * @param {number} ms - The number of milliseconds (delay) to wait before resolving the Promise after 'window' is available.\n *\n * @returns {Promise<T>} A Promise that resolves with the provided `value` after both the 'window' check and the delay (`ms`) are complete.\n *\n * @example\n * ```typescript\n * // Use this in an environment where 'window' might not be immediately available (e.g., Next.js component).\n * async function waitForWindowAndDelay() {\n * console.log(\"Start wait...\");\n * // This will wait for window, and then wait 100ms.\n * const data = await delay(\"Ready to connect\", 100);\n * console.log(data);\n * }\n * waitForWindowAndDelay();\n * ```\n */\nexport const delay = <T>(value: T, ms: number): Promise<T> => {\n return new Promise((resolve) => {\n const runTimeout = () => {\n setTimeout(() => resolve(value), ms);\n };\n\n if (typeof window !== 'undefined') {\n runTimeout();\n } else {\n setTimeout(runTimeout, 0);\n }\n });\n};\n","/**\n * Filters an array of objects to keep only the first occurrence of an object\n * based on a unique value of a specified key.\n *\n * This function is generic and type-safe. It iterates through the array and uses a\n * Set to track already encountered key values, effectively removing duplicates.\n *\n * @template T The type of the objects in the array.\n * @param {T[]} array - The array of objects to be filtered.\n * @param {keyof T} key - The object key (property name) whose values must be unique.\n * @returns {T[]} The filtered array containing only objects with unique key values.\n */\nexport function filterUniqueByKey<T>(array: T[], key: keyof T): T[] {\n // 1. Create a Set to store the unique values of the key encountered so far.\n // Set is a collection of unique values, which is perfect for fast duplicate checks.\n const seenValues = new Set<T[keyof T]>();\n\n // 2. Use the native Array.prototype.filter() method to create a new, filtered array.\n return array.filter((item) => {\n // Access the value of the specified key from the current object.\n const keyValue = item[key];\n\n // 3. Check if this key value has been seen before.\n if (seenValues.has(keyValue)) {\n // If the value is already in the Set, return false.\n // This object is a duplicate and will be excluded from the result.\n return false;\n } else {\n // If the value is encountered for the first time, add it to the Set.\n seenValues.add(keyValue);\n // Return true to include the object in the resulting unique array.\n return true;\n }\n });\n}\n","import { OrbitAdapter } from '../types';\n\nexport function formatWalletChainId(chainId: string | number, connectedAdapter: OrbitAdapter) {\n if (typeof chainId === 'string') {\n return `${connectedAdapter}:${chainId}`;\n } else {\n return chainId;\n }\n}\n","const WALLET_MAPPINGS = new Map([\n ['Impersonated Connector', 'impersonatedwallet'],\n ['Safe', 'safewallet'],\n ['Trust', 'trustwallet'],\n ['Trust Wallet', 'trustwallet'],\n ['Brave Кошелек', 'bravewallet'],\n ['Brave Wallet', 'bravewallet'],\n]);\n\nexport const formatWalletName = (walletName: string): string => {\n return WALLET_MAPPINGS.get(walletName) ?? walletName.replace(/\\s+/g, '').toLowerCase();\n};\n","import { OrbitAdapter, WalletType } from '../types';\n\n/**\n * Extracts the adapter type from a wallet type string\n *\n * @example\n * ```typescript\n * // Returns OrbitAdapter.EVM\n * getAdapterFromWalletType('evm:metamask');\n *\n * // Returns OrbitAdapter.SOLANA\n * getAdapterFromWalletType('solana:phantom');\n *\n * // Returns OrbitAdapter.EVM (default)\n * getAdapterFromWalletType('unknown');\n * ```\n *\n * @param walletType - Wallet type in format \"chain:wallet\" (e.g. \"evm:metamask\", \"solana:phantom\")\n * @returns The corresponding {@link OrbitAdapter} type or EVM as default\n *\n * @remarks\n * The function splits the wallet type string by \":\" and takes the first part as the adapter type.\n * If the split fails or the first part is empty, it defaults to EVM adapter.\n */\nexport function getAdapterFromWalletType(walletType: WalletType): OrbitAdapter {\n return (walletType?.split(':')[0] as OrbitAdapter.EVM) ?? OrbitAdapter.EVM;\n}\n","/**\n * Internal function for safely retrieving and parsing data from localStorage.\n *\n * @param key - The key for localStorage\n * @returns The parsed LastConnectedWallet object or undefined if data is not found/invalid\n */\nexport function getParsedStorageItem<ReturnType>(key: string): ReturnType | undefined {\n if (typeof window === 'undefined') {\n return undefined;\n }\n\n const item = window.localStorage.getItem(key);\n\n // If the item is null (not set) or an empty string, return undefined\n if (!item) {\n return undefined;\n }\n\n try {\n // Safe JSON parsing\n return JSON.parse(item) as ReturnType;\n } catch (error) {\n // In case of a parsing error (e.g., invalid JSON), log the error and return undefined\n console.error(`Error parsing ${key} from localStorage:`, error);\n return undefined;\n }\n}\n","import { OrbitAdapter } from '../types';\n\n/**\n * Generates a standardized wallet type identifier from adapter type and connector name\n *\n * @example\n * ```typescript\n * // Returns \"evm:metamask\"\n * getWalletTypeFromConnectorName(OrbitAdapter.EVM, \"MetaMask\");\n *\n * // Returns \"solana:phantom\"\n * getWalletTypeFromConnectorName(OrbitAdapter.SOLANA, \"Phantom\");\n *\n * // Returns \"evm:coinbasewallet\" (removes spaces)\n * getWalletTypeFromConnectorName(OrbitAdapter.EVM, \"Coinbase Wallet\");\n * ```\n *\n * @param adapter - The blockchain adapter type (e.g. EVM, SOLANA)\n * @param name - The wallet connector name (e.g. \"MetaMask\", \"Phantom\")\n * @returns A formatted wallet type string in format \"chain:wallet\"\n *\n * @remarks\n * The function:\n * 1. Combines adapter type with connector name using \":\" as separator\n * 2. Removes all whitespace from connector name\n * 3. Converts connector name to lowercase\n * This ensures consistent wallet type identifiers across the application\n */\nexport function getWalletTypeFromConnectorName(adapter: OrbitAdapter, name: string): string {\n return `${adapter}:${name.replace(/\\s+/g, '').toLowerCase()}`;\n}\n","/**\n * Helper utilities for managing impersonated wallet addresses\n *\n * @remarks\n * These utilities are primarily used for development and testing purposes.\n * They provide a way to simulate different wallet addresses without actually connecting a wallet.\n * All data is stored in localStorage with the 'satellite-connect:impersonatedAddress' key.\n * Functions are safe to use in both browser and SSR environments.\n */\nexport const impersonatedHelpers = {\n /**\n * Currently impersonated address from localStorage\n * Returns empty string if not set or in SSR context\n */\n impersonatedAddress:\n typeof window !== 'undefined' ? (window.localStorage.getItem('satellite-connect:impersonatedAddress') ?? '') : '',\n\n /**\n * Stores an impersonated address in localStorage\n *\n * @example\n * ```typescript\n * // Set impersonated address\n * impersonatedHelpers.setImpersonated('0x1234...5678');\n * ```\n *\n * @param address - Ethereum or Solana address to impersonate\n * @returns undefined in SSR context, void in browser\n */\n setImpersonated: (address: string) =>\n typeof window !== 'undefined'\n ? window.localStorage.setItem('satellite-connect:impersonatedAddress', address)\n : undefined,\n\n /**\n * Retrieves the current impersonated address from localStorage\n *\n * @example\n * ```typescript\n * // Get current impersonated address\n * const address = impersonatedHelpers.getImpersonated();\n * if (address) {\n * console.log('Currently impersonating:', address);\n * }\n * ```\n * @returns The impersonated address or undefined if not set or in SSR context\n */\n getImpersonated: () =>\n typeof window !== 'undefined' ? window.localStorage.getItem('satellite-connect:impersonatedAddress') : undefined,\n\n removeImpersonated: () =>\n typeof window !== 'undefined' ? window.localStorage.removeItem('satellite-connect:impersonatedAddress') : undefined,\n};\n","export const isSafeApp = typeof window !== 'undefined' && window !== window.parent;\n","import { WalletType } from '../types';\nimport { getParsedStorageItem } from './getParsedStorageItem';\n\ntype LastConnectedWallet = { walletType: WalletType; chainId: number | string; address?: string };\n\n/**\n * Helper utilities for managing the last connected wallet state\n *\n * @remarks\n * All data is stored in localStorage with the 'orbit-core:lastConnectedWallet' key.\n * Functions are safe to use in both browser and SSR environments.\n */\nexport const lastConnectedWalletHelpers = {\n // Key used for localStorage\n STORAGE_KEY: 'orbit-core:lastConnectedWallet',\n\n /**\n * The value of the last connected wallet, initialized when the module loads.\n * Returns undefined if not set, invalid, or in an SSR context.\n */\n lastConnectedWallet: getParsedStorageItem<LastConnectedWallet>('orbit-core:lastConnectedWallet'),\n\n /**\n * Stores the last connected wallet data in localStorage.\n *\n * @param data - Object containing the wallet type and chain ID.\n * @returns undefined in SSR context, void in browser\n */\n setLastConnectedWallet: ({ walletType, chainId, address }: LastConnectedWallet) =>\n typeof window !== 'undefined'\n ? window.localStorage.setItem(\n lastConnectedWalletHelpers.STORAGE_KEY,\n JSON.stringify({ walletType, chainId, address }),\n )\n : undefined,\n\n /**\n * Retrieves the current last connected wallet data from localStorage.\n *\n * @returns The LastConnectedWallet object or undefined if not set or in SSR context\n */\n getLastConnectedWallet: () => getParsedStorageItem<LastConnectedWallet>(lastConnectedWalletHelpers.STORAGE_KEY),\n\n /**\n * Removes the last connected wallet data from localStorage.\n *\n * @returns undefined in SSR context, void in browser\n */\n removeLastConnectedWallet: () =>\n typeof window !== 'undefined' ? window.localStorage.removeItem(lastConnectedWalletHelpers.STORAGE_KEY) : undefined,\n};\n","import { OrbitAdapter } from '../types';\nimport { getParsedStorageItem } from './getParsedStorageItem';\n\nexport type RecentConnectedWallet = Record<OrbitAdapter, Record<string, boolean>>;\n\n/**\n * Helper utilities for managing the last connected wallet state\n *\n * @remarks\n * All data is stored in localStorage with the 'orbit-core:lastConnectedWallet' key.\n * Functions are safe to use in both browser and SSR environments.\n */\nexport const recentConnectedWalletHelpers = {\n // Key used for localStorage\n STORAGE_KEY: 'orbit-core:recentConnectedWallet',\n\n /**\n * The value of the last connected wallet, initialized when the module loads.\n * Returns undefined if not set, invalid, or in an SSR context.\n */\n recentConnectedWallet: getParsedStorageItem<RecentConnectedWallet>('orbit-core:recentConnectedWallets'),\n\n /**\n * Stores the last connected wallet data in localStorage.\n *\n * @param wallets - RecentConnectedWallet\n * @returns undefined in SSR context, void in browser\n */\n setRecentConnectedWallet: (wallets: RecentConnectedWallet) =>\n typeof window !== 'undefined'\n ? window.localStorage.setItem(recentConnectedWalletHelpers.STORAGE_KEY, JSON.stringify(wallets))\n : undefined,\n\n /**\n * Retrieves the current last connected wallet data from localStorage.\n *\n * @returns The LastConnectedWallet object or undefined if not set or in SSR context\n */\n getRecentConnectedWallet: () => getParsedStorageItem<RecentConnectedWallet>(recentConnectedWalletHelpers.STORAGE_KEY),\n\n /**\n * Removes the last connected wallet data from localStorage.\n *\n * @returns undefined in SSR context, void in browser\n */\n removeRecentConnectedWallet: () =>\n typeof window !== 'undefined'\n ? window.localStorage.removeItem(recentConnectedWalletHelpers.STORAGE_KEY)\n : undefined,\n};\n","/**\n * @file\n * This module provides adapter selection functionality for the Orbit system.\n * Part of the core infrastructure for managing blockchain adapters.\n */\n\nimport { OrbitAdapter, OrbitGenericAdapter } from '../types';\n\n/**\n * Selects an appropriate adapter based on the provided key from either a single adapter\n * or an array of adapters.\n *\n * @typeParam A - Type extending basic adapter interface with a key property\n *\n * @param options - Selection configuration object\n * @param options.adapterKey - Target adapter key to search for\n * @param options.adapter - Single adapter or array of adapters to search within\n *\n * @returns Selected adapter or undefined if no suitable adapter found\n *\n * @remarks\n * If an array is provided but no matching adapter is found, falls back to the first adapter\n * in the array with a warning message.\n *\n * @example\n * ```typescript\n * // Single adapter usage\n * const singleResult = selectAdapterByKey({\n * adapterKey: OrbitAdapter.SOLANA,\n * adapter: { key: OrbitAdapter.SOLANA, connect: async () => {...} }\n * });\n *\n * // Multiple adapters usage\n * const multiResult = selectAdapterByKey({\n * adapterKey: OrbitAdapter.EVM,\n * adapter: [\n * { key: OrbitAdapter.SOLANA, connect: async () => {...} },\n * { key: OrbitAdapter.EVM, connect: async () => {...} }\n * ]\n * });\n * ```\n *\n * @throws {Error} Logs error if adapter array is empty\n * @throws {Warning} Logs warning if requested adapter key not found in array\n */\nexport const selectAdapterByKey = <A extends { key: OrbitAdapter }>({\n adapterKey,\n adapter,\n}: { adapterKey: OrbitAdapter } & OrbitGenericAdapter<A>): A | undefined => {\n if (Array.isArray(adapter)) {\n if (adapter.length === 0) {\n console.error('Adapter selection failed: The provided adapters array is empty.');\n return undefined;\n }\n\n const foundAdapter = adapter.find((a) => a.key === adapterKey);\n\n if (foundAdapter) {\n return foundAdapter;\n } else {\n console.warn(\n `No adapter found for key: \"${adapterKey}\". Falling back to the first available adapter: \"${adapter[0].key}\".`,\n );\n return adapter[0];\n }\n }\n return adapter;\n};\n","export async function waitFor(\n predicate: () => boolean | undefined,\n maxChecks: number = 50,\n checkIntervalMs: number = 200,\n) {\n for (let i = 0; i < maxChecks; i++) {\n if (predicate()) {\n return;\n }\n await new Promise((resolve) => setTimeout(resolve, checkIntervalMs));\n }\n throw new Error('Predicate not fulfilled in time');\n}\n","/**\n * Checks whether the given chain ID belongs to a Solana network.\n * Supports common Solana network names: 'devnet', 'testnet', 'mainnet-beta', 'mainnet'.\n *\n * @param {number | string} chainId - The chain ID or chain name.\n * @returns {boolean} - True if the chain ID corresponds to a Solana network, false otherwise.\n */\nexport function isSolanaChain(chainId: number | string): boolean {\n if (typeof chainId === 'string') {\n return ['devnet', 'testnet', 'mainnet-beta', 'mainnet'].includes(chainId);\n }\n return false;\n}\n\n/**\n * Sets the chain ID to a Solana-specific format if the chain is a Solana network.\n *\n * @param {number | string} chainId - The original chain ID or name.\n * @returns {string | number} - The formatted chain ID prefixed with 'solana:' if Solana, otherwise the original.\n */\nexport function setChainId(chainId: number | string): string | number {\n if (isSolanaChain(chainId)) {\n return `solana:${chainId}`;\n } else {\n return chainId;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/types.ts","../src/utils/delay.ts","../src/utils/filterUniqueByKey.ts","../src/utils/formatConnectorChainId.ts","../src/utils/formatConnectorName.ts","../src/utils/getAdapterFromConnectorType.ts","../src/utils/getConnectorTypeFromName.ts","../src/utils/getParsedStorageItem.ts","../src/utils/impersonatedHelpers.ts","../src/utils/isSafeApp.ts","../src/utils/lastConnectedConnectorHelpers.ts","../src/utils/recentlyConnectedConnectorsListHelpers.ts","../src/utils/selectAdapterByKey.ts","../src/utils/waitFor.ts","../src/utils/%D1%81hainHelpers.ts"],"names":["OrbitAdapter","delay","value","ms","resolve","runTimeout","filterUniqueByKey","array","key","seenValues","item","keyValue","formatConnectorChainId","chainId","connectedAdapter","CONNECTOR_MAPPINGS","formatConnectorName","connectorName","getAdapterFromConnectorType","connectorType","getConnectorTypeFromName","adapter","name","getParsedStorageItem","error","impersonatedHelpers","address","isSafeApp","lastConnectedConnectorHelpers","recentlyConnectedConnectorsListHelpers","connectors","connectorData","updatedList","currentList","_","remainingConnectors","a","b","beforeTimestamp","filteredList","data","selectAdapterByKey","adapterKey","foundAdapter","waitFor","predicate","maxChecks","checkIntervalMs","i","isSolanaChain","setChainId"],"mappings":"aAgCO,IAAKA,OAUVA,CAAAA,CAAA,GAAA,CAAM,MASNA,CAAAA,CAAA,MAAA,CAAS,SASTA,CAAAA,CAAA,QAAA,CAAW,UAAA,CA5BDA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,ICHL,IAAMC,CAAAA,CAAQ,CAAIC,CAAAA,CAAUC,CAAAA,GAC1B,IAAI,OAAA,CAASC,CAAAA,EAAY,CAC9B,IAAMC,EAAa,IAAM,CACvB,WAAW,IAAMD,CAAAA,CAAQF,CAAK,CAAA,CAAGC,CAAE,EACrC,CAAA,CAEI,OAAO,MAAA,CAAW,GAAA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A,OAAA,EAAUA,CAAO,GAEjBA,CAEX","file":"index.js","sourcesContent":["/**\n * @file\n * Core type definitions for the Orbit blockchain adapter system.\n * This file contains fundamental enums and types that define the supported blockchain architectures\n * and their adapter interfaces.\n */\n\n// =================================================================================================\n// 1. ENUMS AND CORE TRANSACTION TYPES\n// =================================================================================================\n\n/**\n * Defines the supported blockchain adapters in the Orbit system.\n * Each adapter corresponds to a specific blockchain architecture and implements\n * the necessary interfaces for that chain's functionality.\n *\n * @enum {string}\n *\n * @example\n * ```typescript\n * // Using adapter types in configuration\n * const config = {\n * chainType: OrbitAdapter.EVM,\n * // other configuration...\n * };\n *\n * // Checking adapter compatibility\n * if (chainType === OrbitAdapter.SOLANA) {\n * // Solana-specific logic\n * }\n * ```\n */\nexport enum OrbitAdapter {\n /**\n * For Ethereum Virtual Machine (EVM) compatible chains.\n * Supports networks like:\n * - Ethereum Mainnet\n * - Polygon\n * - Binance Smart Chain\n * - Avalanche\n * - Other EVM-compatible L1/L2 chains\n */\n EVM = 'evm',\n\n /**\n * For the Solana blockchain.\n * Supports:\n * - Solana Mainnet\n * - Devnet\n * - Testnet\n */\n SOLANA = 'solana',\n\n /**\n * For the Starknet L2 network.\n * Supports:\n * - Starknet Mainnet\n * - Testnet (Goerli)\n * - Other Starknet deployments\n */\n Starknet = 'starknet',\n}\n\n/**\n * Generic type for creating blockchain adapters with type safety.\n * This type ensures that all adapters implement the required interface\n * and are properly keyed by their blockchain type.\n *\n * @typeParam A - Type that extends the base adapter interface with a key property\n *\n * @property {A | A[]} adapter - Single adapter instance or array of adapters\n *\n * @example\n * ```typescript\n * // Single adapter implementation\n * interface EVMAdapter extends BaseAdapter {\n * key: OrbitAdapter.EVM;\n * // EVM-specific methods...\n * }\n * const evmConfig: OrbitGenericAdapter<EVMAdapter> = {\n * adapter: {\n * key: OrbitAdapter.EVM,\n * // implementation...\n * }\n * };\n *\n * // Multiple adapters\n * const multiChainConfig: OrbitGenericAdapter<EVMAdapter> = {\n * adapter: [\n * { key: OrbitAdapter.EVM, ... },\n * { key: OrbitAdapter.SOLANA, ... }\n * ]\n * };\n * ```\n */\nexport type OrbitGenericAdapter<A extends { key: OrbitAdapter }> = {\n adapter: A | A[];\n};\n\nexport type BaseAdapter = {\n /**\n * Generates blockchain explorer URL\n * @returns Explorer URL or undefined if not available\n */\n getExplorerUrl: (url?: string, chainId?: string | number) => string | undefined;\n\n /** Optional method to resolve ENS-like names */\n getName?: (address: string) => Promise<string | null>;\n\n /** Optional method to get avatar for resolved names */\n getAvatar?: (name: string) => Promise<string | null>;\n\n /** Optional method to resolve names to addresses */\n getAddress?: (name: string) => Promise<string | null>;\n};\n\n/**\n * Type representing a connector identifier in format \"OrbitAdapter:connector\"\n * @example \"evm:metamask\" | \"solana:phantom\"\n */\nexport type ConnectorType = `${OrbitAdapter}:${string}`;\n","/**\n * @name delay\n *\n * Ensures the global 'window' object is available (if running in a browser-like environment),\n * then pauses execution for a specified duration, and finally resolves the Promise with the given value.\n *\n * This utility function is designed to be safe for use in Server-Side Rendering (SSR) environments.\n * It asynchronously waits for the 'window' object to be defined before starting the actual timer,\n * helping to prevent errors during the initial server render while still providing a time delay on the client.\n *\n * @template T - The type of the value being resolved.\n *\n * @param {T} value - The value to resolve the Promise with after the delay.\n * @param {number} ms - The number of milliseconds (delay) to wait before resolving the Promise after 'window' is available.\n *\n * @returns {Promise<T>} A Promise that resolves with the provided `value` after both the 'window' check and the delay (`ms`) are complete.\n *\n * @example\n * ```typescript\n * // Use this in an environment where 'window' might not be immediately available (e.g., Next.js component).\n * async function waitForWindowAndDelay() {\n * console.log(\"Start wait...\");\n * // This will wait for window, and then wait 100ms.\n * const data = await delay(\"Ready to connect\", 100);\n * console.log(data);\n * }\n * waitForWindowAndDelay();\n * ```\n */\nexport const delay = <T>(value: T, ms: number): Promise<T> => {\n return new Promise((resolve) => {\n const runTimeout = () => {\n setTimeout(() => resolve(value), ms);\n };\n\n if (typeof window !== 'undefined') {\n runTimeout();\n } else {\n setTimeout(runTimeout, 0);\n }\n });\n};\n","/**\n * Filters an array of objects to keep only the first occurrence of an object\n * based on a unique value of a specified key.\n *\n * This function is generic and type-safe. It iterates through the array and uses a\n * Set to track already encountered key values, effectively removing duplicates.\n *\n * @template T The type of the objects in the array.\n * @param {T[]} array - The array of objects to be filtered.\n * @param {keyof T} key - The object key (property name) whose values must be unique.\n * @returns {T[]} The filtered array containing only objects with unique key values.\n */\nexport function filterUniqueByKey<T>(array: T[], key: keyof T): T[] {\n // 1. Create a Set to store the unique values of the key encountered so far.\n // Set is a collection of unique values, which is perfect for fast duplicate checks.\n const seenValues = new Set<T[keyof T]>();\n\n // 2. Use the native Array.prototype.filter() method to create a new, filtered array.\n return array.filter((item) => {\n // Access the value of the specified key from the current object.\n const keyValue = item[key];\n\n // 3. Check if this key value has been seen before.\n if (seenValues.has(keyValue)) {\n // If the value is already in the Set, return false.\n // This object is a duplicate and will be excluded from the result.\n return false;\n } else {\n // If the value is encountered for the first time, add it to the Set.\n seenValues.add(keyValue);\n // Return true to include the object in the resulting unique array.\n return true;\n }\n });\n}\n","import { OrbitAdapter } from '../types';\n\nexport function formatConnectorChainId(chainId: string | number, connectedAdapter: OrbitAdapter) {\n if (typeof chainId === 'string') {\n return `${connectedAdapter}:${chainId}`;\n } else {\n return chainId;\n }\n}\n","const CONNECTOR_MAPPINGS = new Map([\n ['Impersonated Connector', 'impersonatedwallet'],\n ['Safe', 'safewallet'],\n ['Trust', 'trustwallet'],\n ['Trust Wallet', 'trustwallet'],\n ['Brave Кошелек', 'bravewallet'],\n ['Brave Wallet', 'bravewallet'],\n ['Base Account', 'coinbasewallet'], // TODO: need fix\n]);\n\nexport const formatConnectorName = (connectorName: string): string => {\n return CONNECTOR_MAPPINGS.get(connectorName) ?? connectorName.replace(/\\s+/g, '').toLowerCase();\n};\n","import { ConnectorType, OrbitAdapter } from '../types';\n\n/**\n * Extracts the adapter type from a connector type string\n *\n * @example\n * ```typescript\n * // Returns OrbitAdapter.EVM\n * getAdapterFromConnectorType('evm:metamask');\n *\n * // Returns OrbitAdapter.SOLANA\n * getAdapterFromConnectorType('solana:phantom');\n *\n * // Returns OrbitAdapter.EVM (default)\n * getAdapterFromConnectorType('unknown');\n * ```\n *\n * @param connectorType - Connector type in format \"orbit-adapter:connector\" (e.g. \"evm:metamask\", \"solana:phantom\")\n * @returns The corresponding {@link OrbitAdapter} type or EVM as default\n *\n * @remarks\n * The function splits the connector type string by \":\" and takes the first part as the adapter type.\n * If the split fails or the first part is empty, it defaults to EVM adapter.\n */\nexport function getAdapterFromConnectorType(connectorType: ConnectorType): OrbitAdapter {\n return (connectorType?.split(':')[0] as OrbitAdapter.EVM) ?? OrbitAdapter.EVM;\n}\n","import { OrbitAdapter } from '../types';\n\n/**\n * Generates a standardized connector type identifier from adapter type and connector name\n *\n * @example\n * ```typescript\n * // Returns \"evm:metamask\"\n * getConnectorTypeFromName(OrbitAdapter.EVM, \"MetaMask\");\n *\n * // Returns \"solana:phantom\"\n * getConnectorTypeFromName(OrbitAdapter.SOLANA, \"Phantom\");\n *\n * // Returns \"evm:coinbasewallet\" (removes spaces)\n * getConnectorTypeFromName(OrbitAdapter.EVM, \"Coinbase Wallet\");\n * ```\n *\n * @param adapter - The blockchain adapter type (e.g. EVM, SOLANA)\n * @param name - The connector name (e.g. \"MetaMask\", \"Phantom\")\n * @returns A formatted connector type string in format \"orbit-adapter:connector\"\n *\n * @remarks\n * The function:\n * 1. Combines adapter type with connector name using \":\" as separator\n * 2. Removes all whitespace from connector name\n * 3. Converts connector name to lowercase\n * This ensures consistent connector type identifiers across the application\n * and normalizes connector names for better UX/consistency.\n */\nexport function getConnectorTypeFromName(adapter: OrbitAdapter, name: string): string {\n return `${adapter}:${name.replace(/\\s+/g, '').toLowerCase()}`;\n}\n","/**\n * Internal function for safely retrieving and parsing data from localStorage.\n *\n * @param key - The key for localStorage\n * @returns The parsed LastConnectedConnector object or undefined if data is not found/invalid\n */\nexport function getParsedStorageItem<ReturnType>(key: string): ReturnType | undefined {\n if (typeof window === 'undefined') {\n return undefined;\n }\n\n const item = window.localStorage.getItem(key);\n\n // If the item is null (not set) or an empty string, return undefined\n if (!item) {\n return undefined;\n }\n\n try {\n // Safe JSON parsing\n return JSON.parse(item) as ReturnType;\n } catch (error) {\n // In case of a parsing error (e.g., invalid JSON), log the error and return undefined\n console.error(`Error parsing ${key} from localStorage:`, error);\n return undefined;\n }\n}\n","/**\n * Helper utilities for managing impersonated wallet addresses\n *\n * @remarks\n * These utilities are primarily used for development and testing purposes.\n * They provide a way to simulate different wallet addresses without actually connecting a wallet.\n * All data is stored in localStorage with the 'satellite-connect:impersonatedAddress' key.\n * Functions are safe to use in both browser and SSR environments.\n */\nexport const impersonatedHelpers = {\n /**\n * Currently impersonated address from localStorage\n * Returns empty string if not set or in SSR context\n */\n impersonatedAddress:\n typeof window !== 'undefined' ? (window.localStorage.getItem('satellite-connect:impersonatedAddress') ?? '') : '',\n\n /**\n * Stores an impersonated address in localStorage\n *\n * @example\n * ```typescript\n * // Set impersonated address\n * impersonatedHelpers.setImpersonated('0x1234...5678');\n * ```\n *\n * @param address - Ethereum or Solana address to impersonate\n * @returns undefined in SSR context, void in browser\n */\n setImpersonated: (address: string) =>\n typeof window !== 'undefined'\n ? window.localStorage.setItem('satellite-connect:impersonatedAddress', address)\n : undefined,\n\n /**\n * Retrieves the current impersonated address from localStorage\n *\n * @example\n * ```typescript\n * // Get current impersonated address\n * const address = impersonatedHelpers.getImpersonated();\n * if (address) {\n * console.log('Currently impersonating:', address);\n * }\n * ```\n * @returns The impersonated address or undefined if not set or in SSR context\n */\n getImpersonated: () =>\n typeof window !== 'undefined' ? window.localStorage.getItem('satellite-connect:impersonatedAddress') : undefined,\n\n removeImpersonated: () =>\n typeof window !== 'undefined' ? window.localStorage.removeItem('satellite-connect:impersonatedAddress') : undefined,\n};\n","export const isSafeApp = typeof window !== 'undefined' && window !== window.parent;\n","import { ConnectorType } from '../types';\nimport { getParsedStorageItem } from './getParsedStorageItem';\n\ntype LastConnectedConnector = { connectorType: ConnectorType; chainId: number | string; address?: string };\n\n/**\n * Helper utilities for managing the last connected wallet state\n *\n * @remarks\n * All data is stored in localStorage with the 'orbit-core:lastConnectedConnector' key.\n * Functions are safe to use in both browser and SSR environments.\n */\nexport const lastConnectedConnectorHelpers = {\n // Key used for localStorage\n STORAGE_KEY: 'orbit-core:lastConnectedConnector',\n\n /**\n * The value of the last connected wallet, initialized when the module loads.\n * Returns undefined if not set, invalid, or in an SSR context.\n */\n lastConnectedConnector: getParsedStorageItem<LastConnectedConnector>('orbit-core:lastConnectedConnector'),\n\n /**\n * Stores the last connected wallet data in localStorage.\n *\n * @param data - Object containing the wallet type and chain ID.\n * @returns undefined in SSR context, void in browser\n */\n setLastConnectedConnector: ({ connectorType, chainId, address }: LastConnectedConnector) =>\n typeof window !== 'undefined'\n ? window.localStorage.setItem(\n lastConnectedConnectorHelpers.STORAGE_KEY,\n JSON.stringify({ connectorType, chainId, address }),\n )\n : undefined,\n\n /**\n * Retrieves the current last connected wallet data from localStorage.\n *\n * @returns The LastConnectedConnector object or undefined if not set or in SSR context\n */\n getLastConnectedConnector: () =>\n getParsedStorageItem<LastConnectedConnector>(lastConnectedConnectorHelpers.STORAGE_KEY),\n\n /**\n * Removes the last connected wallet data from localStorage.\n *\n * @returns undefined in SSR context, void in browser\n */\n removeLastConnectedConnector: () =>\n typeof window !== 'undefined'\n ? window.localStorage.removeItem(lastConnectedConnectorHelpers.STORAGE_KEY)\n : undefined,\n};\n","import { ConnectorType } from '../types';\nimport { getParsedStorageItem } from './getParsedStorageItem';\n\n/**\n * Data structure for a recently connected connector\n *\n * @interface RecentlyConnectedConnectorData\n * @property {string} address - The wallet address that was connected\n * @property {number} disconnectedTimestamp - Unix timestamp in milliseconds when the connector was disconnected\n * @property {string} [icon] - Optional icon URL or identifier for the connector\n */\nexport type RecentlyConnectedConnectorData = {\n address: string;\n disconnectedTimestamp: number;\n icon?: string;\n};\n\n/**\n * Record mapping connector types to their recently connected data\n *\n * @type RecentlyConnectedConnectorsList\n */\nexport type RecentlyConnectedConnectorsList = Record<ConnectorType, RecentlyConnectedConnectorData>;\n\n/**\n * Helper utilities for managing recently connected connectors list with disconnect timestamps\n *\n * @remarks\n * All data is stored in localStorage with the 'orbit-core:recentlyConnectedConnectorsListHelpers' key.\n * Functions are safe to use in both browser and SSR environments.\n *\n * The storage contains a record where each key is a ConnectorType and value contains\n * address, disconnectedTimestamp (Unix timestamp in milliseconds), and optional icon for that connector.\n * This allows tracking when each connector was last disconnected for cleanup and sorting purposes.\n *\n * @example\n * ```typescript\n * // Set entire list\n * recentlyConnectedConnectorsListHelpers.setRecentlyConnectedConnectorsList({\n * 'evm:metamask': {\n * address: '0x123...',\n * disconnectedTimestamp: Date.now(),\n * icon: 'metamask-icon.png'\n * },\n * 'solana:phantom': {\n * address: 'ABC123...',\n * disconnectedTimestamp: Date.now() - 3600000, // 1 hour ago\n * icon: 'phantom-icon.png'\n * }\n * });\n *\n * // Add single connector\n * recentlyConnectedConnectorsListHelpers.addConnector('evm:walletconnect', {\n * address: '0x456...',\n * disconnectedTimestamp: Date.now(),\n * icon: 'walletconnect-icon.png'\n * });\n *\n * // Remove single connector\n * recentlyConnectedConnectorsListHelpers.removeConnector('evm:metamask');\n * ```\n */\nexport const recentlyConnectedConnectorsListHelpers = {\n /** Key used for localStorage storage */\n STORAGE_KEY: 'orbit-core:recentlyConnectedConnectorsListHelpers',\n\n /**\n * The current recently connected connectors list, initialized when the module loads.\n * Returns undefined if not set, invalid, or in an SSR context.\n *\n * @readonly\n */\n recentlyConnectedConnectorsList: getParsedStorageItem<RecentlyConnectedConnectorsList>(\n 'orbit-core:recentlyConnectedConnectorsListHelpers',\n ),\n\n /**\n * Stores the complete recently connected connectors list in localStorage.\n * This will overwrite the entire existing list.\n *\n * @param connectors - Complete RecentlyConnectedConnectorsList object\n * @returns undefined in SSR context, void in browser\n *\n * @example\n * ```typescript\n * recentlyConnectedConnectorsListHelpers.setRecentlyConnectedConnectorsList({\n * 'evm:metamask': {\n * address: '0x123...',\n * disconnectedTimestamp: Date.now(),\n * icon: 'metamask.png'\n * },\n * 'solana:phantom': {\n * address: 'ABC123...',\n * disconnectedTimestamp: Date.now() - 1800000 // 30 minutes ago\n * }\n * });\n * ```\n */\n setRecentlyConnectedConnectorsList: (connectors: RecentlyConnectedConnectorsList) =>\n typeof window !== 'undefined'\n ? window.localStorage.setItem(recentlyConnectedConnectorsListHelpers.STORAGE_KEY, JSON.stringify(connectors))\n : undefined,\n\n /**\n * Retrieves the current recently connected connectors list from localStorage.\n *\n * @returns The RecentlyConnectedConnectorsList object or undefined if not set or in SSR context\n *\n * @example\n * ```typescript\n * const connectors = recentlyConnectedConnectorsListHelpers.getRecentlyConnectedConnectorsList();\n * if (connectors) {\n * console.log('Available connectors:', Object.keys(connectors));\n * // Sort by most recently disconnected\n * const sorted = Object.entries(connectors)\n * .sort(([,a], [,b]) => b.disconnectedTimestamp - a.disconnectedTimestamp);\n * }\n * ```\n */\n getRecentlyConnectedConnectorsList: () =>\n getParsedStorageItem<RecentlyConnectedConnectorsList>(recentlyConnectedConnectorsListHelpers.STORAGE_KEY),\n\n /**\n * Adds or updates a single connector in the recently connected connectors list.\n * Preserves existing connectors and only adds/updates the specified one.\n *\n * @param connectorType - The connector type to add/update\n * @param connectorData - The connector data (address, disconnectedTimestamp, and optional icon)\n * @returns undefined in SSR context, void in browser\n *\n * @example\n * ```typescript\n * // Add new connector with current timestamp\n * recentlyConnectedConnectorsListHelpers.addConnector('evm:metamask', {\n * address: '0x123...',\n * disconnectedTimestamp: Date.now(),\n * icon: 'metamask.png'\n * });\n *\n * // Update existing connector with new disconnect time\n * recentlyConnectedConnectorsListHelpers.addConnector('evm:metamask', {\n * address: '0x456...',\n * disconnectedTimestamp: Date.now(),\n * icon: 'new-metamask.png'\n * });\n * ```\n */\n addConnector: (connectorType: ConnectorType, connectorData: RecentlyConnectedConnectorData) => {\n if (typeof window === 'undefined') {\n return undefined;\n }\n\n const currentList = recentlyConnectedConnectorsListHelpers.getRecentlyConnectedConnectorsList() || {};\n const updatedList = {\n ...currentList,\n [connectorType]: connectorData,\n };\n\n window.localStorage.setItem(recentlyConnectedConnectorsListHelpers.STORAGE_KEY, JSON.stringify(updatedList));\n },\n\n /**\n * Removes a single connector from the recently connected connectors list.\n * Preserves all other connectors in the list.\n *\n * @param connectorType - The connector type to remove\n * @returns undefined in SSR context, void in browser\n *\n * @example\n * ```typescript\n * // Remove specific connector\n * recentlyConnectedConnectorsListHelpers.removeConnector('evm:metamask');\n * ```\n */\n removeConnector: (connectorType: ConnectorType) => {\n if (typeof window === 'undefined') {\n return undefined;\n }\n\n const currentList = recentlyConnectedConnectorsListHelpers.getRecentlyConnectedConnectorsList();\n if (!currentList || !(connectorType in currentList)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { [connectorType]: _, ...remainingConnectors } = currentList;\n window.localStorage.setItem(\n recentlyConnectedConnectorsListHelpers.STORAGE_KEY,\n JSON.stringify(remainingConnectors),\n );\n },\n\n /**\n * Checks if a specific connector exists in the recently connected connectors list.\n *\n * @param connectorType - The connector type to check\n * @returns true if the connector exists, false otherwise, undefined in SSR context\n *\n * @example\n * ```typescript\n * if (recentlyConnectedConnectorsListHelpers.hasConnector('evm:metamask')) {\n * console.log('MetaMask was recently connected');\n * }\n * ```\n */\n hasConnector: (connectorType: ConnectorType): boolean | undefined => {\n if (typeof window === 'undefined') {\n return undefined;\n }\n\n const currentList = recentlyConnectedConnectorsListHelpers.getRecentlyConnectedConnectorsList();\n return currentList ? connectorType in currentList : false;\n },\n\n /**\n * Gets data for a specific connector from the recently connected connectors list.\n *\n * @param connectorType - The connector type to get data for\n * @returns The connector data (including address, disconnectedTimestamp, and optional icon) or undefined if not found or in SSR context\n *\n * @example\n * ```typescript\n * const metamaskData = recentlyConnectedConnectorsListHelpers.getConnector('evm:metamask');\n * if (metamaskData) {\n * console.log('MetaMask address:', metamaskData.address);\n * console.log('Disconnected at:', new Date(metamaskData.disconnectedTimestamp));\n * console.log('MetaMask icon:', metamaskData.icon);\n * }\n * ```\n */\n getConnector: (connectorType: ConnectorType): RecentlyConnectedConnectorData | undefined => {\n if (typeof window === 'undefined') {\n return undefined;\n }\n\n const currentList = recentlyConnectedConnectorsListHelpers.getRecentlyConnectedConnectorsList();\n return currentList?.[connectorType];\n },\n\n /**\n * Gets the count of recently connected connectors.\n *\n * @returns Number of connectors in the list, 0 in SSR context or if list is empty\n *\n * @example\n * ```typescript\n * const count = recentlyConnectedConnectorsListHelpers.getConnectorCount();\n * console.log(`${count} connectors recently connected`);\n * ```\n */\n getConnectorCount: (): number => {\n if (typeof window === 'undefined') {\n return 0;\n }\n\n const currentList = recentlyConnectedConnectorsListHelpers.getRecentlyConnectedConnectorsList();\n return currentList ? Object.keys(currentList).length : 0;\n },\n\n /**\n * Gets recently connected connectors sorted by disconnect time (most recent first).\n * Useful for showing connectors in order of recent usage.\n *\n * @returns Array of [ConnectorType, RecentlyConnectedConnectorData] tuples sorted by disconnectedTimestamp (descending), empty array in SSR context\n *\n * @example\n * ```typescript\n * const sortedConnectors = recentlyConnectedConnectorsListHelpers.getConnectorsSortedByTime();\n * sortedConnectors.forEach(([connectorType, data]) => {\n * console.log(`${connectorType}: disconnected ${new Date(data.disconnectedTimestamp)}`);\n * });\n * ```\n */\n getConnectorsSortedByTime: (): [ConnectorType, RecentlyConnectedConnectorData][] => {\n if (typeof window === 'undefined') {\n return [];\n }\n\n const currentList = recentlyConnectedConnectorsListHelpers.getRecentlyConnectedConnectorsList();\n if (!currentList) {\n return [];\n }\n\n return Object.entries(currentList).sort(([, a], [, b]) => b.disconnectedTimestamp - a.disconnectedTimestamp) as [\n ConnectorType,\n RecentlyConnectedConnectorData,\n ][];\n },\n\n /**\n * Removes connectors that were disconnected before the specified timestamp.\n * Useful for cleaning up old connector entries.\n *\n * @param beforeTimestamp - Unix timestamp in milliseconds; connectors disconnected before this time will be removed\n * @returns undefined in SSR context, void in browser\n *\n * @example\n * ```typescript\n * // Remove connectors disconnected more than 7 days ago\n * const weekAgo = Date.now() - (7 * 24 * 60 * 60 * 1000);\n * recentlyConnectedConnectorsListHelpers.removeConnectorsOlderThan(weekAgo);\n * ```\n */\n removeConnectorsOlderThan: (beforeTimestamp: number) => {\n if (typeof window === 'undefined') {\n return undefined;\n }\n\n const currentList = recentlyConnectedConnectorsListHelpers.getRecentlyConnectedConnectorsList();\n if (!currentList) {\n return;\n }\n\n const filteredList = Object.fromEntries(\n Object.entries(currentList).filter(([, data]) => data.disconnectedTimestamp >= beforeTimestamp),\n ) as RecentlyConnectedConnectorsList;\n\n window.localStorage.setItem(recentlyConnectedConnectorsListHelpers.STORAGE_KEY, JSON.stringify(filteredList));\n },\n\n /**\n * Removes all recently connected connectors from localStorage.\n *\n * @returns undefined in SSR context, void in browser\n *\n * @example\n * ```typescript\n * // Clear all recently connected connectors\n * recentlyConnectedConnectorsListHelpers.removeRecentlyConnectedConnectorsList();\n * ```\n */\n removeRecentlyConnectedConnectorsList: () =>\n typeof window !== 'undefined'\n ? window.localStorage.removeItem(recentlyConnectedConnectorsListHelpers.STORAGE_KEY)\n : undefined,\n};\n","/**\n * @file\n * This module provides adapter selection functionality for the Orbit system.\n * Part of the core infrastructure for managing blockchain adapters.\n */\n\nimport { OrbitAdapter, OrbitGenericAdapter } from '../types';\n\n/**\n * Selects an appropriate adapter based on the provided key from either a single adapter\n * or an array of adapters.\n *\n * @typeParam A - Type extending basic adapter interface with a key property\n *\n * @param options - Selection configuration object\n * @param options.adapterKey - Target adapter key to search for\n * @param options.adapter - Single adapter or array of adapters to search within\n *\n * @returns Selected adapter or undefined if no suitable adapter found\n *\n * @remarks\n * If an array is provided but no matching adapter is found, falls back to the first adapter\n * in the array with a warning message.\n *\n * @example\n * ```typescript\n * // Single adapter usage\n * const singleResult = selectAdapterByKey({\n * adapterKey: OrbitAdapter.SOLANA,\n * adapter: { key: OrbitAdapter.SOLANA, connect: async () => {...} }\n * });\n *\n * // Multiple adapters usage\n * const multiResult = selectAdapterByKey({\n * adapterKey: OrbitAdapter.EVM,\n * adapter: [\n * { key: OrbitAdapter.SOLANA, connect: async () => {...} },\n * { key: OrbitAdapter.EVM, connect: async () => {...} }\n * ]\n * });\n * ```\n *\n * @throws {Error} Logs error if adapter array is empty\n * @throws {Warning} Logs warning if requested adapter key not found in array\n */\nexport const selectAdapterByKey = <A extends { key: OrbitAdapter }>({\n adapterKey,\n adapter,\n}: { adapterKey: OrbitAdapter } & OrbitGenericAdapter<A>): A | undefined => {\n if (Array.isArray(adapter)) {\n if (adapter.length === 0) {\n console.error('Adapter selection failed: The provided adapters array is empty.');\n return undefined;\n }\n\n const foundAdapter = adapter.find((a) => a.key === adapterKey);\n\n if (foundAdapter) {\n return foundAdapter;\n } else {\n console.warn(\n `No adapter found for key: \"${adapterKey}\". Falling back to the first available adapter: \"${adapter[0].key}\".`,\n );\n return adapter[0];\n }\n }\n return adapter;\n};\n","export async function waitFor(\n predicate: () => boolean | undefined,\n maxChecks: number = 50,\n checkIntervalMs: number = 200,\n) {\n for (let i = 0; i < maxChecks; i++) {\n if (predicate()) {\n return;\n }\n await new Promise((resolve) => setTimeout(resolve, checkIntervalMs));\n }\n throw new Error('Predicate not fulfilled in time');\n}\n","/**\n * Checks whether the given chain ID belongs to a Solana network.\n * Supports common Solana network names: 'devnet', 'testnet', 'mainnet-beta', 'mainnet'.\n *\n * @param {number | string} chainId - The chain ID or chain name.\n * @returns {boolean} - True if the chain ID corresponds to a Solana network, false otherwise.\n */\nexport function isSolanaChain(chainId: number | string): boolean {\n if (typeof chainId === 'string') {\n return ['devnet', 'testnet', 'mainnet-beta', 'mainnet'].includes(chainId);\n }\n return false;\n}\n\n/**\n * Sets the chain ID to a Solana-specific format if the chain is a Solana network.\n *\n * @param {number | string} chainId - The original chain ID or name.\n * @returns {string | number} - The formatted chain ID prefixed with 'solana:' if Solana, otherwise the original.\n */\nexport function setChainId(chainId: number | string): string | number {\n if (isSolanaChain(chainId)) {\n return `solana:${chainId}`;\n } else {\n return chainId;\n }\n}\n"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var l=(n=>(n.EVM="evm",n.SOLANA="solana",n.Starknet="starknet",n))(l||{});var c=(e,t)=>new Promise(r=>{let n=()=>{setTimeout(()=>r(e),t);};typeof window<"u"?n():setTimeout(n,0);});function u(e,t){let r=new Set;return e.filter(n=>{let a=n[t];return r.has(a)?false:(r.add(a),true)})}function g(e,t){return typeof e=="string"?`${t}:${e}`:e}var s=new Map([["Impersonated Connector","impersonatedwallet"],["Safe","safewallet"],["Trust","trustwallet"],["Trust Wallet","trustwallet"],["Brave \u041A\u043E\u0448\u0435\u043B\u0435\u043A","bravewallet"],["Brave Wallet","bravewallet"]]),A=e=>s.get(e)??e.replace(/\s+/g,"").toLowerCase();function W(e){return e?.split(":")[0]??"evm"}function o(e){if(typeof window>"u")return;let t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(r){console.error(`Error parsing ${e} from localStorage:`,r);return}}function O(e,t){return `${e}:${t.replace(/\s+/g,"").toLowerCase()}`}var R={impersonatedAddress:typeof window<"u"?window.localStorage.getItem("satellite-connect:impersonatedAddress")??"":"",setImpersonated:e=>typeof window<"u"?window.localStorage.setItem("satellite-connect:impersonatedAddress",e):void 0,getImpersonated:()=>typeof window<"u"?window.localStorage.getItem("satellite-connect:impersonatedAddress"):void 0,removeImpersonated:()=>typeof window<"u"?window.localStorage.removeItem("satellite-connect:impersonatedAddress"):void 0};var v=typeof window<"u"&&window!==window.parent;var i={STORAGE_KEY:"orbit-core:lastConnectedWallet",lastConnectedWallet:o("orbit-core:lastConnectedWallet"),setLastConnectedWallet:({walletType:e,chainId:t,address:r})=>typeof window<"u"?window.localStorage.setItem(i.STORAGE_KEY,JSON.stringify({walletType:e,chainId:t,address:r})):void 0,getLastConnectedWallet:()=>o(i.STORAGE_KEY),removeLastConnectedWallet:()=>typeof window<"u"?window.localStorage.removeItem(i.STORAGE_KEY):void 0};var d={STORAGE_KEY:"orbit-core:recentConnectedWallet",recentConnectedWallet:o("orbit-core:recentConnectedWallets"),setRecentConnectedWallet:e=>typeof window<"u"?window.localStorage.setItem(d.STORAGE_KEY,JSON.stringify(e)):void 0,getRecentConnectedWallet:()=>o(d.STORAGE_KEY),removeRecentConnectedWallet:()=>typeof window<"u"?window.localStorage.removeItem(d.STORAGE_KEY):void 0};var $=({adapterKey:e,adapter:t})=>{if(Array.isArray(t)){if(t.length===0){console.error("Adapter selection failed: The provided adapters array is empty.");return}let r=t.find(n=>n.key===e);return r||(console.warn(`No adapter found for key: "${e}". Falling back to the first available adapter: "${t[0].key}".`),t[0])}return t};async function N(e,t=50,r=200){for(let n=0;n<t;n++){if(e())return;await new Promise(a=>setTimeout(a,r));}throw new Error("Predicate not fulfilled in time")}function p(e){return typeof e=="string"?["devnet","testnet","mainnet-beta","mainnet"].includes(e):false}function h(e){return p(e)?`solana:${e}`:e}export{l as OrbitAdapter,c as delay,u as filterUniqueByKey,g as formatWalletChainId,A as formatWalletName,W as getAdapterFromWalletType,o as getParsedStorageItem,O as getWalletTypeFromConnectorName,R as impersonatedHelpers,v as isSafeApp,p as isSolanaChain,i as lastConnectedWalletHelpers,d as recentConnectedWalletHelpers,$ as selectAdapterByKey,h as setChainId,N as waitFor};//# sourceMappingURL=index.mjs.map
1
+ var c=(r=>(r.EVM="evm",r.SOLANA="solana",r.Starknet="starknet",r))(c||{});var p=(e,t)=>new Promise(n=>{let r=()=>{setTimeout(()=>n(e),t);};typeof window<"u"?r():setTimeout(r,0);});function m(e,t){let n=new Set;return e.filter(r=>{let s=r[t];return n.has(s)?false:(n.add(s),true)})}function y(e,t){return typeof e=="string"?`${t}:${e}`:e}var a=new Map([["Impersonated Connector","impersonatedwallet"],["Safe","safewallet"],["Trust","trustwallet"],["Trust Wallet","trustwallet"],["Brave \u041A\u043E\u0448\u0435\u043B\u0435\u043A","bravewallet"],["Brave Wallet","bravewallet"],["Base Account","coinbasewallet"]]),g=e=>a.get(e)??e.replace(/\s+/g,"").toLowerCase();function S(e){return e?.split(":")[0]??"evm"}function x(e,t){return `${e}:${t.replace(/\s+/g,"").toLowerCase()}`}function i(e){if(typeof window>"u")return;let t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(n){console.error(`Error parsing ${e} from localStorage:`,n);return}}var E={impersonatedAddress:typeof window<"u"?window.localStorage.getItem("satellite-connect:impersonatedAddress")??"":"",setImpersonated:e=>typeof window<"u"?window.localStorage.setItem("satellite-connect:impersonatedAddress",e):void 0,getImpersonated:()=>typeof window<"u"?window.localStorage.getItem("satellite-connect:impersonatedAddress"):void 0,removeImpersonated:()=>typeof window<"u"?window.localStorage.removeItem("satellite-connect:impersonatedAddress"):void 0};var v=typeof window<"u"&&window!==window.parent;var d={STORAGE_KEY:"orbit-core:lastConnectedConnector",lastConnectedConnector:i("orbit-core:lastConnectedConnector"),setLastConnectedConnector:({connectorType:e,chainId:t,address:n})=>typeof window<"u"?window.localStorage.setItem(d.STORAGE_KEY,JSON.stringify({connectorType:e,chainId:t,address:n})):void 0,getLastConnectedConnector:()=>i(d.STORAGE_KEY),removeLastConnectedConnector:()=>typeof window<"u"?window.localStorage.removeItem(d.STORAGE_KEY):void 0};var o={STORAGE_KEY:"orbit-core:recentlyConnectedConnectorsListHelpers",recentlyConnectedConnectorsList:i("orbit-core:recentlyConnectedConnectorsListHelpers"),setRecentlyConnectedConnectorsList:e=>typeof window<"u"?window.localStorage.setItem(o.STORAGE_KEY,JSON.stringify(e)):void 0,getRecentlyConnectedConnectorsList:()=>i(o.STORAGE_KEY),addConnector:(e,t)=>{if(typeof window>"u")return;let r={...o.getRecentlyConnectedConnectorsList()||{},[e]:t};window.localStorage.setItem(o.STORAGE_KEY,JSON.stringify(r));},removeConnector:e=>{if(typeof window>"u")return;let t=o.getRecentlyConnectedConnectorsList();if(!t||!(e in t))return;let{[e]:n,...r}=t;window.localStorage.setItem(o.STORAGE_KEY,JSON.stringify(r));},hasConnector:e=>{if(typeof window>"u")return;let t=o.getRecentlyConnectedConnectorsList();return t?e in t:false},getConnector:e=>typeof window>"u"?void 0:o.getRecentlyConnectedConnectorsList()?.[e],getConnectorCount:()=>{if(typeof window>"u")return 0;let e=o.getRecentlyConnectedConnectorsList();return e?Object.keys(e).length:0},getConnectorsSortedByTime:()=>{if(typeof window>"u")return [];let e=o.getRecentlyConnectedConnectorsList();return e?Object.entries(e).sort(([,t],[,n])=>n.disconnectedTimestamp-t.disconnectedTimestamp):[]},removeConnectorsOlderThan:e=>{if(typeof window>"u")return;let t=o.getRecentlyConnectedConnectorsList();if(!t)return;let n=Object.fromEntries(Object.entries(t).filter(([,r])=>r.disconnectedTimestamp>=e));window.localStorage.setItem(o.STORAGE_KEY,JSON.stringify(n));},removeRecentlyConnectedConnectorsList:()=>typeof window<"u"?window.localStorage.removeItem(o.STORAGE_KEY):void 0};var k=({adapterKey:e,adapter:t})=>{if(Array.isArray(t)){if(t.length===0){console.error("Adapter selection failed: The provided adapters array is empty.");return}let n=t.find(r=>r.key===e);return n||(console.warn(`No adapter found for key: "${e}". Falling back to the first available adapter: "${t[0].key}".`),t[0])}return t};async function $(e,t=50,n=200){for(let r=0;r<t;r++){if(e())return;await new Promise(s=>setTimeout(s,n));}throw new Error("Predicate not fulfilled in time")}function f(e){return typeof e=="string"?["devnet","testnet","mainnet-beta","mainnet"].includes(e):false}function B(e){return f(e)?`solana:${e}`:e}export{c as OrbitAdapter,p as delay,m as filterUniqueByKey,y as formatConnectorChainId,g as formatConnectorName,S as getAdapterFromConnectorType,x as getConnectorTypeFromName,i as getParsedStorageItem,E as impersonatedHelpers,v as isSafeApp,f as isSolanaChain,d as lastConnectedConnectorHelpers,o as recentlyConnectedConnectorsListHelpers,k as selectAdapterByKey,B as setChainId,$ as waitFor};//# sourceMappingURL=index.mjs.map
2
2
  //# sourceMappingURL=index.mjs.map