@tuwaio/satellite-core 0.1.3 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/index.d.mts +64 -56
- package/dist/index.d.ts +64 -56
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -22,6 +22,7 @@ Built with TypeScript, it leverages modern tools for state management and type-s
|
|
|
22
22
|
- **Type Safety:** Full TypeScript support
|
|
23
23
|
- **Modular Architecture:** Easy extension for new wallet types
|
|
24
24
|
- **State Management:** Built-in connection state management system
|
|
25
|
+
- **Multi-Wallet Support:** Manage multiple simultaneous wallet connections
|
|
25
26
|
- **Bundle Optimization:** Efficient tree-shaking optimization
|
|
26
27
|
|
|
27
28
|
---
|
|
@@ -29,8 +30,10 @@ Built with TypeScript, it leverages modern tools for state management and type-s
|
|
|
29
30
|
## 💾 Installation
|
|
30
31
|
|
|
31
32
|
### Requirements
|
|
33
|
+
|
|
32
34
|
- Node.js 20+
|
|
33
35
|
- TypeScript 5.9+
|
|
36
|
+
|
|
34
37
|
```bash
|
|
35
38
|
# Using pnpm (recommended)
|
|
36
39
|
pnpm add @tuwaio/satellite-core @tuwaio/orbit-core immer zustand
|
|
@@ -41,6 +44,7 @@ npm install @tuwaio/satellite-core @tuwaio/orbit-core immer zustand
|
|
|
41
44
|
# Using yarn
|
|
42
45
|
yarn add @tuwaio/satellite-core @tuwaio/orbit-core immer zustand
|
|
43
46
|
```
|
|
47
|
+
|
|
44
48
|
---
|
|
45
49
|
|
|
46
50
|
## 🔧 Architecture
|
|
@@ -48,11 +52,13 @@ yarn add @tuwaio/satellite-core @tuwaio/orbit-core immer zustand
|
|
|
48
52
|
The package is structured around these core components:
|
|
49
53
|
|
|
50
54
|
### Build System
|
|
55
|
+
|
|
51
56
|
- Built with `tsup`
|
|
52
57
|
- Supports CommonJS and ESM formats
|
|
53
58
|
- Generates TypeScript declarations
|
|
54
59
|
|
|
55
60
|
### Core Modules
|
|
61
|
+
|
|
56
62
|
- **Store:** Connection state management system
|
|
57
63
|
- **Types:** Type system for unified wallet operations
|
|
58
64
|
|
package/dist/index.d.mts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import * as zustand_vanilla from 'zustand/vanilla';
|
|
2
|
-
import {
|
|
2
|
+
import { ConnectorType, OrbitGenericAdapter, BaseAdapter, OrbitAdapter } from '@tuwaio/orbit-core';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* Configuration properties for initializing
|
|
5
|
+
* Configuration properties for initializing connectors
|
|
6
6
|
*/
|
|
7
7
|
type ConnectorsInitProps = {
|
|
8
8
|
/** Application name displayed in wallet interfaces */
|
|
@@ -21,12 +21,12 @@ type ConnectorsInitProps = {
|
|
|
21
21
|
appIcons?: string[];
|
|
22
22
|
};
|
|
23
23
|
/**
|
|
24
|
-
* Base interface for connected
|
|
24
|
+
* Base interface for connected connector information
|
|
25
25
|
*/
|
|
26
|
-
interface
|
|
27
|
-
/** Unique identifier of the
|
|
28
|
-
|
|
29
|
-
/** Wallet
|
|
26
|
+
interface BaseConnector {
|
|
27
|
+
/** Unique identifier of the connector */
|
|
28
|
+
connectorType: ConnectorType;
|
|
29
|
+
/** Wallet public address */
|
|
30
30
|
address: string | `0x${string}`;
|
|
31
31
|
/** Connected chain ID */
|
|
32
32
|
chainId: string | number;
|
|
@@ -36,112 +36,120 @@ interface BaseWallet {
|
|
|
36
36
|
isContractAddress: boolean;
|
|
37
37
|
/** Connection status */
|
|
38
38
|
isConnected: boolean;
|
|
39
|
-
/** Optional:
|
|
40
|
-
|
|
39
|
+
/** Optional: connector icon base64 string */
|
|
40
|
+
icon?: string;
|
|
41
41
|
}
|
|
42
|
-
/** Generic type for all supported
|
|
43
|
-
type
|
|
42
|
+
/** Generic type for all supported connector types */
|
|
43
|
+
type Connector<W extends BaseConnector> = BaseConnector | W;
|
|
44
44
|
/**
|
|
45
45
|
* Interface for blockchain network adapters
|
|
46
46
|
* @remarks
|
|
47
|
-
* Adapters provide chain-specific implementation for
|
|
47
|
+
* Adapters provide chain-specific implementation for connector interactions
|
|
48
48
|
*/
|
|
49
|
-
type SatelliteAdapter<C, W extends
|
|
49
|
+
type SatelliteAdapter<C, W extends BaseConnector = BaseConnector> = BaseAdapter & {
|
|
50
50
|
/** Unique identifier for the adapter */
|
|
51
51
|
key: OrbitAdapter;
|
|
52
52
|
/**
|
|
53
|
-
* Initiates
|
|
54
|
-
* @returns Promise resolving to connected
|
|
53
|
+
* Initiates connection
|
|
54
|
+
* @returns Promise resolving to connected connector instance
|
|
55
55
|
*/
|
|
56
|
-
connect: ({
|
|
57
|
-
|
|
56
|
+
connect: ({ connectorType, chainId, }: {
|
|
57
|
+
connectorType: ConnectorType;
|
|
58
58
|
chainId: number | string;
|
|
59
|
-
}) => Promise<
|
|
60
|
-
/** Disconnects current
|
|
61
|
-
disconnect: (
|
|
62
|
-
/** Retrieves available
|
|
59
|
+
}) => Promise<Connector<W>>;
|
|
60
|
+
/** Disconnects current connector session */
|
|
61
|
+
disconnect: (activeConnector?: Connector<W>) => Promise<void>;
|
|
62
|
+
/** Retrieves available connectors for this adapter */
|
|
63
63
|
getConnectors: () => {
|
|
64
64
|
adapter: OrbitAdapter;
|
|
65
65
|
connectors: C[];
|
|
66
66
|
};
|
|
67
67
|
/**
|
|
68
|
-
* Handles network switching for connected
|
|
68
|
+
* Handles network switching for connected connector
|
|
69
69
|
* @param chainId - Target chain ID
|
|
70
70
|
* @param currentChainId - Current chain ID
|
|
71
|
-
* @param
|
|
71
|
+
* @param updateActiveConnector - Callback to update connector state
|
|
72
72
|
*/
|
|
73
|
-
checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number,
|
|
73
|
+
checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number, updateActiveConnector?: (connector: Partial<Connector<W>>) => void) => Promise<void>;
|
|
74
74
|
getBalance: (address: string, chainId: number | string) => Promise<{
|
|
75
75
|
value: string;
|
|
76
76
|
symbol: string;
|
|
77
77
|
}>;
|
|
78
78
|
/** Optional method to check if address is a smart contract */
|
|
79
|
-
|
|
79
|
+
checkIsContractAddress?: ({ address, chainId }: {
|
|
80
80
|
address: string;
|
|
81
81
|
chainId: string | number;
|
|
82
82
|
}) => Promise<boolean>;
|
|
83
83
|
/** Optional method to get a safe connector chainId for auto connect */
|
|
84
84
|
getSafeConnectorChainId?: () => Promise<number | undefined>;
|
|
85
|
+
/** Optional method to switch active connector */
|
|
86
|
+
switchConnection?: (connectorType: ConnectorType) => Promise<void>;
|
|
85
87
|
};
|
|
86
88
|
/**
|
|
87
|
-
* Store interface for managing
|
|
89
|
+
* Store interface for managing connector connections
|
|
88
90
|
*/
|
|
89
|
-
type ISatelliteConnectStore<C, W extends
|
|
91
|
+
type ISatelliteConnectStore<C, W extends BaseConnector = BaseConnector> = {
|
|
90
92
|
/** Returns configured adapter(s) */
|
|
91
93
|
getAdapter: (adapterKey: OrbitAdapter) => SatelliteAdapter<C, W> | undefined;
|
|
92
|
-
/** Get
|
|
94
|
+
/** Get connectors */
|
|
93
95
|
getConnectors: () => Partial<Record<OrbitAdapter, C[]>>;
|
|
94
96
|
/** Initialize auto connect logic */
|
|
95
97
|
initializeAutoConnect: (autoConnect: boolean) => Promise<void>;
|
|
96
|
-
/** Connects to specified
|
|
97
|
-
connect: ({
|
|
98
|
-
|
|
98
|
+
/** Connects to specified connector */
|
|
99
|
+
connect: ({ connectorType, chainId }: {
|
|
100
|
+
connectorType: ConnectorType;
|
|
99
101
|
chainId: number | string;
|
|
100
102
|
}) => Promise<void>;
|
|
101
|
-
/** Disconnects active
|
|
102
|
-
disconnect: () => Promise<void>;
|
|
103
|
-
/** Disconnects all
|
|
103
|
+
/** Disconnects active connector */
|
|
104
|
+
disconnect: (connectorType?: ConnectorType) => Promise<void>;
|
|
105
|
+
/** Disconnects all connectors, used for initialize application */
|
|
104
106
|
disconnectAll: () => Promise<void>;
|
|
105
107
|
/** Indicates ongoing connection attempt */
|
|
106
|
-
|
|
108
|
+
connecting: boolean;
|
|
109
|
+
/** Indicates ongoing disconnection attempt */
|
|
110
|
+
disconnecting: boolean;
|
|
107
111
|
/** Contains error message if connection failed */
|
|
108
|
-
|
|
112
|
+
connectionError?: string;
|
|
109
113
|
/** Sets error message if connection failed or form validation failed */
|
|
110
|
-
|
|
111
|
-
/** Currently connected
|
|
112
|
-
|
|
114
|
+
setConnectionError: (error: string) => void;
|
|
115
|
+
/** Currently connected connector */
|
|
116
|
+
activeConnection?: Connector<W>;
|
|
117
|
+
/** List of all connected connectors */
|
|
118
|
+
connections: Record<ConnectorType, Connector<W>>;
|
|
113
119
|
/** Clears connection error state */
|
|
114
|
-
|
|
115
|
-
/** Updates active
|
|
116
|
-
|
|
117
|
-
/** Switches
|
|
118
|
-
|
|
120
|
+
resetConnectionError: () => void;
|
|
121
|
+
/** Updates active connector properties */
|
|
122
|
+
updateActiveConnection: (connector: Partial<Connector<W>>) => void;
|
|
123
|
+
/** Switches active connector from the list of connections */
|
|
124
|
+
switchConnection: (connectorType: ConnectorType) => Promise<void>;
|
|
125
|
+
/** Switches network for connected connector */
|
|
126
|
+
switchNetwork: (chainId: string | number, connectorType?: ConnectorType) => Promise<void>;
|
|
119
127
|
/** Contains error message if network switch failed */
|
|
120
128
|
switchNetworkError?: string;
|
|
121
129
|
/** Clears network switch error state */
|
|
122
130
|
resetSwitchNetworkError: () => void;
|
|
123
131
|
};
|
|
124
132
|
/**
|
|
125
|
-
* Callback type for successful
|
|
133
|
+
* Callback type for successful connections
|
|
126
134
|
*/
|
|
127
|
-
type
|
|
135
|
+
type ConnectedCallback<W extends BaseConnector = BaseConnector> = (connector: Connector<W>) => void | Promise<void>;
|
|
128
136
|
/**
|
|
129
137
|
* Configuration parameters for initializing Satellite Connect store
|
|
130
138
|
*/
|
|
131
|
-
type SatelliteConnectStoreInitialParameters<C, W extends
|
|
132
|
-
/** Optional callback executed after successful
|
|
133
|
-
callbackAfterConnected?:
|
|
139
|
+
type SatelliteConnectStoreInitialParameters<C, W extends BaseConnector = BaseConnector> = OrbitGenericAdapter<SatelliteAdapter<C, W>> & {
|
|
140
|
+
/** Optional callback executed after successful connection */
|
|
141
|
+
callbackAfterConnected?: ConnectedCallback<W>;
|
|
134
142
|
};
|
|
135
143
|
|
|
136
144
|
/**
|
|
137
|
-
* Creates a Satellite Connect store instance for managing
|
|
145
|
+
* Creates a Satellite Connect store instance for managing connector connections and state
|
|
138
146
|
*
|
|
139
|
-
* @param params -
|
|
140
|
-
* @param params.adapter -
|
|
141
|
-
* @param params.callbackAfterConnected - Optional callback function called after successful
|
|
147
|
+
* @param params - Initial parameters for the store
|
|
148
|
+
* @param params.adapter - Blockchain adapter(s) to use
|
|
149
|
+
* @param params.callbackAfterConnected - Optional callback function called after successful connection
|
|
142
150
|
*
|
|
143
|
-
* @returns A Zustand store instance with
|
|
151
|
+
* @returns A Zustand store instance with connection state and methods
|
|
144
152
|
*/
|
|
145
|
-
declare function createSatelliteConnectStore<C, W extends
|
|
153
|
+
declare function createSatelliteConnectStore<C, W extends BaseConnector = BaseConnector>({ adapter, callbackAfterConnected, }: SatelliteConnectStoreInitialParameters<C, W>): zustand_vanilla.StoreApi<ISatelliteConnectStore<C, W>>;
|
|
146
154
|
|
|
147
|
-
export { type
|
|
155
|
+
export { type BaseConnector, type ConnectedCallback, type Connector, type ConnectorsInitProps, type ISatelliteConnectStore, type SatelliteAdapter, type SatelliteConnectStoreInitialParameters, createSatelliteConnectStore };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import * as zustand_vanilla from 'zustand/vanilla';
|
|
2
|
-
import {
|
|
2
|
+
import { ConnectorType, OrbitGenericAdapter, BaseAdapter, OrbitAdapter } from '@tuwaio/orbit-core';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* Configuration properties for initializing
|
|
5
|
+
* Configuration properties for initializing connectors
|
|
6
6
|
*/
|
|
7
7
|
type ConnectorsInitProps = {
|
|
8
8
|
/** Application name displayed in wallet interfaces */
|
|
@@ -21,12 +21,12 @@ type ConnectorsInitProps = {
|
|
|
21
21
|
appIcons?: string[];
|
|
22
22
|
};
|
|
23
23
|
/**
|
|
24
|
-
* Base interface for connected
|
|
24
|
+
* Base interface for connected connector information
|
|
25
25
|
*/
|
|
26
|
-
interface
|
|
27
|
-
/** Unique identifier of the
|
|
28
|
-
|
|
29
|
-
/** Wallet
|
|
26
|
+
interface BaseConnector {
|
|
27
|
+
/** Unique identifier of the connector */
|
|
28
|
+
connectorType: ConnectorType;
|
|
29
|
+
/** Wallet public address */
|
|
30
30
|
address: string | `0x${string}`;
|
|
31
31
|
/** Connected chain ID */
|
|
32
32
|
chainId: string | number;
|
|
@@ -36,112 +36,120 @@ interface BaseWallet {
|
|
|
36
36
|
isContractAddress: boolean;
|
|
37
37
|
/** Connection status */
|
|
38
38
|
isConnected: boolean;
|
|
39
|
-
/** Optional:
|
|
40
|
-
|
|
39
|
+
/** Optional: connector icon base64 string */
|
|
40
|
+
icon?: string;
|
|
41
41
|
}
|
|
42
|
-
/** Generic type for all supported
|
|
43
|
-
type
|
|
42
|
+
/** Generic type for all supported connector types */
|
|
43
|
+
type Connector<W extends BaseConnector> = BaseConnector | W;
|
|
44
44
|
/**
|
|
45
45
|
* Interface for blockchain network adapters
|
|
46
46
|
* @remarks
|
|
47
|
-
* Adapters provide chain-specific implementation for
|
|
47
|
+
* Adapters provide chain-specific implementation for connector interactions
|
|
48
48
|
*/
|
|
49
|
-
type SatelliteAdapter<C, W extends
|
|
49
|
+
type SatelliteAdapter<C, W extends BaseConnector = BaseConnector> = BaseAdapter & {
|
|
50
50
|
/** Unique identifier for the adapter */
|
|
51
51
|
key: OrbitAdapter;
|
|
52
52
|
/**
|
|
53
|
-
* Initiates
|
|
54
|
-
* @returns Promise resolving to connected
|
|
53
|
+
* Initiates connection
|
|
54
|
+
* @returns Promise resolving to connected connector instance
|
|
55
55
|
*/
|
|
56
|
-
connect: ({
|
|
57
|
-
|
|
56
|
+
connect: ({ connectorType, chainId, }: {
|
|
57
|
+
connectorType: ConnectorType;
|
|
58
58
|
chainId: number | string;
|
|
59
|
-
}) => Promise<
|
|
60
|
-
/** Disconnects current
|
|
61
|
-
disconnect: (
|
|
62
|
-
/** Retrieves available
|
|
59
|
+
}) => Promise<Connector<W>>;
|
|
60
|
+
/** Disconnects current connector session */
|
|
61
|
+
disconnect: (activeConnector?: Connector<W>) => Promise<void>;
|
|
62
|
+
/** Retrieves available connectors for this adapter */
|
|
63
63
|
getConnectors: () => {
|
|
64
64
|
adapter: OrbitAdapter;
|
|
65
65
|
connectors: C[];
|
|
66
66
|
};
|
|
67
67
|
/**
|
|
68
|
-
* Handles network switching for connected
|
|
68
|
+
* Handles network switching for connected connector
|
|
69
69
|
* @param chainId - Target chain ID
|
|
70
70
|
* @param currentChainId - Current chain ID
|
|
71
|
-
* @param
|
|
71
|
+
* @param updateActiveConnector - Callback to update connector state
|
|
72
72
|
*/
|
|
73
|
-
checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number,
|
|
73
|
+
checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number, updateActiveConnector?: (connector: Partial<Connector<W>>) => void) => Promise<void>;
|
|
74
74
|
getBalance: (address: string, chainId: number | string) => Promise<{
|
|
75
75
|
value: string;
|
|
76
76
|
symbol: string;
|
|
77
77
|
}>;
|
|
78
78
|
/** Optional method to check if address is a smart contract */
|
|
79
|
-
|
|
79
|
+
checkIsContractAddress?: ({ address, chainId }: {
|
|
80
80
|
address: string;
|
|
81
81
|
chainId: string | number;
|
|
82
82
|
}) => Promise<boolean>;
|
|
83
83
|
/** Optional method to get a safe connector chainId for auto connect */
|
|
84
84
|
getSafeConnectorChainId?: () => Promise<number | undefined>;
|
|
85
|
+
/** Optional method to switch active connector */
|
|
86
|
+
switchConnection?: (connectorType: ConnectorType) => Promise<void>;
|
|
85
87
|
};
|
|
86
88
|
/**
|
|
87
|
-
* Store interface for managing
|
|
89
|
+
* Store interface for managing connector connections
|
|
88
90
|
*/
|
|
89
|
-
type ISatelliteConnectStore<C, W extends
|
|
91
|
+
type ISatelliteConnectStore<C, W extends BaseConnector = BaseConnector> = {
|
|
90
92
|
/** Returns configured adapter(s) */
|
|
91
93
|
getAdapter: (adapterKey: OrbitAdapter) => SatelliteAdapter<C, W> | undefined;
|
|
92
|
-
/** Get
|
|
94
|
+
/** Get connectors */
|
|
93
95
|
getConnectors: () => Partial<Record<OrbitAdapter, C[]>>;
|
|
94
96
|
/** Initialize auto connect logic */
|
|
95
97
|
initializeAutoConnect: (autoConnect: boolean) => Promise<void>;
|
|
96
|
-
/** Connects to specified
|
|
97
|
-
connect: ({
|
|
98
|
-
|
|
98
|
+
/** Connects to specified connector */
|
|
99
|
+
connect: ({ connectorType, chainId }: {
|
|
100
|
+
connectorType: ConnectorType;
|
|
99
101
|
chainId: number | string;
|
|
100
102
|
}) => Promise<void>;
|
|
101
|
-
/** Disconnects active
|
|
102
|
-
disconnect: () => Promise<void>;
|
|
103
|
-
/** Disconnects all
|
|
103
|
+
/** Disconnects active connector */
|
|
104
|
+
disconnect: (connectorType?: ConnectorType) => Promise<void>;
|
|
105
|
+
/** Disconnects all connectors, used for initialize application */
|
|
104
106
|
disconnectAll: () => Promise<void>;
|
|
105
107
|
/** Indicates ongoing connection attempt */
|
|
106
|
-
|
|
108
|
+
connecting: boolean;
|
|
109
|
+
/** Indicates ongoing disconnection attempt */
|
|
110
|
+
disconnecting: boolean;
|
|
107
111
|
/** Contains error message if connection failed */
|
|
108
|
-
|
|
112
|
+
connectionError?: string;
|
|
109
113
|
/** Sets error message if connection failed or form validation failed */
|
|
110
|
-
|
|
111
|
-
/** Currently connected
|
|
112
|
-
|
|
114
|
+
setConnectionError: (error: string) => void;
|
|
115
|
+
/** Currently connected connector */
|
|
116
|
+
activeConnection?: Connector<W>;
|
|
117
|
+
/** List of all connected connectors */
|
|
118
|
+
connections: Record<ConnectorType, Connector<W>>;
|
|
113
119
|
/** Clears connection error state */
|
|
114
|
-
|
|
115
|
-
/** Updates active
|
|
116
|
-
|
|
117
|
-
/** Switches
|
|
118
|
-
|
|
120
|
+
resetConnectionError: () => void;
|
|
121
|
+
/** Updates active connector properties */
|
|
122
|
+
updateActiveConnection: (connector: Partial<Connector<W>>) => void;
|
|
123
|
+
/** Switches active connector from the list of connections */
|
|
124
|
+
switchConnection: (connectorType: ConnectorType) => Promise<void>;
|
|
125
|
+
/** Switches network for connected connector */
|
|
126
|
+
switchNetwork: (chainId: string | number, connectorType?: ConnectorType) => Promise<void>;
|
|
119
127
|
/** Contains error message if network switch failed */
|
|
120
128
|
switchNetworkError?: string;
|
|
121
129
|
/** Clears network switch error state */
|
|
122
130
|
resetSwitchNetworkError: () => void;
|
|
123
131
|
};
|
|
124
132
|
/**
|
|
125
|
-
* Callback type for successful
|
|
133
|
+
* Callback type for successful connections
|
|
126
134
|
*/
|
|
127
|
-
type
|
|
135
|
+
type ConnectedCallback<W extends BaseConnector = BaseConnector> = (connector: Connector<W>) => void | Promise<void>;
|
|
128
136
|
/**
|
|
129
137
|
* Configuration parameters for initializing Satellite Connect store
|
|
130
138
|
*/
|
|
131
|
-
type SatelliteConnectStoreInitialParameters<C, W extends
|
|
132
|
-
/** Optional callback executed after successful
|
|
133
|
-
callbackAfterConnected?:
|
|
139
|
+
type SatelliteConnectStoreInitialParameters<C, W extends BaseConnector = BaseConnector> = OrbitGenericAdapter<SatelliteAdapter<C, W>> & {
|
|
140
|
+
/** Optional callback executed after successful connection */
|
|
141
|
+
callbackAfterConnected?: ConnectedCallback<W>;
|
|
134
142
|
};
|
|
135
143
|
|
|
136
144
|
/**
|
|
137
|
-
* Creates a Satellite Connect store instance for managing
|
|
145
|
+
* Creates a Satellite Connect store instance for managing connector connections and state
|
|
138
146
|
*
|
|
139
|
-
* @param params -
|
|
140
|
-
* @param params.adapter -
|
|
141
|
-
* @param params.callbackAfterConnected - Optional callback function called after successful
|
|
147
|
+
* @param params - Initial parameters for the store
|
|
148
|
+
* @param params.adapter - Blockchain adapter(s) to use
|
|
149
|
+
* @param params.callbackAfterConnected - Optional callback function called after successful connection
|
|
142
150
|
*
|
|
143
|
-
* @returns A Zustand store instance with
|
|
151
|
+
* @returns A Zustand store instance with connection state and methods
|
|
144
152
|
*/
|
|
145
|
-
declare function createSatelliteConnectStore<C, W extends
|
|
153
|
+
declare function createSatelliteConnectStore<C, W extends BaseConnector = BaseConnector>({ adapter, callbackAfterConnected, }: SatelliteConnectStoreInitialParameters<C, W>): zustand_vanilla.StoreApi<ISatelliteConnectStore<C, W>>;
|
|
146
154
|
|
|
147
|
-
export { type
|
|
155
|
+
export { type BaseConnector, type ConnectedCallback, type Connector, type ConnectorsInitProps, type ISatelliteConnectStore, type SatelliteAdapter, type SatelliteConnectStoreInitialParameters, createSatelliteConnectStore };
|
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
|
|
1
|
+
'use strict';var orbitCore=require('@tuwaio/orbit-core'),immer=require('immer'),vanilla=require('zustand/vanilla');function b({adapter:l,callbackAfterConnected:h}){return immer.setAutoFreeze(false),vanilla.createStore()((r,c)=>({getAdapter:n=>orbitCore.selectAdapterByKey({adapter:l,adapterKey:n}),getConnectors:()=>{let n;return Array.isArray(l)?n=l.map(o=>o.getConnectors()):n=[l.getConnectors()],n.reduce((o,e)=>{let i=e.adapter,t=e.connectors;return {...o,[i]:t}},{})},initializeAutoConnect:async n=>{await orbitCore.delay(null,300),await c().disconnectAll();let o=Date.now()-10080*60*1e3;if(orbitCore.recentlyConnectedConnectorsListHelpers.removeConnectorsOlderThan(o),n){let e=orbitCore.lastConnectedConnectorHelpers.getLastConnectedConnector();e&&!["impersonatedwallet","walletconnect","coinbasewallet","bitgetwallet"].includes(e.connectorType.split(":")[1])&&(await orbitCore.delay(null,100),await c().connect({connectorType:e.connectorType,chainId:e.chainId}));}else if(orbitCore.isSafeApp){await orbitCore.delay(null,100);let e=c().getAdapter(orbitCore.OrbitAdapter.EVM);if(e&&e.getSafeConnectorChainId){let i=await e.getSafeConnectorChainId();i&&await c().connect({connectorType:`${orbitCore.OrbitAdapter.EVM}:safewallet`,chainId:i});}}},connecting:false,disconnecting:false,connectionError:void 0,switchNetworkError:void 0,activeConnection:void 0,connections:{},setConnectionError:n=>r({connectionError:n}),connect:async({connectorType:n,chainId:o})=>{r({connecting:true,connectionError:void 0});let e=c().getAdapter(orbitCore.getAdapterFromConnectorType(n));if(!e){r({connecting:false,connectionError:`No adapter found for connector type: ${n}`});return}try{if(c().connections[n])return;let t=await e.connect({connectorType:n,chainId:o});if(r(s=>({activeConnection:t,connections:{...s.connections,[t.connectorType]:t}})),e.checkIsContractAddress){let s=await e.checkIsContractAddress({address:t.address,chainId:o});c().updateActiveConnection({...t,isContractAddress:s});}if(h){let s=c().activeConnection;s&&s.connectorType===n&&await h(s);}r({connecting:!1}),orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:n,chainId:o,address:c().activeConnection?.address});let a=c().activeConnection;a&&a.address&&orbitCore.recentlyConnectedConnectorsListHelpers.addConnector(a.connectorType,{address:a.address,disconnectedTimestamp:Date.now(),icon:a.icon});}catch(i){r({connecting:false,connectionError:"Connector connection failed: "+(i instanceof Error?i.message:String(i))});}},disconnect:async n=>{if(!c().disconnecting){r({disconnecting:true});try{if(n){let e=c(),i=e.connections[n];if(!i){console.warn(`No connection found for connector type: ${n}`);return}let t=c().getAdapter(orbitCore.getAdapterFromConnectorType(i.connectorType));if(t)try{await t.disconnect(i);}catch(d){console.error(`Failed to disconnect connector ${n}:`,d);}let a=e.activeConnection?.connectorType===n,s=Object.values(e.connections).filter(d=>d.connectorType!==n),w;if(a&&s.length>0){let d=s[0];try{let C=c().getAdapter(orbitCore.getAdapterFromConnectorType(d.connectorType));C?.switchConnection&&await C.switchConnection(d.connectorType),w=d;}catch(C){console.error("Failed to switch to remaining connector:",C),w=void 0;}}else a||(w=e.activeConnection);r(d=>immer.produce(d,C=>{delete C.connections[n],C.activeConnection=w,C.connectionError=void 0,C.switchNetworkError=void 0;}));}else await c().disconnectAll();let o=c();Object.keys(o.connections).length===0?(orbitCore.lastConnectedConnectorHelpers.removeLastConnectedConnector(),orbitCore.impersonatedHelpers.removeImpersonated()):o.activeConnection&&orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:o.activeConnection.connectorType,chainId:o.activeConnection.chainId,address:o.activeConnection.address});}catch(o){console.error("Disconnect operation failed:",o),r(e=>immer.produce(e,i=>{i.connectionError=`Disconnect failed: ${o instanceof Error?o.message:String(o)}`;}));}finally{r({disconnecting:false});}}},disconnectAll:async()=>{if(Array.isArray(l))await Promise.allSettled(l.map(async n=>{try{await n.disconnect();}catch{}}));else try{await l.disconnect();}catch{}r({activeConnection:void 0,connections:{},connectionError:void 0,switchNetworkError:void 0}),orbitCore.impersonatedHelpers.removeImpersonated();},resetConnectionError:()=>{r({connectionError:void 0});},updateActiveConnection:n=>{let o=c().activeConnection,e=n.connectorType??o?.connectorType;e?(n.chainId&&e===o?.connectorType&&orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:e,chainId:n.chainId,address:n.address??o?.address}),r(i=>immer.produce(i,t=>{t.connections[e]&&(t.connections[e]={...t.connections[e],...n},t.activeConnection?.connectorType===e&&(t.activeConnection=t.connections[e]));}))):n.connectorType!==void 0&&n.chainId!==void 0&&n.address!==void 0?(orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:n.connectorType,chainId:n.chainId,address:n.address}),r(t=>{let a=n;return {activeConnection:a,connections:{...t.connections,[a.connectorType]:a}}})):console.warn("Attempted to set activeConnection with incomplete data while activeConnection was undefined.");},switchConnection:async n=>{let o=c().connections[n];if(!o){console.warn(`No connection found for connector type: ${n}`);return}if(c().activeConnection?.connectorType!==n)try{let e=c().getAdapter(orbitCore.getAdapterFromConnectorType(n));e?.switchConnection&&await e.switchConnection(n),r(i=>immer.produce(i,t=>{t.activeConnection=o;})),orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:o.connectorType,chainId:o.chainId,address:o.address});}catch(e){console.error("Failed to switch connection:",e);}},switchNetwork:async(n,o)=>{r({switchNetworkError:void 0});let e=o?c().connections[o]:c().activeConnection;if(e){let i=c().getAdapter(orbitCore.getAdapterFromConnectorType(e.connectorType));if(!i){r({switchNetworkError:`No adapter found for active connector type: ${e.connectorType}`});return}try{await i.checkAndSwitchNetwork(n,e.chainId,c().updateActiveConnection);}catch(t){r({switchNetworkError:"Switch network failed: "+(t instanceof Error?t.message:String(t))});}}},resetSwitchNetworkError:()=>r({switchNetworkError:void 0})}))}exports.createSatelliteConnectStore=b;//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/store/satelliteConnectStore.ts"],"names":["createSatelliteConnectStore","adapter","callbackAfterConnected","createStore","set","get","adapterKey","selectAdapterByKey","results","a","accumulator","currentResult","key","value","autoConnect","lastConnectedWallet","lastConnectedWalletHelpers","delay","isSafeApp","foundAdapter","OrbitAdapter","safeConnectorChainId","error","walletType","chainId","getAdapterFromWalletType","wallet","isContractAddress","updatedWallet","recentConnectedWalletHelpers","e","activeWallet","impersonatedHelpers","state","produce","draft"],"mappings":"mHAyBO,SAASA,CAAAA,CAAkE,CAChF,OAAA,CAAAC,CAAAA,CACA,uBAAAC,CACF,CAAA,CAAiD,CAC/C,OAAOC,mBAAAA,GAA4C,CAACC,CAAAA,CAAKC,CAAAA,IAAS,CAIhE,WAAaC,CAAAA,EAAeC,4BAAAA,CAAmB,CAAE,OAAA,CAAAN,EAAS,UAAA,CAAAK,CAAW,CAAC,CAAA,CAKtE,cAAe,IAAM,CACnB,IAAIE,CAAAA,CAEJ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I,CAAE,YAAA,CAAcsB,CAAY,CAAC,CAAA,EAEjC,QAAQ,IAAA,CAAK,sFAAsF,EAGzG,CAAA,CAMA,aAAA,CAAe,MAAOF,CAAAA,EAA6B,CACjDpB,CAAAA,CAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CAAA,CACrC,IAAM2B,CAAAA,CAAe1B,CAAAA,GAAM,YAAA,CAC3B,GAAI0B,EAAc,CAChB,IAAMZ,EAAed,CAAAA,EAAI,CAAE,UAAA,CAAWoB,kCAAAA,CAAyBM,EAAa,UAAU,CAAC,CAAA,CAEvF,GAAI,CAACZ,CAAAA,CAAc,CACjBf,CAAAA,CAAI,CAAE,mBAAoB,CAAA,yCAAA,EAA4C2B,CAAAA,CAAa,UAAU,CAAA,CAAG,CAAC,EACjG,MACF,CAEA,GAAI,CAEF,MAAMZ,CAAAA,CAAa,qBAAA,CAAsBK,CAAAA,CAASO,CAAAA,CAAa,QAAS1B,CAAAA,EAAI,CAAE,kBAAkB,EAClG,OAASyB,CAAAA,CAAG,CACV1B,EAAI,CAAE,kBAAA,CAAoB,2BAA6B0B,CAAAA,YAAa,KAAA,CAAQA,CAAAA,CAAE,OAAA,CAAU,OAAOA,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,CAAA,CAUA,uBAAA,CAAyB,IAAM1B,EAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CACtE,EAAE,CACJ","file":"index.js","sourcesContent":["import {\n delay,\n getAdapterFromWalletType,\n impersonatedHelpers,\n isSafeApp,\n lastConnectedWalletHelpers,\n OrbitAdapter,\n RecentConnectedWallet,\n recentConnectedWalletHelpers,\n selectAdapterByKey,\n} from '@tuwaio/orbit-core';\nimport { produce } from 'immer';\nimport { createStore } from 'zustand/vanilla';\n\nimport { BaseWallet, ISatelliteConnectStore, SatelliteConnectStoreInitialParameters, Wallet } from '../types';\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 active adapter\n */\n getAdapter: (adapterKey) => selectAdapterByKey({ adapter, adapterKey }),\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 (\n lastConnectedWallet &&\n !['impersonatedwallet', 'walletconnect', 'coinbasewallet', 'bitgetwallet'].includes(\n lastConnectedWallet.walletType.split(':')[1],\n )\n ) {\n await delay(null, 200);\n await get().connect({ walletType: lastConnectedWallet.walletType, chainId: lastConnectedWallet.chainId });\n }\n } else if (isSafeApp) {\n await delay(null, 200);\n const foundAdapter = get().getAdapter(OrbitAdapter.EVM);\n if (foundAdapter && foundAdapter.getSafeConnectorChainId) {\n const safeConnectorChainId = await foundAdapter.getSafeConnectorChainId();\n if (safeConnectorChainId) {\n await get().connect({ walletType: `${OrbitAdapter.EVM}:safewallet`, chainId: safeConnectorChainId });\n }\n }\n }\n },\n\n walletConnecting: false,\n walletConnectionError: undefined,\n switchNetworkError: undefined,\n activeWallet: undefined,\n\n setWalletConnectionError: (error) => set({ walletConnectionError: error }),\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 foundAdapter = get().getAdapter(getAdapterFromWalletType(walletType));\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 // 1. Check if wallet is already connected, case when you reconnect by another wallet\n if (get().activeWallet?.isConnected) {\n await get().disconnectAll();\n }\n const wallet = await foundAdapter.connect({\n walletType,\n chainId,\n });\n\n // 2. Set initial wallet state\n set({ activeWallet: wallet });\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({\n walletType,\n chainId,\n address: get().activeWallet?.address,\n });\n recentConnectedWalletHelpers.setRecentConnectedWallet({\n [getAdapterFromWalletType(walletType)]: {\n [walletType.split(':')[1]]: true,\n },\n } as RecentConnectedWallet);\n } catch (e) {\n await get().disconnectAll();\n lastConnectedWalletHelpers.removeLastConnectedWallet();\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 // Clear all states and storages\n set({ activeWallet: undefined, walletConnectionError: undefined, switchNetworkError: undefined });\n lastConnectedWalletHelpers.removeLastConnectedWallet();\n impersonatedHelpers.removeImpersonated();\n const foundAdapter = get().getAdapter(getAdapterFromWalletType(activeWallet.walletType));\n // Call disconnect only if adapter is found\n await foundAdapter?.disconnect(activeWallet);\n }\n },\n\n disconnectAll: async () => {\n await delay(null, 150);\n\n if (Array.isArray(adapter)) {\n await Promise.allSettled(\n adapter.map(async (a) => {\n try {\n await a.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }),\n );\n } else {\n try {\n await adapter.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }\n\n set({ activeWallet: undefined, walletConnectionError: undefined, switchNetworkError: undefined });\n impersonatedHelpers.removeImpersonated();\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 // Update lastConnectedWallet storage if chainId changes\n lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: wallet.walletType ?? activeWallet.walletType,\n chainId: wallet.chainId ?? activeWallet.chainId,\n address: wallet.address ?? activeWallet.address,\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 lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: wallet.walletType!,\n chainId: wallet.chainId!,\n address: wallet.address!,\n });\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 foundAdapter = get().getAdapter(getAdapterFromWalletType(activeWallet.walletType));\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/store/satelliteConnectStore.ts"],"names":["createSatelliteConnectStore","adapter","callbackAfterConnected","setAutoFreeze","createStore","set","get","adapterKey","selectAdapterByKey","results","a","accumulator","currentResult","key","value","autoConnect","delay","sevenDaysAgo","recentlyConnectedConnectorsListHelpers","lastConnectedConnector","lastConnectedConnectorHelpers","isSafeApp","foundAdapter","OrbitAdapter","safeConnectorChainId","error","connectorType","chainId","getAdapterFromConnectorType","connector","state","isContractAddress","updatedConnector","activeConnection","e","currentState","connectorToDisconnect","wasActiveConnection","remainingConnectors","conn","newActiveConnection","candidateConnection","newAdapter","produce","draft","finalState","impersonatedHelpers","targetConnectorType","newConnector","targetConnector"],"mappings":"mHAyBO,SAASA,CAAAA,CAAwE,CACtF,OAAA,CAAAC,CAAAA,CACA,sBAAA,CAAAC,CACF,CAAA,CAAiD,CAE/C,OAAAC,mBAAAA,CAAc,KAAK,CAAA,CAEZC,mBAAAA,EAA0C,CAAE,CAACC,CAA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CAAAA,CAAkBvB,CAAAA,CACpBpB,CAAAA,EAAI,CAAE,WAAA,CAAYoB,CAA8B,CAAA,CAChDpB,CAAAA,EAAI,CAAE,gBAAA,CAEV,GAAI2C,CAAAA,CAAiB,CACnB,IAAM3B,CAAAA,CAAehB,CAAAA,EAAI,CAAE,UAAA,CAAWsB,qCAAAA,CAA4BqB,CAAAA,CAAgB,aAAa,CAAC,CAAA,CAEhG,GAAI,CAAC3B,CAAAA,CAAc,CACjBjB,CAAAA,CAAI,CAAE,kBAAA,CAAoB,CAAA,4CAAA,EAA+C4C,CAAAA,CAAgB,aAAa,CAAA,CAAG,CAAC,CAAA,CAC1G,MACF,CAEA,GAAI,CAEF,MAAM3B,CAAAA,CAAa,qBAAA,CAAsBK,CAAAA,CAASsB,CAAAA,CAAgB,OAAA,CAAS3C,CAAAA,EAAI,CAAE,sBAAsB,EACzG,CAAA,MAAS4B,CAAAA,CAAG,CACV7B,CAAAA,CAAI,CAAE,kBAAA,CAAoB,yBAAA,EAA6B6B,CAAAA,YAAa,KAAA,CAAQA,CAAAA,CAAE,OAAA,CAAU,MAAA,CAAOA,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,CAAA,CAUA,uBAAA,CAAyB,IAAM7B,CAAAA,CAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CACtE,EAAE,CACJ","file":"index.js","sourcesContent":["import {\n ConnectorType,\n delay,\n getAdapterFromConnectorType,\n impersonatedHelpers,\n isSafeApp,\n lastConnectedConnectorHelpers,\n OrbitAdapter,\n recentlyConnectedConnectorsListHelpers,\n selectAdapterByKey,\n} from '@tuwaio/orbit-core';\nimport { produce, setAutoFreeze } from 'immer';\nimport { createStore } from 'zustand/vanilla';\n\nimport { BaseConnector, Connector, ISatelliteConnectStore, SatelliteConnectStoreInitialParameters } from '../types';\n\n/**\n * Creates a Satellite Connect store instance for managing connector connections and state\n *\n * @param params - Initial parameters for the store\n * @param params.adapter - Blockchain adapter(s) to use\n * @param params.callbackAfterConnected - Optional callback function called after successful connection\n *\n * @returns A Zustand store instance with connection state and methods\n */\nexport function createSatelliteConnectStore<C, W extends BaseConnector = BaseConnector>({\n adapter,\n callbackAfterConnected,\n}: SatelliteConnectStoreInitialParameters<C, W>) {\n // Disable autoFreeze for immers in this store, since connectors contain EventEmitter objects that must remain mutable to function correctly\n setAutoFreeze(false);\n\n return createStore<ISatelliteConnectStore<C, W>>()((set, get) => ({\n /**\n * Returns active adapter\n */\n getAdapter: (adapterKey) => selectAdapterByKey({ adapter, adapterKey }),\n\n /**\n * Get 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 await delay(null, 300);\n await get().disconnectAll();\n\n // Cleanup old recently connected connectors (older than 7 days)\n const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;\n recentlyConnectedConnectorsListHelpers.removeConnectorsOlderThan(sevenDaysAgo);\n\n if (autoConnect) {\n const lastConnectedConnector = lastConnectedConnectorHelpers.getLastConnectedConnector();\n if (\n lastConnectedConnector &&\n !['impersonatedwallet', 'walletconnect', 'coinbasewallet', 'bitgetwallet'].includes(\n lastConnectedConnector.connectorType.split(':')[1],\n )\n ) {\n await delay(null, 100);\n await get().connect({\n connectorType: lastConnectedConnector.connectorType,\n chainId: lastConnectedConnector.chainId,\n });\n }\n } else if (isSafeApp) {\n await delay(null, 100);\n const foundAdapter = get().getAdapter(OrbitAdapter.EVM);\n if (foundAdapter && foundAdapter.getSafeConnectorChainId) {\n const safeConnectorChainId = await foundAdapter.getSafeConnectorChainId();\n if (safeConnectorChainId) {\n await get().connect({ connectorType: `${OrbitAdapter.EVM}:safewallet`, chainId: safeConnectorChainId });\n }\n }\n }\n },\n\n connecting: false,\n disconnecting: false,\n connectionError: undefined,\n switchNetworkError: undefined,\n activeConnection: undefined,\n connections: {},\n\n setConnectionError: (error) => set({ connectionError: error }),\n\n /**\n * Connects to a connector\n * @param connectorType - Type of connector to connect to\n * @param chainId - Chain ID to connect on\n */\n connect: async ({ connectorType, chainId }) => {\n set({ connecting: true, connectionError: undefined });\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorType));\n\n if (!foundAdapter) {\n set({\n connecting: false,\n connectionError: `No adapter found for connector type: ${connectorType}`,\n });\n return;\n }\n\n try {\n // 1. Check if connector is already connected\n const existingConnector = get().connections[connectorType as ConnectorType];\n if (existingConnector) {\n return;\n }\n\n const connector = await foundAdapter.connect({\n connectorType,\n chainId,\n });\n\n // 2. Set initial connector state\n set((state) => {\n return {\n activeConnection: connector,\n connections: {\n ...state.connections,\n [connector.connectorType]: connector,\n },\n };\n });\n\n // 3. Check for contract address if the adapter supports it\n if (foundAdapter.checkIsContractAddress) {\n const isContractAddress = await foundAdapter.checkIsContractAddress({\n address: connector.address,\n chainId,\n });\n\n // Update only the isContractAddress property\n get().updateActiveConnection({ ...connector, isContractAddress });\n }\n\n // 4. Run callback if provided\n if (callbackAfterConnected) {\n // Use the latest connector state after potential updates (like isContractAddress)\n const updatedConnector = get().activeConnection;\n if (updatedConnector && updatedConnector.connectorType === connectorType) {\n await callbackAfterConnected(updatedConnector);\n }\n }\n\n // 5. Final state updates\n set({ connecting: false });\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType,\n chainId,\n address: get().activeConnection?.address,\n });\n\n // Add to recently connected list\n const activeConnection = get().activeConnection;\n if (activeConnection && activeConnection.address) {\n recentlyConnectedConnectorsListHelpers.addConnector(activeConnection.connectorType, {\n address: activeConnection.address,\n disconnectedTimestamp: Date.now(),\n icon: activeConnection.icon,\n });\n }\n } catch (e) {\n set({\n connecting: false,\n connectionError: 'Connector connection failed: ' + (e instanceof Error ? e.message : String(e)),\n });\n }\n },\n\n /**\n * Disconnects the currently active wallet or a specific wallet\n */\n disconnect: async (connectorType?: string) => {\n // Guard against re-entry\n if (get().disconnecting) return;\n set({ disconnecting: true });\n\n try {\n if (connectorType) {\n // Disconnect specific connector\n const currentState = get();\n const connectorToDisconnect = currentState.connections[connectorType as ConnectorType];\n\n if (!connectorToDisconnect) {\n console.warn(`No connection found for connector type: ${connectorType}`);\n return;\n }\n\n // 1. Disconnect at adapter level\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorToDisconnect.connectorType));\n if (foundAdapter) {\n try {\n await foundAdapter.disconnect(connectorToDisconnect);\n } catch (e) {\n console.error(`Failed to disconnect connector ${connectorType}:`, e);\n // Continue with state cleanup even if adapter disconnect fails\n }\n }\n\n // 2. Determine if we need to switch to another connector\n const wasActiveConnection = currentState.activeConnection?.connectorType === connectorType;\n const remainingConnectors = Object.values(currentState.connections).filter(\n (conn) => conn.connectorType !== connectorType,\n );\n\n let newActiveConnection: typeof currentState.activeConnection = undefined;\n\n // 3. If the disconnected connector was active and there are remaining ones, switch first\n if (wasActiveConnection && remainingConnectors.length > 0) {\n const candidateConnection = remainingConnectors[0];\n\n try {\n const newAdapter = get().getAdapter(getAdapterFromConnectorType(candidateConnection.connectorType));\n if (newAdapter?.switchConnection) {\n await newAdapter.switchConnection(candidateConnection.connectorType);\n }\n // Only set as active if switchConnection succeeded\n newActiveConnection = candidateConnection;\n } catch (e) {\n console.error('Failed to switch to remaining connector:', e);\n // If switching fails, we'll leave activeConnection as undefined\n newActiveConnection = undefined;\n }\n } else if (!wasActiveConnection) {\n // If the disconnected connector wasn't active, keep the current active connection\n newActiveConnection = currentState.activeConnection;\n }\n\n // 4. Update state atomically using produce\n set((state) =>\n produce(state, (draft) => {\n // Remove the disconnected connector\n delete draft.connections[connectorType as ConnectorType];\n\n // Set the new active connection (could be undefined, another connector, or unchanged)\n draft.activeConnection = newActiveConnection;\n\n // Clear errors\n draft.connectionError = undefined;\n draft.switchNetworkError = undefined;\n }),\n );\n } else {\n // Disconnect ALL connectors\n await get().disconnectAll();\n }\n\n // 5. Handle storage updates\n const finalState = get();\n if (Object.keys(finalState.connections).length === 0) {\n lastConnectedConnectorHelpers.removeLastConnectedConnector();\n impersonatedHelpers.removeImpersonated();\n } else if (finalState.activeConnection) {\n // Update last connected to the current active one\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: finalState.activeConnection.connectorType,\n chainId: finalState.activeConnection.chainId,\n address: finalState.activeConnection.address,\n });\n }\n } catch (e) {\n console.error('Disconnect operation failed:', e);\n // Set error state if needed\n set((state) =>\n produce(state, (draft) => {\n draft.connectionError = `Disconnect failed: ${e instanceof Error ? e.message : String(e)}`;\n }),\n );\n } finally {\n set({ disconnecting: false });\n }\n },\n\n disconnectAll: async () => {\n if (Array.isArray(adapter)) {\n await Promise.allSettled(\n adapter.map(async (a) => {\n try {\n await a.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }),\n );\n } else {\n try {\n await adapter.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }\n\n set({\n activeConnection: undefined,\n connections: {},\n connectionError: undefined,\n switchNetworkError: undefined,\n });\n impersonatedHelpers.removeImpersonated();\n },\n\n /**\n * Contains error message if connection failed\n */\n // connectionError is declared above with an initial value\n\n /**\n * Resets any connection errors\n */\n resetConnectionError: () => {\n set({ connectionError: undefined });\n },\n\n /**\n * Updates the active connection's properties\n * @param connector - Partial connector object with properties to update\n */\n updateActiveConnection: (connector: Partial<Connector<W>>) => {\n const activeConnection = get().activeConnection;\n // Determine which connector to update. If connectorType is provided, use it. Otherwise use activeConnection.\n const targetConnectorType = connector.connectorType ?? activeConnection?.connectorType;\n\n if (targetConnectorType) {\n // If chainId is updated, update storage\n if (connector.chainId && targetConnectorType === activeConnection?.connectorType) {\n // Update lastConnectedConnector storage if chainId changes and it's the active connector\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: targetConnectorType,\n chainId: connector.chainId,\n address: connector.address ?? activeConnection?.address,\n });\n }\n\n // Use produce for immutable state update\n set((state) =>\n produce(state, (draft) => {\n if (draft.connections[targetConnectorType as ConnectorType]) {\n draft.connections[targetConnectorType as ConnectorType] = {\n ...draft.connections[targetConnectorType as ConnectorType],\n ...connector,\n } as Connector<W>;\n\n // Also update activeConnection if it matches\n if (draft.activeConnection?.connectorType === targetConnectorType) {\n draft.activeConnection = draft.connections[targetConnectorType as ConnectorType];\n }\n }\n }),\n );\n } else {\n const isConnectorCanChange =\n connector.connectorType !== undefined && connector.chainId !== undefined && connector.address !== undefined;\n\n if (isConnectorCanChange) {\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: connector.connectorType!,\n chainId: connector.chainId!,\n address: connector.address!,\n });\n // It's a new connector or full replacement\n set((state) => {\n const newConnector = connector as Connector<W>;\n return {\n activeConnection: newConnector,\n connections: {\n ...state.connections,\n [newConnector.connectorType]: newConnector,\n },\n };\n });\n } else {\n console.warn('Attempted to set activeConnection with incomplete data while activeConnection was undefined.');\n }\n }\n },\n\n /**\n * Switches active connection from the list of connections\n */\n switchConnection: async (connectorType) => {\n const targetConnector = get().connections[connectorType as ConnectorType];\n if (!targetConnector) {\n console.warn(`No connection found for connector type: ${connectorType}`);\n return;\n }\n\n if (get().activeConnection?.connectorType === connectorType) {\n return;\n }\n\n try {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorType));\n if (foundAdapter?.switchConnection) {\n await foundAdapter.switchConnection(connectorType);\n }\n\n set((state) =>\n produce(state, (draft) => {\n draft.activeConnection = targetConnector;\n }),\n );\n\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: targetConnector.connectorType,\n chainId: targetConnector.chainId,\n address: targetConnector.address,\n });\n } catch (e) {\n console.error('Failed to switch connection:', e);\n }\n },\n\n /**\n * Switches the connected connector to a different network\n * @param chainId - Target chain ID to switch to\n * @param connectorType - Optional connector type to switch to. If not provided, will switch to the active connection.\n */\n switchNetwork: async (chainId: string | number, connectorType?: string) => {\n set({ switchNetworkError: undefined });\n const targetConnector = connectorType\n ? get().connections[connectorType as ConnectorType]\n : get().activeConnection;\n\n if (targetConnector) {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(targetConnector.connectorType));\n\n if (!foundAdapter) {\n set({ switchNetworkError: `No adapter found for active connector type: ${targetConnector.connectorType}` });\n return;\n }\n\n try {\n // Pass the local updateActiveConnection method from 'get()' to the adapter\n await foundAdapter.checkAndSwitchNetwork(chainId, targetConnector.chainId, get().updateActiveConnection);\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 {selectAdapterByKey,
|
|
1
|
+
import {selectAdapterByKey,getAdapterFromConnectorType,lastConnectedConnectorHelpers,impersonatedHelpers,recentlyConnectedConnectorsListHelpers,delay,isSafeApp,OrbitAdapter}from'@tuwaio/orbit-core';import {setAutoFreeze,produce}from'immer';import {createStore}from'zustand/vanilla';function b({adapter:l,callbackAfterConnected:h}){return setAutoFreeze(false),createStore()((r,c)=>({getAdapter:n=>selectAdapterByKey({adapter:l,adapterKey:n}),getConnectors:()=>{let n;return Array.isArray(l)?n=l.map(o=>o.getConnectors()):n=[l.getConnectors()],n.reduce((o,e)=>{let i=e.adapter,t=e.connectors;return {...o,[i]:t}},{})},initializeAutoConnect:async n=>{await delay(null,300),await c().disconnectAll();let o=Date.now()-10080*60*1e3;if(recentlyConnectedConnectorsListHelpers.removeConnectorsOlderThan(o),n){let e=lastConnectedConnectorHelpers.getLastConnectedConnector();e&&!["impersonatedwallet","walletconnect","coinbasewallet","bitgetwallet"].includes(e.connectorType.split(":")[1])&&(await delay(null,100),await c().connect({connectorType:e.connectorType,chainId:e.chainId}));}else if(isSafeApp){await delay(null,100);let e=c().getAdapter(OrbitAdapter.EVM);if(e&&e.getSafeConnectorChainId){let i=await e.getSafeConnectorChainId();i&&await c().connect({connectorType:`${OrbitAdapter.EVM}:safewallet`,chainId:i});}}},connecting:false,disconnecting:false,connectionError:void 0,switchNetworkError:void 0,activeConnection:void 0,connections:{},setConnectionError:n=>r({connectionError:n}),connect:async({connectorType:n,chainId:o})=>{r({connecting:true,connectionError:void 0});let e=c().getAdapter(getAdapterFromConnectorType(n));if(!e){r({connecting:false,connectionError:`No adapter found for connector type: ${n}`});return}try{if(c().connections[n])return;let t=await e.connect({connectorType:n,chainId:o});if(r(s=>({activeConnection:t,connections:{...s.connections,[t.connectorType]:t}})),e.checkIsContractAddress){let s=await e.checkIsContractAddress({address:t.address,chainId:o});c().updateActiveConnection({...t,isContractAddress:s});}if(h){let s=c().activeConnection;s&&s.connectorType===n&&await h(s);}r({connecting:!1}),lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:n,chainId:o,address:c().activeConnection?.address});let a=c().activeConnection;a&&a.address&&recentlyConnectedConnectorsListHelpers.addConnector(a.connectorType,{address:a.address,disconnectedTimestamp:Date.now(),icon:a.icon});}catch(i){r({connecting:false,connectionError:"Connector connection failed: "+(i instanceof Error?i.message:String(i))});}},disconnect:async n=>{if(!c().disconnecting){r({disconnecting:true});try{if(n){let e=c(),i=e.connections[n];if(!i){console.warn(`No connection found for connector type: ${n}`);return}let t=c().getAdapter(getAdapterFromConnectorType(i.connectorType));if(t)try{await t.disconnect(i);}catch(d){console.error(`Failed to disconnect connector ${n}:`,d);}let a=e.activeConnection?.connectorType===n,s=Object.values(e.connections).filter(d=>d.connectorType!==n),w;if(a&&s.length>0){let d=s[0];try{let C=c().getAdapter(getAdapterFromConnectorType(d.connectorType));C?.switchConnection&&await C.switchConnection(d.connectorType),w=d;}catch(C){console.error("Failed to switch to remaining connector:",C),w=void 0;}}else a||(w=e.activeConnection);r(d=>produce(d,C=>{delete C.connections[n],C.activeConnection=w,C.connectionError=void 0,C.switchNetworkError=void 0;}));}else await c().disconnectAll();let o=c();Object.keys(o.connections).length===0?(lastConnectedConnectorHelpers.removeLastConnectedConnector(),impersonatedHelpers.removeImpersonated()):o.activeConnection&&lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:o.activeConnection.connectorType,chainId:o.activeConnection.chainId,address:o.activeConnection.address});}catch(o){console.error("Disconnect operation failed:",o),r(e=>produce(e,i=>{i.connectionError=`Disconnect failed: ${o instanceof Error?o.message:String(o)}`;}));}finally{r({disconnecting:false});}}},disconnectAll:async()=>{if(Array.isArray(l))await Promise.allSettled(l.map(async n=>{try{await n.disconnect();}catch{}}));else try{await l.disconnect();}catch{}r({activeConnection:void 0,connections:{},connectionError:void 0,switchNetworkError:void 0}),impersonatedHelpers.removeImpersonated();},resetConnectionError:()=>{r({connectionError:void 0});},updateActiveConnection:n=>{let o=c().activeConnection,e=n.connectorType??o?.connectorType;e?(n.chainId&&e===o?.connectorType&&lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:e,chainId:n.chainId,address:n.address??o?.address}),r(i=>produce(i,t=>{t.connections[e]&&(t.connections[e]={...t.connections[e],...n},t.activeConnection?.connectorType===e&&(t.activeConnection=t.connections[e]));}))):n.connectorType!==void 0&&n.chainId!==void 0&&n.address!==void 0?(lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:n.connectorType,chainId:n.chainId,address:n.address}),r(t=>{let a=n;return {activeConnection:a,connections:{...t.connections,[a.connectorType]:a}}})):console.warn("Attempted to set activeConnection with incomplete data while activeConnection was undefined.");},switchConnection:async n=>{let o=c().connections[n];if(!o){console.warn(`No connection found for connector type: ${n}`);return}if(c().activeConnection?.connectorType!==n)try{let e=c().getAdapter(getAdapterFromConnectorType(n));e?.switchConnection&&await e.switchConnection(n),r(i=>produce(i,t=>{t.activeConnection=o;})),lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:o.connectorType,chainId:o.chainId,address:o.address});}catch(e){console.error("Failed to switch connection:",e);}},switchNetwork:async(n,o)=>{r({switchNetworkError:void 0});let e=o?c().connections[o]:c().activeConnection;if(e){let i=c().getAdapter(getAdapterFromConnectorType(e.connectorType));if(!i){r({switchNetworkError:`No adapter found for active connector type: ${e.connectorType}`});return}try{await i.checkAndSwitchNetwork(n,e.chainId,c().updateActiveConnection);}catch(t){r({switchNetworkError:"Switch network failed: "+(t instanceof Error?t.message:String(t))});}}},resetSwitchNetworkError:()=>r({switchNetworkError:void 0})}))}export{b as createSatelliteConnectStore};//# sourceMappingURL=index.mjs.map
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/store/satelliteConnectStore.ts"],"names":["createSatelliteConnectStore","adapter","callbackAfterConnected","createStore","set","get","adapterKey","selectAdapterByKey","results","a","accumulator","currentResult","key","value","autoConnect","lastConnectedWallet","lastConnectedWalletHelpers","delay","isSafeApp","foundAdapter","OrbitAdapter","safeConnectorChainId","error","walletType","chainId","getAdapterFromWalletType","wallet","isContractAddress","updatedWallet","recentConnectedWalletHelpers","e","activeWallet","impersonatedHelpers","state","produce","draft"],"mappings":"4PAyBO,SAASA,CAAAA,CAAkE,CAChF,OAAA,CAAAC,CAAAA,CACA,uBAAAC,CACF,CAAA,CAAiD,CAC/C,OAAOC,WAAAA,GAA4C,CAACC,CAAAA,CAAKC,CAAAA,IAAS,CAIhE,WAAaC,CAAAA,EAAeC,kBAAAA,CAAmB,CAAE,OAAA,CAAAN,EAAS,UAAA,CAAAK,CAAW,CAAC,CAAA,CAKtE,cAAe,IAAM,CACnB,IAAIE,CAAAA,CAEJ,OAAI,MAAM,OAAA,CAAQP,CAAO,CAAA,CAC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jC,QAAQ,IAAA,CAAK,sFAAsF,EAGzG,CAAA,CAMA,aAAA,CAAe,MAAOF,CAAAA,EAA6B,CACjDpB,CAAAA,CAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CAAA,CACrC,IAAM2B,CAAAA,CAAe1B,CAAAA,GAAM,YAAA,CAC3B,GAAI0B,EAAc,CAChB,IAAMZ,EAAed,CAAAA,EAAI,CAAE,UAAA,CAAWoB,wBAAAA,CAAyBM,EAAa,UAAU,CAAC,CAAA,CAEvF,GAAI,CAACZ,CAAAA,CAAc,CACjBf,CAAAA,CAAI,CAAE,mBAAoB,CAAA,yCAAA,EAA4C2B,CAAAA,CAAa,UAAU,CAAA,CAAG,CAAC,EACjG,MACF,CAEA,GAAI,CAEF,MAAMZ,CAAAA,CAAa,qBAAA,CAAsBK,CAAAA,CAASO,CAAAA,CAAa,QAAS1B,CAAAA,EAAI,CAAE,kBAAkB,EAClG,OAASyB,CAAAA,CAAG,CACV1B,EAAI,CAAE,kBAAA,CAAoB,2BAA6B0B,CAAAA,YAAa,KAAA,CAAQA,CAAAA,CAAE,OAAA,CAAU,OAAOA,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,CAAA,CAUA,uBAAA,CAAyB,IAAM1B,EAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CACtE,EAAE,CACJ","file":"index.mjs","sourcesContent":["import {\n delay,\n getAdapterFromWalletType,\n impersonatedHelpers,\n isSafeApp,\n lastConnectedWalletHelpers,\n OrbitAdapter,\n RecentConnectedWallet,\n recentConnectedWalletHelpers,\n selectAdapterByKey,\n} from '@tuwaio/orbit-core';\nimport { produce } from 'immer';\nimport { createStore } from 'zustand/vanilla';\n\nimport { BaseWallet, ISatelliteConnectStore, SatelliteConnectStoreInitialParameters, Wallet } from '../types';\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 active adapter\n */\n getAdapter: (adapterKey) => selectAdapterByKey({ adapter, adapterKey }),\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 (\n lastConnectedWallet &&\n !['impersonatedwallet', 'walletconnect', 'coinbasewallet', 'bitgetwallet'].includes(\n lastConnectedWallet.walletType.split(':')[1],\n )\n ) {\n await delay(null, 200);\n await get().connect({ walletType: lastConnectedWallet.walletType, chainId: lastConnectedWallet.chainId });\n }\n } else if (isSafeApp) {\n await delay(null, 200);\n const foundAdapter = get().getAdapter(OrbitAdapter.EVM);\n if (foundAdapter && foundAdapter.getSafeConnectorChainId) {\n const safeConnectorChainId = await foundAdapter.getSafeConnectorChainId();\n if (safeConnectorChainId) {\n await get().connect({ walletType: `${OrbitAdapter.EVM}:safewallet`, chainId: safeConnectorChainId });\n }\n }\n }\n },\n\n walletConnecting: false,\n walletConnectionError: undefined,\n switchNetworkError: undefined,\n activeWallet: undefined,\n\n setWalletConnectionError: (error) => set({ walletConnectionError: error }),\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 foundAdapter = get().getAdapter(getAdapterFromWalletType(walletType));\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 // 1. Check if wallet is already connected, case when you reconnect by another wallet\n if (get().activeWallet?.isConnected) {\n await get().disconnectAll();\n }\n const wallet = await foundAdapter.connect({\n walletType,\n chainId,\n });\n\n // 2. Set initial wallet state\n set({ activeWallet: wallet });\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({\n walletType,\n chainId,\n address: get().activeWallet?.address,\n });\n recentConnectedWalletHelpers.setRecentConnectedWallet({\n [getAdapterFromWalletType(walletType)]: {\n [walletType.split(':')[1]]: true,\n },\n } as RecentConnectedWallet);\n } catch (e) {\n await get().disconnectAll();\n lastConnectedWalletHelpers.removeLastConnectedWallet();\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 // Clear all states and storages\n set({ activeWallet: undefined, walletConnectionError: undefined, switchNetworkError: undefined });\n lastConnectedWalletHelpers.removeLastConnectedWallet();\n impersonatedHelpers.removeImpersonated();\n const foundAdapter = get().getAdapter(getAdapterFromWalletType(activeWallet.walletType));\n // Call disconnect only if adapter is found\n await foundAdapter?.disconnect(activeWallet);\n }\n },\n\n disconnectAll: async () => {\n await delay(null, 150);\n\n if (Array.isArray(adapter)) {\n await Promise.allSettled(\n adapter.map(async (a) => {\n try {\n await a.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }),\n );\n } else {\n try {\n await adapter.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }\n\n set({ activeWallet: undefined, walletConnectionError: undefined, switchNetworkError: undefined });\n impersonatedHelpers.removeImpersonated();\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 // Update lastConnectedWallet storage if chainId changes\n lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: wallet.walletType ?? activeWallet.walletType,\n chainId: wallet.chainId ?? activeWallet.chainId,\n address: wallet.address ?? activeWallet.address,\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 lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: wallet.walletType!,\n chainId: wallet.chainId!,\n address: wallet.address!,\n });\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 foundAdapter = get().getAdapter(getAdapterFromWalletType(activeWallet.walletType));\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/store/satelliteConnectStore.ts"],"names":["createSatelliteConnectStore","adapter","callbackAfterConnected","setAutoFreeze","createStore","set","get","adapterKey","selectAdapterByKey","results","a","accumulator","currentResult","key","value","autoConnect","delay","sevenDaysAgo","recentlyConnectedConnectorsListHelpers","lastConnectedConnector","lastConnectedConnectorHelpers","isSafeApp","foundAdapter","OrbitAdapter","safeConnectorChainId","error","connectorType","chainId","getAdapterFromConnectorType","connector","state","isContractAddress","updatedConnector","activeConnection","e","currentState","connectorToDisconnect","wasActiveConnection","remainingConnectors","conn","newActiveConnection","candidateConnection","newAdapter","produce","draft","finalState","impersonatedHelpers","targetConnectorType","newConnector","targetConnector"],"mappings":"0RAyBO,SAASA,CAAAA,CAAwE,CACtF,OAAA,CAAAC,CAAAA,CACA,sBAAA,CAAAC,CACF,CAAA,CAAiD,CAE/C,OAAAC,aAAAA,CAAc,KAAK,CAAA,CAEZC,WAAAA,EAA0C,CAAE,CAACC,CAAAA,CAAKC,CAAAA,IAAS,CAIhE,UAAA,CAAaC,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AE,WAAA,CAAYoB,CAA8B,CAAA,CAChDpB,CAAAA,EAAI,CAAE,gBAAA,CAEV,GAAI2C,CAAAA,CAAiB,CACnB,IAAM3B,CAAAA,CAAehB,CAAAA,EAAI,CAAE,UAAA,CAAWsB,2BAAAA,CAA4BqB,CAAAA,CAAgB,aAAa,CAAC,CAAA,CAEhG,GAAI,CAAC3B,CAAAA,CAAc,CACjBjB,CAAAA,CAAI,CAAE,kBAAA,CAAoB,CAAA,4CAAA,EAA+C4C,CAAAA,CAAgB,aAAa,CAAA,CAAG,CAAC,CAAA,CAC1G,MACF,CAEA,GAAI,CAEF,MAAM3B,CAAAA,CAAa,qBAAA,CAAsBK,CAAAA,CAASsB,CAAAA,CAAgB,OAAA,CAAS3C,CAAAA,EAAI,CAAE,sBAAsB,EACzG,CAAA,MAAS4B,CAAAA,CAAG,CACV7B,CAAAA,CAAI,CAAE,kBAAA,CAAoB,yBAAA,EAA6B6B,CAAAA,YAAa,KAAA,CAAQA,CAAAA,CAAE,OAAA,CAAU,MAAA,CAAOA,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,CAAA,CAUA,uBAAA,CAAyB,IAAM7B,CAAAA,CAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CACtE,EAAE,CACJ","file":"index.mjs","sourcesContent":["import {\n ConnectorType,\n delay,\n getAdapterFromConnectorType,\n impersonatedHelpers,\n isSafeApp,\n lastConnectedConnectorHelpers,\n OrbitAdapter,\n recentlyConnectedConnectorsListHelpers,\n selectAdapterByKey,\n} from '@tuwaio/orbit-core';\nimport { produce, setAutoFreeze } from 'immer';\nimport { createStore } from 'zustand/vanilla';\n\nimport { BaseConnector, Connector, ISatelliteConnectStore, SatelliteConnectStoreInitialParameters } from '../types';\n\n/**\n * Creates a Satellite Connect store instance for managing connector connections and state\n *\n * @param params - Initial parameters for the store\n * @param params.adapter - Blockchain adapter(s) to use\n * @param params.callbackAfterConnected - Optional callback function called after successful connection\n *\n * @returns A Zustand store instance with connection state and methods\n */\nexport function createSatelliteConnectStore<C, W extends BaseConnector = BaseConnector>({\n adapter,\n callbackAfterConnected,\n}: SatelliteConnectStoreInitialParameters<C, W>) {\n // Disable autoFreeze for immers in this store, since connectors contain EventEmitter objects that must remain mutable to function correctly\n setAutoFreeze(false);\n\n return createStore<ISatelliteConnectStore<C, W>>()((set, get) => ({\n /**\n * Returns active adapter\n */\n getAdapter: (adapterKey) => selectAdapterByKey({ adapter, adapterKey }),\n\n /**\n * Get 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 await delay(null, 300);\n await get().disconnectAll();\n\n // Cleanup old recently connected connectors (older than 7 days)\n const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;\n recentlyConnectedConnectorsListHelpers.removeConnectorsOlderThan(sevenDaysAgo);\n\n if (autoConnect) {\n const lastConnectedConnector = lastConnectedConnectorHelpers.getLastConnectedConnector();\n if (\n lastConnectedConnector &&\n !['impersonatedwallet', 'walletconnect', 'coinbasewallet', 'bitgetwallet'].includes(\n lastConnectedConnector.connectorType.split(':')[1],\n )\n ) {\n await delay(null, 100);\n await get().connect({\n connectorType: lastConnectedConnector.connectorType,\n chainId: lastConnectedConnector.chainId,\n });\n }\n } else if (isSafeApp) {\n await delay(null, 100);\n const foundAdapter = get().getAdapter(OrbitAdapter.EVM);\n if (foundAdapter && foundAdapter.getSafeConnectorChainId) {\n const safeConnectorChainId = await foundAdapter.getSafeConnectorChainId();\n if (safeConnectorChainId) {\n await get().connect({ connectorType: `${OrbitAdapter.EVM}:safewallet`, chainId: safeConnectorChainId });\n }\n }\n }\n },\n\n connecting: false,\n disconnecting: false,\n connectionError: undefined,\n switchNetworkError: undefined,\n activeConnection: undefined,\n connections: {},\n\n setConnectionError: (error) => set({ connectionError: error }),\n\n /**\n * Connects to a connector\n * @param connectorType - Type of connector to connect to\n * @param chainId - Chain ID to connect on\n */\n connect: async ({ connectorType, chainId }) => {\n set({ connecting: true, connectionError: undefined });\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorType));\n\n if (!foundAdapter) {\n set({\n connecting: false,\n connectionError: `No adapter found for connector type: ${connectorType}`,\n });\n return;\n }\n\n try {\n // 1. Check if connector is already connected\n const existingConnector = get().connections[connectorType as ConnectorType];\n if (existingConnector) {\n return;\n }\n\n const connector = await foundAdapter.connect({\n connectorType,\n chainId,\n });\n\n // 2. Set initial connector state\n set((state) => {\n return {\n activeConnection: connector,\n connections: {\n ...state.connections,\n [connector.connectorType]: connector,\n },\n };\n });\n\n // 3. Check for contract address if the adapter supports it\n if (foundAdapter.checkIsContractAddress) {\n const isContractAddress = await foundAdapter.checkIsContractAddress({\n address: connector.address,\n chainId,\n });\n\n // Update only the isContractAddress property\n get().updateActiveConnection({ ...connector, isContractAddress });\n }\n\n // 4. Run callback if provided\n if (callbackAfterConnected) {\n // Use the latest connector state after potential updates (like isContractAddress)\n const updatedConnector = get().activeConnection;\n if (updatedConnector && updatedConnector.connectorType === connectorType) {\n await callbackAfterConnected(updatedConnector);\n }\n }\n\n // 5. Final state updates\n set({ connecting: false });\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType,\n chainId,\n address: get().activeConnection?.address,\n });\n\n // Add to recently connected list\n const activeConnection = get().activeConnection;\n if (activeConnection && activeConnection.address) {\n recentlyConnectedConnectorsListHelpers.addConnector(activeConnection.connectorType, {\n address: activeConnection.address,\n disconnectedTimestamp: Date.now(),\n icon: activeConnection.icon,\n });\n }\n } catch (e) {\n set({\n connecting: false,\n connectionError: 'Connector connection failed: ' + (e instanceof Error ? e.message : String(e)),\n });\n }\n },\n\n /**\n * Disconnects the currently active wallet or a specific wallet\n */\n disconnect: async (connectorType?: string) => {\n // Guard against re-entry\n if (get().disconnecting) return;\n set({ disconnecting: true });\n\n try {\n if (connectorType) {\n // Disconnect specific connector\n const currentState = get();\n const connectorToDisconnect = currentState.connections[connectorType as ConnectorType];\n\n if (!connectorToDisconnect) {\n console.warn(`No connection found for connector type: ${connectorType}`);\n return;\n }\n\n // 1. Disconnect at adapter level\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorToDisconnect.connectorType));\n if (foundAdapter) {\n try {\n await foundAdapter.disconnect(connectorToDisconnect);\n } catch (e) {\n console.error(`Failed to disconnect connector ${connectorType}:`, e);\n // Continue with state cleanup even if adapter disconnect fails\n }\n }\n\n // 2. Determine if we need to switch to another connector\n const wasActiveConnection = currentState.activeConnection?.connectorType === connectorType;\n const remainingConnectors = Object.values(currentState.connections).filter(\n (conn) => conn.connectorType !== connectorType,\n );\n\n let newActiveConnection: typeof currentState.activeConnection = undefined;\n\n // 3. If the disconnected connector was active and there are remaining ones, switch first\n if (wasActiveConnection && remainingConnectors.length > 0) {\n const candidateConnection = remainingConnectors[0];\n\n try {\n const newAdapter = get().getAdapter(getAdapterFromConnectorType(candidateConnection.connectorType));\n if (newAdapter?.switchConnection) {\n await newAdapter.switchConnection(candidateConnection.connectorType);\n }\n // Only set as active if switchConnection succeeded\n newActiveConnection = candidateConnection;\n } catch (e) {\n console.error('Failed to switch to remaining connector:', e);\n // If switching fails, we'll leave activeConnection as undefined\n newActiveConnection = undefined;\n }\n } else if (!wasActiveConnection) {\n // If the disconnected connector wasn't active, keep the current active connection\n newActiveConnection = currentState.activeConnection;\n }\n\n // 4. Update state atomically using produce\n set((state) =>\n produce(state, (draft) => {\n // Remove the disconnected connector\n delete draft.connections[connectorType as ConnectorType];\n\n // Set the new active connection (could be undefined, another connector, or unchanged)\n draft.activeConnection = newActiveConnection;\n\n // Clear errors\n draft.connectionError = undefined;\n draft.switchNetworkError = undefined;\n }),\n );\n } else {\n // Disconnect ALL connectors\n await get().disconnectAll();\n }\n\n // 5. Handle storage updates\n const finalState = get();\n if (Object.keys(finalState.connections).length === 0) {\n lastConnectedConnectorHelpers.removeLastConnectedConnector();\n impersonatedHelpers.removeImpersonated();\n } else if (finalState.activeConnection) {\n // Update last connected to the current active one\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: finalState.activeConnection.connectorType,\n chainId: finalState.activeConnection.chainId,\n address: finalState.activeConnection.address,\n });\n }\n } catch (e) {\n console.error('Disconnect operation failed:', e);\n // Set error state if needed\n set((state) =>\n produce(state, (draft) => {\n draft.connectionError = `Disconnect failed: ${e instanceof Error ? e.message : String(e)}`;\n }),\n );\n } finally {\n set({ disconnecting: false });\n }\n },\n\n disconnectAll: async () => {\n if (Array.isArray(adapter)) {\n await Promise.allSettled(\n adapter.map(async (a) => {\n try {\n await a.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }),\n );\n } else {\n try {\n await adapter.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }\n\n set({\n activeConnection: undefined,\n connections: {},\n connectionError: undefined,\n switchNetworkError: undefined,\n });\n impersonatedHelpers.removeImpersonated();\n },\n\n /**\n * Contains error message if connection failed\n */\n // connectionError is declared above with an initial value\n\n /**\n * Resets any connection errors\n */\n resetConnectionError: () => {\n set({ connectionError: undefined });\n },\n\n /**\n * Updates the active connection's properties\n * @param connector - Partial connector object with properties to update\n */\n updateActiveConnection: (connector: Partial<Connector<W>>) => {\n const activeConnection = get().activeConnection;\n // Determine which connector to update. If connectorType is provided, use it. Otherwise use activeConnection.\n const targetConnectorType = connector.connectorType ?? activeConnection?.connectorType;\n\n if (targetConnectorType) {\n // If chainId is updated, update storage\n if (connector.chainId && targetConnectorType === activeConnection?.connectorType) {\n // Update lastConnectedConnector storage if chainId changes and it's the active connector\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: targetConnectorType,\n chainId: connector.chainId,\n address: connector.address ?? activeConnection?.address,\n });\n }\n\n // Use produce for immutable state update\n set((state) =>\n produce(state, (draft) => {\n if (draft.connections[targetConnectorType as ConnectorType]) {\n draft.connections[targetConnectorType as ConnectorType] = {\n ...draft.connections[targetConnectorType as ConnectorType],\n ...connector,\n } as Connector<W>;\n\n // Also update activeConnection if it matches\n if (draft.activeConnection?.connectorType === targetConnectorType) {\n draft.activeConnection = draft.connections[targetConnectorType as ConnectorType];\n }\n }\n }),\n );\n } else {\n const isConnectorCanChange =\n connector.connectorType !== undefined && connector.chainId !== undefined && connector.address !== undefined;\n\n if (isConnectorCanChange) {\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: connector.connectorType!,\n chainId: connector.chainId!,\n address: connector.address!,\n });\n // It's a new connector or full replacement\n set((state) => {\n const newConnector = connector as Connector<W>;\n return {\n activeConnection: newConnector,\n connections: {\n ...state.connections,\n [newConnector.connectorType]: newConnector,\n },\n };\n });\n } else {\n console.warn('Attempted to set activeConnection with incomplete data while activeConnection was undefined.');\n }\n }\n },\n\n /**\n * Switches active connection from the list of connections\n */\n switchConnection: async (connectorType) => {\n const targetConnector = get().connections[connectorType as ConnectorType];\n if (!targetConnector) {\n console.warn(`No connection found for connector type: ${connectorType}`);\n return;\n }\n\n if (get().activeConnection?.connectorType === connectorType) {\n return;\n }\n\n try {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorType));\n if (foundAdapter?.switchConnection) {\n await foundAdapter.switchConnection(connectorType);\n }\n\n set((state) =>\n produce(state, (draft) => {\n draft.activeConnection = targetConnector;\n }),\n );\n\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: targetConnector.connectorType,\n chainId: targetConnector.chainId,\n address: targetConnector.address,\n });\n } catch (e) {\n console.error('Failed to switch connection:', e);\n }\n },\n\n /**\n * Switches the connected connector to a different network\n * @param chainId - Target chain ID to switch to\n * @param connectorType - Optional connector type to switch to. If not provided, will switch to the active connection.\n */\n switchNetwork: async (chainId: string | number, connectorType?: string) => {\n set({ switchNetworkError: undefined });\n const targetConnector = connectorType\n ? get().connections[connectorType as ConnectorType]\n : get().activeConnection;\n\n if (targetConnector) {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(targetConnector.connectorType));\n\n if (!foundAdapter) {\n set({ switchNetworkError: `No adapter found for active connector type: ${targetConnector.connectorType}` });\n return;\n }\n\n try {\n // Pass the local updateActiveConnection method from 'get()' to the adapter\n await foundAdapter.checkAndSwitchNetwork(chainId, targetConnector.chainId, get().updateActiveConnection);\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": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"author": "Oleksandr Tkach",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -40,16 +40,16 @@
|
|
|
40
40
|
}
|
|
41
41
|
],
|
|
42
42
|
"peerDependencies": {
|
|
43
|
-
"@tuwaio/orbit-core": ">=0.
|
|
44
|
-
"immer": "
|
|
43
|
+
"@tuwaio/orbit-core": ">=0.2",
|
|
44
|
+
"immer": "11.x.x",
|
|
45
45
|
"zustand": "5.x.x"
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
|
-
"@tuwaio/orbit-core": "^0.
|
|
49
|
-
"immer": "^
|
|
50
|
-
"tsup": "^8.5.
|
|
48
|
+
"@tuwaio/orbit-core": "^0.2.0",
|
|
49
|
+
"immer": "^11.0.1",
|
|
50
|
+
"tsup": "^8.5.1",
|
|
51
51
|
"typescript": "^5.9.3",
|
|
52
|
-
"zustand": "^5.0.
|
|
52
|
+
"zustand": "^5.0.9"
|
|
53
53
|
},
|
|
54
54
|
"scripts": {
|
|
55
55
|
"start": "tsup src/index.ts --watch",
|