@tuwaio/satellite-core 1.0.0-fix-test-alpha.17.cf65aef → 1.0.0-fix-test-alpha.18.0fe490a

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.mts CHANGED
@@ -1,10 +1,8 @@
1
1
  import * as zustand from 'zustand';
2
- import { OrbitGenericAdapter, BaseAdapter, OrbitAdapter } from '@tuwaio/orbit-core';
3
- import { Connector as Connector$1, CreateConnectorFn } from '@wagmi/core';
4
- import { UiWalletAccount, UiWallet } from '@wallet-standard/ui';
2
+ import { OrbitAdapter, OrbitGenericAdapter, BaseAdapter } from '@tuwaio/orbit-core';
5
3
 
6
4
  /**
7
- * Type representing a wallet identifier in format "chain:wallet"
5
+ * Type representing a wallet identifier in format "OrbitAdapter:wallet"
8
6
  * @example "evm:metamask" | "solana:phantom"
9
7
  */
10
8
  type WalletType = `${OrbitAdapter}:${string}`;
@@ -46,29 +44,14 @@ interface BaseWallet {
46
44
  /** Connection status */
47
45
  isConnected: boolean;
48
46
  }
49
- /**
50
- * Extended wallet interface for Solana-specific properties
51
- */
52
- interface SolanaWallet extends BaseWallet {
53
- /** Connected Wallet Standard account */
54
- connectedAccount?: UiWalletAccount;
55
- /** Connected Wallet Standard wallet instance */
56
- connectedWallet?: UiWallet;
57
- }
58
- /** Union type for all supported wallet types */
59
- type Wallet = BaseWallet | SolanaWallet;
60
- /** EVM-specific connector type */
61
- type ConnectorEVM = Connector$1<CreateConnectorFn>;
62
- /** Solana-specific connector type */
63
- type ConnectorSolana = UiWallet;
64
- /** Union type for all supported connector types */
65
- type Connector = ConnectorEVM | ConnectorSolana;
47
+ /** Generic type for all supported wallet types */
48
+ type Wallet<W extends BaseWallet> = BaseWallet | W;
66
49
  /**
67
50
  * Interface for blockchain network adapters
68
51
  * @remarks
69
52
  * Adapters provide chain-specific implementation for wallet interactions
70
53
  */
71
- type SatelliteAdapter = BaseAdapter & {
54
+ type SatelliteAdapter<C, W extends BaseWallet = BaseWallet> = BaseAdapter & {
72
55
  /** Unique identifier for the adapter */
73
56
  key: OrbitAdapter;
74
57
  /**
@@ -78,13 +61,13 @@ type SatelliteAdapter = BaseAdapter & {
78
61
  connect: ({ walletType, chainId }: {
79
62
  walletType: WalletType;
80
63
  chainId: number | string;
81
- }) => Promise<Wallet>;
64
+ }) => Promise<Wallet<W>>;
82
65
  /** Disconnects current wallet session */
83
66
  disconnect: () => Promise<void>;
84
67
  /** Retrieves available wallet connectors for this adapter */
85
68
  getConnectors: () => {
86
69
  adapter: OrbitAdapter;
87
- connectors: Connector[];
70
+ connectors: C[];
88
71
  };
89
72
  /**
90
73
  * Handles network switching for connected wallet
@@ -92,7 +75,7 @@ type SatelliteAdapter = BaseAdapter & {
92
75
  * @param currentChainId - Current chain ID
93
76
  * @param updateActiveWallet - Callback to update wallet state
94
77
  */
95
- checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number, updateActiveWallet?: (wallet: Partial<Wallet>) => void) => Promise<void>;
78
+ checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number, updateActiveWallet?: (wallet: Partial<Wallet<W>>) => void) => Promise<void>;
96
79
  getBalance: (address: string, chainId: number | string) => Promise<{
97
80
  value: string;
98
81
  symbol: string;
@@ -106,11 +89,12 @@ type SatelliteAdapter = BaseAdapter & {
106
89
  /**
107
90
  * Store interface for managing wallet connections
108
91
  */
109
- type ISatelliteConnectStore = {
92
+ type ISatelliteConnectStore<C, W extends BaseWallet = BaseWallet> = {
110
93
  /** Returns configured adapter(s) */
111
- getAdapter: () => SatelliteAdapter | SatelliteAdapter[];
94
+ getAdapter: () => SatelliteAdapter<C, W> | SatelliteAdapter<C, W>[];
112
95
  /** Get wallet connectors */
113
- getConnectors: () => Partial<Record<OrbitAdapter, Connector[]>>;
96
+ getConnectors: () => Partial<Record<OrbitAdapter, C[]>>;
97
+ /** Initialize auto connect logic */
114
98
  initializeAutoConnect: (autoConnect: boolean) => Promise<void>;
115
99
  /** Connects to specified wallet */
116
100
  connect: ({ walletType, chainId }: {
@@ -124,11 +108,11 @@ type ISatelliteConnectStore = {
124
108
  /** Contains error message if connection failed */
125
109
  walletConnectionError?: string;
126
110
  /** Currently connected wallet */
127
- activeWallet?: Wallet;
111
+ activeWallet?: Wallet<W>;
128
112
  /** Clears connection error state */
129
113
  resetWalletConnectionError: () => void;
130
114
  /** Updates active wallet properties */
131
- updateActiveWallet: (wallet: Partial<Wallet>) => void;
115
+ updateActiveWallet: (wallet: Partial<Wallet<W>>) => void;
132
116
  /** Switches network for connected wallet */
133
117
  switchNetwork: (chainId: string | number) => Promise<void>;
134
118
  /** Contains error message if network switch failed */
@@ -139,13 +123,13 @@ type ISatelliteConnectStore = {
139
123
  /**
140
124
  * Callback type for successful wallet connections
141
125
  */
142
- type WalletConnectedCallback = (wallet: Wallet) => void | Promise<void>;
126
+ type WalletConnectedCallback<W extends BaseWallet = BaseWallet> = (wallet: Wallet<W>) => void | Promise<void>;
143
127
  /**
144
128
  * Configuration parameters for initializing Satellite Connect store
145
129
  */
146
- type SatelliteConnectStoreInitialParameters = OrbitGenericAdapter<SatelliteAdapter> & {
130
+ type SatelliteConnectStoreInitialParameters<C, W extends BaseWallet = BaseWallet> = OrbitGenericAdapter<SatelliteAdapter<C, W>> & {
147
131
  /** Optional callback executed after successful wallet connection */
148
- callbackAfterConnected?: WalletConnectedCallback;
132
+ callbackAfterConnected?: WalletConnectedCallback<W>;
149
133
  };
150
134
 
151
135
  /**
@@ -157,7 +141,7 @@ type SatelliteConnectStoreInitialParameters = OrbitGenericAdapter<SatelliteAdapt
157
141
  *
158
142
  * @returns A Zustand store instance with wallet connection state and methods
159
143
  */
160
- declare function createSatelliteConnectStore({ adapter, callbackAfterConnected, }: SatelliteConnectStoreInitialParameters): zustand.StoreApi<ISatelliteConnectStore>;
144
+ declare function createSatelliteConnectStore<C, W extends BaseWallet = BaseWallet>({ adapter, callbackAfterConnected, }: SatelliteConnectStoreInitialParameters<C, W>): zustand.StoreApi<ISatelliteConnectStore<C, W>>;
161
145
 
162
146
  /**
163
147
  * Extracts the adapter type from a wallet type string
@@ -313,4 +297,4 @@ declare const recentConnectedWalletHelpers: {
313
297
  removeRecentConnectedWallet: () => void;
314
298
  };
315
299
 
316
- export { type BaseWallet, type Connector, type ConnectorEVM, type ConnectorSolana, type ConnectorsInitProps, type ISatelliteConnectStore, type RecentConnectedWallet, type SatelliteAdapter, type SatelliteConnectStoreInitialParameters, type SolanaWallet, type Wallet, type WalletConnectedCallback, type WalletType, createSatelliteConnectStore, getAdapterFromWalletType, getParsedStorageItem, impersonatedHelpers, lastConnectedWalletHelpers, recentConnectedWalletHelpers };
300
+ export { type BaseWallet, type ConnectorsInitProps, type ISatelliteConnectStore, type RecentConnectedWallet, type SatelliteAdapter, type SatelliteConnectStoreInitialParameters, type Wallet, type WalletConnectedCallback, type WalletType, createSatelliteConnectStore, getAdapterFromWalletType, getParsedStorageItem, impersonatedHelpers, lastConnectedWalletHelpers, recentConnectedWalletHelpers };
package/dist/index.d.ts CHANGED
@@ -1,10 +1,8 @@
1
1
  import * as zustand from 'zustand';
2
- import { OrbitGenericAdapter, BaseAdapter, OrbitAdapter } from '@tuwaio/orbit-core';
3
- import { Connector as Connector$1, CreateConnectorFn } from '@wagmi/core';
4
- import { UiWalletAccount, UiWallet } from '@wallet-standard/ui';
2
+ import { OrbitAdapter, OrbitGenericAdapter, BaseAdapter } from '@tuwaio/orbit-core';
5
3
 
6
4
  /**
7
- * Type representing a wallet identifier in format "chain:wallet"
5
+ * Type representing a wallet identifier in format "OrbitAdapter:wallet"
8
6
  * @example "evm:metamask" | "solana:phantom"
9
7
  */
10
8
  type WalletType = `${OrbitAdapter}:${string}`;
@@ -46,29 +44,14 @@ interface BaseWallet {
46
44
  /** Connection status */
47
45
  isConnected: boolean;
48
46
  }
49
- /**
50
- * Extended wallet interface for Solana-specific properties
51
- */
52
- interface SolanaWallet extends BaseWallet {
53
- /** Connected Wallet Standard account */
54
- connectedAccount?: UiWalletAccount;
55
- /** Connected Wallet Standard wallet instance */
56
- connectedWallet?: UiWallet;
57
- }
58
- /** Union type for all supported wallet types */
59
- type Wallet = BaseWallet | SolanaWallet;
60
- /** EVM-specific connector type */
61
- type ConnectorEVM = Connector$1<CreateConnectorFn>;
62
- /** Solana-specific connector type */
63
- type ConnectorSolana = UiWallet;
64
- /** Union type for all supported connector types */
65
- type Connector = ConnectorEVM | ConnectorSolana;
47
+ /** Generic type for all supported wallet types */
48
+ type Wallet<W extends BaseWallet> = BaseWallet | W;
66
49
  /**
67
50
  * Interface for blockchain network adapters
68
51
  * @remarks
69
52
  * Adapters provide chain-specific implementation for wallet interactions
70
53
  */
71
- type SatelliteAdapter = BaseAdapter & {
54
+ type SatelliteAdapter<C, W extends BaseWallet = BaseWallet> = BaseAdapter & {
72
55
  /** Unique identifier for the adapter */
73
56
  key: OrbitAdapter;
74
57
  /**
@@ -78,13 +61,13 @@ type SatelliteAdapter = BaseAdapter & {
78
61
  connect: ({ walletType, chainId }: {
79
62
  walletType: WalletType;
80
63
  chainId: number | string;
81
- }) => Promise<Wallet>;
64
+ }) => Promise<Wallet<W>>;
82
65
  /** Disconnects current wallet session */
83
66
  disconnect: () => Promise<void>;
84
67
  /** Retrieves available wallet connectors for this adapter */
85
68
  getConnectors: () => {
86
69
  adapter: OrbitAdapter;
87
- connectors: Connector[];
70
+ connectors: C[];
88
71
  };
89
72
  /**
90
73
  * Handles network switching for connected wallet
@@ -92,7 +75,7 @@ type SatelliteAdapter = BaseAdapter & {
92
75
  * @param currentChainId - Current chain ID
93
76
  * @param updateActiveWallet - Callback to update wallet state
94
77
  */
95
- checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number, updateActiveWallet?: (wallet: Partial<Wallet>) => void) => Promise<void>;
78
+ checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number, updateActiveWallet?: (wallet: Partial<Wallet<W>>) => void) => Promise<void>;
96
79
  getBalance: (address: string, chainId: number | string) => Promise<{
97
80
  value: string;
98
81
  symbol: string;
@@ -106,11 +89,12 @@ type SatelliteAdapter = BaseAdapter & {
106
89
  /**
107
90
  * Store interface for managing wallet connections
108
91
  */
109
- type ISatelliteConnectStore = {
92
+ type ISatelliteConnectStore<C, W extends BaseWallet = BaseWallet> = {
110
93
  /** Returns configured adapter(s) */
111
- getAdapter: () => SatelliteAdapter | SatelliteAdapter[];
94
+ getAdapter: () => SatelliteAdapter<C, W> | SatelliteAdapter<C, W>[];
112
95
  /** Get wallet connectors */
113
- getConnectors: () => Partial<Record<OrbitAdapter, Connector[]>>;
96
+ getConnectors: () => Partial<Record<OrbitAdapter, C[]>>;
97
+ /** Initialize auto connect logic */
114
98
  initializeAutoConnect: (autoConnect: boolean) => Promise<void>;
115
99
  /** Connects to specified wallet */
116
100
  connect: ({ walletType, chainId }: {
@@ -124,11 +108,11 @@ type ISatelliteConnectStore = {
124
108
  /** Contains error message if connection failed */
125
109
  walletConnectionError?: string;
126
110
  /** Currently connected wallet */
127
- activeWallet?: Wallet;
111
+ activeWallet?: Wallet<W>;
128
112
  /** Clears connection error state */
129
113
  resetWalletConnectionError: () => void;
130
114
  /** Updates active wallet properties */
131
- updateActiveWallet: (wallet: Partial<Wallet>) => void;
115
+ updateActiveWallet: (wallet: Partial<Wallet<W>>) => void;
132
116
  /** Switches network for connected wallet */
133
117
  switchNetwork: (chainId: string | number) => Promise<void>;
134
118
  /** Contains error message if network switch failed */
@@ -139,13 +123,13 @@ type ISatelliteConnectStore = {
139
123
  /**
140
124
  * Callback type for successful wallet connections
141
125
  */
142
- type WalletConnectedCallback = (wallet: Wallet) => void | Promise<void>;
126
+ type WalletConnectedCallback<W extends BaseWallet = BaseWallet> = (wallet: Wallet<W>) => void | Promise<void>;
143
127
  /**
144
128
  * Configuration parameters for initializing Satellite Connect store
145
129
  */
146
- type SatelliteConnectStoreInitialParameters = OrbitGenericAdapter<SatelliteAdapter> & {
130
+ type SatelliteConnectStoreInitialParameters<C, W extends BaseWallet = BaseWallet> = OrbitGenericAdapter<SatelliteAdapter<C, W>> & {
147
131
  /** Optional callback executed after successful wallet connection */
148
- callbackAfterConnected?: WalletConnectedCallback;
132
+ callbackAfterConnected?: WalletConnectedCallback<W>;
149
133
  };
150
134
 
151
135
  /**
@@ -157,7 +141,7 @@ type SatelliteConnectStoreInitialParameters = OrbitGenericAdapter<SatelliteAdapt
157
141
  *
158
142
  * @returns A Zustand store instance with wallet connection state and methods
159
143
  */
160
- declare function createSatelliteConnectStore({ adapter, callbackAfterConnected, }: SatelliteConnectStoreInitialParameters): zustand.StoreApi<ISatelliteConnectStore>;
144
+ declare function createSatelliteConnectStore<C, W extends BaseWallet = BaseWallet>({ adapter, callbackAfterConnected, }: SatelliteConnectStoreInitialParameters<C, W>): zustand.StoreApi<ISatelliteConnectStore<C, W>>;
161
145
 
162
146
  /**
163
147
  * Extracts the adapter type from a wallet type string
@@ -313,4 +297,4 @@ declare const recentConnectedWalletHelpers: {
313
297
  removeRecentConnectedWallet: () => void;
314
298
  };
315
299
 
316
- export { type BaseWallet, type Connector, type ConnectorEVM, type ConnectorSolana, type ConnectorsInitProps, type ISatelliteConnectStore, type RecentConnectedWallet, type SatelliteAdapter, type SatelliteConnectStoreInitialParameters, type SolanaWallet, type Wallet, type WalletConnectedCallback, type WalletType, createSatelliteConnectStore, getAdapterFromWalletType, getParsedStorageItem, impersonatedHelpers, lastConnectedWalletHelpers, recentConnectedWalletHelpers };
300
+ export { type BaseWallet, type ConnectorsInitProps, type ISatelliteConnectStore, type RecentConnectedWallet, type SatelliteAdapter, type SatelliteConnectStoreInitialParameters, type Wallet, type WalletConnectedCallback, type WalletType, createSatelliteConnectStore, getAdapterFromWalletType, getParsedStorageItem, impersonatedHelpers, lastConnectedWalletHelpers, recentConnectedWalletHelpers };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var orbitCore=require('@tuwaio/orbit-core'),immer=require('immer'),vanilla=require('zustand/vanilla');function f(n){return n.split(":")[0]??orbitCore.OrbitAdapter.EVM}var u={impersonatedAddress:typeof window<"u"?window.localStorage.getItem("satellite-connect:impersonatedAddress")??"":"",setImpersonated:n=>typeof window<"u"?window.localStorage.setItem("satellite-connect:impersonatedAddress",n):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};function m(n){if(typeof window>"u")return;let d=window.localStorage.getItem(n);if(d)try{return JSON.parse(d)}catch(o){console.error(`Error parsing ${n} from localStorage:`,o);return}}var i={STORAGE_KEY:"satellite-connect:lastConnectedWallet",lastConnectedWallet:m("satellite-connect:lastConnectedWallet"),setLastConnectedWallet:({walletType:n,chainId:d})=>typeof window<"u"?window.localStorage.setItem(i.STORAGE_KEY,JSON.stringify({walletType:n,chainId:d})):void 0,getLastConnectedWallet:()=>m(i.STORAGE_KEY),removeLastConnectedWallet:()=>typeof window<"u"?window.localStorage.removeItem(i.STORAGE_KEY):void 0};var p={STORAGE_KEY:"satellite-connect:recentConnectedWallet",recentConnectedWallet:m("satellite-connect:recentConnectedWallet"),setRecentConnectedWallet:({wallets:n})=>typeof window<"u"?window.localStorage.setItem(p.STORAGE_KEY,JSON.stringify({wallets:n})):void 0,getRecentConnectedWallet:()=>m(p.STORAGE_KEY),removeRecentConnectedWallet:()=>typeof window<"u"?window.localStorage.removeItem(p.STORAGE_KEY):void 0};function H({adapter:n,callbackAfterConnected:d}){return vanilla.createStore()((o,s)=>({getAdapter:()=>n,getConnectors:()=>{let e;return Array.isArray(n)?e=n.map(t=>t.getConnectors()):e=[n.getConnectors()],e.reduce((t,l)=>{let r=l.adapter,a=l.connectors;return {...t,[r]:a}},{})},initializeAutoConnect:async e=>{if(e){let t=i.getLastConnectedWallet();t&&await s().connect({walletType:t.walletType,chainId:t.chainId});}},walletConnecting:false,walletConnectionError:void 0,switchNetworkError:void 0,activeWallet:void 0,connect:async({walletType:e,chainId:t})=>{o({walletConnecting:true,walletConnectionError:void 0});let l=f(e),r=orbitCore.selectAdapterByKey({adapter:n,adapterKey:l});if(!r){o({walletConnecting:false,walletConnectionError:`No adapter found for wallet type: ${e}`});return}try{let a=await r.connect({walletType:e,chainId:t});if(o({activeWallet:a}),orbitCore.connectedWalletChainHelpers.setConnectedWalletChain(t),r.checkIsContractWallet){let c=await r.checkIsContractWallet({address:a.address,chainId:t});s().updateActiveWallet({isContractAddress:c});}if(d){let c=s().activeWallet;c&&await d(c);}o({walletConnecting:!1}),i.setLastConnectedWallet({walletType:e,chainId:t});let C=p.getRecentConnectedWallet();if(C){let c={wallets:{...C.wallets,[f(e)]:e}};p.setRecentConnectedWallet(c);}else {let c={wallets:{[f(e)]:e}};p.setRecentConnectedWallet(c);}}catch(a){o({walletConnecting:false,walletConnectionError:"Wallet connection failed: "+(a instanceof Error?a.message:String(a))});}},disconnect:async()=>{let e=s().activeWallet;e&&(await orbitCore.selectAdapterByKey({adapter:n,adapterKey:f(e.walletType)})?.disconnect(),o({activeWallet:void 0,walletConnectionError:void 0,switchNetworkError:void 0}),i.removeLastConnectedWallet(),orbitCore.connectedWalletChainHelpers.removeConnectedWalletChain(),u.removeImpersonated());},resetWalletConnectionError:()=>{o({walletConnectionError:void 0});},updateActiveWallet:e=>{let t=s().activeWallet;t?(e.chainId&&(orbitCore.connectedWalletChainHelpers.setConnectedWalletChain(e.chainId),i.setLastConnectedWallet({walletType:t.walletType,chainId:e.chainId})),o(l=>immer.produce(l,r=>{r.activeWallet&&(r.activeWallet={...r.activeWallet,...e});}))):e.walletType!==void 0&&e.chainId!==void 0&&e.address!==void 0?(orbitCore.connectedWalletChainHelpers.setConnectedWalletChain(e.chainId),o({activeWallet:e})):console.warn("Attempted to set activeWallet with incomplete data while activeWallet was undefined.");},switchNetwork:async e=>{o({switchNetworkError:void 0});let t=s().activeWallet;if(t){let l=f(t.walletType),r=orbitCore.selectAdapterByKey({adapter:n,adapterKey:l});if(!r){o({switchNetworkError:`No adapter found for active wallet type: ${t.walletType}`});return}try{await r.checkAndSwitchNetwork(e,t.chainId,s().updateActiveWallet);}catch(a){o({switchNetworkError:"Switch network failed: "+(a instanceof Error?a.message:String(a))});}}},resetSwitchNetworkError:()=>o({switchNetworkError:void 0})}))}exports.createSatelliteConnectStore=H;exports.getAdapterFromWalletType=f;exports.getParsedStorageItem=m;exports.impersonatedHelpers=u;exports.lastConnectedWalletHelpers=i;exports.recentConnectedWalletHelpers=p;//# sourceMappingURL=index.js.map
1
+ 'use strict';var orbitCore=require('@tuwaio/orbit-core'),immer=require('immer'),vanilla=require('zustand/vanilla');function f(n){return n.split(":")[0]??orbitCore.OrbitAdapter.EVM}var u={impersonatedAddress:typeof window<"u"?window.localStorage.getItem("satellite-connect:impersonatedAddress")??"":"",setImpersonated:n=>typeof window<"u"?window.localStorage.setItem("satellite-connect:impersonatedAddress",n):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};function W(n){if(typeof window>"u")return;let d=window.localStorage.getItem(n);if(d)try{return JSON.parse(d)}catch(o){console.error(`Error parsing ${n} from localStorage:`,o);return}}var i={STORAGE_KEY:"satellite-connect:lastConnectedWallet",lastConnectedWallet:W("satellite-connect:lastConnectedWallet"),setLastConnectedWallet:({walletType:n,chainId:d})=>typeof window<"u"?window.localStorage.setItem(i.STORAGE_KEY,JSON.stringify({walletType:n,chainId:d})):void 0,getLastConnectedWallet:()=>W(i.STORAGE_KEY),removeLastConnectedWallet:()=>typeof window<"u"?window.localStorage.removeItem(i.STORAGE_KEY):void 0};var p={STORAGE_KEY:"satellite-connect:recentConnectedWallet",recentConnectedWallet:W("satellite-connect:recentConnectedWallet"),setRecentConnectedWallet:({wallets:n})=>typeof window<"u"?window.localStorage.setItem(p.STORAGE_KEY,JSON.stringify({wallets:n})):void 0,getRecentConnectedWallet:()=>W(p.STORAGE_KEY),removeRecentConnectedWallet:()=>typeof window<"u"?window.localStorage.removeItem(p.STORAGE_KEY):void 0};function H({adapter:n,callbackAfterConnected:d}){return vanilla.createStore()((o,s)=>({getAdapter:()=>n,getConnectors:()=>{let e;return Array.isArray(n)?e=n.map(t=>t.getConnectors()):e=[n.getConnectors()],e.reduce((t,l)=>{let a=l.adapter,r=l.connectors;return {...t,[a]:r}},{})},initializeAutoConnect:async e=>{if(e){let t=i.getLastConnectedWallet();t&&await s().connect({walletType:t.walletType,chainId:t.chainId});}},walletConnecting:false,walletConnectionError:void 0,switchNetworkError:void 0,activeWallet:void 0,connect:async({walletType:e,chainId:t})=>{o({walletConnecting:true,walletConnectionError:void 0});let l=f(e),a=orbitCore.selectAdapterByKey({adapter:n,adapterKey:l});if(!a){o({walletConnecting:false,walletConnectionError:`No adapter found for wallet type: ${e}`});return}try{let r=await a.connect({walletType:e,chainId:t});if(o({activeWallet:r}),orbitCore.connectedWalletChainHelpers.setConnectedWalletChain(t),a.checkIsContractWallet){let c=await a.checkIsContractWallet({address:r.address,chainId:t});s().updateActiveWallet({isContractAddress:c});}if(d){let c=s().activeWallet;c&&await d(c);}o({walletConnecting:!1}),i.setLastConnectedWallet({walletType:e,chainId:t});let C=p.getRecentConnectedWallet();if(C){let c={wallets:{...C.wallets,[f(e)]:e}};p.setRecentConnectedWallet(c);}else {let c={wallets:{[f(e)]:e}};p.setRecentConnectedWallet(c);}}catch(r){o({walletConnecting:false,walletConnectionError:"Wallet connection failed: "+(r instanceof Error?r.message:String(r))});}},disconnect:async()=>{let e=s().activeWallet;e&&(await orbitCore.selectAdapterByKey({adapter:n,adapterKey:f(e.walletType)})?.disconnect(),o({activeWallet:void 0,walletConnectionError:void 0,switchNetworkError:void 0}),i.removeLastConnectedWallet(),orbitCore.connectedWalletChainHelpers.removeConnectedWalletChain(),u.removeImpersonated());},resetWalletConnectionError:()=>{o({walletConnectionError:void 0});},updateActiveWallet:e=>{let t=s().activeWallet;t?(e.chainId&&(orbitCore.connectedWalletChainHelpers.setConnectedWalletChain(e.chainId),i.setLastConnectedWallet({walletType:t.walletType,chainId:e.chainId})),o(l=>immer.produce(l,a=>{a.activeWallet&&(a.activeWallet={...a.activeWallet,...e});}))):e.walletType!==void 0&&e.chainId!==void 0&&e.address!==void 0?(orbitCore.connectedWalletChainHelpers.setConnectedWalletChain(e.chainId),o({activeWallet:e})):console.warn("Attempted to set activeWallet with incomplete data while activeWallet was undefined.");},switchNetwork:async e=>{o({switchNetworkError:void 0});let t=s().activeWallet;if(t){let l=f(t.walletType),a=orbitCore.selectAdapterByKey({adapter:n,adapterKey:l});if(!a){o({switchNetworkError:`No adapter found for active wallet type: ${t.walletType}`});return}try{await a.checkAndSwitchNetwork(e,t.chainId,s().updateActiveWallet);}catch(r){o({switchNetworkError:"Switch network failed: "+(r instanceof Error?r.message:String(r))});}}},resetSwitchNetworkError:()=>o({switchNetworkError:void 0})}))}exports.createSatelliteConnectStore=H;exports.getAdapterFromWalletType=f;exports.getParsedStorageItem=W;exports.impersonatedHelpers=u;exports.lastConnectedWalletHelpers=i;exports.recentConnectedWalletHelpers=p;//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/getAdapterFromWalletType.ts","../src/utils/impersonatedHelpers.ts","../src/utils/getParsedStorageItem.ts","../src/utils/lastConnectedWalletHelpers.ts","../src/utils/recentConnectedWalletHelpers.ts","../src/store/satelliteConnectStore.ts"],"names":["getAdapterFromWalletType","walletType","OrbitAdapter","impersonatedHelpers","address","getParsedStorageItem","key","item","error","lastConnectedWalletHelpers","chainId","recentConnectedWalletHelpers","wallets","createSatelliteConnectStore","adapter","callbackAfterConnected","createStore","set","get","results","a","accumulator","currentResult","value","autoConnect","lastConnectedWallet","adapterKey","foundAdapter","selectAdapterByKey","wallet","connectedWalletChainHelpers","isContractAddress","updatedWallet","recentlyConnectedWallet","updatedRecentlyConnectedWallet","e","activeWallet","state","produce","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AAmB,CAAE,OAAA,CAAAd,EAAS,UAAA,CAAAY,CAAW,CAAC,CAAA,CAE/D,GAAI,CAACC,CAAAA,CAAc,CACjBV,EAAI,CAAE,kBAAA,CAAoB,4CAA4CmB,CAAAA,CAAa,UAAU,CAAA,CAAG,CAAC,EACjG,MACF,CAEA,GAAI,CAEF,MAAMT,EAAa,qBAAA,CAAsBjB,CAAAA,CAAS0B,EAAa,OAAA,CAASlB,CAAAA,GAAM,kBAAkB,EAClG,OAASiB,CAAAA,CAAG,CACVlB,EAAI,CAAE,kBAAA,CAAoB,2BAA6BkB,CAAAA,YAAa,KAAA,CAAQA,EAAE,OAAA,CAAU,MAAA,CAAOA,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,EAUA,uBAAA,CAAyB,IAAMlB,EAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CACtE,EAAE,CACJ","file":"index.js","sourcesContent":["import { OrbitAdapter } from '@tuwaio/orbit-core';\n\nimport { 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] ?? OrbitAdapter.EVM) as OrbitAdapter;\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","/**\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 { WalletType } from '../types';\nimport { getParsedStorageItem } from './getParsedStorageItem';\n\ntype LastConnectedWallet = { walletType: WalletType; chainId: number | 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 'satellite-connect: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: 'satellite-connect: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>('satellite-connect: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 }: LastConnectedWallet) =>\n typeof window !== 'undefined'\n ? window.localStorage.setItem(lastConnectedWalletHelpers.STORAGE_KEY, JSON.stringify({ walletType, chainId }))\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 '@tuwaio/orbit-core';\n\nimport { WalletType } from '../types';\nimport { getParsedStorageItem } from './getParsedStorageItem';\n\nexport type RecentConnectedWallet = { wallets: Record<OrbitAdapter, WalletType> };\n\n/**\n * Helper utilities for managing the last connected wallet state\n *\n * @remarks\n * All data is stored in localStorage with the 'satellite-connect: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: 'satellite-connect: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>('satellite-connect:recentConnectedWallet'),\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 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","import { connectedWalletChainHelpers, OrbitAdapter, selectAdapterByKey } from '@tuwaio/orbit-core';\nimport { produce } from 'immer';\nimport { createStore } from 'zustand/vanilla';\n\nimport { Connector, ISatelliteConnectStore, SatelliteConnectStoreInitialParameters, Wallet } from '../types';\nimport { getAdapterFromWalletType } from '../utils/getAdapterFromWalletType';\nimport { impersonatedHelpers } from '../utils/impersonatedHelpers';\nimport { lastConnectedWalletHelpers } from '../utils/lastConnectedWalletHelpers';\nimport { RecentConnectedWallet, recentConnectedWalletHelpers } from '../utils/recentConnectedWalletHelpers';\n\n/**\n * Creates a Satellite Connect store instance for managing wallet connections and state\n *\n * @param params - Configuration parameters for the store\n * @param params.adapter - Single adapter or array of adapters for different chains\n * @param params.callbackAfterConnected - Optional callback function called after successful wallet connection\n *\n * @returns A Zustand store instance with wallet connection state and methods\n */\nexport function createSatelliteConnectStore({\n adapter,\n callbackAfterConnected,\n}: SatelliteConnectStoreInitialParameters) {\n return createStore<ISatelliteConnectStore>()((set, get) => ({\n /**\n * Returns configured adapter(s)\n */\n getAdapter: () => adapter,\n\n /**\n * Get wallet connectors for all configured adapters\n */\n getConnectors: () => {\n let results: { adapter: OrbitAdapter; connectors: Connector[] }[];\n\n if (Array.isArray(adapter)) {\n results = adapter.map((a) => a.getConnectors());\n } else {\n // Ensure the single adapter result is wrapped in an array for consistent processing\n results = [adapter.getConnectors()];\n }\n\n return results.reduce(\n (accumulator, currentResult) => {\n const key = currentResult.adapter;\n const value = currentResult.connectors;\n return {\n ...accumulator,\n [key]: value,\n };\n },\n {} as Partial<Record<OrbitAdapter, Connector[]>>,\n );\n },\n\n initializeAutoConnect: async (autoConnect) => {\n if (autoConnect) {\n const lastConnectedWallet = lastConnectedWalletHelpers.getLastConnectedWallet();\n if (lastConnectedWallet) {\n // Explicitly await the connect call\n await get().connect({ walletType: lastConnectedWallet.walletType, chainId: lastConnectedWallet.chainId });\n }\n }\n },\n\n walletConnecting: false,\n walletConnectionError: undefined,\n switchNetworkError: undefined,\n activeWallet: undefined,\n\n /**\n * Connects to a wallet\n * @param walletType - Type of wallet to connect to\n * @param chainId - Chain ID to connect on\n */\n connect: async ({ walletType, chainId }) => {\n set({ walletConnecting: true, walletConnectionError: undefined });\n const adapterKey = getAdapterFromWalletType(walletType);\n const foundAdapter = selectAdapterByKey({ adapter, adapterKey });\n\n if (!foundAdapter) {\n set({\n walletConnecting: false,\n walletConnectionError: `No adapter found for wallet type: ${walletType}`,\n });\n return;\n }\n\n try {\n const wallet = await foundAdapter.connect({\n walletType,\n chainId,\n });\n\n // 1. Set initial wallet state\n set({ activeWallet: wallet });\n\n // 2. Set connected chain storage\n connectedWalletChainHelpers.setConnectedWalletChain(chainId);\n\n // 3. Check for contract address if the adapter supports it\n if (foundAdapter.checkIsContractWallet) {\n const isContractAddress = await foundAdapter.checkIsContractWallet({\n address: wallet.address,\n chainId,\n });\n\n // Update only the isContractAddress property\n get().updateActiveWallet({ isContractAddress });\n }\n\n // 4. Run callback if provided\n if (callbackAfterConnected) {\n // Use the latest wallet state after potential updates (like isContractAddress)\n const updatedWallet = get().activeWallet;\n if (updatedWallet) {\n await callbackAfterConnected(updatedWallet);\n }\n }\n\n // 5. Final state updates\n set({ walletConnecting: false });\n lastConnectedWalletHelpers.setLastConnectedWallet({ walletType, chainId });\n const recentlyConnectedWallet = recentConnectedWalletHelpers.getRecentConnectedWallet();\n if (recentlyConnectedWallet) {\n const updatedRecentlyConnectedWallet = {\n wallets: {\n ...recentlyConnectedWallet.wallets,\n [getAdapterFromWalletType(walletType)]: walletType,\n },\n };\n recentConnectedWalletHelpers.setRecentConnectedWallet(updatedRecentlyConnectedWallet);\n } else {\n const updatedRecentlyConnectedWallet = {\n wallets: {\n [getAdapterFromWalletType(walletType)]: walletType,\n },\n } as RecentConnectedWallet;\n recentConnectedWalletHelpers.setRecentConnectedWallet(updatedRecentlyConnectedWallet);\n }\n } catch (e) {\n set({\n walletConnecting: false,\n walletConnectionError: 'Wallet connection failed: ' + (e instanceof Error ? e.message : String(e)),\n });\n }\n },\n\n /**\n * Disconnects the currently active wallet\n */\n disconnect: async () => {\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n const foundAdapter = selectAdapterByKey({\n adapter,\n adapterKey: getAdapterFromWalletType(activeWallet.walletType),\n });\n\n // Call disconnect only if adapter is found\n await foundAdapter?.disconnect();\n\n // Clear all states and storages\n set({ activeWallet: undefined, walletConnectionError: undefined, switchNetworkError: undefined });\n lastConnectedWalletHelpers.removeLastConnectedWallet();\n connectedWalletChainHelpers.removeConnectedWalletChain();\n impersonatedHelpers.removeImpersonated();\n }\n },\n\n /**\n * Contains error message if connection failed\n */\n // walletConnectionError is declared above with an initial value\n\n /**\n * Resets any wallet connection errors\n */\n resetWalletConnectionError: () => {\n set({ walletConnectionError: undefined });\n },\n\n /**\n * Updates the active wallet's properties\n * @param wallet - Partial wallet object with properties to update\n */\n updateActiveWallet: (wallet: Partial<Wallet>) => {\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n // If chainId is updated, update storage\n if (wallet.chainId) {\n connectedWalletChainHelpers.setConnectedWalletChain(wallet.chainId);\n\n // Update lastConnectedWallet storage if chainId changes\n lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: activeWallet.walletType,\n chainId: wallet.chainId,\n });\n }\n\n // Use produce for immutable state update\n set((state) =>\n produce(state, (draft) => {\n if (draft.activeWallet) {\n // Ensure we merge partial properties into the existing activeWallet object\n draft.activeWallet = {\n ...draft.activeWallet,\n ...wallet,\n } as Wallet; // Cast ensures type compatibility after merging\n }\n }),\n );\n } else {\n const isWalletCanChange =\n wallet.walletType !== undefined && wallet.chainId !== undefined && wallet.address !== undefined;\n\n if (isWalletCanChange) {\n connectedWalletChainHelpers.setConnectedWalletChain(wallet.chainId!);\n set({ activeWallet: wallet as Wallet });\n } else {\n console.warn('Attempted to set activeWallet with incomplete data while activeWallet was undefined.');\n }\n }\n },\n\n /**\n * Switches the connected wallet to a different network\n * @param chainId - Target chain ID to switch to\n */\n switchNetwork: async (chainId: string | number) => {\n set({ switchNetworkError: undefined });\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n const adapterKey = getAdapterFromWalletType(activeWallet.walletType);\n const foundAdapter = selectAdapterByKey({ adapter, adapterKey });\n\n if (!foundAdapter) {\n set({ switchNetworkError: `No adapter found for active wallet type: ${activeWallet.walletType}` });\n return;\n }\n\n try {\n // Pass the local updateActiveWallet method from 'get()' to the adapter\n await foundAdapter.checkAndSwitchNetwork(chainId, activeWallet.chainId, get().updateActiveWallet);\n } catch (e) {\n set({ switchNetworkError: 'Switch network failed: ' + (e instanceof Error ? e.message : String(e)) });\n }\n }\n },\n\n /**\n * Contains error message if network switch failed\n */\n // switchNetworkError is declared above with an initial value\n\n /**\n * Resets any network switching errors\n */\n resetSwitchNetworkError: () => set({ switchNetworkError: undefined }),\n }));\n}\n"]}
1
+ {"version":3,"sources":["../src/utils/getAdapterFromWalletType.ts","../src/utils/impersonatedHelpers.ts","../src/utils/getParsedStorageItem.ts","../src/utils/lastConnectedWalletHelpers.ts","../src/utils/recentConnectedWalletHelpers.ts","../src/store/satelliteConnectStore.ts"],"names":["getAdapterFromWalletType","walletType","OrbitAdapter","impersonatedHelpers","address","getParsedStorageItem","key","item","error","lastConnectedWalletHelpers","chainId","recentConnectedWalletHelpers","wallets","createSatelliteConnectStore","adapter","callbackAfterConnected","createStore","set","get","results","a","accumulator","currentResult","value","autoConnect","lastConnectedWallet","adapterKey","foundAdapter","selectAdapterByKey","wallet","connectedWalletChainHelpers","isContractAddress","updatedWallet","recentlyConnectedWallet","updatedRecentlyConnectedWallet","e","activeWallet","state","produce","draft"],"mappings":"mHA0BO,SAASA,EAAyBC,CAAAA,CAAsC,CAC7E,OAAQA,CAAAA,CAAW,MAAM,GAAG,CAAA,CAAE,CAAC,CAAA,EAAKC,sBAAAA,CAAa,GACnD,CCnBO,IAAMC,EAAsB,CAKjC,mBAAA,CACE,OAAO,MAAA,CAAW,GAAA,CAAe,OAAO,YAAA,CAAa,OAAA,CAAQ,uCAAuC,CAAA,EAAK,EAAA,CAAM,EAAA,CAcjH,eAAA,CAAkBC,GAChB,OAAO,MAAA,CAAW,IACd,MAAA,CAAO,YAAA,CAAa,QAAQ,uCAAA,CAAyCA,CAAO,EAC5E,MAAA,CAeN,eAAA,CAAiB,IACf,OAAO,MAAA,CAAW,IAAc,MAAA,CAAO,YAAA,CAAa,QAAQ,uCAAuC,CAAA,CAAI,MAAA,CAEzG,kBAAA,CAAoB,IAClB,OAAO,MAAA,CAAW,IAAc,MAAA,CAAO,YAAA,CAAa,WAAW,uCAAuC,CAAA,CAAI,MAC9G,EC9CO,SAASC,EAAiCC,CAAAA,CAAqC,CACpF,GAAI,OAAO,MAAA,CAAW,IACpB,OAGF,IAAMC,CAAAA,CAAO,MAAA,CAAO,aAAa,OAAA,CAAQD,CAAG,EAG5C,GAAKC,CAAAA,CAIL,GAAI,CAEF,OAAO,KAAK,KAAA,CAAMA,CAAI,CACxB,CAAA,MAASC,CA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A4B,wBAAwBD,CAAAA,CAAO,OAAQ,EACnEZ,CAAAA,CAAI,CAAE,aAAcY,CAAY,CAAC,GAEjC,OAAA,CAAQ,IAAA,CAAK,sFAAsF,EAGzG,EAMA,aAAA,CAAe,MAAOnB,GAA6B,CACjDO,CAAAA,CAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CAAA,CACrC,IAAMmB,EAAelB,CAAAA,EAAI,CAAE,aAC3B,GAAIkB,CAAAA,CAAc,CAChB,IAAMV,CAAAA,CAAa1B,CAAAA,CAAyBoC,CAAAA,CAAa,UAAU,CAAA,CAC7DT,CAAAA,CAAeC,6BAAmB,CAAE,OAAA,CAAAd,EAAS,UAAA,CAAAY,CAAW,CAAC,CAAA,CAE/D,GAAI,CAACC,CAAAA,CAAc,CACjBV,EAAI,CAAE,kBAAA,CAAoB,4CAA4CmB,CAAAA,CAAa,UAAU,CAAA,CAAG,CAAC,EACjG,MACF,CAEA,GAAI,CAEF,MAAMT,EAAa,qBAAA,CAAsBjB,CAAAA,CAAS0B,EAAa,OAAA,CAASlB,CAAAA,GAAM,kBAAkB,EAClG,OAASiB,CAAAA,CAAG,CACVlB,EAAI,CAAE,kBAAA,CAAoB,2BAA6BkB,CAAAA,YAAa,KAAA,CAAQA,EAAE,OAAA,CAAU,MAAA,CAAOA,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,EAUA,uBAAA,CAAyB,IAAMlB,EAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CACtE,EAAE,CACJ","file":"index.js","sourcesContent":["import { OrbitAdapter } from '@tuwaio/orbit-core';\n\nimport { 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] ?? OrbitAdapter.EVM) as OrbitAdapter;\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","/**\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 { WalletType } from '../types';\nimport { getParsedStorageItem } from './getParsedStorageItem';\n\ntype LastConnectedWallet = { walletType: WalletType; chainId: number | 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 'satellite-connect: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: 'satellite-connect: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>('satellite-connect: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 }: LastConnectedWallet) =>\n typeof window !== 'undefined'\n ? window.localStorage.setItem(lastConnectedWalletHelpers.STORAGE_KEY, JSON.stringify({ walletType, chainId }))\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 '@tuwaio/orbit-core';\n\nimport { WalletType } from '../types';\nimport { getParsedStorageItem } from './getParsedStorageItem';\n\nexport type RecentConnectedWallet = { wallets: Record<OrbitAdapter, WalletType> };\n\n/**\n * Helper utilities for managing the last connected wallet state\n *\n * @remarks\n * All data is stored in localStorage with the 'satellite-connect: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: 'satellite-connect: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>('satellite-connect:recentConnectedWallet'),\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 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","import { connectedWalletChainHelpers, OrbitAdapter, selectAdapterByKey } from '@tuwaio/orbit-core';\nimport { produce } from 'immer';\nimport { createStore } from 'zustand/vanilla';\n\nimport { BaseWallet, ISatelliteConnectStore, SatelliteConnectStoreInitialParameters, Wallet } from '../types';\nimport { getAdapterFromWalletType } from '../utils/getAdapterFromWalletType';\nimport { impersonatedHelpers } from '../utils/impersonatedHelpers';\nimport { lastConnectedWalletHelpers } from '../utils/lastConnectedWalletHelpers';\nimport { RecentConnectedWallet, recentConnectedWalletHelpers } from '../utils/recentConnectedWalletHelpers';\n\n/**\n * Creates a Satellite Connect store instance for managing wallet connections and state\n *\n * @param params - Configuration parameters for the store\n * @param params.adapter - Single adapter or array of adapters for different chains\n * @param params.callbackAfterConnected - Optional callback function called after successful wallet connection\n *\n * @returns A Zustand store instance with wallet connection state and methods\n */\nexport function createSatelliteConnectStore<C, W extends BaseWallet = BaseWallet>({\n adapter,\n callbackAfterConnected,\n}: SatelliteConnectStoreInitialParameters<C, W>) {\n return createStore<ISatelliteConnectStore<C, W>>()((set, get) => ({\n /**\n * Returns configured adapter(s)\n */\n getAdapter: () => adapter,\n\n /**\n * Get wallet connectors for all configured adapters\n */\n getConnectors: () => {\n let results: { adapter: OrbitAdapter; connectors: C[] }[];\n\n if (Array.isArray(adapter)) {\n results = adapter.map((a) => a.getConnectors());\n } else {\n // Ensure the single adapter result is wrapped in an array for consistent processing\n results = [adapter.getConnectors()];\n }\n\n return results.reduce(\n (accumulator, currentResult) => {\n const key = currentResult.adapter;\n const value = currentResult.connectors;\n return {\n ...accumulator,\n [key]: value,\n };\n },\n {} as Partial<Record<OrbitAdapter, C[]>>,\n );\n },\n\n initializeAutoConnect: async (autoConnect) => {\n if (autoConnect) {\n const lastConnectedWallet = lastConnectedWalletHelpers.getLastConnectedWallet();\n if (lastConnectedWallet) {\n // Explicitly await the connect call\n await get().connect({ walletType: lastConnectedWallet.walletType, chainId: lastConnectedWallet.chainId });\n }\n }\n },\n\n walletConnecting: false,\n walletConnectionError: undefined,\n switchNetworkError: undefined,\n activeWallet: undefined,\n\n /**\n * Connects to a wallet\n * @param walletType - Type of wallet to connect to\n * @param chainId - Chain ID to connect on\n */\n connect: async ({ walletType, chainId }) => {\n set({ walletConnecting: true, walletConnectionError: undefined });\n const adapterKey = getAdapterFromWalletType(walletType);\n const foundAdapter = selectAdapterByKey({ adapter, adapterKey });\n\n if (!foundAdapter) {\n set({\n walletConnecting: false,\n walletConnectionError: `No adapter found for wallet type: ${walletType}`,\n });\n return;\n }\n\n try {\n const wallet = await foundAdapter.connect({\n walletType,\n chainId,\n });\n\n // 1. Set initial wallet state\n set({ activeWallet: wallet });\n\n // 2. Set connected chain storage\n connectedWalletChainHelpers.setConnectedWalletChain(chainId);\n\n // 3. Check for contract address if the adapter supports it\n if (foundAdapter.checkIsContractWallet) {\n const isContractAddress = await foundAdapter.checkIsContractWallet({\n address: wallet.address,\n chainId,\n });\n\n // Update only the isContractAddress property\n get().updateActiveWallet({ isContractAddress });\n }\n\n // 4. Run callback if provided\n if (callbackAfterConnected) {\n // Use the latest wallet state after potential updates (like isContractAddress)\n const updatedWallet = get().activeWallet;\n if (updatedWallet) {\n await callbackAfterConnected(updatedWallet);\n }\n }\n\n // 5. Final state updates\n set({ walletConnecting: false });\n lastConnectedWalletHelpers.setLastConnectedWallet({ walletType, chainId });\n const recentlyConnectedWallet = recentConnectedWalletHelpers.getRecentConnectedWallet();\n if (recentlyConnectedWallet) {\n const updatedRecentlyConnectedWallet = {\n wallets: {\n ...recentlyConnectedWallet.wallets,\n [getAdapterFromWalletType(walletType)]: walletType,\n },\n };\n recentConnectedWalletHelpers.setRecentConnectedWallet(updatedRecentlyConnectedWallet);\n } else {\n const updatedRecentlyConnectedWallet = {\n wallets: {\n [getAdapterFromWalletType(walletType)]: walletType,\n },\n } as RecentConnectedWallet;\n recentConnectedWalletHelpers.setRecentConnectedWallet(updatedRecentlyConnectedWallet);\n }\n } catch (e) {\n set({\n walletConnecting: false,\n walletConnectionError: 'Wallet connection failed: ' + (e instanceof Error ? e.message : String(e)),\n });\n }\n },\n\n /**\n * Disconnects the currently active wallet\n */\n disconnect: async () => {\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n const foundAdapter = selectAdapterByKey({\n adapter,\n adapterKey: getAdapterFromWalletType(activeWallet.walletType),\n });\n\n // Call disconnect only if adapter is found\n await foundAdapter?.disconnect();\n\n // Clear all states and storages\n set({ activeWallet: undefined, walletConnectionError: undefined, switchNetworkError: undefined });\n lastConnectedWalletHelpers.removeLastConnectedWallet();\n connectedWalletChainHelpers.removeConnectedWalletChain();\n impersonatedHelpers.removeImpersonated();\n }\n },\n\n /**\n * Contains error message if connection failed\n */\n // walletConnectionError is declared above with an initial value\n\n /**\n * Resets any wallet connection errors\n */\n resetWalletConnectionError: () => {\n set({ walletConnectionError: undefined });\n },\n\n /**\n * Updates the active wallet's properties\n * @param wallet - Partial wallet object with properties to update\n */\n updateActiveWallet: (wallet: Partial<Wallet<W>>) => {\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n // If chainId is updated, update storage\n if (wallet.chainId) {\n connectedWalletChainHelpers.setConnectedWalletChain(wallet.chainId);\n\n // Update lastConnectedWallet storage if chainId changes\n lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: activeWallet.walletType,\n chainId: wallet.chainId,\n });\n }\n\n // Use produce for immutable state update\n set((state) =>\n produce(state, (draft) => {\n if (draft.activeWallet) {\n // Ensure we merge partial properties into the existing activeWallet object\n draft.activeWallet = {\n ...draft.activeWallet,\n ...wallet,\n } as W; // Cast ensures type compatibility after merging\n }\n }),\n );\n } else {\n const isWalletCanChange =\n wallet.walletType !== undefined && wallet.chainId !== undefined && wallet.address !== undefined;\n\n if (isWalletCanChange) {\n connectedWalletChainHelpers.setConnectedWalletChain(wallet.chainId!);\n set({ activeWallet: wallet as W });\n } else {\n console.warn('Attempted to set activeWallet with incomplete data while activeWallet was undefined.');\n }\n }\n },\n\n /**\n * Switches the connected wallet to a different network\n * @param chainId - Target chain ID to switch to\n */\n switchNetwork: async (chainId: string | number) => {\n set({ switchNetworkError: undefined });\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n const adapterKey = getAdapterFromWalletType(activeWallet.walletType);\n const foundAdapter = selectAdapterByKey({ adapter, adapterKey });\n\n if (!foundAdapter) {\n set({ switchNetworkError: `No adapter found for active wallet type: ${activeWallet.walletType}` });\n return;\n }\n\n try {\n // Pass the local updateActiveWallet method from 'get()' to the adapter\n await foundAdapter.checkAndSwitchNetwork(chainId, activeWallet.chainId, get().updateActiveWallet);\n } catch (e) {\n set({ switchNetworkError: 'Switch network failed: ' + (e instanceof Error ? e.message : String(e)) });\n }\n }\n },\n\n /**\n * Contains error message if network switch failed\n */\n // switchNetworkError is declared above with an initial value\n\n /**\n * Resets any network switching errors\n */\n resetSwitchNetworkError: () => set({ switchNetworkError: undefined }),\n }));\n}\n"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import {OrbitAdapter,selectAdapterByKey,connectedWalletChainHelpers}from'@tuwaio/orbit-core';import {produce}from'immer';import {createStore}from'zustand/vanilla';function f(n){return n.split(":")[0]??OrbitAdapter.EVM}var u={impersonatedAddress:typeof window<"u"?window.localStorage.getItem("satellite-connect:impersonatedAddress")??"":"",setImpersonated:n=>typeof window<"u"?window.localStorage.setItem("satellite-connect:impersonatedAddress",n):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};function m(n){if(typeof window>"u")return;let d=window.localStorage.getItem(n);if(d)try{return JSON.parse(d)}catch(o){console.error(`Error parsing ${n} from localStorage:`,o);return}}var i={STORAGE_KEY:"satellite-connect:lastConnectedWallet",lastConnectedWallet:m("satellite-connect:lastConnectedWallet"),setLastConnectedWallet:({walletType:n,chainId:d})=>typeof window<"u"?window.localStorage.setItem(i.STORAGE_KEY,JSON.stringify({walletType:n,chainId:d})):void 0,getLastConnectedWallet:()=>m(i.STORAGE_KEY),removeLastConnectedWallet:()=>typeof window<"u"?window.localStorage.removeItem(i.STORAGE_KEY):void 0};var p={STORAGE_KEY:"satellite-connect:recentConnectedWallet",recentConnectedWallet:m("satellite-connect:recentConnectedWallet"),setRecentConnectedWallet:({wallets:n})=>typeof window<"u"?window.localStorage.setItem(p.STORAGE_KEY,JSON.stringify({wallets:n})):void 0,getRecentConnectedWallet:()=>m(p.STORAGE_KEY),removeRecentConnectedWallet:()=>typeof window<"u"?window.localStorage.removeItem(p.STORAGE_KEY):void 0};function H({adapter:n,callbackAfterConnected:d}){return createStore()((o,s)=>({getAdapter:()=>n,getConnectors:()=>{let e;return Array.isArray(n)?e=n.map(t=>t.getConnectors()):e=[n.getConnectors()],e.reduce((t,l)=>{let r=l.adapter,a=l.connectors;return {...t,[r]:a}},{})},initializeAutoConnect:async e=>{if(e){let t=i.getLastConnectedWallet();t&&await s().connect({walletType:t.walletType,chainId:t.chainId});}},walletConnecting:false,walletConnectionError:void 0,switchNetworkError:void 0,activeWallet:void 0,connect:async({walletType:e,chainId:t})=>{o({walletConnecting:true,walletConnectionError:void 0});let l=f(e),r=selectAdapterByKey({adapter:n,adapterKey:l});if(!r){o({walletConnecting:false,walletConnectionError:`No adapter found for wallet type: ${e}`});return}try{let a=await r.connect({walletType:e,chainId:t});if(o({activeWallet:a}),connectedWalletChainHelpers.setConnectedWalletChain(t),r.checkIsContractWallet){let c=await r.checkIsContractWallet({address:a.address,chainId:t});s().updateActiveWallet({isContractAddress:c});}if(d){let c=s().activeWallet;c&&await d(c);}o({walletConnecting:!1}),i.setLastConnectedWallet({walletType:e,chainId:t});let C=p.getRecentConnectedWallet();if(C){let c={wallets:{...C.wallets,[f(e)]:e}};p.setRecentConnectedWallet(c);}else {let c={wallets:{[f(e)]:e}};p.setRecentConnectedWallet(c);}}catch(a){o({walletConnecting:false,walletConnectionError:"Wallet connection failed: "+(a instanceof Error?a.message:String(a))});}},disconnect:async()=>{let e=s().activeWallet;e&&(await selectAdapterByKey({adapter:n,adapterKey:f(e.walletType)})?.disconnect(),o({activeWallet:void 0,walletConnectionError:void 0,switchNetworkError:void 0}),i.removeLastConnectedWallet(),connectedWalletChainHelpers.removeConnectedWalletChain(),u.removeImpersonated());},resetWalletConnectionError:()=>{o({walletConnectionError:void 0});},updateActiveWallet:e=>{let t=s().activeWallet;t?(e.chainId&&(connectedWalletChainHelpers.setConnectedWalletChain(e.chainId),i.setLastConnectedWallet({walletType:t.walletType,chainId:e.chainId})),o(l=>produce(l,r=>{r.activeWallet&&(r.activeWallet={...r.activeWallet,...e});}))):e.walletType!==void 0&&e.chainId!==void 0&&e.address!==void 0?(connectedWalletChainHelpers.setConnectedWalletChain(e.chainId),o({activeWallet:e})):console.warn("Attempted to set activeWallet with incomplete data while activeWallet was undefined.");},switchNetwork:async e=>{o({switchNetworkError:void 0});let t=s().activeWallet;if(t){let l=f(t.walletType),r=selectAdapterByKey({adapter:n,adapterKey:l});if(!r){o({switchNetworkError:`No adapter found for active wallet type: ${t.walletType}`});return}try{await r.checkAndSwitchNetwork(e,t.chainId,s().updateActiveWallet);}catch(a){o({switchNetworkError:"Switch network failed: "+(a instanceof Error?a.message:String(a))});}}},resetSwitchNetworkError:()=>o({switchNetworkError:void 0})}))}export{H as createSatelliteConnectStore,f as getAdapterFromWalletType,m as getParsedStorageItem,u as impersonatedHelpers,i as lastConnectedWalletHelpers,p as recentConnectedWalletHelpers};//# sourceMappingURL=index.mjs.map
1
+ import {OrbitAdapter,selectAdapterByKey,connectedWalletChainHelpers}from'@tuwaio/orbit-core';import {produce}from'immer';import {createStore}from'zustand/vanilla';function f(n){return n.split(":")[0]??OrbitAdapter.EVM}var u={impersonatedAddress:typeof window<"u"?window.localStorage.getItem("satellite-connect:impersonatedAddress")??"":"",setImpersonated:n=>typeof window<"u"?window.localStorage.setItem("satellite-connect:impersonatedAddress",n):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};function W(n){if(typeof window>"u")return;let d=window.localStorage.getItem(n);if(d)try{return JSON.parse(d)}catch(o){console.error(`Error parsing ${n} from localStorage:`,o);return}}var i={STORAGE_KEY:"satellite-connect:lastConnectedWallet",lastConnectedWallet:W("satellite-connect:lastConnectedWallet"),setLastConnectedWallet:({walletType:n,chainId:d})=>typeof window<"u"?window.localStorage.setItem(i.STORAGE_KEY,JSON.stringify({walletType:n,chainId:d})):void 0,getLastConnectedWallet:()=>W(i.STORAGE_KEY),removeLastConnectedWallet:()=>typeof window<"u"?window.localStorage.removeItem(i.STORAGE_KEY):void 0};var p={STORAGE_KEY:"satellite-connect:recentConnectedWallet",recentConnectedWallet:W("satellite-connect:recentConnectedWallet"),setRecentConnectedWallet:({wallets:n})=>typeof window<"u"?window.localStorage.setItem(p.STORAGE_KEY,JSON.stringify({wallets:n})):void 0,getRecentConnectedWallet:()=>W(p.STORAGE_KEY),removeRecentConnectedWallet:()=>typeof window<"u"?window.localStorage.removeItem(p.STORAGE_KEY):void 0};function H({adapter:n,callbackAfterConnected:d}){return createStore()((o,s)=>({getAdapter:()=>n,getConnectors:()=>{let e;return Array.isArray(n)?e=n.map(t=>t.getConnectors()):e=[n.getConnectors()],e.reduce((t,l)=>{let a=l.adapter,r=l.connectors;return {...t,[a]:r}},{})},initializeAutoConnect:async e=>{if(e){let t=i.getLastConnectedWallet();t&&await s().connect({walletType:t.walletType,chainId:t.chainId});}},walletConnecting:false,walletConnectionError:void 0,switchNetworkError:void 0,activeWallet:void 0,connect:async({walletType:e,chainId:t})=>{o({walletConnecting:true,walletConnectionError:void 0});let l=f(e),a=selectAdapterByKey({adapter:n,adapterKey:l});if(!a){o({walletConnecting:false,walletConnectionError:`No adapter found for wallet type: ${e}`});return}try{let r=await a.connect({walletType:e,chainId:t});if(o({activeWallet:r}),connectedWalletChainHelpers.setConnectedWalletChain(t),a.checkIsContractWallet){let c=await a.checkIsContractWallet({address:r.address,chainId:t});s().updateActiveWallet({isContractAddress:c});}if(d){let c=s().activeWallet;c&&await d(c);}o({walletConnecting:!1}),i.setLastConnectedWallet({walletType:e,chainId:t});let C=p.getRecentConnectedWallet();if(C){let c={wallets:{...C.wallets,[f(e)]:e}};p.setRecentConnectedWallet(c);}else {let c={wallets:{[f(e)]:e}};p.setRecentConnectedWallet(c);}}catch(r){o({walletConnecting:false,walletConnectionError:"Wallet connection failed: "+(r instanceof Error?r.message:String(r))});}},disconnect:async()=>{let e=s().activeWallet;e&&(await selectAdapterByKey({adapter:n,adapterKey:f(e.walletType)})?.disconnect(),o({activeWallet:void 0,walletConnectionError:void 0,switchNetworkError:void 0}),i.removeLastConnectedWallet(),connectedWalletChainHelpers.removeConnectedWalletChain(),u.removeImpersonated());},resetWalletConnectionError:()=>{o({walletConnectionError:void 0});},updateActiveWallet:e=>{let t=s().activeWallet;t?(e.chainId&&(connectedWalletChainHelpers.setConnectedWalletChain(e.chainId),i.setLastConnectedWallet({walletType:t.walletType,chainId:e.chainId})),o(l=>produce(l,a=>{a.activeWallet&&(a.activeWallet={...a.activeWallet,...e});}))):e.walletType!==void 0&&e.chainId!==void 0&&e.address!==void 0?(connectedWalletChainHelpers.setConnectedWalletChain(e.chainId),o({activeWallet:e})):console.warn("Attempted to set activeWallet with incomplete data while activeWallet was undefined.");},switchNetwork:async e=>{o({switchNetworkError:void 0});let t=s().activeWallet;if(t){let l=f(t.walletType),a=selectAdapterByKey({adapter:n,adapterKey:l});if(!a){o({switchNetworkError:`No adapter found for active wallet type: ${t.walletType}`});return}try{await a.checkAndSwitchNetwork(e,t.chainId,s().updateActiveWallet);}catch(r){o({switchNetworkError:"Switch network failed: "+(r instanceof Error?r.message:String(r))});}}},resetSwitchNetworkError:()=>o({switchNetworkError:void 0})}))}export{H as createSatelliteConnectStore,f as getAdapterFromWalletType,W as getParsedStorageItem,u as impersonatedHelpers,i as lastConnectedWalletHelpers,p as recentConnectedWalletHelpers};//# sourceMappingURL=index.mjs.map
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/getAdapterFromWalletType.ts","../src/utils/impersonatedHelpers.ts","../src/utils/getParsedStorageItem.ts","../src/utils/lastConnectedWalletHelpers.ts","../src/utils/recentConnectedWalletHelpers.ts","../src/store/satelliteConnectStore.ts"],"names":["getAdapterFromWalletType","walletType","OrbitAdapter","impersonatedHelpers","address","getParsedStorageItem","key","item","error","lastConnectedWalletHelpers","chainId","recentConnectedWalletHelpers","wallets","createSatelliteConnectStore","adapter","callbackAfterConnected","createStore","set","get","results","a","accumulator","currentResult","value","autoConnect","lastConnectedWallet","adapterKey","foundAdapter","selectAdapterByKey","wallet","connectedWalletChainHelpers","isContractAddress","updatedWallet","recentlyConnectedWallet","updatedRecentlyConnectedWallet","e","activeWallet","state","produce","draft"],"mappings":"mKA0BO,SAASA,EAAyBC,CAAAA,CAAsC,CAC7E,OAAQA,CAAAA,CAAW,MAAM,GAAG,CAAA,CAAE,CAAC,CAAA,EAAKC,YAAAA,CAAa,GACnD,CCnBO,IAAMC,EAAsB,CAKjC,mBAAA,CACE,OAAO,MAAA,CAAW,GAAA,CAAe,OAAO,YAAA,CAAa,OAAA,CAAQ,uCAAuC,CAAA,EAAK,EAAA,CAAM,EAAA,CAcjH,eAAA,CAAkBC,GAChB,OAAO,MAAA,CAAW,IACd,MAAA,CAAO,YAAA,CAAa,QAAQ,uCAAA,CAAyCA,CAAO,EAC5E,MAAA,CAeN,eAAA,CAAiB,IACf,OAAO,MAAA,CAAW,IAAc,MAAA,CAAO,YAAA,CAAa,QAAQ,uCAAuC,CAAA,CAAI,MAAA,CAEzG,kBAAA,CAAoB,IAClB,OAAO,MAAA,CAAW,IAAc,MAAA,CAAO,YAAA,CAAa,WAAW,uCAAuC,CAAA,CAAI,MAC9G,EC9CO,SAASC,EAAiCC,CAAAA,CAAqC,CACpF,GAAI,OAAO,MAAA,CAAW,IACpB,OAGF,IAAMC,CAAAA,CAAO,MAAA,CAAO,aAAa,OAAA,CAAQD,CAAG,EAG5C,GAAKC,CAAAA,CAIL,GAAI,CAEF,OAAO,KAAK,KAAA,CAAMA,CAAI,CACxB,CAAA,MAASC,CAAAA,CAAO,CAEd,OAAA,CAAQ,KAAA,CAAM,iBA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AAA,CAAI,CAAE,aAAcY,CAAiB,CAAC,GAEtC,OAAA,CAAQ,IAAA,CAAK,sFAAsF,EAGzG,EAMA,aAAA,CAAe,MAAOnB,GAA6B,CACjDO,CAAAA,CAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CAAA,CACrC,IAAMmB,EAAelB,CAAAA,EAAI,CAAE,aAC3B,GAAIkB,CAAAA,CAAc,CAChB,IAAMV,CAAAA,CAAa1B,CAAAA,CAAyBoC,CAAAA,CAAa,UAAU,CAAA,CAC7DT,CAAAA,CAAeC,mBAAmB,CAAE,OAAA,CAAAd,EAAS,UAAA,CAAAY,CAAW,CAAC,CAAA,CAE/D,GAAI,CAACC,CAAAA,CAAc,CACjBV,EAAI,CAAE,kBAAA,CAAoB,4CAA4CmB,CAAAA,CAAa,UAAU,CAAA,CAAG,CAAC,EACjG,MACF,CAEA,GAAI,CAEF,MAAMT,EAAa,qBAAA,CAAsBjB,CAAAA,CAAS0B,EAAa,OAAA,CAASlB,CAAAA,GAAM,kBAAkB,EAClG,OAASiB,CAAAA,CAAG,CACVlB,EAAI,CAAE,kBAAA,CAAoB,2BAA6BkB,CAAAA,YAAa,KAAA,CAAQA,EAAE,OAAA,CAAU,MAAA,CAAOA,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,EAUA,uBAAA,CAAyB,IAAMlB,EAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CACtE,EAAE,CACJ","file":"index.mjs","sourcesContent":["import { OrbitAdapter } from '@tuwaio/orbit-core';\n\nimport { 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] ?? OrbitAdapter.EVM) as OrbitAdapter;\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","/**\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 { WalletType } from '../types';\nimport { getParsedStorageItem } from './getParsedStorageItem';\n\ntype LastConnectedWallet = { walletType: WalletType; chainId: number | 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 'satellite-connect: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: 'satellite-connect: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>('satellite-connect: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 }: LastConnectedWallet) =>\n typeof window !== 'undefined'\n ? window.localStorage.setItem(lastConnectedWalletHelpers.STORAGE_KEY, JSON.stringify({ walletType, chainId }))\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 '@tuwaio/orbit-core';\n\nimport { WalletType } from '../types';\nimport { getParsedStorageItem } from './getParsedStorageItem';\n\nexport type RecentConnectedWallet = { wallets: Record<OrbitAdapter, WalletType> };\n\n/**\n * Helper utilities for managing the last connected wallet state\n *\n * @remarks\n * All data is stored in localStorage with the 'satellite-connect: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: 'satellite-connect: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>('satellite-connect:recentConnectedWallet'),\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 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","import { connectedWalletChainHelpers, OrbitAdapter, selectAdapterByKey } from '@tuwaio/orbit-core';\nimport { produce } from 'immer';\nimport { createStore } from 'zustand/vanilla';\n\nimport { Connector, ISatelliteConnectStore, SatelliteConnectStoreInitialParameters, Wallet } from '../types';\nimport { getAdapterFromWalletType } from '../utils/getAdapterFromWalletType';\nimport { impersonatedHelpers } from '../utils/impersonatedHelpers';\nimport { lastConnectedWalletHelpers } from '../utils/lastConnectedWalletHelpers';\nimport { RecentConnectedWallet, recentConnectedWalletHelpers } from '../utils/recentConnectedWalletHelpers';\n\n/**\n * Creates a Satellite Connect store instance for managing wallet connections and state\n *\n * @param params - Configuration parameters for the store\n * @param params.adapter - Single adapter or array of adapters for different chains\n * @param params.callbackAfterConnected - Optional callback function called after successful wallet connection\n *\n * @returns A Zustand store instance with wallet connection state and methods\n */\nexport function createSatelliteConnectStore({\n adapter,\n callbackAfterConnected,\n}: SatelliteConnectStoreInitialParameters) {\n return createStore<ISatelliteConnectStore>()((set, get) => ({\n /**\n * Returns configured adapter(s)\n */\n getAdapter: () => adapter,\n\n /**\n * Get wallet connectors for all configured adapters\n */\n getConnectors: () => {\n let results: { adapter: OrbitAdapter; connectors: Connector[] }[];\n\n if (Array.isArray(adapter)) {\n results = adapter.map((a) => a.getConnectors());\n } else {\n // Ensure the single adapter result is wrapped in an array for consistent processing\n results = [adapter.getConnectors()];\n }\n\n return results.reduce(\n (accumulator, currentResult) => {\n const key = currentResult.adapter;\n const value = currentResult.connectors;\n return {\n ...accumulator,\n [key]: value,\n };\n },\n {} as Partial<Record<OrbitAdapter, Connector[]>>,\n );\n },\n\n initializeAutoConnect: async (autoConnect) => {\n if (autoConnect) {\n const lastConnectedWallet = lastConnectedWalletHelpers.getLastConnectedWallet();\n if (lastConnectedWallet) {\n // Explicitly await the connect call\n await get().connect({ walletType: lastConnectedWallet.walletType, chainId: lastConnectedWallet.chainId });\n }\n }\n },\n\n walletConnecting: false,\n walletConnectionError: undefined,\n switchNetworkError: undefined,\n activeWallet: undefined,\n\n /**\n * Connects to a wallet\n * @param walletType - Type of wallet to connect to\n * @param chainId - Chain ID to connect on\n */\n connect: async ({ walletType, chainId }) => {\n set({ walletConnecting: true, walletConnectionError: undefined });\n const adapterKey = getAdapterFromWalletType(walletType);\n const foundAdapter = selectAdapterByKey({ adapter, adapterKey });\n\n if (!foundAdapter) {\n set({\n walletConnecting: false,\n walletConnectionError: `No adapter found for wallet type: ${walletType}`,\n });\n return;\n }\n\n try {\n const wallet = await foundAdapter.connect({\n walletType,\n chainId,\n });\n\n // 1. Set initial wallet state\n set({ activeWallet: wallet });\n\n // 2. Set connected chain storage\n connectedWalletChainHelpers.setConnectedWalletChain(chainId);\n\n // 3. Check for contract address if the adapter supports it\n if (foundAdapter.checkIsContractWallet) {\n const isContractAddress = await foundAdapter.checkIsContractWallet({\n address: wallet.address,\n chainId,\n });\n\n // Update only the isContractAddress property\n get().updateActiveWallet({ isContractAddress });\n }\n\n // 4. Run callback if provided\n if (callbackAfterConnected) {\n // Use the latest wallet state after potential updates (like isContractAddress)\n const updatedWallet = get().activeWallet;\n if (updatedWallet) {\n await callbackAfterConnected(updatedWallet);\n }\n }\n\n // 5. Final state updates\n set({ walletConnecting: false });\n lastConnectedWalletHelpers.setLastConnectedWallet({ walletType, chainId });\n const recentlyConnectedWallet = recentConnectedWalletHelpers.getRecentConnectedWallet();\n if (recentlyConnectedWallet) {\n const updatedRecentlyConnectedWallet = {\n wallets: {\n ...recentlyConnectedWallet.wallets,\n [getAdapterFromWalletType(walletType)]: walletType,\n },\n };\n recentConnectedWalletHelpers.setRecentConnectedWallet(updatedRecentlyConnectedWallet);\n } else {\n const updatedRecentlyConnectedWallet = {\n wallets: {\n [getAdapterFromWalletType(walletType)]: walletType,\n },\n } as RecentConnectedWallet;\n recentConnectedWalletHelpers.setRecentConnectedWallet(updatedRecentlyConnectedWallet);\n }\n } catch (e) {\n set({\n walletConnecting: false,\n walletConnectionError: 'Wallet connection failed: ' + (e instanceof Error ? e.message : String(e)),\n });\n }\n },\n\n /**\n * Disconnects the currently active wallet\n */\n disconnect: async () => {\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n const foundAdapter = selectAdapterByKey({\n adapter,\n adapterKey: getAdapterFromWalletType(activeWallet.walletType),\n });\n\n // Call disconnect only if adapter is found\n await foundAdapter?.disconnect();\n\n // Clear all states and storages\n set({ activeWallet: undefined, walletConnectionError: undefined, switchNetworkError: undefined });\n lastConnectedWalletHelpers.removeLastConnectedWallet();\n connectedWalletChainHelpers.removeConnectedWalletChain();\n impersonatedHelpers.removeImpersonated();\n }\n },\n\n /**\n * Contains error message if connection failed\n */\n // walletConnectionError is declared above with an initial value\n\n /**\n * Resets any wallet connection errors\n */\n resetWalletConnectionError: () => {\n set({ walletConnectionError: undefined });\n },\n\n /**\n * Updates the active wallet's properties\n * @param wallet - Partial wallet object with properties to update\n */\n updateActiveWallet: (wallet: Partial<Wallet>) => {\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n // If chainId is updated, update storage\n if (wallet.chainId) {\n connectedWalletChainHelpers.setConnectedWalletChain(wallet.chainId);\n\n // Update lastConnectedWallet storage if chainId changes\n lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: activeWallet.walletType,\n chainId: wallet.chainId,\n });\n }\n\n // Use produce for immutable state update\n set((state) =>\n produce(state, (draft) => {\n if (draft.activeWallet) {\n // Ensure we merge partial properties into the existing activeWallet object\n draft.activeWallet = {\n ...draft.activeWallet,\n ...wallet,\n } as Wallet; // Cast ensures type compatibility after merging\n }\n }),\n );\n } else {\n const isWalletCanChange =\n wallet.walletType !== undefined && wallet.chainId !== undefined && wallet.address !== undefined;\n\n if (isWalletCanChange) {\n connectedWalletChainHelpers.setConnectedWalletChain(wallet.chainId!);\n set({ activeWallet: wallet as Wallet });\n } else {\n console.warn('Attempted to set activeWallet with incomplete data while activeWallet was undefined.');\n }\n }\n },\n\n /**\n * Switches the connected wallet to a different network\n * @param chainId - Target chain ID to switch to\n */\n switchNetwork: async (chainId: string | number) => {\n set({ switchNetworkError: undefined });\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n const adapterKey = getAdapterFromWalletType(activeWallet.walletType);\n const foundAdapter = selectAdapterByKey({ adapter, adapterKey });\n\n if (!foundAdapter) {\n set({ switchNetworkError: `No adapter found for active wallet type: ${activeWallet.walletType}` });\n return;\n }\n\n try {\n // Pass the local updateActiveWallet method from 'get()' to the adapter\n await foundAdapter.checkAndSwitchNetwork(chainId, activeWallet.chainId, get().updateActiveWallet);\n } catch (e) {\n set({ switchNetworkError: 'Switch network failed: ' + (e instanceof Error ? e.message : String(e)) });\n }\n }\n },\n\n /**\n * Contains error message if network switch failed\n */\n // switchNetworkError is declared above with an initial value\n\n /**\n * Resets any network switching errors\n */\n resetSwitchNetworkError: () => set({ switchNetworkError: undefined }),\n }));\n}\n"]}
1
+ {"version":3,"sources":["../src/utils/getAdapterFromWalletType.ts","../src/utils/impersonatedHelpers.ts","../src/utils/getParsedStorageItem.ts","../src/utils/lastConnectedWalletHelpers.ts","../src/utils/recentConnectedWalletHelpers.ts","../src/store/satelliteConnectStore.ts"],"names":["getAdapterFromWalletType","walletType","OrbitAdapter","impersonatedHelpers","address","getParsedStorageItem","key","item","error","lastConnectedWalletHelpers","chainId","recentConnectedWalletHelpers","wallets","createSatelliteConnectStore","adapter","callbackAfterConnected","createStore","set","get","results","a","accumulator","currentResult","value","autoConnect","lastConnectedWallet","adapterKey","foundAdapter","selectAdapterByKey","wallet","connectedWalletChainHelpers","isContractAddress","updatedWallet","recentlyConnectedWallet","updatedRecentlyConnectedWallet","e","activeWallet","state","produce","draft"],"mappings":"mKA0BO,SAASA,EAAyBC,CAAAA,CAAsC,CAC7E,OAAQA,CAAAA,CAAW,MAAM,GAAG,CAAA,CAAE,CAAC,CAAA,EAAKC,YAAAA,CAAa,GACnD,CCnBO,IAAMC,EAAsB,CAKjC,mBAAA,CACE,OAAO,MAAA,CAAW,GAAA,CAAe,OAAO,YAAA,CAAa,OAAA,CAAQ,uCAAuC,CAAA,EAAK,EAAA,CAAM,EAAA,CAcjH,eAAA,CAAkBC,GAChB,OAAO,MAAA,CAAW,IACd,MAAA,CAAO,YAAA,CAAa,QAAQ,uCAAA,CAAyCA,CAAO,EAC5E,MAAA,CAeN,eAAA,CAAiB,IACf,OAAO,MAAA,CAAW,IAAc,MAAA,CAAO,YAAA,CAAa,QAAQ,uCAAuC,CAAA,CAA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E,kBAAA,CAAoB,MAAU,CAAC,CACtE,EAAE,CACJ","file":"index.mjs","sourcesContent":["import { OrbitAdapter } from '@tuwaio/orbit-core';\n\nimport { 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] ?? OrbitAdapter.EVM) as OrbitAdapter;\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","/**\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 { WalletType } from '../types';\nimport { getParsedStorageItem } from './getParsedStorageItem';\n\ntype LastConnectedWallet = { walletType: WalletType; chainId: number | 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 'satellite-connect: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: 'satellite-connect: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>('satellite-connect: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 }: LastConnectedWallet) =>\n typeof window !== 'undefined'\n ? window.localStorage.setItem(lastConnectedWalletHelpers.STORAGE_KEY, JSON.stringify({ walletType, chainId }))\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 '@tuwaio/orbit-core';\n\nimport { WalletType } from '../types';\nimport { getParsedStorageItem } from './getParsedStorageItem';\n\nexport type RecentConnectedWallet = { wallets: Record<OrbitAdapter, WalletType> };\n\n/**\n * Helper utilities for managing the last connected wallet state\n *\n * @remarks\n * All data is stored in localStorage with the 'satellite-connect: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: 'satellite-connect: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>('satellite-connect:recentConnectedWallet'),\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 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","import { connectedWalletChainHelpers, OrbitAdapter, selectAdapterByKey } from '@tuwaio/orbit-core';\nimport { produce } from 'immer';\nimport { createStore } from 'zustand/vanilla';\n\nimport { BaseWallet, ISatelliteConnectStore, SatelliteConnectStoreInitialParameters, Wallet } from '../types';\nimport { getAdapterFromWalletType } from '../utils/getAdapterFromWalletType';\nimport { impersonatedHelpers } from '../utils/impersonatedHelpers';\nimport { lastConnectedWalletHelpers } from '../utils/lastConnectedWalletHelpers';\nimport { RecentConnectedWallet, recentConnectedWalletHelpers } from '../utils/recentConnectedWalletHelpers';\n\n/**\n * Creates a Satellite Connect store instance for managing wallet connections and state\n *\n * @param params - Configuration parameters for the store\n * @param params.adapter - Single adapter or array of adapters for different chains\n * @param params.callbackAfterConnected - Optional callback function called after successful wallet connection\n *\n * @returns A Zustand store instance with wallet connection state and methods\n */\nexport function createSatelliteConnectStore<C, W extends BaseWallet = BaseWallet>({\n adapter,\n callbackAfterConnected,\n}: SatelliteConnectStoreInitialParameters<C, W>) {\n return createStore<ISatelliteConnectStore<C, W>>()((set, get) => ({\n /**\n * Returns configured adapter(s)\n */\n getAdapter: () => adapter,\n\n /**\n * Get wallet connectors for all configured adapters\n */\n getConnectors: () => {\n let results: { adapter: OrbitAdapter; connectors: C[] }[];\n\n if (Array.isArray(adapter)) {\n results = adapter.map((a) => a.getConnectors());\n } else {\n // Ensure the single adapter result is wrapped in an array for consistent processing\n results = [adapter.getConnectors()];\n }\n\n return results.reduce(\n (accumulator, currentResult) => {\n const key = currentResult.adapter;\n const value = currentResult.connectors;\n return {\n ...accumulator,\n [key]: value,\n };\n },\n {} as Partial<Record<OrbitAdapter, C[]>>,\n );\n },\n\n initializeAutoConnect: async (autoConnect) => {\n if (autoConnect) {\n const lastConnectedWallet = lastConnectedWalletHelpers.getLastConnectedWallet();\n if (lastConnectedWallet) {\n // Explicitly await the connect call\n await get().connect({ walletType: lastConnectedWallet.walletType, chainId: lastConnectedWallet.chainId });\n }\n }\n },\n\n walletConnecting: false,\n walletConnectionError: undefined,\n switchNetworkError: undefined,\n activeWallet: undefined,\n\n /**\n * Connects to a wallet\n * @param walletType - Type of wallet to connect to\n * @param chainId - Chain ID to connect on\n */\n connect: async ({ walletType, chainId }) => {\n set({ walletConnecting: true, walletConnectionError: undefined });\n const adapterKey = getAdapterFromWalletType(walletType);\n const foundAdapter = selectAdapterByKey({ adapter, adapterKey });\n\n if (!foundAdapter) {\n set({\n walletConnecting: false,\n walletConnectionError: `No adapter found for wallet type: ${walletType}`,\n });\n return;\n }\n\n try {\n const wallet = await foundAdapter.connect({\n walletType,\n chainId,\n });\n\n // 1. Set initial wallet state\n set({ activeWallet: wallet });\n\n // 2. Set connected chain storage\n connectedWalletChainHelpers.setConnectedWalletChain(chainId);\n\n // 3. Check for contract address if the adapter supports it\n if (foundAdapter.checkIsContractWallet) {\n const isContractAddress = await foundAdapter.checkIsContractWallet({\n address: wallet.address,\n chainId,\n });\n\n // Update only the isContractAddress property\n get().updateActiveWallet({ isContractAddress });\n }\n\n // 4. Run callback if provided\n if (callbackAfterConnected) {\n // Use the latest wallet state after potential updates (like isContractAddress)\n const updatedWallet = get().activeWallet;\n if (updatedWallet) {\n await callbackAfterConnected(updatedWallet);\n }\n }\n\n // 5. Final state updates\n set({ walletConnecting: false });\n lastConnectedWalletHelpers.setLastConnectedWallet({ walletType, chainId });\n const recentlyConnectedWallet = recentConnectedWalletHelpers.getRecentConnectedWallet();\n if (recentlyConnectedWallet) {\n const updatedRecentlyConnectedWallet = {\n wallets: {\n ...recentlyConnectedWallet.wallets,\n [getAdapterFromWalletType(walletType)]: walletType,\n },\n };\n recentConnectedWalletHelpers.setRecentConnectedWallet(updatedRecentlyConnectedWallet);\n } else {\n const updatedRecentlyConnectedWallet = {\n wallets: {\n [getAdapterFromWalletType(walletType)]: walletType,\n },\n } as RecentConnectedWallet;\n recentConnectedWalletHelpers.setRecentConnectedWallet(updatedRecentlyConnectedWallet);\n }\n } catch (e) {\n set({\n walletConnecting: false,\n walletConnectionError: 'Wallet connection failed: ' + (e instanceof Error ? e.message : String(e)),\n });\n }\n },\n\n /**\n * Disconnects the currently active wallet\n */\n disconnect: async () => {\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n const foundAdapter = selectAdapterByKey({\n adapter,\n adapterKey: getAdapterFromWalletType(activeWallet.walletType),\n });\n\n // Call disconnect only if adapter is found\n await foundAdapter?.disconnect();\n\n // Clear all states and storages\n set({ activeWallet: undefined, walletConnectionError: undefined, switchNetworkError: undefined });\n lastConnectedWalletHelpers.removeLastConnectedWallet();\n connectedWalletChainHelpers.removeConnectedWalletChain();\n impersonatedHelpers.removeImpersonated();\n }\n },\n\n /**\n * Contains error message if connection failed\n */\n // walletConnectionError is declared above with an initial value\n\n /**\n * Resets any wallet connection errors\n */\n resetWalletConnectionError: () => {\n set({ walletConnectionError: undefined });\n },\n\n /**\n * Updates the active wallet's properties\n * @param wallet - Partial wallet object with properties to update\n */\n updateActiveWallet: (wallet: Partial<Wallet<W>>) => {\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n // If chainId is updated, update storage\n if (wallet.chainId) {\n connectedWalletChainHelpers.setConnectedWalletChain(wallet.chainId);\n\n // Update lastConnectedWallet storage if chainId changes\n lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: activeWallet.walletType,\n chainId: wallet.chainId,\n });\n }\n\n // Use produce for immutable state update\n set((state) =>\n produce(state, (draft) => {\n if (draft.activeWallet) {\n // Ensure we merge partial properties into the existing activeWallet object\n draft.activeWallet = {\n ...draft.activeWallet,\n ...wallet,\n } as W; // Cast ensures type compatibility after merging\n }\n }),\n );\n } else {\n const isWalletCanChange =\n wallet.walletType !== undefined && wallet.chainId !== undefined && wallet.address !== undefined;\n\n if (isWalletCanChange) {\n connectedWalletChainHelpers.setConnectedWalletChain(wallet.chainId!);\n set({ activeWallet: wallet as W });\n } else {\n console.warn('Attempted to set activeWallet with incomplete data while activeWallet was undefined.');\n }\n }\n },\n\n /**\n * Switches the connected wallet to a different network\n * @param chainId - Target chain ID to switch to\n */\n switchNetwork: async (chainId: string | number) => {\n set({ switchNetworkError: undefined });\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n const adapterKey = getAdapterFromWalletType(activeWallet.walletType);\n const foundAdapter = selectAdapterByKey({ adapter, adapterKey });\n\n if (!foundAdapter) {\n set({ switchNetworkError: `No adapter found for active wallet type: ${activeWallet.walletType}` });\n return;\n }\n\n try {\n // Pass the local updateActiveWallet method from 'get()' to the adapter\n await foundAdapter.checkAndSwitchNetwork(chainId, activeWallet.chainId, get().updateActiveWallet);\n } catch (e) {\n set({ switchNetworkError: 'Switch network failed: ' + (e instanceof Error ? e.message : String(e)) });\n }\n }\n },\n\n /**\n * Contains error message if network switch failed\n */\n // switchNetworkError is declared above with an initial value\n\n /**\n * Resets any network switching errors\n */\n resetSwitchNetworkError: () => set({ switchNetworkError: undefined }),\n }));\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuwaio/satellite-core",
3
- "version": "1.0.0-fix-test-alpha.17.cf65aef",
3
+ "version": "1.0.0-fix-test-alpha.18.0fe490a",
4
4
  "private": false,
5
5
  "author": "Oleksandr Tkach",
6
6
  "license": "Apache-2.0",
@@ -40,20 +40,16 @@
40
40
  }
41
41
  ],
42
42
  "peerDependencies": {
43
- "@wagmi/core": ">=2.2",
44
- "@wallet-standard/ui": ">=1",
45
43
  "@tuwaio/orbit-core": ">=0",
46
- "immer": ">=10",
47
- "zustand": ">=5"
44
+ "immer": "10.x.x",
45
+ "zustand": "5.x.x"
48
46
  },
49
47
  "devDependencies": {
50
- "@wagmi/core": "^2.21.1",
51
- "@wallet-standard/ui": "^1.0.1",
52
48
  "immer": "^10.1.3",
53
49
  "tsup": "^8.5.0",
54
50
  "typescript": "^5.9.2",
55
51
  "zustand": "^5.0.8",
56
- "@tuwaio/orbit-core": "^1.0.0-fix-test-alpha.17.cf65aef"
52
+ "@tuwaio/orbit-core": "^1.0.0-fix-test-alpha.18.0fe490a"
57
53
  },
58
54
  "scripts": {
59
55
  "start": "tsup src/index.ts --watch",