@tuwaio/satellite-core 1.0.0-fix-packages-alpha.2.a842786 → 1.0.0-fix-packages-alpha.4.ce09a66
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 +60 -56
- package/dist/index.d.ts +60 -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 +3 -3
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,47 +36,47 @@ 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>;
|
|
@@ -84,64 +84,68 @@ type SatelliteAdapter<C, W extends BaseWallet = BaseWallet> = BaseAdapter & {
|
|
|
84
84
|
getSafeConnectorChainId?: () => Promise<number | undefined>;
|
|
85
85
|
};
|
|
86
86
|
/**
|
|
87
|
-
* Store interface for managing
|
|
87
|
+
* Store interface for managing connector connections
|
|
88
88
|
*/
|
|
89
|
-
type ISatelliteConnectStore<C, W extends
|
|
89
|
+
type ISatelliteConnectStore<C, W extends BaseConnector = BaseConnector> = {
|
|
90
90
|
/** Returns configured adapter(s) */
|
|
91
91
|
getAdapter: (adapterKey: OrbitAdapter) => SatelliteAdapter<C, W> | undefined;
|
|
92
|
-
/** Get
|
|
92
|
+
/** Get connectors */
|
|
93
93
|
getConnectors: () => Partial<Record<OrbitAdapter, C[]>>;
|
|
94
94
|
/** Initialize auto connect logic */
|
|
95
95
|
initializeAutoConnect: (autoConnect: boolean) => Promise<void>;
|
|
96
|
-
/** Connects to specified
|
|
97
|
-
connect: ({
|
|
98
|
-
|
|
96
|
+
/** Connects to specified connector */
|
|
97
|
+
connect: ({ connectorType, chainId }: {
|
|
98
|
+
connectorType: ConnectorType;
|
|
99
99
|
chainId: number | string;
|
|
100
100
|
}) => Promise<void>;
|
|
101
|
-
/** Disconnects active
|
|
102
|
-
disconnect: () => Promise<void>;
|
|
103
|
-
/** Disconnects all
|
|
101
|
+
/** Disconnects active connector */
|
|
102
|
+
disconnect: (connectorType?: ConnectorType) => Promise<void>;
|
|
103
|
+
/** Disconnects all connectors, used for initialize application */
|
|
104
104
|
disconnectAll: () => Promise<void>;
|
|
105
105
|
/** Indicates ongoing connection attempt */
|
|
106
|
-
|
|
106
|
+
connecting: boolean;
|
|
107
107
|
/** Contains error message if connection failed */
|
|
108
|
-
|
|
108
|
+
connectionError?: string;
|
|
109
109
|
/** Sets error message if connection failed or form validation failed */
|
|
110
|
-
|
|
111
|
-
/** Currently connected
|
|
112
|
-
|
|
110
|
+
setConnectionError: (error: string) => void;
|
|
111
|
+
/** Currently connected connector */
|
|
112
|
+
activeConnection?: Connector<W>;
|
|
113
|
+
/** List of all connected connectors */
|
|
114
|
+
connections: Record<ConnectorType, Connector<W>>;
|
|
113
115
|
/** Clears connection error state */
|
|
114
|
-
|
|
115
|
-
/** Updates active
|
|
116
|
-
|
|
117
|
-
/** Switches
|
|
118
|
-
|
|
116
|
+
resetConnectionError: () => void;
|
|
117
|
+
/** Updates active connector properties */
|
|
118
|
+
updateActiveConnection: (connector: Partial<Connector<W>>) => void;
|
|
119
|
+
/** Switches active connector from the list of connections */
|
|
120
|
+
switchConnection: (connectorType: ConnectorType) => void;
|
|
121
|
+
/** Switches network for connected connector */
|
|
122
|
+
switchNetwork: (chainId: string | number, connectorType?: ConnectorType) => Promise<void>;
|
|
119
123
|
/** Contains error message if network switch failed */
|
|
120
124
|
switchNetworkError?: string;
|
|
121
125
|
/** Clears network switch error state */
|
|
122
126
|
resetSwitchNetworkError: () => void;
|
|
123
127
|
};
|
|
124
128
|
/**
|
|
125
|
-
* Callback type for successful
|
|
129
|
+
* Callback type for successful connections
|
|
126
130
|
*/
|
|
127
|
-
type
|
|
131
|
+
type ConnectedCallback<W extends BaseConnector = BaseConnector> = (connector: Connector<W>) => void | Promise<void>;
|
|
128
132
|
/**
|
|
129
133
|
* Configuration parameters for initializing Satellite Connect store
|
|
130
134
|
*/
|
|
131
|
-
type SatelliteConnectStoreInitialParameters<C, W extends
|
|
132
|
-
/** Optional callback executed after successful
|
|
133
|
-
callbackAfterConnected?:
|
|
135
|
+
type SatelliteConnectStoreInitialParameters<C, W extends BaseConnector = BaseConnector> = OrbitGenericAdapter<SatelliteAdapter<C, W>> & {
|
|
136
|
+
/** Optional callback executed after successful connection */
|
|
137
|
+
callbackAfterConnected?: ConnectedCallback<W>;
|
|
134
138
|
};
|
|
135
139
|
|
|
136
140
|
/**
|
|
137
|
-
* Creates a Satellite Connect store instance for managing
|
|
141
|
+
* Creates a Satellite Connect store instance for managing connector connections and state
|
|
138
142
|
*
|
|
139
|
-
* @param params -
|
|
140
|
-
* @param params.adapter -
|
|
141
|
-
* @param params.callbackAfterConnected - Optional callback function called after successful
|
|
143
|
+
* @param params - Initial parameters for the store
|
|
144
|
+
* @param params.adapter - Blockchain adapter(s) to use
|
|
145
|
+
* @param params.callbackAfterConnected - Optional callback function called after successful connection
|
|
142
146
|
*
|
|
143
|
-
* @returns A Zustand store instance with
|
|
147
|
+
* @returns A Zustand store instance with connection state and methods
|
|
144
148
|
*/
|
|
145
|
-
declare function createSatelliteConnectStore<C, W extends
|
|
149
|
+
declare function createSatelliteConnectStore<C, W extends BaseConnector = BaseConnector>({ adapter, callbackAfterConnected, }: SatelliteConnectStoreInitialParameters<C, W>): zustand_vanilla.StoreApi<ISatelliteConnectStore<C, W>>;
|
|
146
150
|
|
|
147
|
-
export { type
|
|
151
|
+
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,47 +36,47 @@ 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>;
|
|
@@ -84,64 +84,68 @@ type SatelliteAdapter<C, W extends BaseWallet = BaseWallet> = BaseAdapter & {
|
|
|
84
84
|
getSafeConnectorChainId?: () => Promise<number | undefined>;
|
|
85
85
|
};
|
|
86
86
|
/**
|
|
87
|
-
* Store interface for managing
|
|
87
|
+
* Store interface for managing connector connections
|
|
88
88
|
*/
|
|
89
|
-
type ISatelliteConnectStore<C, W extends
|
|
89
|
+
type ISatelliteConnectStore<C, W extends BaseConnector = BaseConnector> = {
|
|
90
90
|
/** Returns configured adapter(s) */
|
|
91
91
|
getAdapter: (adapterKey: OrbitAdapter) => SatelliteAdapter<C, W> | undefined;
|
|
92
|
-
/** Get
|
|
92
|
+
/** Get connectors */
|
|
93
93
|
getConnectors: () => Partial<Record<OrbitAdapter, C[]>>;
|
|
94
94
|
/** Initialize auto connect logic */
|
|
95
95
|
initializeAutoConnect: (autoConnect: boolean) => Promise<void>;
|
|
96
|
-
/** Connects to specified
|
|
97
|
-
connect: ({
|
|
98
|
-
|
|
96
|
+
/** Connects to specified connector */
|
|
97
|
+
connect: ({ connectorType, chainId }: {
|
|
98
|
+
connectorType: ConnectorType;
|
|
99
99
|
chainId: number | string;
|
|
100
100
|
}) => Promise<void>;
|
|
101
|
-
/** Disconnects active
|
|
102
|
-
disconnect: () => Promise<void>;
|
|
103
|
-
/** Disconnects all
|
|
101
|
+
/** Disconnects active connector */
|
|
102
|
+
disconnect: (connectorType?: ConnectorType) => Promise<void>;
|
|
103
|
+
/** Disconnects all connectors, used for initialize application */
|
|
104
104
|
disconnectAll: () => Promise<void>;
|
|
105
105
|
/** Indicates ongoing connection attempt */
|
|
106
|
-
|
|
106
|
+
connecting: boolean;
|
|
107
107
|
/** Contains error message if connection failed */
|
|
108
|
-
|
|
108
|
+
connectionError?: string;
|
|
109
109
|
/** Sets error message if connection failed or form validation failed */
|
|
110
|
-
|
|
111
|
-
/** Currently connected
|
|
112
|
-
|
|
110
|
+
setConnectionError: (error: string) => void;
|
|
111
|
+
/** Currently connected connector */
|
|
112
|
+
activeConnection?: Connector<W>;
|
|
113
|
+
/** List of all connected connectors */
|
|
114
|
+
connections: Record<ConnectorType, Connector<W>>;
|
|
113
115
|
/** Clears connection error state */
|
|
114
|
-
|
|
115
|
-
/** Updates active
|
|
116
|
-
|
|
117
|
-
/** Switches
|
|
118
|
-
|
|
116
|
+
resetConnectionError: () => void;
|
|
117
|
+
/** Updates active connector properties */
|
|
118
|
+
updateActiveConnection: (connector: Partial<Connector<W>>) => void;
|
|
119
|
+
/** Switches active connector from the list of connections */
|
|
120
|
+
switchConnection: (connectorType: ConnectorType) => void;
|
|
121
|
+
/** Switches network for connected connector */
|
|
122
|
+
switchNetwork: (chainId: string | number, connectorType?: ConnectorType) => Promise<void>;
|
|
119
123
|
/** Contains error message if network switch failed */
|
|
120
124
|
switchNetworkError?: string;
|
|
121
125
|
/** Clears network switch error state */
|
|
122
126
|
resetSwitchNetworkError: () => void;
|
|
123
127
|
};
|
|
124
128
|
/**
|
|
125
|
-
* Callback type for successful
|
|
129
|
+
* Callback type for successful connections
|
|
126
130
|
*/
|
|
127
|
-
type
|
|
131
|
+
type ConnectedCallback<W extends BaseConnector = BaseConnector> = (connector: Connector<W>) => void | Promise<void>;
|
|
128
132
|
/**
|
|
129
133
|
* Configuration parameters for initializing Satellite Connect store
|
|
130
134
|
*/
|
|
131
|
-
type SatelliteConnectStoreInitialParameters<C, W extends
|
|
132
|
-
/** Optional callback executed after successful
|
|
133
|
-
callbackAfterConnected?:
|
|
135
|
+
type SatelliteConnectStoreInitialParameters<C, W extends BaseConnector = BaseConnector> = OrbitGenericAdapter<SatelliteAdapter<C, W>> & {
|
|
136
|
+
/** Optional callback executed after successful connection */
|
|
137
|
+
callbackAfterConnected?: ConnectedCallback<W>;
|
|
134
138
|
};
|
|
135
139
|
|
|
136
140
|
/**
|
|
137
|
-
* Creates a Satellite Connect store instance for managing
|
|
141
|
+
* Creates a Satellite Connect store instance for managing connector connections and state
|
|
138
142
|
*
|
|
139
|
-
* @param params -
|
|
140
|
-
* @param params.adapter -
|
|
141
|
-
* @param params.callbackAfterConnected - Optional callback function called after successful
|
|
143
|
+
* @param params - Initial parameters for the store
|
|
144
|
+
* @param params.adapter - Blockchain adapter(s) to use
|
|
145
|
+
* @param params.callbackAfterConnected - Optional callback function called after successful connection
|
|
142
146
|
*
|
|
143
|
-
* @returns A Zustand store instance with
|
|
147
|
+
* @returns A Zustand store instance with connection state and methods
|
|
144
148
|
*/
|
|
145
|
-
declare function createSatelliteConnectStore<C, W extends
|
|
149
|
+
declare function createSatelliteConnectStore<C, W extends BaseConnector = BaseConnector>({ adapter, callbackAfterConnected, }: SatelliteConnectStoreInitialParameters<C, W>): zustand_vanilla.StoreApi<ISatelliteConnectStore<C, W>>;
|
|
146
150
|
|
|
147
|
-
export { type
|
|
151
|
+
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 g({adapter:s,callbackAfterConnected:p}){return vanilla.createStore()((r,c)=>({getAdapter:n=>orbitCore.selectAdapterByKey({adapter:s,adapterKey:n}),getConnectors:()=>{let n;return Array.isArray(s)?n=s.map(e=>e.getConnectors()):n=[s.getConnectors()],n.reduce((e,o)=>{let i=o.adapter,t=o.connectors;return {...e,[i]:t}},{})},initializeAutoConnect:async n=>{if(n){let e=orbitCore.lastConnectedConnectorHelpers.getLastConnectedConnector();e&&!["impersonatedwallet","walletconnect","coinbasewallet","bitgetwallet"].includes(e.connectorType.split(":")[1])&&(await orbitCore.delay(null,200),await c().connect({connectorType:e.connectorType,chainId:e.chainId}));}else if(orbitCore.isSafeApp){await orbitCore.delay(null,200);let e=c().getAdapter(orbitCore.OrbitAdapter.EVM);if(e&&e.getSafeConnectorChainId){let o=await e.getSafeConnectorChainId();o&&await c().connect({connectorType:`${orbitCore.OrbitAdapter.EVM}:safewallet`,chainId:o});}}},connecting:false,connectionError:void 0,switchNetworkError:void 0,activeConnection:void 0,connections:{},setConnectionError:n=>r({connectionError:n}),connect:async({connectorType:n,chainId:e})=>{r({connecting:true,connectionError:void 0});let o=c().getAdapter(orbitCore.getAdapterFromConnectorType(n));if(!o){r({connecting:false,connectionError:`No adapter found for connector type: ${n}`});return}try{if(c().connections[n])return;let t=await o.connect({connectorType:n,chainId:e});if(r(a=>({activeConnection:t,connections:{...a.connections,[t.connectorType]:t}})),o.checkIsContractAddress){let a=await o.checkIsContractAddress({address:t.address,chainId:e});c().updateActiveConnection({...t,isContractAddress:a});}if(p){let a=c().activeConnection;a&&a.connectorType===n&&await p(a);}r({connecting:!1}),orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:n,chainId:e,address:c().activeConnection?.address}),orbitCore.recentConnectedConnectorHelpers.setRecentConnectedConnector({[orbitCore.getAdapterFromConnectorType(n)]:{[n.split(":")[1]]:!0}});}catch(i){r({connecting:false,connectionError:"Connector connection failed: "+(i instanceof Error?i.message:String(i))});}},disconnect:async n=>{if(n){let e=c().connections[n];e&&(await c().getAdapter(orbitCore.getAdapterFromConnectorType(e.connectorType))?.disconnect(e),r(i=>{let t={...i.connections};delete t[n];let a=i.activeConnection?.connectorType===n?void 0:i.activeConnection;return {connections:t,activeConnection:a,connectionError:void 0,switchNetworkError:void 0}}));}else await c().disconnectAll();if(Object.keys(c().connections).length===0)orbitCore.lastConnectedConnectorHelpers.removeLastConnectedConnector(),orbitCore.impersonatedHelpers.removeImpersonated();else {let e=c().activeConnection;e&&orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:e.connectorType,chainId:e.chainId,address:e.address});}},disconnectAll:async()=>{if(await orbitCore.delay(null,150),Array.isArray(s))await Promise.allSettled(s.map(async n=>{try{await n.disconnect();}catch{}}));else try{await s.disconnect();}catch{}r({activeConnection:void 0,connections:{},connectionError:void 0,switchNetworkError:void 0}),orbitCore.impersonatedHelpers.removeImpersonated();},resetConnectionError:()=>{r({connectionError:void 0});},updateActiveConnection:n=>{let e=c().activeConnection,o=n.connectorType??e?.connectorType;o?(n.chainId&&o===e?.connectorType&&orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:o,chainId:n.chainId,address:n.address??e?.address}),r(i=>immer.produce(i,t=>{t.connections[o]&&(t.connections[o]={...t.connections[o],...n},t.activeConnection?.connectorType===o&&(t.activeConnection=t.connections[o]));}))):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:n=>{let e=c().connections[n];e&&(r({activeConnection:e}),orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:e.connectorType,chainId:e.chainId,address:e.address}));},switchNetwork:async(n,e)=>{r({switchNetworkError:void 0});let o=e?c().connections[e]:c().activeConnection;if(o){let i=c().getAdapter(orbitCore.getAdapterFromConnectorType(o.connectorType));if(!i){r({switchNetworkError:`No adapter found for active connector type: ${o.connectorType}`});return}try{await i.checkAndSwitchNetwork(n,o.chainId,c().updateActiveConnection);}catch(t){r({switchNetworkError:"Switch network failed: "+(t instanceof Error?t.message:String(t))});}}},resetSwitchNetworkError:()=>r({switchNetworkError:void 0})}))}exports.createSatelliteConnectStore=g;//# 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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\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","createStore","set","get","adapterKey","selectAdapterByKey","results","a","accumulator","currentResult","key","value","autoConnect","lastConnectedConnector","lastConnectedConnectorHelpers","delay","isSafeApp","foundAdapter","OrbitAdapter","safeConnectorChainId","error","connectorType","chainId","getAdapterFromConnectorType","connector","state","isContractAddress","updatedConnector","recentConnectedConnectorHelpers","e","connectorToDisconnect","newConnections","newActiveConnection","impersonatedHelpers","currentActive","activeConnection","targetConnectorType","produce","draft","newConnector","targetConnector"],"mappings":"mHA0BO,SAASA,EAAwE,CACtF,OAAA,CAAAC,EACA,sBAAA,CAAAC,CACF,CAAA,CAAiD,CAC/C,OAAOC,mBAAAA,GAA4C,CAACC,CAAAA,CAAKC,KAAS,CAIhE,UAAA,CAAaC,GAAeC,4BAAAA,CAAmB,CAAE,OAAA,CAAAN,CAAAA,CAAS,UAAA,CAAAK,CAAW,CAAC,CAAA,CAKtE,aAAA,CAAe,IAAM,CACnB,IAAIE,EAEJ,OAAI,KAAA,CAAM,OAAA,CAAQP,CAAO,CAAA,CACvBO,CAAAA,CAAUP,EAAQ,GAAA,CAAKQ,CAAAA,EAAMA,EAAE,aAAA,EAAe,EAG9CD,CAAAA,CAAU,CAACP,CAAAA,CAAQ,aAAA,EAAe,CAAA,CAG7BO,EAAQ,MAAA,CACb,CAACE,EAAaC,CAAAA,GAAkB,CAC9B,IAAMC,CAAAA,CAAMD,CAAAA,CAAc,OAAA,CACpBE,CAAAA,CAAQF,CAAAA,CAAc,UAAA,CAC5B,OAAO,CACL,GAAGD,EACH,CAACE,CAAG,EAAGC,CACT,CACF,CAAA,CACA,EACF,CACF,EAEA,qBAAA,CAAuB,MAAOC,GAAgB,CAC5C,GAAIA,EAAa,CACf,IAAMC,EAAyBC,uCAAAA,CAA8B,yBAAA,GAE3DD,CAAAA,EACA,CAAC,CAAC,oBAAA,CAAsB,eAAA,CAAiB,iBAAkB,cAAc,CAAA,CAAE,QAAA,CACzEA,CAAAA,CAAuB,aAAA,CAAc,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,CACnD,CAAA,GAEA,MAAME,gBAAM,IAAA,CAAM,GAAG,CAAA,CACrB,MAAMZ,CAAAA,EAAI,CAAE,QAAQ,CAClB,aAAA,CAAeU,EAAuB,aAAA,CACtC,OAAA,CAASA,EAAuB,OAClC,CAAC,CAAA,EAEL,CA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G,MACF,CAEA,GAAI,CAEF,MAAMvB,EAAa,qBAAA,CAAsBK,CAAAA,CAASkB,EAAgB,OAAA,CAASrC,CAAAA,GAAM,sBAAsB,EACzG,CAAA,MAAS0B,CAAAA,CAAG,CACV3B,CAAAA,CAAI,CAAE,kBAAA,CAAoB,yBAAA,EAA6B2B,aAAa,KAAA,CAAQA,CAAAA,CAAE,QAAU,MAAA,CAAOA,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,CAAA,CAUA,uBAAA,CAAyB,IAAM3B,CAAAA,CAAI,CAAE,mBAAoB,MAAU,CAAC,CACtE,CAAA,CAAE,CACJ","file":"index.js","sourcesContent":["import {\n ConnectorType,\n delay,\n getAdapterFromConnectorType,\n impersonatedHelpers,\n isSafeApp,\n lastConnectedConnectorHelpers,\n OrbitAdapter,\n RecentConnectedConnector,\n recentConnectedConnectorHelpers,\n selectAdapterByKey,\n} from '@tuwaio/orbit-core';\nimport { produce } 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 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 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, 200);\n await get().connect({\n connectorType: lastConnectedConnector.connectorType,\n chainId: lastConnectedConnector.chainId,\n });\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({ connectorType: `${OrbitAdapter.EVM}:safewallet`, chainId: safeConnectorChainId });\n }\n }\n }\n },\n\n connecting: 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 recentConnectedConnectorHelpers.setRecentConnectedConnector({\n [getAdapterFromConnectorType(connectorType)]: {\n [connectorType.split(':')[1]]: true,\n },\n } as RecentConnectedConnector);\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 /**\n * Disconnects the currently active wallet or a specific wallet\n */\n disconnect: async (connectorType?: string) => {\n if (connectorType) {\n // Disconnect specific connector\n const connectorToDisconnect = get().connections[connectorType as ConnectorType];\n\n if (connectorToDisconnect) {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorToDisconnect.connectorType));\n await foundAdapter?.disconnect(connectorToDisconnect);\n\n set((state) => {\n const newConnections = { ...state.connections };\n delete newConnections[connectorType as ConnectorType];\n\n // If the disconnected connector was the active one, set activeConnection to undefined\n const newActiveConnection =\n state.activeConnection?.connectorType === connectorType ? undefined : state.activeConnection;\n\n return {\n connections: newConnections,\n activeConnection: newActiveConnection,\n connectionError: undefined,\n switchNetworkError: undefined,\n };\n });\n }\n } else {\n // Disconnect ALL connectors\n await get().disconnectAll();\n }\n\n if (Object.keys(get().connections).length === 0) {\n lastConnectedConnectorHelpers.removeLastConnectedConnector();\n impersonatedHelpers.removeImpersonated();\n } else {\n // Update last connected to the current active one (if any)\n const currentActive = get().activeConnection;\n if (currentActive) {\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: currentActive.connectorType,\n chainId: currentActive.chainId,\n address: currentActive.address,\n });\n }\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({\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: (connectorType: string) => {\n const targetConnector = get().connections[connectorType as ConnectorType];\n if (targetConnector) {\n set({ activeConnection: targetConnector });\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: targetConnector.connectorType,\n chainId: targetConnector.chainId,\n address: targetConnector.address,\n });\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,delay,impersonatedHelpers,recentConnectedConnectorHelpers,isSafeApp,OrbitAdapter}from'@tuwaio/orbit-core';import {produce}from'immer';import {createStore}from'zustand/vanilla';function g({adapter:s,callbackAfterConnected:p}){return createStore()((r,c)=>({getAdapter:n=>selectAdapterByKey({adapter:s,adapterKey:n}),getConnectors:()=>{let n;return Array.isArray(s)?n=s.map(e=>e.getConnectors()):n=[s.getConnectors()],n.reduce((e,o)=>{let i=o.adapter,t=o.connectors;return {...e,[i]:t}},{})},initializeAutoConnect:async n=>{if(n){let e=lastConnectedConnectorHelpers.getLastConnectedConnector();e&&!["impersonatedwallet","walletconnect","coinbasewallet","bitgetwallet"].includes(e.connectorType.split(":")[1])&&(await delay(null,200),await c().connect({connectorType:e.connectorType,chainId:e.chainId}));}else if(isSafeApp){await delay(null,200);let e=c().getAdapter(OrbitAdapter.EVM);if(e&&e.getSafeConnectorChainId){let o=await e.getSafeConnectorChainId();o&&await c().connect({connectorType:`${OrbitAdapter.EVM}:safewallet`,chainId:o});}}},connecting:false,connectionError:void 0,switchNetworkError:void 0,activeConnection:void 0,connections:{},setConnectionError:n=>r({connectionError:n}),connect:async({connectorType:n,chainId:e})=>{r({connecting:true,connectionError:void 0});let o=c().getAdapter(getAdapterFromConnectorType(n));if(!o){r({connecting:false,connectionError:`No adapter found for connector type: ${n}`});return}try{if(c().connections[n])return;let t=await o.connect({connectorType:n,chainId:e});if(r(a=>({activeConnection:t,connections:{...a.connections,[t.connectorType]:t}})),o.checkIsContractAddress){let a=await o.checkIsContractAddress({address:t.address,chainId:e});c().updateActiveConnection({...t,isContractAddress:a});}if(p){let a=c().activeConnection;a&&a.connectorType===n&&await p(a);}r({connecting:!1}),lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:n,chainId:e,address:c().activeConnection?.address}),recentConnectedConnectorHelpers.setRecentConnectedConnector({[getAdapterFromConnectorType(n)]:{[n.split(":")[1]]:!0}});}catch(i){r({connecting:false,connectionError:"Connector connection failed: "+(i instanceof Error?i.message:String(i))});}},disconnect:async n=>{if(n){let e=c().connections[n];e&&(await c().getAdapter(getAdapterFromConnectorType(e.connectorType))?.disconnect(e),r(i=>{let t={...i.connections};delete t[n];let a=i.activeConnection?.connectorType===n?void 0:i.activeConnection;return {connections:t,activeConnection:a,connectionError:void 0,switchNetworkError:void 0}}));}else await c().disconnectAll();if(Object.keys(c().connections).length===0)lastConnectedConnectorHelpers.removeLastConnectedConnector(),impersonatedHelpers.removeImpersonated();else {let e=c().activeConnection;e&&lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:e.connectorType,chainId:e.chainId,address:e.address});}},disconnectAll:async()=>{if(await delay(null,150),Array.isArray(s))await Promise.allSettled(s.map(async n=>{try{await n.disconnect();}catch{}}));else try{await s.disconnect();}catch{}r({activeConnection:void 0,connections:{},connectionError:void 0,switchNetworkError:void 0}),impersonatedHelpers.removeImpersonated();},resetConnectionError:()=>{r({connectionError:void 0});},updateActiveConnection:n=>{let e=c().activeConnection,o=n.connectorType??e?.connectorType;o?(n.chainId&&o===e?.connectorType&&lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:o,chainId:n.chainId,address:n.address??e?.address}),r(i=>produce(i,t=>{t.connections[o]&&(t.connections[o]={...t.connections[o],...n},t.activeConnection?.connectorType===o&&(t.activeConnection=t.connections[o]));}))):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:n=>{let e=c().connections[n];e&&(r({activeConnection:e}),lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:e.connectorType,chainId:e.chainId,address:e.address}));},switchNetwork:async(n,e)=>{r({switchNetworkError:void 0});let o=e?c().connections[e]:c().activeConnection;if(o){let i=c().getAdapter(getAdapterFromConnectorType(o.connectorType));if(!i){r({switchNetworkError:`No adapter found for active connector type: ${o.connectorType}`});return}try{await i.checkAndSwitchNetwork(n,o.chainId,c().updateActiveConnection);}catch(t){r({switchNetworkError:"Switch network failed: "+(t instanceof Error?t.message:String(t))});}}},resetSwitchNetworkError:()=>r({switchNetworkError:void 0})}))}export{g 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,CACvBO,CAAAA,CAAUP,EAAQ,GAAA,CAAKQ,CAAAA,EAAMA,CAAAA,CAAE,aAAA,EAAe,CAAA,CAG9CD,CAAAA,CAAU,CAACP,CAAAA,CAAQ,eAAe,CAAA,CAG7BO,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,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","createStore","set","get","adapterKey","selectAdapterByKey","results","a","accumulator","currentResult","key","value","autoConnect","lastConnectedConnector","lastConnectedConnectorHelpers","delay","isSafeApp","foundAdapter","OrbitAdapter","safeConnectorChainId","error","connectorType","chainId","getAdapterFromConnectorType","connector","state","isContractAddress","updatedConnector","recentConnectedConnectorHelpers","e","connectorToDisconnect","newConnections","newActiveConnection","impersonatedHelpers","currentActive","activeConnection","targetConnectorType","produce","draft","newConnector","targetConnector"],"mappings":"qQA0BO,SAASA,EAAwE,CACtF,OAAA,CAAAC,EACA,sBAAA,CAAAC,CACF,CAAA,CAAiD,CAC/C,OAAOC,WAAAA,GAA4C,CAACC,CAAAA,CAAKC,KAAS,CAIhE,UAAA,CAAaC,GAAeC,kBAAAA,CAAmB,CAAE,OAAA,CAAAN,CAAAA,CAAS,UAAA,CAAAK,CAAW,CAAC,CAAA,CAKtE,aAAA,CAAe,IAAM,CACnB,IAAIE,EAEJ,OAAI,KAAA,CAAM,OAAA,CAAQP,CAAO,CAAA,CACvBO,CAAAA,CAAUP,EAAQ,GAAA,CAAKQ,CAAAA,EAAMA,EAAE,aAAA,EAAe,EAG9CD,CAAAA,CAAU,C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,EAAI,CAAE,gBAAA,CAAkBsC,CAAgB,CAAC,CAAA,CACzC1B,6BAAAA,CAA8B,yBAAA,CAA0B,CACtD,aAAA,CAAe0B,EAAgB,aAAA,CAC/B,OAAA,CAASA,EAAgB,OAAA,CACzB,OAAA,CAASA,EAAgB,OAC3B,CAAC,GAEL,CAAA,CAOA,aAAA,CAAe,MAAOlB,CAAAA,CAA0BD,CAAAA,GAA2B,CACzEnB,CAAAA,CAAI,CAAE,mBAAoB,MAAU,CAAC,CAAA,CACrC,IAAMsC,CAAAA,CAAkBnB,CAAAA,CACpBlB,GAAI,CAAE,WAAA,CAAYkB,CAA8B,CAAA,CAChDlB,CAAAA,GAAM,gBAAA,CAEV,GAAIqC,CAAAA,CAAiB,CACnB,IAAMvB,CAAAA,CAAed,GAAI,CAAE,UAAA,CAAWoB,4BAA4BiB,CAAAA,CAAgB,aAAa,CAAC,CAAA,CAEhG,GAAI,CAACvB,CAAAA,CAAc,CACjBf,CAAAA,CAAI,CAAE,kBAAA,CAAoB,CAAA,4CAAA,EAA+CsC,EAAgB,aAAa,CAAA,CAAG,CAAC,CAAA,CAC1G,MACF,CAEA,GAAI,CAEF,MAAMvB,EAAa,qBAAA,CAAsBK,CAAAA,CAASkB,EAAgB,OAAA,CAASrC,CAAAA,GAAM,sBAAsB,EACzG,CAAA,MAAS0B,CAAAA,CAAG,CACV3B,CAAAA,CAAI,CAAE,kBAAA,CAAoB,yBAAA,EAA6B2B,aAAa,KAAA,CAAQA,CAAAA,CAAE,QAAU,MAAA,CAAOA,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,CAAA,CAUA,uBAAA,CAAyB,IAAM3B,CAAAA,CAAI,CAAE,mBAAoB,MAAU,CAAC,CACtE,CAAA,CAAE,CACJ","file":"index.mjs","sourcesContent":["import {\n ConnectorType,\n delay,\n getAdapterFromConnectorType,\n impersonatedHelpers,\n isSafeApp,\n lastConnectedConnectorHelpers,\n OrbitAdapter,\n RecentConnectedConnector,\n recentConnectedConnectorHelpers,\n selectAdapterByKey,\n} from '@tuwaio/orbit-core';\nimport { produce } 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 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 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, 200);\n await get().connect({\n connectorType: lastConnectedConnector.connectorType,\n chainId: lastConnectedConnector.chainId,\n });\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({ connectorType: `${OrbitAdapter.EVM}:safewallet`, chainId: safeConnectorChainId });\n }\n }\n }\n },\n\n connecting: 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 recentConnectedConnectorHelpers.setRecentConnectedConnector({\n [getAdapterFromConnectorType(connectorType)]: {\n [connectorType.split(':')[1]]: true,\n },\n } as RecentConnectedConnector);\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 /**\n * Disconnects the currently active wallet or a specific wallet\n */\n disconnect: async (connectorType?: string) => {\n if (connectorType) {\n // Disconnect specific connector\n const connectorToDisconnect = get().connections[connectorType as ConnectorType];\n\n if (connectorToDisconnect) {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorToDisconnect.connectorType));\n await foundAdapter?.disconnect(connectorToDisconnect);\n\n set((state) => {\n const newConnections = { ...state.connections };\n delete newConnections[connectorType as ConnectorType];\n\n // If the disconnected connector was the active one, set activeConnection to undefined\n const newActiveConnection =\n state.activeConnection?.connectorType === connectorType ? undefined : state.activeConnection;\n\n return {\n connections: newConnections,\n activeConnection: newActiveConnection,\n connectionError: undefined,\n switchNetworkError: undefined,\n };\n });\n }\n } else {\n // Disconnect ALL connectors\n await get().disconnectAll();\n }\n\n if (Object.keys(get().connections).length === 0) {\n lastConnectedConnectorHelpers.removeLastConnectedConnector();\n impersonatedHelpers.removeImpersonated();\n } else {\n // Update last connected to the current active one (if any)\n const currentActive = get().activeConnection;\n if (currentActive) {\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: currentActive.connectorType,\n chainId: currentActive.chainId,\n address: currentActive.address,\n });\n }\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({\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: (connectorType: string) => {\n const targetConnector = get().connections[connectorType as ConnectorType];\n if (targetConnector) {\n set({ activeConnection: targetConnector });\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: targetConnector.connectorType,\n chainId: targetConnector.chainId,\n address: targetConnector.address,\n });\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": "1.0.0-fix-packages-alpha.
|
|
3
|
+
"version": "1.0.0-fix-packages-alpha.4.ce09a66",
|
|
4
4
|
"private": false,
|
|
5
5
|
"author": "Oleksandr Tkach",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -40,12 +40,12 @@
|
|
|
40
40
|
}
|
|
41
41
|
],
|
|
42
42
|
"peerDependencies": {
|
|
43
|
-
"@tuwaio/orbit-core": ">=0.
|
|
43
|
+
"@tuwaio/orbit-core": ">=0.2",
|
|
44
44
|
"immer": "11.x.x",
|
|
45
45
|
"zustand": "5.x.x"
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
|
-
"@tuwaio/orbit-core": "1.0.0-fix-packages-alpha.
|
|
48
|
+
"@tuwaio/orbit-core": "1.0.0-fix-packages-alpha.3.dc7f910",
|
|
49
49
|
"immer": "^11.0.0",
|
|
50
50
|
"tsup": "^8.5.1",
|
|
51
51
|
"typescript": "^5.9.3",
|