@tuwaio/orbit-core 0.6.0 → 0.6.1

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/README.md CHANGED
@@ -108,7 +108,7 @@ isAddress('So11111111111111111111111111111111111111112', 'solana'); // true
108
108
 
109
109
  ## 🗄️ Browser Storage
110
110
 
111
- The storage helpers write the following keys. Clear them to reset the connection state of a user:
111
+ The storage helpers write the following keys. Clear them to reset the connection state of a user. In a browser that blocks site data they find nothing saved and write nothing, and a full storage still throws from a write:
112
112
 
113
113
  | Key | Written by | Where |
114
114
  | --------------------------------------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
package/dist/index.d.mts CHANGED
@@ -125,6 +125,25 @@ type ConnectorType = `${OrbitAdapter}:${string}`;
125
125
  */
126
126
  type ChainIdentifierArray = readonly (string | number)[];
127
127
 
128
+ /**
129
+ * An account address in the form to compare it in: an EVM address in any case, as its case is only a checksum; any
130
+ * other exactly, as a base58 address in another case is another account.
131
+ *
132
+ * @param namespace - The CAIP-2 namespace of the account, e.g. `eip155` or `solana`.
133
+ * @param address - The address.
134
+ * @returns The address to compare.
135
+ */
136
+ declare function normalizeAccountAddress(namespace: string, address: string): string;
137
+ /**
138
+ * Whether two addresses of one namespace are the same account, by {@link normalizeAccountAddress}.
139
+ *
140
+ * @param namespace - The CAIP-2 namespace of both addresses, e.g. `eip155` or `solana`.
141
+ * @param left - One address.
142
+ * @param right - The other address.
143
+ * @returns `true` when they are the same account.
144
+ */
145
+ declare function isSameAddress(namespace: string, left: string, right: string): boolean;
146
+
128
147
  /**
129
148
  * Universal address validation function that supports multiple blockchain formats
130
149
  * @param value - Address string to validate
@@ -133,6 +152,23 @@ type ChainIdentifierArray = readonly (string | number)[];
133
152
  */
134
153
  declare function isAddress(value: string, type?: 'evm' | 'solana' | 'auto'): boolean;
135
154
 
155
+ /**
156
+ * The storage of the browser, reached safely. A browser that blocks site data throws on reaching `window.localStorage`,
157
+ * not on what is called on it, so a guard on `typeof window` is not enough.
158
+ *
159
+ * @param area - The storage to reach: `localStorage` (default) or `sessionStorage`.
160
+ * @returns The storage, or `null` without a browser or when the browser refuses it.
161
+ */
162
+ declare function getBrowserStorage(area?: 'localStorage' | 'sessionStorage'): Storage | null;
163
+ /**
164
+ * Reads a value of the browser's storage. Never throws.
165
+ *
166
+ * @param key - The storage key.
167
+ * @param area - The storage to read: `localStorage` (default) or `sessionStorage`.
168
+ * @returns The value, or `null` when it is not set, without a browser, or when the browser refuses it.
169
+ */
170
+ declare function readBrowserStorage(key: string, area?: 'localStorage' | 'sessionStorage'): string | null;
171
+
136
172
  /**
137
173
  * A CAIP-2 chain ID: `<namespace>:<reference>`, for example `eip155:8453` or
138
174
  * `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`.
@@ -312,6 +348,15 @@ declare function setChainId(chainId: number | string): string | number;
312
348
  */
313
349
  declare const delay: <T>(value: T, ms: number) => Promise<T>;
314
350
 
351
+ /**
352
+ * An error and the causes it wraps, of any kind, as wallet libraries wrap what the wallet answered several levels down.
353
+ * A cause that loops ends the list.
354
+ *
355
+ * @param error - What was thrown.
356
+ * @returns The error first, then each `cause` in turn; empty for `null` or `undefined`.
357
+ */
358
+ declare function errorChain(error: unknown): unknown[];
359
+
315
360
  /**
316
361
  * Filters an array of objects to keep only the first occurrence of an object
317
362
  * based on a unique value of a specified key.
@@ -326,6 +371,22 @@ declare const delay: <T>(value: T, ms: number) => Promise<T>;
326
371
  */
327
372
  declare function filterUniqueByKey<T>(array: T[], key: keyof T): T[];
328
373
 
374
+ /**
375
+ * An integer amount in the smallest unit of a currency as a decimal number, for example wei as gwei (`decimals` 9) or
376
+ * lamports as SOL (`decimals` 9): exact, with a dot, without grouping, trailing zeros or rounding.
377
+ *
378
+ * @example
379
+ * ```typescript
380
+ * formatBaseUnits('89540000', 6); // "89.54"
381
+ * formatBaseUnits(1500000000n, 9); // "1.5"
382
+ * ```
383
+ *
384
+ * @param value - The amount, as a number, a decimal string or a bigint.
385
+ * @param decimals - The number of decimals of the displayed unit.
386
+ * @returns The decimal string, or `undefined` when `value` is missing, negative or not an integer.
387
+ */
388
+ declare function formatBaseUnits(value: string | number | bigint | null | undefined, decimals: number): string | undefined;
389
+
329
390
  /**
330
391
  * Formats a chain ID for use in connector identifiers.
331
392
  * Solana clusters become CAIP-2 chain IDs with the genesis hash (see {@link getSolanaChainId}); other string chain
@@ -344,6 +405,10 @@ declare function filterUniqueByKey<T>(array: T[], key: keyof T): T[];
344
405
  */
345
406
  declare function formatConnectorChainId(chainId: string | number, connectedAdapter: OrbitAdapter): string | number;
346
407
 
408
+ /** The connector ID of the impersonated wallet. It is saved in the last connection, so it can never change. */
409
+ declare const IMPERSONATED_CONNECTOR_ID = "impersonatedwallet";
410
+ /** The connector ID of Safe{Wallet}. It is saved in the last connection, so it can never change. */
411
+ declare const SAFE_CONNECTOR_ID = "safe";
347
412
  /**
348
413
  * Normalizes a wallet connector display name into a stable identifier.
349
414
  * Known names are mapped explicitly (e.g. "Trust Wallet" → "trust", "Base Account" → "coinbase");
@@ -397,21 +462,21 @@ declare function getAdapterFromConnectorType(connectorType: ConnectorType): Orbi
397
462
  *
398
463
  * // Returns "evm:coinbasewallet" (removes spaces)
399
464
  * getConnectorTypeFromName(OrbitAdapter.EVM, "Coinbase Wallet");
465
+ *
466
+ * // Returns "evm:coinbase" (a known name, by formatConnectorName)
467
+ * getConnectorTypeFromName(OrbitAdapter.EVM, "Base Account");
400
468
  * ```
401
469
  *
402
470
  * @param adapter - The blockchain adapter type (e.g. EVM, SOLANA)
403
- * @param name - The connector name (e.g. "MetaMask", "Phantom")
471
+ * @param name - The connector name (e.g. "MetaMask", "Phantom"), as the wallet reports it or as {@link formatConnectorName} gave it
404
472
  * @returns A formatted connector type string in format "orbit-adapter:connector"
405
473
  *
406
474
  * @remarks
407
- * The function:
408
- * 1. Combines adapter type with connector name using ":" as separator
409
- * 2. Removes all whitespace from connector name
410
- * 3. Converts connector name to lowercase
411
- * This ensures consistent connector type identifiers across the application
412
- * and normalizes connector names for better UX/consistency.
413
- */
414
- declare function getConnectorTypeFromName(adapter: OrbitAdapter, name: string): string;
475
+ * The function goes through {@link formatConnectorName}: known names are mapped, any other has its whitespace removed
476
+ * and is lowercased. So one wallet has one type wherever it is read, on its connection and on its transactions, and a
477
+ * value that already went through the mapping stays as it is.
478
+ */
479
+ declare function getConnectorTypeFromName(adapter: OrbitAdapter, name: string): ConnectorType;
415
480
 
416
481
  /**
417
482
  * Returns the default network and educational links for an adapter, e.g. to render a
@@ -449,10 +514,36 @@ declare const getNetworkData: (adapter: OrbitAdapter) => {
449
514
  *
450
515
  * @param key - The storage key
451
516
  * @param area - The storage to read: `localStorage` (default) or `sessionStorage`
452
- * @returns The parsed value or undefined if data is not found/invalid, or in an SSR context
517
+ * @returns The parsed value or undefined if data is not found/invalid, in an SSR context, or when the browser refuses
518
+ * the storage
453
519
  */
454
520
  declare function getParsedStorageItem<ReturnType>(key: string, area?: 'localStorage' | 'sessionStorage'): ReturnType | undefined;
455
521
 
522
+ /**
523
+ * The wallet part of a connector type.
524
+ *
525
+ * @example
526
+ * ```typescript
527
+ * getWalletFromConnectorType('evm:metamask'); // "metamask"
528
+ * getWalletFromConnectorType('metamask'); // undefined
529
+ * ```
530
+ *
531
+ * @param connectorType - A connector type, in the format "orbit-adapter:connector".
532
+ * @returns The part after the adapter, or `undefined` when there is no adapter or no value.
533
+ */
534
+ declare function getWalletFromConnectorType(connectorType: string | null | undefined): string | undefined;
535
+
536
+ /**
537
+ * One object for all copies of a package on a page, kept on `globalThis` under `Symbol.for(key)`. A bundler can load a
538
+ * package twice, and two copies of a React context or a registry do not see each other.
539
+ *
540
+ * @template T - The type of the object.
541
+ * @param key - The name of the symbol. It must never change: published copies find each other through it.
542
+ * @param create - Makes the object, called only when no copy has made it yet.
543
+ * @returns The object.
544
+ */
545
+ declare function globalSingleton<T>(key: string, create: () => T): T;
546
+
456
547
  /**
457
548
  * Helper utilities for managing impersonated wallet addresses
458
549
  *
@@ -480,7 +571,7 @@ declare const impersonatedHelpers: {
480
571
  * @param address - Ethereum or Solana address to impersonate
481
572
  * @returns undefined in SSR context, void in browser
482
573
  */
483
- setImpersonated: (address: string) => void;
574
+ setImpersonated: (address: string) => void | undefined;
484
575
  /**
485
576
  * Retrieves the current impersonated address from localStorage
486
577
  *
@@ -500,9 +591,17 @@ declare const impersonatedHelpers: {
500
591
  *
501
592
  * @returns undefined in SSR context, void in browser
502
593
  */
503
- removeImpersonated: () => void;
594
+ removeImpersonated: () => void | undefined;
504
595
  };
505
596
 
597
+ /**
598
+ * Whether a value is an object with fields to read: anything but `null` and an array, class instances included.
599
+ *
600
+ * @param value - The value.
601
+ * @returns `true` for an object.
602
+ */
603
+ declare function isRecord(value: unknown): value is Record<string, unknown>;
604
+
506
605
  /**
507
606
  * Checks if the current window is running inside a Safe App iframe
508
607
  * by attempting postMessage communication with the parent window.
@@ -524,6 +623,27 @@ declare const isInSecureIframe: boolean;
524
623
  */
525
624
  declare const isSafeApp: boolean;
526
625
 
626
+ /**
627
+ * A URL without the slashes at its end.
628
+ *
629
+ * @param url - The URL.
630
+ * @returns The URL without them.
631
+ */
632
+ declare function trimTrailingSlashes(url: string): string;
633
+ /**
634
+ * Joins a base URL and a path with one slash, as an explorer URL may end in a slash and a path may start with one.
635
+ *
636
+ * @example
637
+ * ```typescript
638
+ * joinUrlPath('https://etherscan.io/', '/tx/0x1'); // "https://etherscan.io/tx/0x1"
639
+ * ```
640
+ *
641
+ * @param base - The base URL.
642
+ * @param path - The path. Without it the base comes back as it is.
643
+ * @returns The joined URL.
644
+ */
645
+ declare function joinUrlPath(base: string, path?: string): string;
646
+
527
647
  /**
528
648
  * Connection data persisted by {@link lastConnectedConnectorHelpers}.
529
649
  */
@@ -567,7 +687,7 @@ declare const lastConnectedConnectorHelpers: {
567
687
  * @param options - Whether the wallet is remembered after the tab closes.
568
688
  * @returns undefined in SSR context, void in browser
569
689
  */
570
- setLastConnectedConnector: ({ connectorType, chainId, address }: LastConnectedConnector, options?: WalletMemoryOptions) => undefined;
690
+ setLastConnectedConnector: ({ connectorType, chainId, address }: LastConnectedConnector, options?: WalletMemoryOptions) => void;
571
691
  /**
572
692
  * Retrieves the current last connected wallet data, from sessionStorage first, then from localStorage.
573
693
  *
@@ -585,7 +705,7 @@ declare const lastConnectedConnectorHelpers: {
585
705
  *
586
706
  * @returns undefined in SSR context, void in browser
587
707
  */
588
- removeLastConnectedConnector: () => undefined;
708
+ removeLastConnectedConnector: () => void;
589
709
  };
590
710
 
591
711
  /**
@@ -709,7 +829,7 @@ declare const recentlyConnectedConnectorsListHelpers: {
709
829
  * });
710
830
  * ```
711
831
  */
712
- setRecentlyConnectedConnectorsList: (connectors: RecentlyConnectedConnectorsList) => void;
832
+ setRecentlyConnectedConnectorsList: (connectors: RecentlyConnectedConnectorsList) => void | undefined;
713
833
  /**
714
834
  * Retrieves the current recently connected connectors list from localStorage.
715
835
  *
@@ -851,7 +971,7 @@ declare const recentlyConnectedConnectorsListHelpers: {
851
971
  * recentlyConnectedConnectorsListHelpers.removeRecentlyConnectedConnectorsList();
852
972
  * ```
853
973
  */
854
- removeRecentlyConnectedConnectorsList: () => void;
974
+ removeRecentlyConnectedConnectorsList: () => void | undefined;
855
975
  };
856
976
 
857
977
  /**
@@ -903,6 +1023,21 @@ declare const selectAdapterByKey: <A extends {
903
1023
  adapterKey: OrbitAdapter;
904
1024
  } & OrbitGenericAdapter<A>) => A | undefined;
905
1025
 
1026
+ /**
1027
+ * An address or a hash shortened to its start and end, as wallets show it.
1028
+ *
1029
+ * @example
1030
+ * ```typescript
1031
+ * shortAddress('0x1111111111111111111111111111111111112222'); // "0x1111…2222"
1032
+ * ```
1033
+ *
1034
+ * @param address - The address or hash (`0x…` or base58).
1035
+ * @param head - Characters kept at the start; `0x` counts toward it (default `6` for `0x`, `4` otherwise).
1036
+ * @param tail - Characters kept at the end (default `4`).
1037
+ * @returns The shortened value; a value that nothing would be saved on stays unchanged.
1038
+ */
1039
+ declare function shortAddress(address: string, head?: number, tail?: number): string;
1040
+
906
1041
  /**
907
1042
  * CAIP-2 chain IDs of the public Solana clusters. By CAIP-30, the reference is the first 32 characters of the base58
908
1043
  * genesis hash of the cluster.
@@ -971,5 +1106,5 @@ declare function getSolanaChainId(chainId: string | number): string | undefined;
971
1106
  */
972
1107
  declare function waitFor(predicate: () => boolean | undefined, maxChecks?: number, checkIntervalMs?: number): Promise<void>;
973
1108
 
974
- export { OrbitAdapter, SOLANA_CHAIN_IDS, delay, detectSafeApp, filterUniqueByKey, formatCaip10AccountId, formatCaip19AssetId, formatConnectorChainId, formatConnectorName, getAdapterFromConnectorType, getConnectorTypeFromName, getNetworkData, getParsedStorageItem, getSolanaChainId, getSolanaCluster, impersonatedHelpers, isAddress, isInSecureIframe, isSafeApp, isSolanaChain, lastConnectedConnectorHelpers, normalizeError, parseCaip10AccountId, parseCaip19AssetId, parseCaip2ChainId, recentlyConnectedConnectorsListHelpers, selectAdapterByKey, setChainId, toCaip2ChainId, toEvmChainId, waitFor };
1109
+ export { IMPERSONATED_CONNECTOR_ID, OrbitAdapter, SAFE_CONNECTOR_ID, SOLANA_CHAIN_IDS, delay, detectSafeApp, errorChain, filterUniqueByKey, formatBaseUnits, formatCaip10AccountId, formatCaip19AssetId, formatConnectorChainId, formatConnectorName, getAdapterFromConnectorType, getBrowserStorage, getConnectorTypeFromName, getNetworkData, getParsedStorageItem, getSolanaChainId, getSolanaCluster, getWalletFromConnectorType, globalSingleton, impersonatedHelpers, isAddress, isInSecureIframe, isRecord, isSafeApp, isSameAddress, isSolanaChain, joinUrlPath, lastConnectedConnectorHelpers, normalizeAccountAddress, normalizeError, parseCaip10AccountId, parseCaip19AssetId, parseCaip2ChainId, readBrowserStorage, recentlyConnectedConnectorsListHelpers, selectAdapterByKey, setChainId, shortAddress, toCaip2ChainId, toEvmChainId, trimTrailingSlashes, waitFor };
975
1110
  export type { BaseAdapter, Caip10AccountId, Caip19AssetId, Caip2ChainId, ChainIdentifierArray, ConnectorType, LastConnectedConnector, OrbitGenericAdapter, RecentlyConnectedConnectorData, RecentlyConnectedConnectorsList, SolanaCluster, TuwaErrorState, WalletMemoryOptions };
package/dist/index.d.ts CHANGED
@@ -125,6 +125,25 @@ type ConnectorType = `${OrbitAdapter}:${string}`;
125
125
  */
126
126
  type ChainIdentifierArray = readonly (string | number)[];
127
127
 
128
+ /**
129
+ * An account address in the form to compare it in: an EVM address in any case, as its case is only a checksum; any
130
+ * other exactly, as a base58 address in another case is another account.
131
+ *
132
+ * @param namespace - The CAIP-2 namespace of the account, e.g. `eip155` or `solana`.
133
+ * @param address - The address.
134
+ * @returns The address to compare.
135
+ */
136
+ declare function normalizeAccountAddress(namespace: string, address: string): string;
137
+ /**
138
+ * Whether two addresses of one namespace are the same account, by {@link normalizeAccountAddress}.
139
+ *
140
+ * @param namespace - The CAIP-2 namespace of both addresses, e.g. `eip155` or `solana`.
141
+ * @param left - One address.
142
+ * @param right - The other address.
143
+ * @returns `true` when they are the same account.
144
+ */
145
+ declare function isSameAddress(namespace: string, left: string, right: string): boolean;
146
+
128
147
  /**
129
148
  * Universal address validation function that supports multiple blockchain formats
130
149
  * @param value - Address string to validate
@@ -133,6 +152,23 @@ type ChainIdentifierArray = readonly (string | number)[];
133
152
  */
134
153
  declare function isAddress(value: string, type?: 'evm' | 'solana' | 'auto'): boolean;
135
154
 
155
+ /**
156
+ * The storage of the browser, reached safely. A browser that blocks site data throws on reaching `window.localStorage`,
157
+ * not on what is called on it, so a guard on `typeof window` is not enough.
158
+ *
159
+ * @param area - The storage to reach: `localStorage` (default) or `sessionStorage`.
160
+ * @returns The storage, or `null` without a browser or when the browser refuses it.
161
+ */
162
+ declare function getBrowserStorage(area?: 'localStorage' | 'sessionStorage'): Storage | null;
163
+ /**
164
+ * Reads a value of the browser's storage. Never throws.
165
+ *
166
+ * @param key - The storage key.
167
+ * @param area - The storage to read: `localStorage` (default) or `sessionStorage`.
168
+ * @returns The value, or `null` when it is not set, without a browser, or when the browser refuses it.
169
+ */
170
+ declare function readBrowserStorage(key: string, area?: 'localStorage' | 'sessionStorage'): string | null;
171
+
136
172
  /**
137
173
  * A CAIP-2 chain ID: `<namespace>:<reference>`, for example `eip155:8453` or
138
174
  * `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`.
@@ -312,6 +348,15 @@ declare function setChainId(chainId: number | string): string | number;
312
348
  */
313
349
  declare const delay: <T>(value: T, ms: number) => Promise<T>;
314
350
 
351
+ /**
352
+ * An error and the causes it wraps, of any kind, as wallet libraries wrap what the wallet answered several levels down.
353
+ * A cause that loops ends the list.
354
+ *
355
+ * @param error - What was thrown.
356
+ * @returns The error first, then each `cause` in turn; empty for `null` or `undefined`.
357
+ */
358
+ declare function errorChain(error: unknown): unknown[];
359
+
315
360
  /**
316
361
  * Filters an array of objects to keep only the first occurrence of an object
317
362
  * based on a unique value of a specified key.
@@ -326,6 +371,22 @@ declare const delay: <T>(value: T, ms: number) => Promise<T>;
326
371
  */
327
372
  declare function filterUniqueByKey<T>(array: T[], key: keyof T): T[];
328
373
 
374
+ /**
375
+ * An integer amount in the smallest unit of a currency as a decimal number, for example wei as gwei (`decimals` 9) or
376
+ * lamports as SOL (`decimals` 9): exact, with a dot, without grouping, trailing zeros or rounding.
377
+ *
378
+ * @example
379
+ * ```typescript
380
+ * formatBaseUnits('89540000', 6); // "89.54"
381
+ * formatBaseUnits(1500000000n, 9); // "1.5"
382
+ * ```
383
+ *
384
+ * @param value - The amount, as a number, a decimal string or a bigint.
385
+ * @param decimals - The number of decimals of the displayed unit.
386
+ * @returns The decimal string, or `undefined` when `value` is missing, negative or not an integer.
387
+ */
388
+ declare function formatBaseUnits(value: string | number | bigint | null | undefined, decimals: number): string | undefined;
389
+
329
390
  /**
330
391
  * Formats a chain ID for use in connector identifiers.
331
392
  * Solana clusters become CAIP-2 chain IDs with the genesis hash (see {@link getSolanaChainId}); other string chain
@@ -344,6 +405,10 @@ declare function filterUniqueByKey<T>(array: T[], key: keyof T): T[];
344
405
  */
345
406
  declare function formatConnectorChainId(chainId: string | number, connectedAdapter: OrbitAdapter): string | number;
346
407
 
408
+ /** The connector ID of the impersonated wallet. It is saved in the last connection, so it can never change. */
409
+ declare const IMPERSONATED_CONNECTOR_ID = "impersonatedwallet";
410
+ /** The connector ID of Safe{Wallet}. It is saved in the last connection, so it can never change. */
411
+ declare const SAFE_CONNECTOR_ID = "safe";
347
412
  /**
348
413
  * Normalizes a wallet connector display name into a stable identifier.
349
414
  * Known names are mapped explicitly (e.g. "Trust Wallet" → "trust", "Base Account" → "coinbase");
@@ -397,21 +462,21 @@ declare function getAdapterFromConnectorType(connectorType: ConnectorType): Orbi
397
462
  *
398
463
  * // Returns "evm:coinbasewallet" (removes spaces)
399
464
  * getConnectorTypeFromName(OrbitAdapter.EVM, "Coinbase Wallet");
465
+ *
466
+ * // Returns "evm:coinbase" (a known name, by formatConnectorName)
467
+ * getConnectorTypeFromName(OrbitAdapter.EVM, "Base Account");
400
468
  * ```
401
469
  *
402
470
  * @param adapter - The blockchain adapter type (e.g. EVM, SOLANA)
403
- * @param name - The connector name (e.g. "MetaMask", "Phantom")
471
+ * @param name - The connector name (e.g. "MetaMask", "Phantom"), as the wallet reports it or as {@link formatConnectorName} gave it
404
472
  * @returns A formatted connector type string in format "orbit-adapter:connector"
405
473
  *
406
474
  * @remarks
407
- * The function:
408
- * 1. Combines adapter type with connector name using ":" as separator
409
- * 2. Removes all whitespace from connector name
410
- * 3. Converts connector name to lowercase
411
- * This ensures consistent connector type identifiers across the application
412
- * and normalizes connector names for better UX/consistency.
413
- */
414
- declare function getConnectorTypeFromName(adapter: OrbitAdapter, name: string): string;
475
+ * The function goes through {@link formatConnectorName}: known names are mapped, any other has its whitespace removed
476
+ * and is lowercased. So one wallet has one type wherever it is read, on its connection and on its transactions, and a
477
+ * value that already went through the mapping stays as it is.
478
+ */
479
+ declare function getConnectorTypeFromName(adapter: OrbitAdapter, name: string): ConnectorType;
415
480
 
416
481
  /**
417
482
  * Returns the default network and educational links for an adapter, e.g. to render a
@@ -449,10 +514,36 @@ declare const getNetworkData: (adapter: OrbitAdapter) => {
449
514
  *
450
515
  * @param key - The storage key
451
516
  * @param area - The storage to read: `localStorage` (default) or `sessionStorage`
452
- * @returns The parsed value or undefined if data is not found/invalid, or in an SSR context
517
+ * @returns The parsed value or undefined if data is not found/invalid, in an SSR context, or when the browser refuses
518
+ * the storage
453
519
  */
454
520
  declare function getParsedStorageItem<ReturnType>(key: string, area?: 'localStorage' | 'sessionStorage'): ReturnType | undefined;
455
521
 
522
+ /**
523
+ * The wallet part of a connector type.
524
+ *
525
+ * @example
526
+ * ```typescript
527
+ * getWalletFromConnectorType('evm:metamask'); // "metamask"
528
+ * getWalletFromConnectorType('metamask'); // undefined
529
+ * ```
530
+ *
531
+ * @param connectorType - A connector type, in the format "orbit-adapter:connector".
532
+ * @returns The part after the adapter, or `undefined` when there is no adapter or no value.
533
+ */
534
+ declare function getWalletFromConnectorType(connectorType: string | null | undefined): string | undefined;
535
+
536
+ /**
537
+ * One object for all copies of a package on a page, kept on `globalThis` under `Symbol.for(key)`. A bundler can load a
538
+ * package twice, and two copies of a React context or a registry do not see each other.
539
+ *
540
+ * @template T - The type of the object.
541
+ * @param key - The name of the symbol. It must never change: published copies find each other through it.
542
+ * @param create - Makes the object, called only when no copy has made it yet.
543
+ * @returns The object.
544
+ */
545
+ declare function globalSingleton<T>(key: string, create: () => T): T;
546
+
456
547
  /**
457
548
  * Helper utilities for managing impersonated wallet addresses
458
549
  *
@@ -480,7 +571,7 @@ declare const impersonatedHelpers: {
480
571
  * @param address - Ethereum or Solana address to impersonate
481
572
  * @returns undefined in SSR context, void in browser
482
573
  */
483
- setImpersonated: (address: string) => void;
574
+ setImpersonated: (address: string) => void | undefined;
484
575
  /**
485
576
  * Retrieves the current impersonated address from localStorage
486
577
  *
@@ -500,9 +591,17 @@ declare const impersonatedHelpers: {
500
591
  *
501
592
  * @returns undefined in SSR context, void in browser
502
593
  */
503
- removeImpersonated: () => void;
594
+ removeImpersonated: () => void | undefined;
504
595
  };
505
596
 
597
+ /**
598
+ * Whether a value is an object with fields to read: anything but `null` and an array, class instances included.
599
+ *
600
+ * @param value - The value.
601
+ * @returns `true` for an object.
602
+ */
603
+ declare function isRecord(value: unknown): value is Record<string, unknown>;
604
+
506
605
  /**
507
606
  * Checks if the current window is running inside a Safe App iframe
508
607
  * by attempting postMessage communication with the parent window.
@@ -524,6 +623,27 @@ declare const isInSecureIframe: boolean;
524
623
  */
525
624
  declare const isSafeApp: boolean;
526
625
 
626
+ /**
627
+ * A URL without the slashes at its end.
628
+ *
629
+ * @param url - The URL.
630
+ * @returns The URL without them.
631
+ */
632
+ declare function trimTrailingSlashes(url: string): string;
633
+ /**
634
+ * Joins a base URL and a path with one slash, as an explorer URL may end in a slash and a path may start with one.
635
+ *
636
+ * @example
637
+ * ```typescript
638
+ * joinUrlPath('https://etherscan.io/', '/tx/0x1'); // "https://etherscan.io/tx/0x1"
639
+ * ```
640
+ *
641
+ * @param base - The base URL.
642
+ * @param path - The path. Without it the base comes back as it is.
643
+ * @returns The joined URL.
644
+ */
645
+ declare function joinUrlPath(base: string, path?: string): string;
646
+
527
647
  /**
528
648
  * Connection data persisted by {@link lastConnectedConnectorHelpers}.
529
649
  */
@@ -567,7 +687,7 @@ declare const lastConnectedConnectorHelpers: {
567
687
  * @param options - Whether the wallet is remembered after the tab closes.
568
688
  * @returns undefined in SSR context, void in browser
569
689
  */
570
- setLastConnectedConnector: ({ connectorType, chainId, address }: LastConnectedConnector, options?: WalletMemoryOptions) => undefined;
690
+ setLastConnectedConnector: ({ connectorType, chainId, address }: LastConnectedConnector, options?: WalletMemoryOptions) => void;
571
691
  /**
572
692
  * Retrieves the current last connected wallet data, from sessionStorage first, then from localStorage.
573
693
  *
@@ -585,7 +705,7 @@ declare const lastConnectedConnectorHelpers: {
585
705
  *
586
706
  * @returns undefined in SSR context, void in browser
587
707
  */
588
- removeLastConnectedConnector: () => undefined;
708
+ removeLastConnectedConnector: () => void;
589
709
  };
590
710
 
591
711
  /**
@@ -709,7 +829,7 @@ declare const recentlyConnectedConnectorsListHelpers: {
709
829
  * });
710
830
  * ```
711
831
  */
712
- setRecentlyConnectedConnectorsList: (connectors: RecentlyConnectedConnectorsList) => void;
832
+ setRecentlyConnectedConnectorsList: (connectors: RecentlyConnectedConnectorsList) => void | undefined;
713
833
  /**
714
834
  * Retrieves the current recently connected connectors list from localStorage.
715
835
  *
@@ -851,7 +971,7 @@ declare const recentlyConnectedConnectorsListHelpers: {
851
971
  * recentlyConnectedConnectorsListHelpers.removeRecentlyConnectedConnectorsList();
852
972
  * ```
853
973
  */
854
- removeRecentlyConnectedConnectorsList: () => void;
974
+ removeRecentlyConnectedConnectorsList: () => void | undefined;
855
975
  };
856
976
 
857
977
  /**
@@ -903,6 +1023,21 @@ declare const selectAdapterByKey: <A extends {
903
1023
  adapterKey: OrbitAdapter;
904
1024
  } & OrbitGenericAdapter<A>) => A | undefined;
905
1025
 
1026
+ /**
1027
+ * An address or a hash shortened to its start and end, as wallets show it.
1028
+ *
1029
+ * @example
1030
+ * ```typescript
1031
+ * shortAddress('0x1111111111111111111111111111111111112222'); // "0x1111…2222"
1032
+ * ```
1033
+ *
1034
+ * @param address - The address or hash (`0x…` or base58).
1035
+ * @param head - Characters kept at the start; `0x` counts toward it (default `6` for `0x`, `4` otherwise).
1036
+ * @param tail - Characters kept at the end (default `4`).
1037
+ * @returns The shortened value; a value that nothing would be saved on stays unchanged.
1038
+ */
1039
+ declare function shortAddress(address: string, head?: number, tail?: number): string;
1040
+
906
1041
  /**
907
1042
  * CAIP-2 chain IDs of the public Solana clusters. By CAIP-30, the reference is the first 32 characters of the base58
908
1043
  * genesis hash of the cluster.
@@ -971,5 +1106,5 @@ declare function getSolanaChainId(chainId: string | number): string | undefined;
971
1106
  */
972
1107
  declare function waitFor(predicate: () => boolean | undefined, maxChecks?: number, checkIntervalMs?: number): Promise<void>;
973
1108
 
974
- export { OrbitAdapter, SOLANA_CHAIN_IDS, delay, detectSafeApp, filterUniqueByKey, formatCaip10AccountId, formatCaip19AssetId, formatConnectorChainId, formatConnectorName, getAdapterFromConnectorType, getConnectorTypeFromName, getNetworkData, getParsedStorageItem, getSolanaChainId, getSolanaCluster, impersonatedHelpers, isAddress, isInSecureIframe, isSafeApp, isSolanaChain, lastConnectedConnectorHelpers, normalizeError, parseCaip10AccountId, parseCaip19AssetId, parseCaip2ChainId, recentlyConnectedConnectorsListHelpers, selectAdapterByKey, setChainId, toCaip2ChainId, toEvmChainId, waitFor };
1109
+ export { IMPERSONATED_CONNECTOR_ID, OrbitAdapter, SAFE_CONNECTOR_ID, SOLANA_CHAIN_IDS, delay, detectSafeApp, errorChain, filterUniqueByKey, formatBaseUnits, formatCaip10AccountId, formatCaip19AssetId, formatConnectorChainId, formatConnectorName, getAdapterFromConnectorType, getBrowserStorage, getConnectorTypeFromName, getNetworkData, getParsedStorageItem, getSolanaChainId, getSolanaCluster, getWalletFromConnectorType, globalSingleton, impersonatedHelpers, isAddress, isInSecureIframe, isRecord, isSafeApp, isSameAddress, isSolanaChain, joinUrlPath, lastConnectedConnectorHelpers, normalizeAccountAddress, normalizeError, parseCaip10AccountId, parseCaip19AssetId, parseCaip2ChainId, readBrowserStorage, recentlyConnectedConnectorsListHelpers, selectAdapterByKey, setChainId, shortAddress, toCaip2ChainId, toEvmChainId, trimTrailingSlashes, waitFor };
975
1110
  export type { BaseAdapter, Caip10AccountId, Caip19AssetId, Caip2ChainId, ChainIdentifierArray, ConnectorType, LastConnectedConnector, OrbitGenericAdapter, RecentlyConnectedConnectorData, RecentlyConnectedConnectorsList, SolanaCluster, TuwaErrorState, WalletMemoryOptions };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var p=(o=>(o.EVM="evm",o.SOLANA="solana",o.Starknet="starknet",o))(p||{});function b(e){return /^0x[a-fA-F0-9]{40}$/.test(e.trim())}function x(e){return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(e.trim())}function g(e,n="auto"){if(!e)return false;let t=e.trim();switch(n){case "evm":return b(t);case "solana":return x(t);default:return b(t)||x(t)}}var w={mainnet:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",devnet:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",testnet:"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"},C="solana:",R={mainnet:"mainnet","mainnet-beta":"mainnet",devnet:"devnet",testnet:"testnet",localnet:"localnet","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"mainnet",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"devnet","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"testnet","4uhcVJyU9pJkvQyS88uRfhDSfZSm8DoR":"testnet"};function y(e){if(typeof e!="string")return;let n=e.startsWith(C)?e.slice(C.length):e;return Object.hasOwn(R,n)?R[n]:void 0}function d(e){let n=y(e);if(n)return n==="localnet"?`${C}localnet`:w[n]}var S=/^[-a-z0-9]{3,8}$/,I=/^[-_a-zA-Z0-9]{1,32}$/,N=/^[-.%a-zA-Z0-9]{1,128}$/,h=/^[-.%a-zA-Z0-9]{1,128}$/,$=/^(?:eip155:)?([1-9][0-9]{0,15})$/;function l(e){let n=e.indexOf(":");if(n<0)return;let t=e.slice(0,n),o=e.slice(n+1);return S.test(t)&&I.test(o)?{namespace:t,reference:o}:void 0}function T(e){if(typeof e=="number")return Number.isSafeInteger(e)&&e>0?`eip155:${e}`:void 0;let n=d(e);return n||(/^[1-9][0-9]{0,15}$/.test(e)?`eip155:${e}`:l(e)?e:void 0)}function Y(e){let n=typeof e=="number"?e:Number($.exec(e)?.[1]);return Number.isSafeInteger(n)&&n>0?n:void 0}function k(e,n){return e==="eip155"?g(n,"evm"):e==="solana"?g(n,"solana"):N.test(n)}function z(e,n){let t=T(e);if(!t)return;let o=l(t),r=n.trim();if(!(!o||!k(o.namespace,r)))return `${t}:${r}`}function V(e){let n=e.lastIndexOf(":");if(n<0)return;let t=l(e.slice(0,n)),o=e.slice(n+1);if(!(!t||!k(t.namespace,o)))return {chainId:`${t.namespace}:${t.reference}`,namespace:t.namespace,reference:t.reference,address:o}}function W(e,n,t){let o=T(e);if(!(!o||!S.test(n)||!h.test(t)))return `${o}/${n}:${t}`}function H(e){let n=e.indexOf("/");if(n<0)return;let t=l(e.slice(0,n)),o=e.slice(n+1),r=o.indexOf(":");if(!t||r<0)return;let s=o.slice(0,r),u=o.slice(r+1);if(!(!S.test(s)||!h.test(u)))return {chainId:`${t.namespace}:${t.reference}`,assetNamespace:s,assetReference:u}}function Z(e){return y(e)!==void 0}function G(e){return d(e)??e}var X=(e,n)=>new Promise(t=>{let o=()=>{setTimeout(()=>t(e),n);};typeof window<"u"?o():setTimeout(o,0);});function ne(e,n){let t=new Set;return e.filter(o=>{let r=o[n];return t.has(r)?false:(t.add(r),true)})}function se(e,n){if(typeof e!="string")return e;if(n==="solana"){let t=d(e);if(t)return t}return e.startsWith(`${n}:`)?e:`${n}:${e}`}var M=new Map([["Impersonated Connector","impersonatedwallet"],["Safe","safe"],["Trust","trust"],["Trust Wallet","trust"],["Brave \u041A\u043E\u0448\u0435\u043B\u0435\u043A","brave"],["Brave Wallet","brave"],["Base Account","coinbase"]]),ae=e=>M.get(e)??e.replace(/\s+/g,"").toLowerCase();function ue(e){return e?.split(":")[0]??"evm"}function le(e,n){return `${e}:${n.replace(/\s+/g,"").toLowerCase()}`}var we=e=>{switch(e){case "evm":return {chain:{chainId:1,name:"Ethereum"},links:{aboutNetwork:"https://ethereum.org/developers/docs/intro-to-ethereum/",choseWallet:"https://ethereum.org/wallets/find-wallet/",about:"https://ethereum.org/wallets/"}};case "solana":return {chain:{chainId:w.mainnet,name:"Solana"},links:{aboutNetwork:"https://solana.com/en/learn/what-is-solana",choseWallet:"https://solana.com/en/solana-wallets",about:"https://solana.com/en/learn/what-is-a-wallet"}}}};function i(e,n="localStorage"){if(typeof window>"u"||!window[n])return;let t=window[n].getItem(e);if(t)try{return JSON.parse(t)}catch(o){console.error(`Error parsing ${e} from ${n}:`,o);return}}var Ae={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};async function xe(e=1e3){return typeof window>"u"||window===window.parent||window.location.protocol!=="https:"?false:new Promise(n=>{let t=setTimeout(()=>{window.removeEventListener("message",o),n(false);},e);function o(s){s.data&&typeof s.data=="object"&&("safeAddress"in s.data||s.data.data&&"safeAddress"in s.data.data||s.data.method==="getInfo")&&(clearTimeout(t),window.removeEventListener("message",o),n(true));}window.addEventListener("message",o);let r=Math.trunc(Math.random()*1e6);window.parent.postMessage({id:r,method:"getSafeInfo",env:{sdkVersion:"1.0.0"}},"*");})}var v=typeof window<"u"&&window!==window.parent&&window.location.protocol==="https:",Re=v;var a="orbit-core:lastConnectedConnector",L=()=>i(a,"sessionStorage")??i(a),ke={STORAGE_KEY:a,lastConnectedConnector:L(),setLastConnectedConnector:({connectorType:e,chainId:n,address:t},o={})=>{if(typeof window>"u")return;let r=o.remember??true,[s,u]=r?[window.localStorage,window.sessionStorage]:[window.sessionStorage,window.localStorage];s?.setItem(a,JSON.stringify({connectorType:e,chainId:n,address:t})),u?.removeItem(a);},getLastConnectedConnector:()=>L(),isLastConnectedConnectorRemembered:()=>{if(i(a,"sessionStorage"))return false;if(i(a))return true},removeLastConnectedConnector:()=>{typeof window>"u"||(window.localStorage.removeItem(a),window.sessionStorage?.removeItem(a));}};var _=["code","name","shortMessage","details","cause","metaMessages","data","reason","method","transaction","receipt","action","version"];function P(){let e=new WeakSet;return (n,t)=>{if(t===null||typeof t!="object")return typeof t=="function"||typeof t=="symbol"?void 0:typeof t=="bigint"?t.toString():t;if(e.has(t))return "[Circular]";if(e.add(t),t instanceof Error){let o={name:t.name,message:t.message};t.stack&&(o.stack=t.stack);for(let r of Object.keys(t))r in o||(o[r]=t[r]);return o}return t}}function D(e){let n={};if(e&&typeof e=="object"){for(let t of _)t in e&&(n[t]=e[t]);"message"in e&&(n.message=e.message),"stack"in e&&(n.stack=e.stack);}return n}function E(e){try{let n=P(),t=JSON.stringify(e,n);return JSON.parse(t)}catch{return {_serializationError:"Failed to serialize error object"}}}function Ee(e){if(e==null)return {message:"Unknown error",raw:{originalType:"null"}};if(typeof e=="string")return {message:e,raw:{message:e,originalType:"string"}};if(e instanceof Error){let n=("shortMessage"in e&&typeof e.shortMessage=="string"?e.shortMessage:e.message)||"Unknown error",t=D(e),o=E(e);return {message:n,raw:{...o,...t,originalType:e.name||"Error"}}}return typeof e=="object"?{message:("message"in e&&typeof e.message=="string"?e.message:"shortMessage"in e&&typeof e.shortMessage=="string"?e.shortMessage:"Unknown error")||"Unknown error",raw:{...E(e),originalType:"object"}}:{message:String(e),raw:{value:String(e),originalType:typeof e}}}var c="orbit-core:recentlyConnectedConnectorsListHelpers",A=e=>i(c,e)??{},m=(e,n)=>window[e]?.setItem(c,JSON.stringify(n)),O=(e,n)=>{let{[n]:t,...o}=e;return o},f={STORAGE_KEY:c,recentlyConnectedConnectorsList:i(c),setRecentlyConnectedConnectorsList:e=>typeof window<"u"?window.localStorage.setItem(f.STORAGE_KEY,JSON.stringify(e)):void 0,getRecentlyConnectedConnectorsList:()=>{let e=i(c),n=i(c,"sessionStorage");if(!(!e&&!n))return {...e,...n}},addConnector:(e,n,t={})=>{if(typeof window>"u")return;let[o,r]=t.remember??true?["localStorage","sessionStorage"]:["sessionStorage","localStorage"];m(o,{...A(o),[e]:n});let s=A(r);e in s&&m(r,O(s,e));},removeConnector:e=>{if(!(typeof window>"u"))for(let n of ["localStorage","sessionStorage"]){let t=A(n);e in t&&m(n,O(t,e));}},hasConnector:e=>{if(typeof window>"u")return;let n=f.getRecentlyConnectedConnectorsList();return n?e in n:false},getConnector:e=>typeof window>"u"?void 0:f.getRecentlyConnectedConnectorsList()?.[e],getConnectorCount:()=>{if(typeof window>"u")return 0;let e=f.getRecentlyConnectedConnectorsList();return e?Object.keys(e).length:0},getConnectorsSortedByTime:()=>{if(typeof window>"u")return [];let e=f.getRecentlyConnectedConnectorsList();return e?Object.entries(e).sort(([,n],[,t])=>t.disconnectedTimestamp-n.disconnectedTimestamp):[]},removeConnectorsOlderThan:e=>{if(!(typeof window>"u"))for(let n of ["localStorage","sessionStorage"]){let t=i(c,n);if(!t)continue;let o=Object.fromEntries(Object.entries(t).filter(([,r])=>r.disconnectedTimestamp>=e));m(n,o);}},removeRecentlyConnectedConnectorsList:()=>typeof window<"u"?window.localStorage.removeItem(f.STORAGE_KEY):void 0};var $e=({adapterKey:e,adapter:n})=>{if(Array.isArray(n)){if(n.length===0){console.error("Adapter selection failed: The provided adapters array is empty.");return}let t=n.find(o=>o.key===e);return t||(console.warn(`No adapter found for key: "${e}". Falling back to the first available adapter: "${n[0].key}".`),n[0])}return n};async function ve(e,n=50,t=200){for(let o=0;o<n;o++){if(e())return;await new Promise(r=>setTimeout(r,t));}throw new Error("Predicate not fulfilled in time")}
2
- exports.OrbitAdapter=p;exports.SOLANA_CHAIN_IDS=w;exports.delay=X;exports.detectSafeApp=xe;exports.filterUniqueByKey=ne;exports.formatCaip10AccountId=z;exports.formatCaip19AssetId=W;exports.formatConnectorChainId=se;exports.formatConnectorName=ae;exports.getAdapterFromConnectorType=ue;exports.getConnectorTypeFromName=le;exports.getNetworkData=we;exports.getParsedStorageItem=i;exports.getSolanaChainId=d;exports.getSolanaCluster=y;exports.impersonatedHelpers=Ae;exports.isAddress=g;exports.isInSecureIframe=v;exports.isSafeApp=Re;exports.isSolanaChain=Z;exports.lastConnectedConnectorHelpers=ke;exports.normalizeError=Ee;exports.parseCaip10AccountId=V;exports.parseCaip19AssetId=H;exports.parseCaip2ChainId=l;exports.recentlyConnectedConnectorsListHelpers=f;exports.selectAdapterByKey=$e;exports.setChainId=G;exports.toCaip2ChainId=T;exports.toEvmChainId=Y;exports.waitFor=ve;
1
+ 'use strict';var l=(r=>(r.EVM="evm",r.SOLANA="solana",r.Starknet="starknet",r))(l||{});function R(e,n){return e==="eip155"?n.toLowerCase():n}function Y(e,n,t){return R(e,n)===R(e,t)}function T(e){return /^0x[a-fA-F0-9]{40}$/.test(e.trim())}function k(e){return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(e.trim())}function w(e,n="auto"){if(!e)return false;let t=e.trim();switch(n){case "evm":return T(t);case "solana":return k(t);default:return T(t)||k(t)}}function i(e="localStorage"){if(typeof window>"u")return null;try{return window[e]??null}catch{return null}}function f(e,n="localStorage"){try{return i(n)?.getItem(e)??null}catch{return null}}var x={mainnet:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",devnet:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",testnet:"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"},S="solana:",E={mainnet:"mainnet","mainnet-beta":"mainnet",devnet:"devnet",testnet:"testnet",localnet:"localnet","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"mainnet",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"devnet","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"testnet","4uhcVJyU9pJkvQyS88uRfhDSfZSm8DoR":"testnet"};function b(e){if(typeof e!="string")return;let n=e.startsWith(S)?e.slice(S.length):e;return Object.hasOwn(E,n)?E[n]:void 0}function u(e){let n=b(e);if(n)return n==="localnet"?`${S}localnet`:x[n]}var A=/^[-a-z0-9]{3,8}$/,v=/^[-_a-zA-Z0-9]{1,32}$/,D=/^[-.%a-zA-Z0-9]{1,128}$/,L=/^[-.%a-zA-Z0-9]{1,128}$/,P=/^(?:eip155:)?([1-9][0-9]{0,15})$/;function m(e){let n=e.indexOf(":");if(n<0)return;let t=e.slice(0,n),r=e.slice(n+1);return A.test(t)&&v.test(r)?{namespace:t,reference:r}:void 0}function O(e){if(typeof e=="number")return Number.isSafeInteger(e)&&e>0?`eip155:${e}`:void 0;let n=u(e);return n||(/^[1-9][0-9]{0,15}$/.test(e)?`eip155:${e}`:m(e)?e:void 0)}function ee(e){let n=typeof e=="number"?e:Number(P.exec(e)?.[1]);return Number.isSafeInteger(n)&&n>0?n:void 0}function I(e,n){return e==="eip155"?w(n,"evm"):e==="solana"?w(n,"solana"):D.test(n)}function ne(e,n){let t=O(e);if(!t)return;let r=m(t),o=n.trim();if(!(!r||!I(r.namespace,o)))return `${t}:${o}`}function te(e){let n=e.lastIndexOf(":");if(n<0)return;let t=m(e.slice(0,n)),r=e.slice(n+1);if(!(!t||!I(t.namespace,r)))return {chainId:`${t.namespace}:${t.reference}`,namespace:t.namespace,reference:t.reference,address:r}}function re(e,n,t){let r=O(e);if(!(!r||!A.test(n)||!L.test(t)))return `${r}/${n}:${t}`}function oe(e){let n=e.indexOf("/");if(n<0)return;let t=m(e.slice(0,n)),r=e.slice(n+1),o=r.indexOf(":");if(!t||o<0)return;let s=r.slice(0,o),p=r.slice(o+1);if(!(!A.test(s)||!L.test(p)))return {chainId:`${t.namespace}:${t.reference}`,assetNamespace:s,assetReference:p}}function ae(e){return b(e)!==void 0}function ce(e){return u(e)??e}var ue=(e,n)=>new Promise(t=>{let r=()=>{setTimeout(()=>t(e),n);};typeof window<"u"?r():setTimeout(r,0);});function pe(e){let n=[];for(let t=e;t!=null&&!n.includes(t);)n.push(t),t=typeof t=="object"?t.cause:void 0;return n}function me(e,n){let t=new Set;return e.filter(r=>{let o=r[n];return t.has(o)?false:(t.add(o),true)})}function Ce(e,n){if(e==null)return;let t=String(e);if(!/^\d+$/.test(t))return;let r=t.padStart(n+1,"0"),o=r.slice(0,r.length-n).replace(/^0+(?=\d)/,""),s=r.slice(r.length-n).replace(/0+$/,"");return s?`${o}.${s}`:o}function xe(e,n){if(typeof e!="string")return e;if(n==="solana"){let t=u(e);if(t)return t}return e.startsWith(`${n}:`)?e:`${n}:${e}`}var j="impersonatedwallet",B="safe",F=new Map([["Impersonated Connector",j],["Safe",B],["Trust","trust"],["Trust Wallet","trust"],["Brave \u041A\u043E\u0448\u0435\u043B\u0435\u043A","brave"],["Brave Wallet","brave"],["Base Account","coinbase"]]),$=e=>F.get(e)??e.replace(/\s+/g,"").toLowerCase();function Te(e){return e?.split(":")[0]??"evm"}function Le(e,n){return `${e}:${$(n)}`}var Ne=e=>{switch(e){case "evm":return {chain:{chainId:1,name:"Ethereum"},links:{aboutNetwork:"https://ethereum.org/developers/docs/intro-to-ethereum/",choseWallet:"https://ethereum.org/wallets/find-wallet/",about:"https://ethereum.org/wallets/"}};case "solana":return {chain:{chainId:x.mainnet,name:"Solana"},links:{aboutNetwork:"https://solana.com/en/learn/what-is-solana",choseWallet:"https://solana.com/en/solana-wallets",about:"https://solana.com/en/learn/what-is-a-wallet"}}}};function a(e,n="localStorage"){let t=f(e,n);if(t)try{return JSON.parse(t)}catch(r){console.error(`Error parsing ${e} from ${n}:`,r);return}}function De(e){return e?.split(":")[1]}function je(e,n){let t=globalThis,r=Symbol.for(e);return t[r]??=n()}var g="satellite-connect:impersonatedAddress",Ue={impersonatedAddress:f(g)??"",setImpersonated:e=>i()?.setItem(g,e),getImpersonated:()=>typeof window<"u"?f(g):void 0,removeImpersonated:()=>i()?.removeItem(g)};function ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function Ke(e=1e3){return typeof window>"u"||window===window.parent||window.location.protocol!=="https:"?false:new Promise(n=>{let t=setTimeout(()=>{window.removeEventListener("message",r),n(false);},e);function r(s){s.data&&typeof s.data=="object"&&("safeAddress"in s.data||s.data.data&&"safeAddress"in s.data.data||s.data.method==="getInfo")&&(clearTimeout(t),window.removeEventListener("message",r),n(true));}window.addEventListener("message",r);let o=Math.trunc(Math.random()*1e6);window.parent.postMessage({id:o,method:"getSafeInfo",env:{sdkVersion:"1.0.0"}},"*");})}var U=typeof window<"u"&&window!==window.parent&&window.location.protocol==="https:",Ve=U;function W(e){return e.replace(/\/+$/,"")}function He(e,n){return n?`${W(e)}/${n.replace(/^\/+/,"")}`:e}var c="orbit-core:lastConnectedConnector",N=()=>a(c,"sessionStorage")??a(c),Qe={STORAGE_KEY:c,lastConnectedConnector:N(),setLastConnectedConnector:({connectorType:e,chainId:n,address:t},r={})=>{let o=r.remember??true,[s,p]=o?[i("localStorage"),i("sessionStorage")]:[i("sessionStorage"),i("localStorage")];s?.setItem(c,JSON.stringify({connectorType:e,chainId:n,address:t})),p?.removeItem(c);},getLastConnectedConnector:()=>N(),isLastConnectedConnectorRemembered:()=>{if(a(c,"sessionStorage"))return false;if(a(c))return true},removeLastConnectedConnector:()=>{i("localStorage")?.removeItem(c),i("sessionStorage")?.removeItem(c);}};var z=["code","name","shortMessage","details","cause","metaMessages","data","reason","method","transaction","receipt","action","version"];function J(){let e=new WeakSet;return (n,t)=>{if(t===null||typeof t!="object")return typeof t=="function"||typeof t=="symbol"?void 0:typeof t=="bigint"?t.toString():t;if(e.has(t))return "[Circular]";if(e.add(t),t instanceof Error){let r={name:t.name,message:t.message};t.stack&&(r.stack=t.stack);for(let o of Object.keys(t))o in r||(r[o]=t[o]);return r}return t}}function K(e){let n={};if(e&&typeof e=="object"){for(let t of z)t in e&&(n[t]=e[t]);"message"in e&&(n.message=e.message),"stack"in e&&(n.stack=e.stack);}return n}function M(e){try{let n=J(),t=JSON.stringify(e,n);return JSON.parse(t)}catch{return {_serializationError:"Failed to serialize error object"}}}function en(e){if(e==null)return {message:"Unknown error",raw:{originalType:"null"}};if(typeof e=="string")return {message:e,raw:{message:e,originalType:"string"}};if(e instanceof Error){let n=("shortMessage"in e&&typeof e.shortMessage=="string"?e.shortMessage:e.message)||"Unknown error",t=K(e),r=M(e);return {message:n,raw:{...r,...t,originalType:e.name||"Error"}}}return typeof e=="object"?{message:("message"in e&&typeof e.message=="string"?e.message:"shortMessage"in e&&typeof e.shortMessage=="string"?e.shortMessage:"Unknown error")||"Unknown error",raw:{...M(e),originalType:"object"}}:{message:String(e),raw:{value:String(e),originalType:typeof e}}}var d="orbit-core:recentlyConnectedConnectorsListHelpers",h=e=>a(d,e)??{},C=(e,n)=>i(e)?.setItem(d,JSON.stringify(n)),_=(e,n)=>{let{[n]:t,...r}=e;return r},y={STORAGE_KEY:d,recentlyConnectedConnectorsList:a(d),setRecentlyConnectedConnectorsList:e=>i()?.setItem(d,JSON.stringify(e)),getRecentlyConnectedConnectorsList:()=>{let e=a(d),n=a(d,"sessionStorage");if(!(!e&&!n))return {...e,...n}},addConnector:(e,n,t={})=>{if(typeof window>"u")return;let[r,o]=t.remember??true?["localStorage","sessionStorage"]:["sessionStorage","localStorage"];C(r,{...h(r),[e]:n});let s=h(o);e in s&&C(o,_(s,e));},removeConnector:e=>{if(!(typeof window>"u"))for(let n of ["localStorage","sessionStorage"]){let t=h(n);e in t&&C(n,_(t,e));}},hasConnector:e=>{if(typeof window>"u")return;let n=y.getRecentlyConnectedConnectorsList();return n?e in n:false},getConnector:e=>typeof window>"u"?void 0:y.getRecentlyConnectedConnectorsList()?.[e],getConnectorCount:()=>{if(typeof window>"u")return 0;let e=y.getRecentlyConnectedConnectorsList();return e?Object.keys(e).length:0},getConnectorsSortedByTime:()=>{if(typeof window>"u")return [];let e=y.getRecentlyConnectedConnectorsList();return e?Object.entries(e).sort(([,n],[,t])=>t.disconnectedTimestamp-n.disconnectedTimestamp):[]},removeConnectorsOlderThan:e=>{if(!(typeof window>"u"))for(let n of ["localStorage","sessionStorage"]){let t=a(d,n);if(!t)continue;let r=Object.fromEntries(Object.entries(t).filter(([,o])=>o.disconnectedTimestamp>=e));C(n,r);}},removeRecentlyConnectedConnectorsList:()=>i()?.removeItem(d)};var sn=({adapterKey:e,adapter:n})=>{if(Array.isArray(n)){if(n.length===0){console.error("Adapter selection failed: The provided adapters array is empty.");return}let t=n.find(r=>r.key===e);return t||(console.warn(`No adapter found for key: "${e}". Falling back to the first available adapter: "${n[0].key}".`),n[0])}return n};function cn(e,n=e.startsWith("0x")?6:4,t=4){return e.length<=n+t+1?e:`${e.slice(0,n)}\u2026${e.slice(-t)}`}async function un(e,n=50,t=200){for(let r=0;r<n;r++){if(e())return;await new Promise(o=>setTimeout(o,t));}throw new Error("Predicate not fulfilled in time")}
2
+ exports.IMPERSONATED_CONNECTOR_ID=j;exports.OrbitAdapter=l;exports.SAFE_CONNECTOR_ID=B;exports.SOLANA_CHAIN_IDS=x;exports.delay=ue;exports.detectSafeApp=Ke;exports.errorChain=pe;exports.filterUniqueByKey=me;exports.formatBaseUnits=Ce;exports.formatCaip10AccountId=ne;exports.formatCaip19AssetId=re;exports.formatConnectorChainId=xe;exports.formatConnectorName=$;exports.getAdapterFromConnectorType=Te;exports.getBrowserStorage=i;exports.getConnectorTypeFromName=Le;exports.getNetworkData=Ne;exports.getParsedStorageItem=a;exports.getSolanaChainId=u;exports.getSolanaCluster=b;exports.getWalletFromConnectorType=De;exports.globalSingleton=je;exports.impersonatedHelpers=Ue;exports.isAddress=w;exports.isInSecureIframe=U;exports.isRecord=ze;exports.isSafeApp=Ve;exports.isSameAddress=Y;exports.isSolanaChain=ae;exports.joinUrlPath=He;exports.lastConnectedConnectorHelpers=Qe;exports.normalizeAccountAddress=R;exports.normalizeError=en;exports.parseCaip10AccountId=te;exports.parseCaip19AssetId=oe;exports.parseCaip2ChainId=m;exports.readBrowserStorage=f;exports.recentlyConnectedConnectorsListHelpers=y;exports.selectAdapterByKey=sn;exports.setChainId=ce;exports.shortAddress=cn;exports.toCaip2ChainId=O;exports.toEvmChainId=ee;exports.trimTrailingSlashes=W;exports.waitFor=un;
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var p=(o=>(o.EVM="evm",o.SOLANA="solana",o.Starknet="starknet",o))(p||{});function b(e){return /^0x[a-fA-F0-9]{40}$/.test(e.trim())}function x(e){return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(e.trim())}function g(e,n="auto"){if(!e)return false;let t=e.trim();switch(n){case "evm":return b(t);case "solana":return x(t);default:return b(t)||x(t)}}var w={mainnet:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",devnet:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",testnet:"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"},C="solana:",R={mainnet:"mainnet","mainnet-beta":"mainnet",devnet:"devnet",testnet:"testnet",localnet:"localnet","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"mainnet",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"devnet","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"testnet","4uhcVJyU9pJkvQyS88uRfhDSfZSm8DoR":"testnet"};function y(e){if(typeof e!="string")return;let n=e.startsWith(C)?e.slice(C.length):e;return Object.hasOwn(R,n)?R[n]:void 0}function d(e){let n=y(e);if(n)return n==="localnet"?`${C}localnet`:w[n]}var S=/^[-a-z0-9]{3,8}$/,I=/^[-_a-zA-Z0-9]{1,32}$/,N=/^[-.%a-zA-Z0-9]{1,128}$/,h=/^[-.%a-zA-Z0-9]{1,128}$/,$=/^(?:eip155:)?([1-9][0-9]{0,15})$/;function l(e){let n=e.indexOf(":");if(n<0)return;let t=e.slice(0,n),o=e.slice(n+1);return S.test(t)&&I.test(o)?{namespace:t,reference:o}:void 0}function T(e){if(typeof e=="number")return Number.isSafeInteger(e)&&e>0?`eip155:${e}`:void 0;let n=d(e);return n||(/^[1-9][0-9]{0,15}$/.test(e)?`eip155:${e}`:l(e)?e:void 0)}function Y(e){let n=typeof e=="number"?e:Number($.exec(e)?.[1]);return Number.isSafeInteger(n)&&n>0?n:void 0}function k(e,n){return e==="eip155"?g(n,"evm"):e==="solana"?g(n,"solana"):N.test(n)}function z(e,n){let t=T(e);if(!t)return;let o=l(t),r=n.trim();if(!(!o||!k(o.namespace,r)))return `${t}:${r}`}function V(e){let n=e.lastIndexOf(":");if(n<0)return;let t=l(e.slice(0,n)),o=e.slice(n+1);if(!(!t||!k(t.namespace,o)))return {chainId:`${t.namespace}:${t.reference}`,namespace:t.namespace,reference:t.reference,address:o}}function W(e,n,t){let o=T(e);if(!(!o||!S.test(n)||!h.test(t)))return `${o}/${n}:${t}`}function H(e){let n=e.indexOf("/");if(n<0)return;let t=l(e.slice(0,n)),o=e.slice(n+1),r=o.indexOf(":");if(!t||r<0)return;let s=o.slice(0,r),u=o.slice(r+1);if(!(!S.test(s)||!h.test(u)))return {chainId:`${t.namespace}:${t.reference}`,assetNamespace:s,assetReference:u}}function Z(e){return y(e)!==void 0}function G(e){return d(e)??e}var X=(e,n)=>new Promise(t=>{let o=()=>{setTimeout(()=>t(e),n);};typeof window<"u"?o():setTimeout(o,0);});function ne(e,n){let t=new Set;return e.filter(o=>{let r=o[n];return t.has(r)?false:(t.add(r),true)})}function se(e,n){if(typeof e!="string")return e;if(n==="solana"){let t=d(e);if(t)return t}return e.startsWith(`${n}:`)?e:`${n}:${e}`}var M=new Map([["Impersonated Connector","impersonatedwallet"],["Safe","safe"],["Trust","trust"],["Trust Wallet","trust"],["Brave \u041A\u043E\u0448\u0435\u043B\u0435\u043A","brave"],["Brave Wallet","brave"],["Base Account","coinbase"]]),ae=e=>M.get(e)??e.replace(/\s+/g,"").toLowerCase();function ue(e){return e?.split(":")[0]??"evm"}function le(e,n){return `${e}:${n.replace(/\s+/g,"").toLowerCase()}`}var we=e=>{switch(e){case "evm":return {chain:{chainId:1,name:"Ethereum"},links:{aboutNetwork:"https://ethereum.org/developers/docs/intro-to-ethereum/",choseWallet:"https://ethereum.org/wallets/find-wallet/",about:"https://ethereum.org/wallets/"}};case "solana":return {chain:{chainId:w.mainnet,name:"Solana"},links:{aboutNetwork:"https://solana.com/en/learn/what-is-solana",choseWallet:"https://solana.com/en/solana-wallets",about:"https://solana.com/en/learn/what-is-a-wallet"}}}};function i(e,n="localStorage"){if(typeof window>"u"||!window[n])return;let t=window[n].getItem(e);if(t)try{return JSON.parse(t)}catch(o){console.error(`Error parsing ${e} from ${n}:`,o);return}}var Ae={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};async function xe(e=1e3){return typeof window>"u"||window===window.parent||window.location.protocol!=="https:"?false:new Promise(n=>{let t=setTimeout(()=>{window.removeEventListener("message",o),n(false);},e);function o(s){s.data&&typeof s.data=="object"&&("safeAddress"in s.data||s.data.data&&"safeAddress"in s.data.data||s.data.method==="getInfo")&&(clearTimeout(t),window.removeEventListener("message",o),n(true));}window.addEventListener("message",o);let r=Math.trunc(Math.random()*1e6);window.parent.postMessage({id:r,method:"getSafeInfo",env:{sdkVersion:"1.0.0"}},"*");})}var v=typeof window<"u"&&window!==window.parent&&window.location.protocol==="https:",Re=v;var a="orbit-core:lastConnectedConnector",L=()=>i(a,"sessionStorage")??i(a),ke={STORAGE_KEY:a,lastConnectedConnector:L(),setLastConnectedConnector:({connectorType:e,chainId:n,address:t},o={})=>{if(typeof window>"u")return;let r=o.remember??true,[s,u]=r?[window.localStorage,window.sessionStorage]:[window.sessionStorage,window.localStorage];s?.setItem(a,JSON.stringify({connectorType:e,chainId:n,address:t})),u?.removeItem(a);},getLastConnectedConnector:()=>L(),isLastConnectedConnectorRemembered:()=>{if(i(a,"sessionStorage"))return false;if(i(a))return true},removeLastConnectedConnector:()=>{typeof window>"u"||(window.localStorage.removeItem(a),window.sessionStorage?.removeItem(a));}};var _=["code","name","shortMessage","details","cause","metaMessages","data","reason","method","transaction","receipt","action","version"];function P(){let e=new WeakSet;return (n,t)=>{if(t===null||typeof t!="object")return typeof t=="function"||typeof t=="symbol"?void 0:typeof t=="bigint"?t.toString():t;if(e.has(t))return "[Circular]";if(e.add(t),t instanceof Error){let o={name:t.name,message:t.message};t.stack&&(o.stack=t.stack);for(let r of Object.keys(t))r in o||(o[r]=t[r]);return o}return t}}function D(e){let n={};if(e&&typeof e=="object"){for(let t of _)t in e&&(n[t]=e[t]);"message"in e&&(n.message=e.message),"stack"in e&&(n.stack=e.stack);}return n}function E(e){try{let n=P(),t=JSON.stringify(e,n);return JSON.parse(t)}catch{return {_serializationError:"Failed to serialize error object"}}}function Ee(e){if(e==null)return {message:"Unknown error",raw:{originalType:"null"}};if(typeof e=="string")return {message:e,raw:{message:e,originalType:"string"}};if(e instanceof Error){let n=("shortMessage"in e&&typeof e.shortMessage=="string"?e.shortMessage:e.message)||"Unknown error",t=D(e),o=E(e);return {message:n,raw:{...o,...t,originalType:e.name||"Error"}}}return typeof e=="object"?{message:("message"in e&&typeof e.message=="string"?e.message:"shortMessage"in e&&typeof e.shortMessage=="string"?e.shortMessage:"Unknown error")||"Unknown error",raw:{...E(e),originalType:"object"}}:{message:String(e),raw:{value:String(e),originalType:typeof e}}}var c="orbit-core:recentlyConnectedConnectorsListHelpers",A=e=>i(c,e)??{},m=(e,n)=>window[e]?.setItem(c,JSON.stringify(n)),O=(e,n)=>{let{[n]:t,...o}=e;return o},f={STORAGE_KEY:c,recentlyConnectedConnectorsList:i(c),setRecentlyConnectedConnectorsList:e=>typeof window<"u"?window.localStorage.setItem(f.STORAGE_KEY,JSON.stringify(e)):void 0,getRecentlyConnectedConnectorsList:()=>{let e=i(c),n=i(c,"sessionStorage");if(!(!e&&!n))return {...e,...n}},addConnector:(e,n,t={})=>{if(typeof window>"u")return;let[o,r]=t.remember??true?["localStorage","sessionStorage"]:["sessionStorage","localStorage"];m(o,{...A(o),[e]:n});let s=A(r);e in s&&m(r,O(s,e));},removeConnector:e=>{if(!(typeof window>"u"))for(let n of ["localStorage","sessionStorage"]){let t=A(n);e in t&&m(n,O(t,e));}},hasConnector:e=>{if(typeof window>"u")return;let n=f.getRecentlyConnectedConnectorsList();return n?e in n:false},getConnector:e=>typeof window>"u"?void 0:f.getRecentlyConnectedConnectorsList()?.[e],getConnectorCount:()=>{if(typeof window>"u")return 0;let e=f.getRecentlyConnectedConnectorsList();return e?Object.keys(e).length:0},getConnectorsSortedByTime:()=>{if(typeof window>"u")return [];let e=f.getRecentlyConnectedConnectorsList();return e?Object.entries(e).sort(([,n],[,t])=>t.disconnectedTimestamp-n.disconnectedTimestamp):[]},removeConnectorsOlderThan:e=>{if(!(typeof window>"u"))for(let n of ["localStorage","sessionStorage"]){let t=i(c,n);if(!t)continue;let o=Object.fromEntries(Object.entries(t).filter(([,r])=>r.disconnectedTimestamp>=e));m(n,o);}},removeRecentlyConnectedConnectorsList:()=>typeof window<"u"?window.localStorage.removeItem(f.STORAGE_KEY):void 0};var $e=({adapterKey:e,adapter:n})=>{if(Array.isArray(n)){if(n.length===0){console.error("Adapter selection failed: The provided adapters array is empty.");return}let t=n.find(o=>o.key===e);return t||(console.warn(`No adapter found for key: "${e}". Falling back to the first available adapter: "${n[0].key}".`),n[0])}return n};async function ve(e,n=50,t=200){for(let o=0;o<n;o++){if(e())return;await new Promise(r=>setTimeout(r,t));}throw new Error("Predicate not fulfilled in time")}
2
- export{p as OrbitAdapter,w as SOLANA_CHAIN_IDS,X as delay,xe as detectSafeApp,ne as filterUniqueByKey,z as formatCaip10AccountId,W as formatCaip19AssetId,se as formatConnectorChainId,ae as formatConnectorName,ue as getAdapterFromConnectorType,le as getConnectorTypeFromName,we as getNetworkData,i as getParsedStorageItem,d as getSolanaChainId,y as getSolanaCluster,Ae as impersonatedHelpers,g as isAddress,v as isInSecureIframe,Re as isSafeApp,Z as isSolanaChain,ke as lastConnectedConnectorHelpers,Ee as normalizeError,V as parseCaip10AccountId,H as parseCaip19AssetId,l as parseCaip2ChainId,f as recentlyConnectedConnectorsListHelpers,$e as selectAdapterByKey,G as setChainId,T as toCaip2ChainId,Y as toEvmChainId,ve as waitFor};
1
+ var l=(r=>(r.EVM="evm",r.SOLANA="solana",r.Starknet="starknet",r))(l||{});function R(e,n){return e==="eip155"?n.toLowerCase():n}function Y(e,n,t){return R(e,n)===R(e,t)}function T(e){return /^0x[a-fA-F0-9]{40}$/.test(e.trim())}function k(e){return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(e.trim())}function w(e,n="auto"){if(!e)return false;let t=e.trim();switch(n){case "evm":return T(t);case "solana":return k(t);default:return T(t)||k(t)}}function i(e="localStorage"){if(typeof window>"u")return null;try{return window[e]??null}catch{return null}}function f(e,n="localStorage"){try{return i(n)?.getItem(e)??null}catch{return null}}var x={mainnet:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",devnet:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",testnet:"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"},S="solana:",E={mainnet:"mainnet","mainnet-beta":"mainnet",devnet:"devnet",testnet:"testnet",localnet:"localnet","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"mainnet",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"devnet","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"testnet","4uhcVJyU9pJkvQyS88uRfhDSfZSm8DoR":"testnet"};function b(e){if(typeof e!="string")return;let n=e.startsWith(S)?e.slice(S.length):e;return Object.hasOwn(E,n)?E[n]:void 0}function u(e){let n=b(e);if(n)return n==="localnet"?`${S}localnet`:x[n]}var A=/^[-a-z0-9]{3,8}$/,v=/^[-_a-zA-Z0-9]{1,32}$/,D=/^[-.%a-zA-Z0-9]{1,128}$/,L=/^[-.%a-zA-Z0-9]{1,128}$/,P=/^(?:eip155:)?([1-9][0-9]{0,15})$/;function m(e){let n=e.indexOf(":");if(n<0)return;let t=e.slice(0,n),r=e.slice(n+1);return A.test(t)&&v.test(r)?{namespace:t,reference:r}:void 0}function O(e){if(typeof e=="number")return Number.isSafeInteger(e)&&e>0?`eip155:${e}`:void 0;let n=u(e);return n||(/^[1-9][0-9]{0,15}$/.test(e)?`eip155:${e}`:m(e)?e:void 0)}function ee(e){let n=typeof e=="number"?e:Number(P.exec(e)?.[1]);return Number.isSafeInteger(n)&&n>0?n:void 0}function I(e,n){return e==="eip155"?w(n,"evm"):e==="solana"?w(n,"solana"):D.test(n)}function ne(e,n){let t=O(e);if(!t)return;let r=m(t),o=n.trim();if(!(!r||!I(r.namespace,o)))return `${t}:${o}`}function te(e){let n=e.lastIndexOf(":");if(n<0)return;let t=m(e.slice(0,n)),r=e.slice(n+1);if(!(!t||!I(t.namespace,r)))return {chainId:`${t.namespace}:${t.reference}`,namespace:t.namespace,reference:t.reference,address:r}}function re(e,n,t){let r=O(e);if(!(!r||!A.test(n)||!L.test(t)))return `${r}/${n}:${t}`}function oe(e){let n=e.indexOf("/");if(n<0)return;let t=m(e.slice(0,n)),r=e.slice(n+1),o=r.indexOf(":");if(!t||o<0)return;let s=r.slice(0,o),p=r.slice(o+1);if(!(!A.test(s)||!L.test(p)))return {chainId:`${t.namespace}:${t.reference}`,assetNamespace:s,assetReference:p}}function ae(e){return b(e)!==void 0}function ce(e){return u(e)??e}var ue=(e,n)=>new Promise(t=>{let r=()=>{setTimeout(()=>t(e),n);};typeof window<"u"?r():setTimeout(r,0);});function pe(e){let n=[];for(let t=e;t!=null&&!n.includes(t);)n.push(t),t=typeof t=="object"?t.cause:void 0;return n}function me(e,n){let t=new Set;return e.filter(r=>{let o=r[n];return t.has(o)?false:(t.add(o),true)})}function Ce(e,n){if(e==null)return;let t=String(e);if(!/^\d+$/.test(t))return;let r=t.padStart(n+1,"0"),o=r.slice(0,r.length-n).replace(/^0+(?=\d)/,""),s=r.slice(r.length-n).replace(/0+$/,"");return s?`${o}.${s}`:o}function xe(e,n){if(typeof e!="string")return e;if(n==="solana"){let t=u(e);if(t)return t}return e.startsWith(`${n}:`)?e:`${n}:${e}`}var j="impersonatedwallet",B="safe",F=new Map([["Impersonated Connector",j],["Safe",B],["Trust","trust"],["Trust Wallet","trust"],["Brave \u041A\u043E\u0448\u0435\u043B\u0435\u043A","brave"],["Brave Wallet","brave"],["Base Account","coinbase"]]),$=e=>F.get(e)??e.replace(/\s+/g,"").toLowerCase();function Te(e){return e?.split(":")[0]??"evm"}function Le(e,n){return `${e}:${$(n)}`}var Ne=e=>{switch(e){case "evm":return {chain:{chainId:1,name:"Ethereum"},links:{aboutNetwork:"https://ethereum.org/developers/docs/intro-to-ethereum/",choseWallet:"https://ethereum.org/wallets/find-wallet/",about:"https://ethereum.org/wallets/"}};case "solana":return {chain:{chainId:x.mainnet,name:"Solana"},links:{aboutNetwork:"https://solana.com/en/learn/what-is-solana",choseWallet:"https://solana.com/en/solana-wallets",about:"https://solana.com/en/learn/what-is-a-wallet"}}}};function a(e,n="localStorage"){let t=f(e,n);if(t)try{return JSON.parse(t)}catch(r){console.error(`Error parsing ${e} from ${n}:`,r);return}}function De(e){return e?.split(":")[1]}function je(e,n){let t=globalThis,r=Symbol.for(e);return t[r]??=n()}var g="satellite-connect:impersonatedAddress",Ue={impersonatedAddress:f(g)??"",setImpersonated:e=>i()?.setItem(g,e),getImpersonated:()=>typeof window<"u"?f(g):void 0,removeImpersonated:()=>i()?.removeItem(g)};function ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function Ke(e=1e3){return typeof window>"u"||window===window.parent||window.location.protocol!=="https:"?false:new Promise(n=>{let t=setTimeout(()=>{window.removeEventListener("message",r),n(false);},e);function r(s){s.data&&typeof s.data=="object"&&("safeAddress"in s.data||s.data.data&&"safeAddress"in s.data.data||s.data.method==="getInfo")&&(clearTimeout(t),window.removeEventListener("message",r),n(true));}window.addEventListener("message",r);let o=Math.trunc(Math.random()*1e6);window.parent.postMessage({id:o,method:"getSafeInfo",env:{sdkVersion:"1.0.0"}},"*");})}var U=typeof window<"u"&&window!==window.parent&&window.location.protocol==="https:",Ve=U;function W(e){return e.replace(/\/+$/,"")}function He(e,n){return n?`${W(e)}/${n.replace(/^\/+/,"")}`:e}var c="orbit-core:lastConnectedConnector",N=()=>a(c,"sessionStorage")??a(c),Qe={STORAGE_KEY:c,lastConnectedConnector:N(),setLastConnectedConnector:({connectorType:e,chainId:n,address:t},r={})=>{let o=r.remember??true,[s,p]=o?[i("localStorage"),i("sessionStorage")]:[i("sessionStorage"),i("localStorage")];s?.setItem(c,JSON.stringify({connectorType:e,chainId:n,address:t})),p?.removeItem(c);},getLastConnectedConnector:()=>N(),isLastConnectedConnectorRemembered:()=>{if(a(c,"sessionStorage"))return false;if(a(c))return true},removeLastConnectedConnector:()=>{i("localStorage")?.removeItem(c),i("sessionStorage")?.removeItem(c);}};var z=["code","name","shortMessage","details","cause","metaMessages","data","reason","method","transaction","receipt","action","version"];function J(){let e=new WeakSet;return (n,t)=>{if(t===null||typeof t!="object")return typeof t=="function"||typeof t=="symbol"?void 0:typeof t=="bigint"?t.toString():t;if(e.has(t))return "[Circular]";if(e.add(t),t instanceof Error){let r={name:t.name,message:t.message};t.stack&&(r.stack=t.stack);for(let o of Object.keys(t))o in r||(r[o]=t[o]);return r}return t}}function K(e){let n={};if(e&&typeof e=="object"){for(let t of z)t in e&&(n[t]=e[t]);"message"in e&&(n.message=e.message),"stack"in e&&(n.stack=e.stack);}return n}function M(e){try{let n=J(),t=JSON.stringify(e,n);return JSON.parse(t)}catch{return {_serializationError:"Failed to serialize error object"}}}function en(e){if(e==null)return {message:"Unknown error",raw:{originalType:"null"}};if(typeof e=="string")return {message:e,raw:{message:e,originalType:"string"}};if(e instanceof Error){let n=("shortMessage"in e&&typeof e.shortMessage=="string"?e.shortMessage:e.message)||"Unknown error",t=K(e),r=M(e);return {message:n,raw:{...r,...t,originalType:e.name||"Error"}}}return typeof e=="object"?{message:("message"in e&&typeof e.message=="string"?e.message:"shortMessage"in e&&typeof e.shortMessage=="string"?e.shortMessage:"Unknown error")||"Unknown error",raw:{...M(e),originalType:"object"}}:{message:String(e),raw:{value:String(e),originalType:typeof e}}}var d="orbit-core:recentlyConnectedConnectorsListHelpers",h=e=>a(d,e)??{},C=(e,n)=>i(e)?.setItem(d,JSON.stringify(n)),_=(e,n)=>{let{[n]:t,...r}=e;return r},y={STORAGE_KEY:d,recentlyConnectedConnectorsList:a(d),setRecentlyConnectedConnectorsList:e=>i()?.setItem(d,JSON.stringify(e)),getRecentlyConnectedConnectorsList:()=>{let e=a(d),n=a(d,"sessionStorage");if(!(!e&&!n))return {...e,...n}},addConnector:(e,n,t={})=>{if(typeof window>"u")return;let[r,o]=t.remember??true?["localStorage","sessionStorage"]:["sessionStorage","localStorage"];C(r,{...h(r),[e]:n});let s=h(o);e in s&&C(o,_(s,e));},removeConnector:e=>{if(!(typeof window>"u"))for(let n of ["localStorage","sessionStorage"]){let t=h(n);e in t&&C(n,_(t,e));}},hasConnector:e=>{if(typeof window>"u")return;let n=y.getRecentlyConnectedConnectorsList();return n?e in n:false},getConnector:e=>typeof window>"u"?void 0:y.getRecentlyConnectedConnectorsList()?.[e],getConnectorCount:()=>{if(typeof window>"u")return 0;let e=y.getRecentlyConnectedConnectorsList();return e?Object.keys(e).length:0},getConnectorsSortedByTime:()=>{if(typeof window>"u")return [];let e=y.getRecentlyConnectedConnectorsList();return e?Object.entries(e).sort(([,n],[,t])=>t.disconnectedTimestamp-n.disconnectedTimestamp):[]},removeConnectorsOlderThan:e=>{if(!(typeof window>"u"))for(let n of ["localStorage","sessionStorage"]){let t=a(d,n);if(!t)continue;let r=Object.fromEntries(Object.entries(t).filter(([,o])=>o.disconnectedTimestamp>=e));C(n,r);}},removeRecentlyConnectedConnectorsList:()=>i()?.removeItem(d)};var sn=({adapterKey:e,adapter:n})=>{if(Array.isArray(n)){if(n.length===0){console.error("Adapter selection failed: The provided adapters array is empty.");return}let t=n.find(r=>r.key===e);return t||(console.warn(`No adapter found for key: "${e}". Falling back to the first available adapter: "${n[0].key}".`),n[0])}return n};function cn(e,n=e.startsWith("0x")?6:4,t=4){return e.length<=n+t+1?e:`${e.slice(0,n)}\u2026${e.slice(-t)}`}async function un(e,n=50,t=200){for(let r=0;r<n;r++){if(e())return;await new Promise(o=>setTimeout(o,t));}throw new Error("Predicate not fulfilled in time")}
2
+ export{j as IMPERSONATED_CONNECTOR_ID,l as OrbitAdapter,B as SAFE_CONNECTOR_ID,x as SOLANA_CHAIN_IDS,ue as delay,Ke as detectSafeApp,pe as errorChain,me as filterUniqueByKey,Ce as formatBaseUnits,ne as formatCaip10AccountId,re as formatCaip19AssetId,xe as formatConnectorChainId,$ as formatConnectorName,Te as getAdapterFromConnectorType,i as getBrowserStorage,Le as getConnectorTypeFromName,Ne as getNetworkData,a as getParsedStorageItem,u as getSolanaChainId,b as getSolanaCluster,De as getWalletFromConnectorType,je as globalSingleton,Ue as impersonatedHelpers,w as isAddress,U as isInSecureIframe,ze as isRecord,Ve as isSafeApp,Y as isSameAddress,ae as isSolanaChain,He as joinUrlPath,Qe as lastConnectedConnectorHelpers,R as normalizeAccountAddress,en as normalizeError,te as parseCaip10AccountId,oe as parseCaip19AssetId,m as parseCaip2ChainId,f as readBrowserStorage,y as recentlyConnectedConnectorsListHelpers,sn as selectAdapterByKey,ce as setChainId,cn as shortAddress,O as toCaip2ChainId,ee as toEvmChainId,W as trimTrailingSlashes,un as waitFor};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuwaio/orbit-core",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "private": false,
5
5
  "author": "Oleksandr Tkach",
6
6
  "license": "Apache-2.0",