@tuwaio/satellite-core 0.0.4 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -18
- package/dist/index.d.mts +37 -162
- package/dist/index.d.ts +37 -162
- 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 -11
package/README.md
CHANGED
|
@@ -33,23 +33,13 @@ Built with TypeScript, it leverages modern tools for state management and type-s
|
|
|
33
33
|
- TypeScript 5.9+
|
|
34
34
|
```bash
|
|
35
35
|
# Using pnpm (recommended)
|
|
36
|
-
pnpm add @tuwaio/satellite-core @tuwaio/orbit-core
|
|
36
|
+
pnpm add @tuwaio/satellite-core @tuwaio/orbit-core immer zustand
|
|
37
37
|
|
|
38
38
|
# Using npm
|
|
39
|
-
npm install @tuwaio/satellite-core @tuwaio/orbit-core
|
|
39
|
+
npm install @tuwaio/satellite-core @tuwaio/orbit-core immer zustand
|
|
40
40
|
|
|
41
41
|
# Using yarn
|
|
42
|
-
yarn add @tuwaio/satellite-core @tuwaio/orbit-core
|
|
43
|
-
```
|
|
44
|
-
---
|
|
45
|
-
|
|
46
|
-
## 🚀 Quick Start
|
|
47
|
-
|
|
48
|
-
### Basic Usage
|
|
49
|
-
```typescript
|
|
50
|
-
import { getAdapterFromWalletType } from '@tuwaio/satellite-core';
|
|
51
|
-
// Determine adapter type from wallet type
|
|
52
|
-
const adapter = getAdapterFromWalletType('evm:metamask');
|
|
42
|
+
yarn add @tuwaio/satellite-core @tuwaio/orbit-core immer zustand
|
|
53
43
|
```
|
|
54
44
|
---
|
|
55
45
|
|
|
@@ -64,7 +54,6 @@ The package is structured around these core components:
|
|
|
64
54
|
|
|
65
55
|
### Core Modules
|
|
66
56
|
- **Store:** Connection state management system
|
|
67
|
-
- **Utils:** Wallet interaction utilities
|
|
68
57
|
- **Types:** Type system for unified wallet operations
|
|
69
58
|
|
|
70
59
|
---
|
|
@@ -77,6 +66,7 @@ Satellite Core works in conjunction with other ecosystem packages:
|
|
|
77
66
|
- **`@tuwaio/satellite-evm`:** EVM wallet integration
|
|
78
67
|
- **`@tuwaio/satellite-solana`:** Solana wallet integration
|
|
79
68
|
- **`@tuwaio/satellite-react`:** React hooks and components
|
|
69
|
+
- **`@tuwaio/satellite-siwe-next-auth`:** React hooks and components for SIWE auth in the next js app
|
|
80
70
|
|
|
81
71
|
---
|
|
82
72
|
|
|
@@ -91,7 +81,3 @@ If you find this library useful, please consider supporting its development. Eve
|
|
|
91
81
|
## 📄 License
|
|
92
82
|
|
|
93
83
|
This project is licensed under the **Apache-2.0 License** - see the [LICENSE](./LICENSE) file for details.
|
|
94
|
-
|
|
95
|
-
## 👥 Contributors
|
|
96
|
-
|
|
97
|
-
- **Oleksandr Tkach** - [GitHub](https://github.com/Argeare5)
|
package/dist/index.d.mts
CHANGED
|
@@ -1,13 +1,6 @@
|
|
|
1
|
-
import * as
|
|
2
|
-
import { OrbitGenericAdapter, OrbitAdapter } from '@tuwaio/orbit-core';
|
|
3
|
-
import { Connector as Connector$1, CreateConnectorFn } from '@wagmi/core';
|
|
4
|
-
import { UiWallet, UiWalletAccount } from '@wallet-standard/ui';
|
|
1
|
+
import * as zustand_vanilla from 'zustand/vanilla';
|
|
2
|
+
import { WalletType, OrbitGenericAdapter, BaseAdapter, OrbitAdapter } from '@tuwaio/orbit-core';
|
|
5
3
|
|
|
6
|
-
/**
|
|
7
|
-
* Type representing a wallet identifier in format "chain:wallet"
|
|
8
|
-
* @example "evm:metamask" | "solana:phantom"
|
|
9
|
-
*/
|
|
10
|
-
type WalletType = `${OrbitAdapter}:${string}`;
|
|
11
4
|
/**
|
|
12
5
|
* Configuration properties for initializing wallet connectors
|
|
13
6
|
*/
|
|
@@ -26,8 +19,6 @@ type ConnectorsInitProps = {
|
|
|
26
19
|
appUrl?: string;
|
|
27
20
|
/** Array of icon URLs for WalletConnect */
|
|
28
21
|
appIcons?: string[];
|
|
29
|
-
/** Function to get impersonated account address for testing */
|
|
30
|
-
getImpersonatedAccount?: () => string | `0x${string}` | undefined;
|
|
31
22
|
};
|
|
32
23
|
/**
|
|
33
24
|
* Base interface for connected wallet information
|
|
@@ -45,87 +36,63 @@ interface BaseWallet {
|
|
|
45
36
|
isContractAddress: boolean;
|
|
46
37
|
/** Connection status */
|
|
47
38
|
isConnected: boolean;
|
|
39
|
+
/** Optional: wallet icon base64 string */
|
|
40
|
+
walletIcon?: string;
|
|
48
41
|
}
|
|
49
|
-
/**
|
|
50
|
-
|
|
51
|
-
*/
|
|
52
|
-
interface SolanaWallet extends BaseWallet {
|
|
53
|
-
/** Connected Wallet Standard account */
|
|
54
|
-
connectedAccount?: UiWalletAccount;
|
|
55
|
-
/** Connected Wallet Standard wallet instance */
|
|
56
|
-
connectedWallet?: UiWallet;
|
|
57
|
-
}
|
|
58
|
-
/** Union type for all supported wallet types */
|
|
59
|
-
type Wallet = BaseWallet | SolanaWallet;
|
|
60
|
-
/** EVM-specific connector type */
|
|
61
|
-
type ConnectorEVM = Connector$1<CreateConnectorFn>;
|
|
62
|
-
/** Solana-specific connector type */
|
|
63
|
-
type ConnectorSolana = UiWallet;
|
|
64
|
-
/** Union type for all supported connector types */
|
|
65
|
-
type Connector = ConnectorEVM | ConnectorSolana;
|
|
42
|
+
/** Generic type for all supported wallet types */
|
|
43
|
+
type Wallet<W extends BaseWallet> = BaseWallet | W;
|
|
66
44
|
/**
|
|
67
45
|
* Interface for blockchain network adapters
|
|
68
46
|
* @remarks
|
|
69
47
|
* Adapters provide chain-specific implementation for wallet interactions
|
|
70
48
|
*/
|
|
71
|
-
type SatelliteAdapter = {
|
|
49
|
+
type SatelliteAdapter<C, W extends BaseWallet = BaseWallet> = BaseAdapter & {
|
|
72
50
|
/** Unique identifier for the adapter */
|
|
73
51
|
key: OrbitAdapter;
|
|
74
52
|
/**
|
|
75
53
|
* Initiates wallet connection
|
|
76
54
|
* @returns Promise resolving to connected wallet instance
|
|
77
55
|
*/
|
|
78
|
-
connect: ({ walletType, chainId
|
|
56
|
+
connect: ({ walletType, chainId }: {
|
|
79
57
|
walletType: WalletType;
|
|
80
58
|
chainId: number | string;
|
|
81
|
-
|
|
82
|
-
}) => Promise<Wallet>;
|
|
59
|
+
}) => Promise<Wallet<W>>;
|
|
83
60
|
/** Disconnects current wallet session */
|
|
84
|
-
disconnect: () => Promise<void>;
|
|
61
|
+
disconnect: (activeWallet?: Wallet<W>) => Promise<void>;
|
|
85
62
|
/** Retrieves available wallet connectors for this adapter */
|
|
86
|
-
getConnectors: () =>
|
|
63
|
+
getConnectors: () => {
|
|
87
64
|
adapter: OrbitAdapter;
|
|
88
|
-
connectors:
|
|
89
|
-
}
|
|
65
|
+
connectors: C[];
|
|
66
|
+
};
|
|
90
67
|
/**
|
|
91
68
|
* Handles network switching for connected wallet
|
|
92
69
|
* @param chainId - Target chain ID
|
|
93
70
|
* @param currentChainId - Current chain ID
|
|
94
71
|
* @param updateActiveWallet - Callback to update wallet state
|
|
95
72
|
*/
|
|
96
|
-
checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number, updateActiveWallet?: (wallet: Partial<Wallet
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
getExplorerUrl: (url?: string, chainId?: string | number) => string | undefined;
|
|
102
|
-
/** Optional method to resolve ENS-like names */
|
|
103
|
-
getName?: (address: string) => Promise<string | null>;
|
|
104
|
-
/** Optional method to get avatar for resolved names */
|
|
105
|
-
getAvatar?: (name: string) => Promise<string | null>;
|
|
73
|
+
checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number, updateActiveWallet?: (wallet: Partial<Wallet<W>>) => void) => Promise<void>;
|
|
74
|
+
getBalance: (address: string, chainId: number | string) => Promise<{
|
|
75
|
+
value: string;
|
|
76
|
+
symbol: string;
|
|
77
|
+
}>;
|
|
106
78
|
/** Optional method to check if address is a smart contract */
|
|
107
79
|
checkIsContractWallet?: ({ address, chainId }: {
|
|
108
80
|
address: string;
|
|
109
81
|
chainId: string | number;
|
|
110
82
|
}) => Promise<boolean>;
|
|
83
|
+
/** Optional method to get a safe connector chainId for auto connect */
|
|
84
|
+
getSafeConnectorChainId?: () => Promise<number | undefined>;
|
|
111
85
|
};
|
|
112
86
|
/**
|
|
113
87
|
* Store interface for managing wallet connections
|
|
114
88
|
*/
|
|
115
|
-
type ISatelliteConnectStore = {
|
|
89
|
+
type ISatelliteConnectStore<C, W extends BaseWallet = BaseWallet> = {
|
|
116
90
|
/** Returns configured adapter(s) */
|
|
117
|
-
getAdapter: () => SatelliteAdapter |
|
|
118
|
-
/**
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
};
|
|
123
|
-
/** Available connectors mapped by adapter type */
|
|
124
|
-
availableConnectors: Partial<Record<OrbitAdapter, Connector[]>>;
|
|
125
|
-
/** Initializes wallet connectors */
|
|
126
|
-
initializeAppConnectors: ({ autoConnect }: {
|
|
127
|
-
autoConnect?: boolean;
|
|
128
|
-
}) => Promise<void>;
|
|
91
|
+
getAdapter: (adapterKey: OrbitAdapter) => SatelliteAdapter<C, W> | undefined;
|
|
92
|
+
/** Get wallet connectors */
|
|
93
|
+
getConnectors: () => Partial<Record<OrbitAdapter, C[]>>;
|
|
94
|
+
/** Initialize auto connect logic */
|
|
95
|
+
initializeAutoConnect: (autoConnect: boolean) => Promise<void>;
|
|
129
96
|
/** Connects to specified wallet */
|
|
130
97
|
connect: ({ walletType, chainId }: {
|
|
131
98
|
walletType: WalletType;
|
|
@@ -133,16 +100,20 @@ type ISatelliteConnectStore = {
|
|
|
133
100
|
}) => Promise<void>;
|
|
134
101
|
/** Disconnects active wallet */
|
|
135
102
|
disconnect: () => Promise<void>;
|
|
103
|
+
/** Disconnects all wallets, used for initialize application */
|
|
104
|
+
disconnectAll: () => Promise<void>;
|
|
136
105
|
/** Indicates ongoing connection attempt */
|
|
137
106
|
walletConnecting: boolean;
|
|
138
107
|
/** Contains error message if connection failed */
|
|
139
108
|
walletConnectionError?: string;
|
|
109
|
+
/** Sets error message if connection failed or form validation failed */
|
|
110
|
+
setWalletConnectionError: (error: string) => void;
|
|
140
111
|
/** Currently connected wallet */
|
|
141
|
-
activeWallet?: Wallet
|
|
112
|
+
activeWallet?: Wallet<W>;
|
|
142
113
|
/** Clears connection error state */
|
|
143
114
|
resetWalletConnectionError: () => void;
|
|
144
115
|
/** Updates active wallet properties */
|
|
145
|
-
updateActiveWallet: (wallet: Partial<Wallet
|
|
116
|
+
updateActiveWallet: (wallet: Partial<Wallet<W>>) => void;
|
|
146
117
|
/** Switches network for connected wallet */
|
|
147
118
|
switchNetwork: (chainId: string | number) => Promise<void>;
|
|
148
119
|
/** Contains error message if network switch failed */
|
|
@@ -153,13 +124,13 @@ type ISatelliteConnectStore = {
|
|
|
153
124
|
/**
|
|
154
125
|
* Callback type for successful wallet connections
|
|
155
126
|
*/
|
|
156
|
-
type WalletConnectedCallback = (wallet: Wallet) => void | Promise<void>;
|
|
127
|
+
type WalletConnectedCallback<W extends BaseWallet = BaseWallet> = (wallet: Wallet<W>) => void | Promise<void>;
|
|
157
128
|
/**
|
|
158
129
|
* Configuration parameters for initializing Satellite Connect store
|
|
159
130
|
*/
|
|
160
|
-
type SatelliteConnectStoreInitialParameters = OrbitGenericAdapter<SatelliteAdapter
|
|
131
|
+
type SatelliteConnectStoreInitialParameters<C, W extends BaseWallet = BaseWallet> = OrbitGenericAdapter<SatelliteAdapter<C, W>> & {
|
|
161
132
|
/** Optional callback executed after successful wallet connection */
|
|
162
|
-
callbackAfterConnected?: WalletConnectedCallback
|
|
133
|
+
callbackAfterConnected?: WalletConnectedCallback<W>;
|
|
163
134
|
};
|
|
164
135
|
|
|
165
136
|
/**
|
|
@@ -171,102 +142,6 @@ type SatelliteConnectStoreInitialParameters = OrbitGenericAdapter<SatelliteAdapt
|
|
|
171
142
|
*
|
|
172
143
|
* @returns A Zustand store instance with wallet connection state and methods
|
|
173
144
|
*/
|
|
174
|
-
declare function createSatelliteConnectStore({ adapter, callbackAfterConnected, }: SatelliteConnectStoreInitialParameters):
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* Extracts the adapter type from a wallet type string
|
|
178
|
-
*
|
|
179
|
-
* @example
|
|
180
|
-
* ```typescript
|
|
181
|
-
* // Returns OrbitAdapter.EVM
|
|
182
|
-
* getAdapterFromWalletType('evm:metamask');
|
|
183
|
-
*
|
|
184
|
-
* // Returns OrbitAdapter.SOLANA
|
|
185
|
-
* getAdapterFromWalletType('solana:phantom');
|
|
186
|
-
*
|
|
187
|
-
* // Returns OrbitAdapter.EVM (default)
|
|
188
|
-
* getAdapterFromWalletType('unknown');
|
|
189
|
-
* ```
|
|
190
|
-
*
|
|
191
|
-
* @param walletType - Wallet type in format "chain:wallet" (e.g. "evm:metamask", "solana:phantom")
|
|
192
|
-
* @returns The corresponding {@link OrbitAdapter} type or EVM as default
|
|
193
|
-
*
|
|
194
|
-
* @remarks
|
|
195
|
-
* The function splits the wallet type string by ":" and takes the first part as the adapter type.
|
|
196
|
-
* If the split fails or the first part is empty, it defaults to EVM adapter.
|
|
197
|
-
*/
|
|
198
|
-
declare function getAdapterFromWalletType(walletType: WalletType): OrbitAdapter;
|
|
199
|
-
|
|
200
|
-
/**
|
|
201
|
-
* Generates a standardized wallet type identifier from adapter type and connector name
|
|
202
|
-
*
|
|
203
|
-
* @example
|
|
204
|
-
* ```typescript
|
|
205
|
-
* // Returns "evm:metamask"
|
|
206
|
-
* getWalletTypeFromConnectorName(OrbitAdapter.EVM, "MetaMask");
|
|
207
|
-
*
|
|
208
|
-
* // Returns "solana:phantom"
|
|
209
|
-
* getWalletTypeFromConnectorName(OrbitAdapter.SOLANA, "Phantom");
|
|
210
|
-
*
|
|
211
|
-
* // Returns "evm:coinbasewallet" (removes spaces)
|
|
212
|
-
* getWalletTypeFromConnectorName(OrbitAdapter.EVM, "Coinbase Wallet");
|
|
213
|
-
* ```
|
|
214
|
-
*
|
|
215
|
-
* @param adapter - The blockchain adapter type (e.g. EVM, SOLANA)
|
|
216
|
-
* @param name - The wallet connector name (e.g. "MetaMask", "Phantom")
|
|
217
|
-
* @returns A formatted wallet type string in format "chain:wallet"
|
|
218
|
-
*
|
|
219
|
-
* @remarks
|
|
220
|
-
* The function:
|
|
221
|
-
* 1. Combines adapter type with connector name using ":" as separator
|
|
222
|
-
* 2. Removes all whitespace from connector name
|
|
223
|
-
* 3. Converts connector name to lowercase
|
|
224
|
-
* This ensures consistent wallet type identifiers across the application
|
|
225
|
-
*/
|
|
226
|
-
declare function getWalletTypeFromConnectorName(adapter: OrbitAdapter, name: string): string;
|
|
227
|
-
|
|
228
|
-
/**
|
|
229
|
-
* Helper utilities for managing impersonated wallet addresses
|
|
230
|
-
*
|
|
231
|
-
* @remarks
|
|
232
|
-
* These utilities are primarily used for development and testing purposes.
|
|
233
|
-
* They provide a way to simulate different wallet addresses without actually connecting a wallet.
|
|
234
|
-
* All data is stored in localStorage with the 'satellite-connect:impersonatedAddress' key.
|
|
235
|
-
* Functions are safe to use in both browser and SSR environments.
|
|
236
|
-
*/
|
|
237
|
-
declare const impersonatedHelpers: {
|
|
238
|
-
/**
|
|
239
|
-
* Currently impersonated address from localStorage
|
|
240
|
-
* Returns empty string if not set or in SSR context
|
|
241
|
-
*/
|
|
242
|
-
impersonatedAddress: string;
|
|
243
|
-
/**
|
|
244
|
-
* Stores an impersonated address in localStorage
|
|
245
|
-
*
|
|
246
|
-
* @example
|
|
247
|
-
* ```typescript
|
|
248
|
-
* // Set impersonated address
|
|
249
|
-
* impersonatedHelpers.setImpersonated('0x1234...5678');
|
|
250
|
-
* ```
|
|
251
|
-
*
|
|
252
|
-
* @param address - Ethereum or Solana address to impersonate
|
|
253
|
-
* @returns undefined in SSR context, void in browser
|
|
254
|
-
*/
|
|
255
|
-
setImpersonated: (address: string) => void;
|
|
256
|
-
/**
|
|
257
|
-
* Retrieves the current impersonated address from localStorage
|
|
258
|
-
*
|
|
259
|
-
* @example
|
|
260
|
-
* ```typescript
|
|
261
|
-
* // Get current impersonated address
|
|
262
|
-
* const address = impersonatedHelpers.getImpersonated();
|
|
263
|
-
* if (address) {
|
|
264
|
-
* console.log('Currently impersonating:', address);
|
|
265
|
-
* }
|
|
266
|
-
* ```
|
|
267
|
-
* @returns The impersonated address or undefined if not set or in SSR context
|
|
268
|
-
*/
|
|
269
|
-
getImpersonated: () => string | null | undefined;
|
|
270
|
-
};
|
|
145
|
+
declare function createSatelliteConnectStore<C, W extends BaseWallet = BaseWallet>({ adapter, callbackAfterConnected, }: SatelliteConnectStoreInitialParameters<C, W>): zustand_vanilla.StoreApi<ISatelliteConnectStore<C, W>>;
|
|
271
146
|
|
|
272
|
-
export { type BaseWallet, type
|
|
147
|
+
export { type BaseWallet, type ConnectorsInitProps, type ISatelliteConnectStore, type SatelliteAdapter, type SatelliteConnectStoreInitialParameters, type Wallet, type WalletConnectedCallback, createSatelliteConnectStore };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,6 @@
|
|
|
1
|
-
import * as
|
|
2
|
-
import { OrbitGenericAdapter, OrbitAdapter } from '@tuwaio/orbit-core';
|
|
3
|
-
import { Connector as Connector$1, CreateConnectorFn } from '@wagmi/core';
|
|
4
|
-
import { UiWallet, UiWalletAccount } from '@wallet-standard/ui';
|
|
1
|
+
import * as zustand_vanilla from 'zustand/vanilla';
|
|
2
|
+
import { WalletType, OrbitGenericAdapter, BaseAdapter, OrbitAdapter } from '@tuwaio/orbit-core';
|
|
5
3
|
|
|
6
|
-
/**
|
|
7
|
-
* Type representing a wallet identifier in format "chain:wallet"
|
|
8
|
-
* @example "evm:metamask" | "solana:phantom"
|
|
9
|
-
*/
|
|
10
|
-
type WalletType = `${OrbitAdapter}:${string}`;
|
|
11
4
|
/**
|
|
12
5
|
* Configuration properties for initializing wallet connectors
|
|
13
6
|
*/
|
|
@@ -26,8 +19,6 @@ type ConnectorsInitProps = {
|
|
|
26
19
|
appUrl?: string;
|
|
27
20
|
/** Array of icon URLs for WalletConnect */
|
|
28
21
|
appIcons?: string[];
|
|
29
|
-
/** Function to get impersonated account address for testing */
|
|
30
|
-
getImpersonatedAccount?: () => string | `0x${string}` | undefined;
|
|
31
22
|
};
|
|
32
23
|
/**
|
|
33
24
|
* Base interface for connected wallet information
|
|
@@ -45,87 +36,63 @@ interface BaseWallet {
|
|
|
45
36
|
isContractAddress: boolean;
|
|
46
37
|
/** Connection status */
|
|
47
38
|
isConnected: boolean;
|
|
39
|
+
/** Optional: wallet icon base64 string */
|
|
40
|
+
walletIcon?: string;
|
|
48
41
|
}
|
|
49
|
-
/**
|
|
50
|
-
|
|
51
|
-
*/
|
|
52
|
-
interface SolanaWallet extends BaseWallet {
|
|
53
|
-
/** Connected Wallet Standard account */
|
|
54
|
-
connectedAccount?: UiWalletAccount;
|
|
55
|
-
/** Connected Wallet Standard wallet instance */
|
|
56
|
-
connectedWallet?: UiWallet;
|
|
57
|
-
}
|
|
58
|
-
/** Union type for all supported wallet types */
|
|
59
|
-
type Wallet = BaseWallet | SolanaWallet;
|
|
60
|
-
/** EVM-specific connector type */
|
|
61
|
-
type ConnectorEVM = Connector$1<CreateConnectorFn>;
|
|
62
|
-
/** Solana-specific connector type */
|
|
63
|
-
type ConnectorSolana = UiWallet;
|
|
64
|
-
/** Union type for all supported connector types */
|
|
65
|
-
type Connector = ConnectorEVM | ConnectorSolana;
|
|
42
|
+
/** Generic type for all supported wallet types */
|
|
43
|
+
type Wallet<W extends BaseWallet> = BaseWallet | W;
|
|
66
44
|
/**
|
|
67
45
|
* Interface for blockchain network adapters
|
|
68
46
|
* @remarks
|
|
69
47
|
* Adapters provide chain-specific implementation for wallet interactions
|
|
70
48
|
*/
|
|
71
|
-
type SatelliteAdapter = {
|
|
49
|
+
type SatelliteAdapter<C, W extends BaseWallet = BaseWallet> = BaseAdapter & {
|
|
72
50
|
/** Unique identifier for the adapter */
|
|
73
51
|
key: OrbitAdapter;
|
|
74
52
|
/**
|
|
75
53
|
* Initiates wallet connection
|
|
76
54
|
* @returns Promise resolving to connected wallet instance
|
|
77
55
|
*/
|
|
78
|
-
connect: ({ walletType, chainId
|
|
56
|
+
connect: ({ walletType, chainId }: {
|
|
79
57
|
walletType: WalletType;
|
|
80
58
|
chainId: number | string;
|
|
81
|
-
|
|
82
|
-
}) => Promise<Wallet>;
|
|
59
|
+
}) => Promise<Wallet<W>>;
|
|
83
60
|
/** Disconnects current wallet session */
|
|
84
|
-
disconnect: () => Promise<void>;
|
|
61
|
+
disconnect: (activeWallet?: Wallet<W>) => Promise<void>;
|
|
85
62
|
/** Retrieves available wallet connectors for this adapter */
|
|
86
|
-
getConnectors: () =>
|
|
63
|
+
getConnectors: () => {
|
|
87
64
|
adapter: OrbitAdapter;
|
|
88
|
-
connectors:
|
|
89
|
-
}
|
|
65
|
+
connectors: C[];
|
|
66
|
+
};
|
|
90
67
|
/**
|
|
91
68
|
* Handles network switching for connected wallet
|
|
92
69
|
* @param chainId - Target chain ID
|
|
93
70
|
* @param currentChainId - Current chain ID
|
|
94
71
|
* @param updateActiveWallet - Callback to update wallet state
|
|
95
72
|
*/
|
|
96
|
-
checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number, updateActiveWallet?: (wallet: Partial<Wallet
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
getExplorerUrl: (url?: string, chainId?: string | number) => string | undefined;
|
|
102
|
-
/** Optional method to resolve ENS-like names */
|
|
103
|
-
getName?: (address: string) => Promise<string | null>;
|
|
104
|
-
/** Optional method to get avatar for resolved names */
|
|
105
|
-
getAvatar?: (name: string) => Promise<string | null>;
|
|
73
|
+
checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number, updateActiveWallet?: (wallet: Partial<Wallet<W>>) => void) => Promise<void>;
|
|
74
|
+
getBalance: (address: string, chainId: number | string) => Promise<{
|
|
75
|
+
value: string;
|
|
76
|
+
symbol: string;
|
|
77
|
+
}>;
|
|
106
78
|
/** Optional method to check if address is a smart contract */
|
|
107
79
|
checkIsContractWallet?: ({ address, chainId }: {
|
|
108
80
|
address: string;
|
|
109
81
|
chainId: string | number;
|
|
110
82
|
}) => Promise<boolean>;
|
|
83
|
+
/** Optional method to get a safe connector chainId for auto connect */
|
|
84
|
+
getSafeConnectorChainId?: () => Promise<number | undefined>;
|
|
111
85
|
};
|
|
112
86
|
/**
|
|
113
87
|
* Store interface for managing wallet connections
|
|
114
88
|
*/
|
|
115
|
-
type ISatelliteConnectStore = {
|
|
89
|
+
type ISatelliteConnectStore<C, W extends BaseWallet = BaseWallet> = {
|
|
116
90
|
/** Returns configured adapter(s) */
|
|
117
|
-
getAdapter: () => SatelliteAdapter |
|
|
118
|
-
/**
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
};
|
|
123
|
-
/** Available connectors mapped by adapter type */
|
|
124
|
-
availableConnectors: Partial<Record<OrbitAdapter, Connector[]>>;
|
|
125
|
-
/** Initializes wallet connectors */
|
|
126
|
-
initializeAppConnectors: ({ autoConnect }: {
|
|
127
|
-
autoConnect?: boolean;
|
|
128
|
-
}) => Promise<void>;
|
|
91
|
+
getAdapter: (adapterKey: OrbitAdapter) => SatelliteAdapter<C, W> | undefined;
|
|
92
|
+
/** Get wallet connectors */
|
|
93
|
+
getConnectors: () => Partial<Record<OrbitAdapter, C[]>>;
|
|
94
|
+
/** Initialize auto connect logic */
|
|
95
|
+
initializeAutoConnect: (autoConnect: boolean) => Promise<void>;
|
|
129
96
|
/** Connects to specified wallet */
|
|
130
97
|
connect: ({ walletType, chainId }: {
|
|
131
98
|
walletType: WalletType;
|
|
@@ -133,16 +100,20 @@ type ISatelliteConnectStore = {
|
|
|
133
100
|
}) => Promise<void>;
|
|
134
101
|
/** Disconnects active wallet */
|
|
135
102
|
disconnect: () => Promise<void>;
|
|
103
|
+
/** Disconnects all wallets, used for initialize application */
|
|
104
|
+
disconnectAll: () => Promise<void>;
|
|
136
105
|
/** Indicates ongoing connection attempt */
|
|
137
106
|
walletConnecting: boolean;
|
|
138
107
|
/** Contains error message if connection failed */
|
|
139
108
|
walletConnectionError?: string;
|
|
109
|
+
/** Sets error message if connection failed or form validation failed */
|
|
110
|
+
setWalletConnectionError: (error: string) => void;
|
|
140
111
|
/** Currently connected wallet */
|
|
141
|
-
activeWallet?: Wallet
|
|
112
|
+
activeWallet?: Wallet<W>;
|
|
142
113
|
/** Clears connection error state */
|
|
143
114
|
resetWalletConnectionError: () => void;
|
|
144
115
|
/** Updates active wallet properties */
|
|
145
|
-
updateActiveWallet: (wallet: Partial<Wallet
|
|
116
|
+
updateActiveWallet: (wallet: Partial<Wallet<W>>) => void;
|
|
146
117
|
/** Switches network for connected wallet */
|
|
147
118
|
switchNetwork: (chainId: string | number) => Promise<void>;
|
|
148
119
|
/** Contains error message if network switch failed */
|
|
@@ -153,13 +124,13 @@ type ISatelliteConnectStore = {
|
|
|
153
124
|
/**
|
|
154
125
|
* Callback type for successful wallet connections
|
|
155
126
|
*/
|
|
156
|
-
type WalletConnectedCallback = (wallet: Wallet) => void | Promise<void>;
|
|
127
|
+
type WalletConnectedCallback<W extends BaseWallet = BaseWallet> = (wallet: Wallet<W>) => void | Promise<void>;
|
|
157
128
|
/**
|
|
158
129
|
* Configuration parameters for initializing Satellite Connect store
|
|
159
130
|
*/
|
|
160
|
-
type SatelliteConnectStoreInitialParameters = OrbitGenericAdapter<SatelliteAdapter
|
|
131
|
+
type SatelliteConnectStoreInitialParameters<C, W extends BaseWallet = BaseWallet> = OrbitGenericAdapter<SatelliteAdapter<C, W>> & {
|
|
161
132
|
/** Optional callback executed after successful wallet connection */
|
|
162
|
-
callbackAfterConnected?: WalletConnectedCallback
|
|
133
|
+
callbackAfterConnected?: WalletConnectedCallback<W>;
|
|
163
134
|
};
|
|
164
135
|
|
|
165
136
|
/**
|
|
@@ -171,102 +142,6 @@ type SatelliteConnectStoreInitialParameters = OrbitGenericAdapter<SatelliteAdapt
|
|
|
171
142
|
*
|
|
172
143
|
* @returns A Zustand store instance with wallet connection state and methods
|
|
173
144
|
*/
|
|
174
|
-
declare function createSatelliteConnectStore({ adapter, callbackAfterConnected, }: SatelliteConnectStoreInitialParameters):
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* Extracts the adapter type from a wallet type string
|
|
178
|
-
*
|
|
179
|
-
* @example
|
|
180
|
-
* ```typescript
|
|
181
|
-
* // Returns OrbitAdapter.EVM
|
|
182
|
-
* getAdapterFromWalletType('evm:metamask');
|
|
183
|
-
*
|
|
184
|
-
* // Returns OrbitAdapter.SOLANA
|
|
185
|
-
* getAdapterFromWalletType('solana:phantom');
|
|
186
|
-
*
|
|
187
|
-
* // Returns OrbitAdapter.EVM (default)
|
|
188
|
-
* getAdapterFromWalletType('unknown');
|
|
189
|
-
* ```
|
|
190
|
-
*
|
|
191
|
-
* @param walletType - Wallet type in format "chain:wallet" (e.g. "evm:metamask", "solana:phantom")
|
|
192
|
-
* @returns The corresponding {@link OrbitAdapter} type or EVM as default
|
|
193
|
-
*
|
|
194
|
-
* @remarks
|
|
195
|
-
* The function splits the wallet type string by ":" and takes the first part as the adapter type.
|
|
196
|
-
* If the split fails or the first part is empty, it defaults to EVM adapter.
|
|
197
|
-
*/
|
|
198
|
-
declare function getAdapterFromWalletType(walletType: WalletType): OrbitAdapter;
|
|
199
|
-
|
|
200
|
-
/**
|
|
201
|
-
* Generates a standardized wallet type identifier from adapter type and connector name
|
|
202
|
-
*
|
|
203
|
-
* @example
|
|
204
|
-
* ```typescript
|
|
205
|
-
* // Returns "evm:metamask"
|
|
206
|
-
* getWalletTypeFromConnectorName(OrbitAdapter.EVM, "MetaMask");
|
|
207
|
-
*
|
|
208
|
-
* // Returns "solana:phantom"
|
|
209
|
-
* getWalletTypeFromConnectorName(OrbitAdapter.SOLANA, "Phantom");
|
|
210
|
-
*
|
|
211
|
-
* // Returns "evm:coinbasewallet" (removes spaces)
|
|
212
|
-
* getWalletTypeFromConnectorName(OrbitAdapter.EVM, "Coinbase Wallet");
|
|
213
|
-
* ```
|
|
214
|
-
*
|
|
215
|
-
* @param adapter - The blockchain adapter type (e.g. EVM, SOLANA)
|
|
216
|
-
* @param name - The wallet connector name (e.g. "MetaMask", "Phantom")
|
|
217
|
-
* @returns A formatted wallet type string in format "chain:wallet"
|
|
218
|
-
*
|
|
219
|
-
* @remarks
|
|
220
|
-
* The function:
|
|
221
|
-
* 1. Combines adapter type with connector name using ":" as separator
|
|
222
|
-
* 2. Removes all whitespace from connector name
|
|
223
|
-
* 3. Converts connector name to lowercase
|
|
224
|
-
* This ensures consistent wallet type identifiers across the application
|
|
225
|
-
*/
|
|
226
|
-
declare function getWalletTypeFromConnectorName(adapter: OrbitAdapter, name: string): string;
|
|
227
|
-
|
|
228
|
-
/**
|
|
229
|
-
* Helper utilities for managing impersonated wallet addresses
|
|
230
|
-
*
|
|
231
|
-
* @remarks
|
|
232
|
-
* These utilities are primarily used for development and testing purposes.
|
|
233
|
-
* They provide a way to simulate different wallet addresses without actually connecting a wallet.
|
|
234
|
-
* All data is stored in localStorage with the 'satellite-connect:impersonatedAddress' key.
|
|
235
|
-
* Functions are safe to use in both browser and SSR environments.
|
|
236
|
-
*/
|
|
237
|
-
declare const impersonatedHelpers: {
|
|
238
|
-
/**
|
|
239
|
-
* Currently impersonated address from localStorage
|
|
240
|
-
* Returns empty string if not set or in SSR context
|
|
241
|
-
*/
|
|
242
|
-
impersonatedAddress: string;
|
|
243
|
-
/**
|
|
244
|
-
* Stores an impersonated address in localStorage
|
|
245
|
-
*
|
|
246
|
-
* @example
|
|
247
|
-
* ```typescript
|
|
248
|
-
* // Set impersonated address
|
|
249
|
-
* impersonatedHelpers.setImpersonated('0x1234...5678');
|
|
250
|
-
* ```
|
|
251
|
-
*
|
|
252
|
-
* @param address - Ethereum or Solana address to impersonate
|
|
253
|
-
* @returns undefined in SSR context, void in browser
|
|
254
|
-
*/
|
|
255
|
-
setImpersonated: (address: string) => void;
|
|
256
|
-
/**
|
|
257
|
-
* Retrieves the current impersonated address from localStorage
|
|
258
|
-
*
|
|
259
|
-
* @example
|
|
260
|
-
* ```typescript
|
|
261
|
-
* // Get current impersonated address
|
|
262
|
-
* const address = impersonatedHelpers.getImpersonated();
|
|
263
|
-
* if (address) {
|
|
264
|
-
* console.log('Currently impersonating:', address);
|
|
265
|
-
* }
|
|
266
|
-
* ```
|
|
267
|
-
* @returns The impersonated address or undefined if not set or in SSR context
|
|
268
|
-
*/
|
|
269
|
-
getImpersonated: () => string | null | undefined;
|
|
270
|
-
};
|
|
145
|
+
declare function createSatelliteConnectStore<C, W extends BaseWallet = BaseWallet>({ adapter, callbackAfterConnected, }: SatelliteConnectStoreInitialParameters<C, W>): zustand_vanilla.StoreApi<ISatelliteConnectStore<C, W>>;
|
|
271
146
|
|
|
272
|
-
export { type BaseWallet, type
|
|
147
|
+
export { type BaseWallet, type ConnectorsInitProps, type ISatelliteConnectStore, type SatelliteAdapter, type SatelliteConnectStoreInitialParameters, type Wallet, type WalletConnectedCallback, 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 I({adapter:o,callbackAfterConnected:f}){return vanilla.createStore()((r,n)=>({getAdapter:e=>orbitCore.selectAdapterByKey({adapter:o,adapterKey:e}),getConnectors:()=>{let e;return Array.isArray(o)?e=o.map(t=>t.getConnectors()):e=[o.getConnectors()],e.reduce((t,a)=>{let l=a.adapter,i=a.connectors;return {...t,[l]:i}},{})},initializeAutoConnect:async e=>{if(e){let t=orbitCore.lastConnectedWalletHelpers.getLastConnectedWallet();t&&!["impersonatedwallet","walletconnect","coinbasewallet","bitgetwallet"].includes(t.walletType.split(":")[1])&&(await orbitCore.delay(null,200),await n().connect({walletType:t.walletType,chainId:t.chainId}));}else if(orbitCore.isSafeApp){await orbitCore.delay(null,200);let t=n().getAdapter(orbitCore.OrbitAdapter.EVM);if(t&&t.getSafeConnectorChainId){let a=await t.getSafeConnectorChainId();a&&await n().connect({walletType:`${orbitCore.OrbitAdapter.EVM}:safewallet`,chainId:a});}}},walletConnecting:false,walletConnectionError:void 0,switchNetworkError:void 0,activeWallet:void 0,setWalletConnectionError:e=>r({walletConnectionError:e}),connect:async({walletType:e,chainId:t})=>{r({walletConnecting:true,walletConnectionError:void 0});let a=n().getAdapter(orbitCore.getAdapterFromWalletType(e));if(!a){r({walletConnecting:false,walletConnectionError:`No adapter found for wallet type: ${e}`});return}try{n().activeWallet?.isConnected&&await n().disconnectAll();let l=await a.connect({walletType:e,chainId:t});if(r({activeWallet:l}),a.checkIsContractWallet){let i=await a.checkIsContractWallet({address:l.address,chainId:t});n().updateActiveWallet({isContractAddress:i});}if(f){let i=n().activeWallet;i&&await f(i);}r({walletConnecting:!1}),orbitCore.lastConnectedWalletHelpers.setLastConnectedWallet({walletType:e,chainId:t,address:n().activeWallet?.address}),orbitCore.recentConnectedWalletHelpers.setRecentConnectedWallet({[orbitCore.getAdapterFromWalletType(e)]:{[e.split(":")[1]]:!0}});}catch(l){await n().disconnectAll(),orbitCore.lastConnectedWalletHelpers.removeLastConnectedWallet(),r({walletConnecting:false,walletConnectionError:"Wallet connection failed: "+(l instanceof Error?l.message:String(l))});}},disconnect:async()=>{let e=n().activeWallet;e&&(r({activeWallet:void 0,walletConnectionError:void 0,switchNetworkError:void 0}),orbitCore.lastConnectedWalletHelpers.removeLastConnectedWallet(),orbitCore.impersonatedHelpers.removeImpersonated(),await n().getAdapter(orbitCore.getAdapterFromWalletType(e.walletType))?.disconnect(e));},disconnectAll:async()=>{if(await orbitCore.delay(null,150),Array.isArray(o))await Promise.allSettled(o.map(async e=>{try{await e.disconnect();}catch{}}));else try{await o.disconnect();}catch{}r({activeWallet:void 0,walletConnectionError:void 0,switchNetworkError:void 0}),orbitCore.impersonatedHelpers.removeImpersonated();},resetWalletConnectionError:()=>{r({walletConnectionError:void 0});},updateActiveWallet:e=>{let t=n().activeWallet;t?(e.chainId&&orbitCore.lastConnectedWalletHelpers.setLastConnectedWallet({walletType:e.walletType??t.walletType,chainId:e.chainId??t.chainId,address:e.address??t.address}),r(a=>immer.produce(a,l=>{l.activeWallet&&(l.activeWallet={...l.activeWallet,...e});}))):e.walletType!==void 0&&e.chainId!==void 0&&e.address!==void 0?(orbitCore.lastConnectedWalletHelpers.setLastConnectedWallet({walletType:e.walletType,chainId:e.chainId,address:e.address}),r({activeWallet:e})):console.warn("Attempted to set activeWallet with incomplete data while activeWallet was undefined.");},switchNetwork:async e=>{r({switchNetworkError:void 0});let t=n().activeWallet;if(t){let a=n().getAdapter(orbitCore.getAdapterFromWalletType(t.walletType));if(!a){r({switchNetworkError:`No adapter found for active wallet type: ${t.walletType}`});return}try{await a.checkAndSwitchNetwork(e,t.chainId,n().updateActiveWallet);}catch(l){r({switchNetworkError:"Switch network failed: "+(l instanceof Error?l.message:String(l))});}}},resetSwitchNetworkError:()=>r({switchNetworkError:void 0})}))}exports.createSatelliteConnectStore=I;//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/getAdapterFromWalletType.ts","../src/store/satelliteConnectStore.ts","../src/utils/getWalletTypeFromConnectorName.ts","../src/utils/impersonatedHelpers.ts"],"names":["getAdapterFromWalletType","walletType","OrbitAdapter","createSatelliteConnectStore","adapter","callbackAfterConnected","createStore","set","get","autoConnect","a","connectors","state","produce","draft","lastConnectedWallet","chainId","foundAdapter","selectAdapterByKey","wallet","activeWallet","getWalletTypeFromConnectorName","name","impersonatedHelpers","address"],"mappings":"mHA0BO,SAASA,CAAAA,CAAyBC,CAAAA,CAAsC,CAC7E,OAAQA,CAAAA,CAAW,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,CAAA,EAAKC,sBAAAA,C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ACnG,CAAA,MAAS,CAAA,CAAG,CACVD,CAAAA,CAAI,CAAE,kBAAA,CAAoB,yBAAA,EAA6B,CAAA,YAAa,KAAA,CAAQ,CAAA,CAAE,OAAA,CAAU,OAAO,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,CAAA,CAKA,uBAAA,CAAyB,IAAMA,CAAAA,CAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CACtE,CAAA,CAAE,CACJ,CC7IO,SAASc,CAAAA,CAA+BjB,CAAAA,CAAuBkB,CAAAA,CAAsB,CAC1F,OAAO,CAAA,EAAGlB,CAAO,CAAA,CAAA,EAAIkB,CAAAA,CAAK,OAAA,CAAQ,OAAQ,EAAE,CAAA,CAAE,WAAA,EAAa,CAAA,CAC7D,CCrBO,IAAMC,CAAAA,CAAsB,CAKjC,mBAAA,CACE,OAAO,MAAA,CAAW,GAAA,CAAe,MAAA,CAAO,aAAa,OAAA,CAAQ,uCAAuC,CAAA,EAAK,EAAA,CAAM,EAAA,CAcjH,eAAA,CAAkBC,CAAAA,EAChB,OAAO,MAAA,CAAW,GAAA,CACd,MAAA,CAAO,YAAA,CAAa,OAAA,CAAQ,uCAAA,CAAyCA,CAAO,CAAA,CAC5E,MAAA,CAeN,eAAA,CAAiB,IACf,OAAO,MAAA,CAAW,GAAA,CAAc,MAAA,CAAO,YAAA,CAAa,OAAA,CAAQ,uCAAuC,CAAA,CAAI,MAC3G","file":"index.js","sourcesContent":["import { OrbitAdapter } from '@tuwaio/orbit-core';\n\nimport { WalletType } from '../types';\n\n/**\n * Extracts the adapter type from a wallet type string\n *\n * @example\n * ```typescript\n * // Returns OrbitAdapter.EVM\n * getAdapterFromWalletType('evm:metamask');\n *\n * // Returns OrbitAdapter.SOLANA\n * getAdapterFromWalletType('solana:phantom');\n *\n * // Returns OrbitAdapter.EVM (default)\n * getAdapterFromWalletType('unknown');\n * ```\n *\n * @param walletType - Wallet type in format \"chain:wallet\" (e.g. \"evm:metamask\", \"solana:phantom\")\n * @returns The corresponding {@link OrbitAdapter} type or EVM as default\n *\n * @remarks\n * The function splits the wallet type string by \":\" and takes the first part as the adapter type.\n * If the split fails or the first part is empty, it defaults to EVM adapter.\n */\nexport function getAdapterFromWalletType(walletType: WalletType): OrbitAdapter {\n return (walletType.split(':')[0] ?? OrbitAdapter.EVM) as OrbitAdapter;\n}\n","import { selectAdapterByKey } from '@tuwaio/orbit-core';\nimport { Draft, produce } from 'immer';\nimport { createStore } from 'zustand/vanilla';\n\nimport { Connector, ISatelliteConnectStore, SatelliteConnectStoreInitialParameters, Wallet } from '../types';\nimport { getAdapterFromWalletType } from '../utils/getAdapterFromWalletType';\n\n/**\n * Creates a Satellite Connect store instance for managing wallet connections and state\n *\n * @param params - Configuration parameters for the store\n * @param params.adapter - Single adapter or array of adapters for different chains\n * @param params.callbackAfterConnected - Optional callback function called after successful wallet connection\n *\n * @returns A Zustand store instance with wallet connection state and methods\n */\nexport function createSatelliteConnectStore({\n adapter,\n callbackAfterConnected,\n}: SatelliteConnectStoreInitialParameters) {\n return createStore<ISatelliteConnectStore>()((set, get) => ({\n /**\n * Returns configured adapter(s)\n */\n getAdapter: () => adapter,\n\n /**\n * Available wallet connectors for each chain\n */\n availableConnectors: {},\n\n /**\n * Initializes wallet connectors for all configured adapters\n * @param autoConnect - Whether to automatically reconnect to last used wallet\n */\n initializeAppConnectors: async ({ autoConnect }) => {\n if (Array.isArray(adapter)) {\n const connectors = await Promise.all(adapter.map((a) => a.getConnectors()));\n connectors.forEach((connectors) => {\n set((state) =>\n produce(state, (draft) => {\n draft.availableConnectors[connectors.adapter] = connectors.connectors as Draft<Connector[]>;\n }),\n );\n });\n } else {\n const connectors = await adapter.getConnectors();\n set((state) =>\n produce(state, (draft) => {\n draft.availableConnectors[connectors.adapter] = connectors.connectors as Draft<Connector[]>;\n }),\n );\n }\n if (autoConnect) {\n const lastConnectedWallet = get().lastConnectedWallet;\n if (lastConnectedWallet) {\n await get().connect({ walletType: lastConnectedWallet.walletType, chainId: lastConnectedWallet.chainId });\n }\n }\n },\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 = selectAdapterByKey({ adapter, adapterKey: getAdapterFromWalletType(walletType) });\n try {\n const wallet = await foundAdapter?.connect({\n walletType,\n chainId,\n connectors: get().availableConnectors[getAdapterFromWalletType(walletType)] ?? [],\n });\n set({ activeWallet: wallet });\n if (foundAdapter?.checkIsContractWallet && wallet) {\n get().updateActiveWallet({\n isContractAddress: await foundAdapter.checkIsContractWallet({\n address: wallet.address,\n chainId,\n }),\n });\n if (callbackAfterConnected) {\n await callbackAfterConnected(wallet);\n }\n }\n set({ walletConnecting: false, lastConnectedWallet: { walletType, chainId } });\n } catch (e) {\n set({\n walletConnecting: false,\n walletConnectionError: 'Wallet connection failed: ' + (e instanceof Error ? e.message : String(e)),\n });\n }\n },\n\n /**\n * Disconnects the currently active wallet\n */\n disconnect: async () => {\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n const foundAdapter = selectAdapterByKey({\n adapter,\n adapterKey: getAdapterFromWalletType(activeWallet.walletType),\n });\n await foundAdapter?.disconnect();\n set({ activeWallet: undefined, lastConnectedWallet: undefined });\n }\n },\n\n walletConnecting: false,\n\n /**\n * Resets any wallet connection errors\n */\n resetWalletConnectionError: () => {\n set({ walletConnectionError: undefined });\n },\n\n /**\n * Updates the active wallet's properties\n * @param wallet - Partial wallet object with properties to update\n */\n updateActiveWallet: (wallet: Partial<Wallet>) => {\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n set((state) =>\n produce(state, (draft) => {\n if (draft.activeWallet) {\n draft.activeWallet = {\n ...draft.activeWallet,\n ...wallet,\n };\n }\n }),\n );\n } else {\n if (wallet.walletType !== undefined && wallet.chainId !== undefined && wallet.address !== undefined) {\n set({ activeWallet: wallet as Wallet });\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 = selectAdapterByKey({\n adapter,\n adapterKey: getAdapterFromWalletType(activeWallet.walletType),\n });\n try {\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 * Resets any network switching errors\n */\n resetSwitchNetworkError: () => set({ switchNetworkError: undefined }),\n }));\n}\n","import { OrbitAdapter } from '@tuwaio/orbit-core';\n\n/**\n * Generates a standardized wallet type identifier from adapter type and connector name\n *\n * @example\n * ```typescript\n * // Returns \"evm:metamask\"\n * getWalletTypeFromConnectorName(OrbitAdapter.EVM, \"MetaMask\");\n *\n * // Returns \"solana:phantom\"\n * getWalletTypeFromConnectorName(OrbitAdapter.SOLANA, \"Phantom\");\n *\n * // Returns \"evm:coinbasewallet\" (removes spaces)\n * getWalletTypeFromConnectorName(OrbitAdapter.EVM, \"Coinbase Wallet\");\n * ```\n *\n * @param adapter - The blockchain adapter type (e.g. EVM, SOLANA)\n * @param name - The wallet connector name (e.g. \"MetaMask\", \"Phantom\")\n * @returns A formatted wallet type string in format \"chain:wallet\"\n *\n * @remarks\n * The function:\n * 1. Combines adapter type with connector name using \":\" as separator\n * 2. Removes all whitespace from connector name\n * 3. Converts connector name to lowercase\n * This ensures consistent wallet type identifiers across the application\n */\nexport function getWalletTypeFromConnectorName(adapter: OrbitAdapter, name: string): string {\n return `${adapter}:${name.replace(/\\s+/g, '').toLowerCase()}`;\n}\n","/**\n * Helper utilities for managing impersonated wallet addresses\n *\n * @remarks\n * These utilities are primarily used for development and testing purposes.\n * They provide a way to simulate different wallet addresses without actually connecting a wallet.\n * All data is stored in localStorage with the 'satellite-connect:impersonatedAddress' key.\n * Functions are safe to use in both browser and SSR environments.\n */\nexport const impersonatedHelpers = {\n /**\n * Currently impersonated address from localStorage\n * Returns empty string if not set or in SSR context\n */\n impersonatedAddress:\n typeof window !== 'undefined' ? (window.localStorage.getItem('satellite-connect:impersonatedAddress') ?? '') : '',\n\n /**\n * Stores an impersonated address in localStorage\n *\n * @example\n * ```typescript\n * // Set impersonated address\n * impersonatedHelpers.setImpersonated('0x1234...5678');\n * ```\n *\n * @param address - Ethereum or Solana address to impersonate\n * @returns undefined in SSR context, void in browser\n */\n setImpersonated: (address: string) =>\n typeof window !== 'undefined'\n ? window.localStorage.setItem('satellite-connect:impersonatedAddress', address)\n : undefined,\n\n /**\n * Retrieves the current impersonated address from localStorage\n *\n * @example\n * ```typescript\n * // Get current impersonated address\n * const address = impersonatedHelpers.getImpersonated();\n * if (address) {\n * console.log('Currently impersonating:', address);\n * }\n * ```\n * @returns The impersonated address or undefined if not set or in SSR context\n */\n getImpersonated: () =>\n typeof window !== 'undefined' ? window.localStorage.getItem('satellite-connect:impersonatedAddress') : undefined,\n};\n"]}
|
|
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,CAC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CAAA,CACDtB,CAAAA,CAAI,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"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {OrbitAdapter
|
|
1
|
+
import {selectAdapterByKey,getAdapterFromWalletType,lastConnectedWalletHelpers,delay,impersonatedHelpers,recentConnectedWalletHelpers,isSafeApp,OrbitAdapter}from'@tuwaio/orbit-core';import {produce}from'immer';import {createStore}from'zustand/vanilla';function I({adapter:o,callbackAfterConnected:f}){return createStore()((r,n)=>({getAdapter:e=>selectAdapterByKey({adapter:o,adapterKey:e}),getConnectors:()=>{let e;return Array.isArray(o)?e=o.map(t=>t.getConnectors()):e=[o.getConnectors()],e.reduce((t,a)=>{let l=a.adapter,i=a.connectors;return {...t,[l]:i}},{})},initializeAutoConnect:async e=>{if(e){let t=lastConnectedWalletHelpers.getLastConnectedWallet();t&&!["impersonatedwallet","walletconnect","coinbasewallet","bitgetwallet"].includes(t.walletType.split(":")[1])&&(await delay(null,200),await n().connect({walletType:t.walletType,chainId:t.chainId}));}else if(isSafeApp){await delay(null,200);let t=n().getAdapter(OrbitAdapter.EVM);if(t&&t.getSafeConnectorChainId){let a=await t.getSafeConnectorChainId();a&&await n().connect({walletType:`${OrbitAdapter.EVM}:safewallet`,chainId:a});}}},walletConnecting:false,walletConnectionError:void 0,switchNetworkError:void 0,activeWallet:void 0,setWalletConnectionError:e=>r({walletConnectionError:e}),connect:async({walletType:e,chainId:t})=>{r({walletConnecting:true,walletConnectionError:void 0});let a=n().getAdapter(getAdapterFromWalletType(e));if(!a){r({walletConnecting:false,walletConnectionError:`No adapter found for wallet type: ${e}`});return}try{n().activeWallet?.isConnected&&await n().disconnectAll();let l=await a.connect({walletType:e,chainId:t});if(r({activeWallet:l}),a.checkIsContractWallet){let i=await a.checkIsContractWallet({address:l.address,chainId:t});n().updateActiveWallet({isContractAddress:i});}if(f){let i=n().activeWallet;i&&await f(i);}r({walletConnecting:!1}),lastConnectedWalletHelpers.setLastConnectedWallet({walletType:e,chainId:t,address:n().activeWallet?.address}),recentConnectedWalletHelpers.setRecentConnectedWallet({[getAdapterFromWalletType(e)]:{[e.split(":")[1]]:!0}});}catch(l){await n().disconnectAll(),lastConnectedWalletHelpers.removeLastConnectedWallet(),r({walletConnecting:false,walletConnectionError:"Wallet connection failed: "+(l instanceof Error?l.message:String(l))});}},disconnect:async()=>{let e=n().activeWallet;e&&(r({activeWallet:void 0,walletConnectionError:void 0,switchNetworkError:void 0}),lastConnectedWalletHelpers.removeLastConnectedWallet(),impersonatedHelpers.removeImpersonated(),await n().getAdapter(getAdapterFromWalletType(e.walletType))?.disconnect(e));},disconnectAll:async()=>{if(await delay(null,150),Array.isArray(o))await Promise.allSettled(o.map(async e=>{try{await e.disconnect();}catch{}}));else try{await o.disconnect();}catch{}r({activeWallet:void 0,walletConnectionError:void 0,switchNetworkError:void 0}),impersonatedHelpers.removeImpersonated();},resetWalletConnectionError:()=>{r({walletConnectionError:void 0});},updateActiveWallet:e=>{let t=n().activeWallet;t?(e.chainId&&lastConnectedWalletHelpers.setLastConnectedWallet({walletType:e.walletType??t.walletType,chainId:e.chainId??t.chainId,address:e.address??t.address}),r(a=>produce(a,l=>{l.activeWallet&&(l.activeWallet={...l.activeWallet,...e});}))):e.walletType!==void 0&&e.chainId!==void 0&&e.address!==void 0?(lastConnectedWalletHelpers.setLastConnectedWallet({walletType:e.walletType,chainId:e.chainId,address:e.address}),r({activeWallet:e})):console.warn("Attempted to set activeWallet with incomplete data while activeWallet was undefined.");},switchNetwork:async e=>{r({switchNetworkError:void 0});let t=n().activeWallet;if(t){let a=n().getAdapter(getAdapterFromWalletType(t.walletType));if(!a){r({switchNetworkError:`No adapter found for active wallet type: ${t.walletType}`});return}try{await a.checkAndSwitchNetwork(e,t.chainId,n().updateActiveWallet);}catch(l){r({switchNetworkError:"Switch network failed: "+(l instanceof Error?l.message:String(l))});}}},resetSwitchNetworkError:()=>r({switchNetworkError:void 0})}))}export{I 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/utils/getAdapterFromWalletType.ts","../src/store/satelliteConnectStore.ts","../src/utils/getWalletTypeFromConnectorName.ts","../src/utils/impersonatedHelpers.ts"],"names":["getAdapterFromWalletType","walletType","OrbitAdapter","createSatelliteConnectStore","adapter","callbackAfterConnected","createStore","set","get","autoConnect","a","connectors","state","produce","draft","lastConnectedWallet","chainId","foundAdapter","selectAdapterByKey","wallet","activeWallet","getWalletTypeFromConnectorName","name","impersonatedHelpers","address"],"mappings":"uIA0BO,SAASA,CAAAA,CAAyBC,CAAAA,CAAsC,CAC7E,OAAQA,CAAAA,CAAW,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,CAAA,EAAKC,YAAAA,CAAa,GACnD,CCZO,SAASC,CAAAA,CAA4B,CAC1C,OAAA,CAAAC,CAAAA,CACA,sBAAA,CAAAC,CACF,CAA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,KAAA,CAAQ,CAAA,CAAE,OAAA,CAAU,OAAO,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,CAAA,CAKA,uBAAA,CAAyB,IAAMA,CAAAA,CAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CACtE,CAAA,CAAE,CACJ,CC7IO,SAASc,CAAAA,CAA+BjB,CAAAA,CAAuBkB,CAAAA,CAAsB,CAC1F,OAAO,CAAA,EAAGlB,CAAO,CAAA,CAAA,EAAIkB,CAAAA,CAAK,OAAA,CAAQ,OAAQ,EAAE,CAAA,CAAE,WAAA,EAAa,CAAA,CAC7D,CCrBO,IAAMC,CAAAA,CAAsB,CAKjC,mBAAA,CACE,OAAO,MAAA,CAAW,GAAA,CAAe,MAAA,CAAO,aAAa,OAAA,CAAQ,uCAAuC,CAAA,EAAK,EAAA,CAAM,EAAA,CAcjH,eAAA,CAAkBC,CAAAA,EAChB,OAAO,MAAA,CAAW,GAAA,CACd,MAAA,CAAO,YAAA,CAAa,OAAA,CAAQ,uCAAA,CAAyCA,CAAO,CAAA,CAC5E,MAAA,CAeN,eAAA,CAAiB,IACf,OAAO,MAAA,CAAW,GAAA,CAAc,MAAA,CAAO,YAAA,CAAa,OAAA,CAAQ,uCAAuC,CAAA,CAAI,MAC3G","file":"index.mjs","sourcesContent":["import { OrbitAdapter } from '@tuwaio/orbit-core';\n\nimport { WalletType } from '../types';\n\n/**\n * Extracts the adapter type from a wallet type string\n *\n * @example\n * ```typescript\n * // Returns OrbitAdapter.EVM\n * getAdapterFromWalletType('evm:metamask');\n *\n * // Returns OrbitAdapter.SOLANA\n * getAdapterFromWalletType('solana:phantom');\n *\n * // Returns OrbitAdapter.EVM (default)\n * getAdapterFromWalletType('unknown');\n * ```\n *\n * @param walletType - Wallet type in format \"chain:wallet\" (e.g. \"evm:metamask\", \"solana:phantom\")\n * @returns The corresponding {@link OrbitAdapter} type or EVM as default\n *\n * @remarks\n * The function splits the wallet type string by \":\" and takes the first part as the adapter type.\n * If the split fails or the first part is empty, it defaults to EVM adapter.\n */\nexport function getAdapterFromWalletType(walletType: WalletType): OrbitAdapter {\n return (walletType.split(':')[0] ?? OrbitAdapter.EVM) as OrbitAdapter;\n}\n","import { selectAdapterByKey } from '@tuwaio/orbit-core';\nimport { Draft, produce } from 'immer';\nimport { createStore } from 'zustand/vanilla';\n\nimport { Connector, ISatelliteConnectStore, SatelliteConnectStoreInitialParameters, Wallet } from '../types';\nimport { getAdapterFromWalletType } from '../utils/getAdapterFromWalletType';\n\n/**\n * Creates a Satellite Connect store instance for managing wallet connections and state\n *\n * @param params - Configuration parameters for the store\n * @param params.adapter - Single adapter or array of adapters for different chains\n * @param params.callbackAfterConnected - Optional callback function called after successful wallet connection\n *\n * @returns A Zustand store instance with wallet connection state and methods\n */\nexport function createSatelliteConnectStore({\n adapter,\n callbackAfterConnected,\n}: SatelliteConnectStoreInitialParameters) {\n return createStore<ISatelliteConnectStore>()((set, get) => ({\n /**\n * Returns configured adapter(s)\n */\n getAdapter: () => adapter,\n\n /**\n * Available wallet connectors for each chain\n */\n availableConnectors: {},\n\n /**\n * Initializes wallet connectors for all configured adapters\n * @param autoConnect - Whether to automatically reconnect to last used wallet\n */\n initializeAppConnectors: async ({ autoConnect }) => {\n if (Array.isArray(adapter)) {\n const connectors = await Promise.all(adapter.map((a) => a.getConnectors()));\n connectors.forEach((connectors) => {\n set((state) =>\n produce(state, (draft) => {\n draft.availableConnectors[connectors.adapter] = connectors.connectors as Draft<Connector[]>;\n }),\n );\n });\n } else {\n const connectors = await adapter.getConnectors();\n set((state) =>\n produce(state, (draft) => {\n draft.availableConnectors[connectors.adapter] = connectors.connectors as Draft<Connector[]>;\n }),\n );\n }\n if (autoConnect) {\n const lastConnectedWallet = get().lastConnectedWallet;\n if (lastConnectedWallet) {\n await get().connect({ walletType: lastConnectedWallet.walletType, chainId: lastConnectedWallet.chainId });\n }\n }\n },\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 = selectAdapterByKey({ adapter, adapterKey: getAdapterFromWalletType(walletType) });\n try {\n const wallet = await foundAdapter?.connect({\n walletType,\n chainId,\n connectors: get().availableConnectors[getAdapterFromWalletType(walletType)] ?? [],\n });\n set({ activeWallet: wallet });\n if (foundAdapter?.checkIsContractWallet && wallet) {\n get().updateActiveWallet({\n isContractAddress: await foundAdapter.checkIsContractWallet({\n address: wallet.address,\n chainId,\n }),\n });\n if (callbackAfterConnected) {\n await callbackAfterConnected(wallet);\n }\n }\n set({ walletConnecting: false, lastConnectedWallet: { walletType, chainId } });\n } catch (e) {\n set({\n walletConnecting: false,\n walletConnectionError: 'Wallet connection failed: ' + (e instanceof Error ? e.message : String(e)),\n });\n }\n },\n\n /**\n * Disconnects the currently active wallet\n */\n disconnect: async () => {\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n const foundAdapter = selectAdapterByKey({\n adapter,\n adapterKey: getAdapterFromWalletType(activeWallet.walletType),\n });\n await foundAdapter?.disconnect();\n set({ activeWallet: undefined, lastConnectedWallet: undefined });\n }\n },\n\n walletConnecting: false,\n\n /**\n * Resets any wallet connection errors\n */\n resetWalletConnectionError: () => {\n set({ walletConnectionError: undefined });\n },\n\n /**\n * Updates the active wallet's properties\n * @param wallet - Partial wallet object with properties to update\n */\n updateActiveWallet: (wallet: Partial<Wallet>) => {\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n set((state) =>\n produce(state, (draft) => {\n if (draft.activeWallet) {\n draft.activeWallet = {\n ...draft.activeWallet,\n ...wallet,\n };\n }\n }),\n );\n } else {\n if (wallet.walletType !== undefined && wallet.chainId !== undefined && wallet.address !== undefined) {\n set({ activeWallet: wallet as Wallet });\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 = selectAdapterByKey({\n adapter,\n adapterKey: getAdapterFromWalletType(activeWallet.walletType),\n });\n try {\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 * Resets any network switching errors\n */\n resetSwitchNetworkError: () => set({ switchNetworkError: undefined }),\n }));\n}\n","import { OrbitAdapter } from '@tuwaio/orbit-core';\n\n/**\n * Generates a standardized wallet type identifier from adapter type and connector name\n *\n * @example\n * ```typescript\n * // Returns \"evm:metamask\"\n * getWalletTypeFromConnectorName(OrbitAdapter.EVM, \"MetaMask\");\n *\n * // Returns \"solana:phantom\"\n * getWalletTypeFromConnectorName(OrbitAdapter.SOLANA, \"Phantom\");\n *\n * // Returns \"evm:coinbasewallet\" (removes spaces)\n * getWalletTypeFromConnectorName(OrbitAdapter.EVM, \"Coinbase Wallet\");\n * ```\n *\n * @param adapter - The blockchain adapter type (e.g. EVM, SOLANA)\n * @param name - The wallet connector name (e.g. \"MetaMask\", \"Phantom\")\n * @returns A formatted wallet type string in format \"chain:wallet\"\n *\n * @remarks\n * The function:\n * 1. Combines adapter type with connector name using \":\" as separator\n * 2. Removes all whitespace from connector name\n * 3. Converts connector name to lowercase\n * This ensures consistent wallet type identifiers across the application\n */\nexport function getWalletTypeFromConnectorName(adapter: OrbitAdapter, name: string): string {\n return `${adapter}:${name.replace(/\\s+/g, '').toLowerCase()}`;\n}\n","/**\n * Helper utilities for managing impersonated wallet addresses\n *\n * @remarks\n * These utilities are primarily used for development and testing purposes.\n * They provide a way to simulate different wallet addresses without actually connecting a wallet.\n * All data is stored in localStorage with the 'satellite-connect:impersonatedAddress' key.\n * Functions are safe to use in both browser and SSR environments.\n */\nexport const impersonatedHelpers = {\n /**\n * Currently impersonated address from localStorage\n * Returns empty string if not set or in SSR context\n */\n impersonatedAddress:\n typeof window !== 'undefined' ? (window.localStorage.getItem('satellite-connect:impersonatedAddress') ?? '') : '',\n\n /**\n * Stores an impersonated address in localStorage\n *\n * @example\n * ```typescript\n * // Set impersonated address\n * impersonatedHelpers.setImpersonated('0x1234...5678');\n * ```\n *\n * @param address - Ethereum or Solana address to impersonate\n * @returns undefined in SSR context, void in browser\n */\n setImpersonated: (address: string) =>\n typeof window !== 'undefined'\n ? window.localStorage.setItem('satellite-connect:impersonatedAddress', address)\n : undefined,\n\n /**\n * Retrieves the current impersonated address from localStorage\n *\n * @example\n * ```typescript\n * // Get current impersonated address\n * const address = impersonatedHelpers.getImpersonated();\n * if (address) {\n * console.log('Currently impersonating:', address);\n * }\n * ```\n * @returns The impersonated address or undefined if not set or in SSR context\n */\n getImpersonated: () =>\n typeof window !== 'undefined' ? window.localStorage.getItem('satellite-connect:impersonatedAddress') : undefined,\n};\n"]}
|
|
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,G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sF,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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tuwaio/satellite-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"author": "Oleksandr Tkach",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -40,20 +40,16 @@
|
|
|
40
40
|
}
|
|
41
41
|
],
|
|
42
42
|
"peerDependencies": {
|
|
43
|
-
"@
|
|
44
|
-
"
|
|
45
|
-
"
|
|
46
|
-
"immer": ">=10",
|
|
47
|
-
"zustand": ">=5"
|
|
43
|
+
"@tuwaio/orbit-core": ">=0.1",
|
|
44
|
+
"immer": "10.x.x",
|
|
45
|
+
"zustand": "5.x.x"
|
|
48
46
|
},
|
|
49
47
|
"devDependencies": {
|
|
50
|
-
"@
|
|
51
|
-
"@wallet-standard/ui": "^1.0.1",
|
|
48
|
+
"@tuwaio/orbit-core": "^0.1.1",
|
|
52
49
|
"immer": "^10.1.3",
|
|
53
50
|
"tsup": "^8.5.0",
|
|
54
|
-
"typescript": "^5.9.
|
|
55
|
-
"zustand": "^5.0.8"
|
|
56
|
-
"@tuwaio/orbit-core": "^0.0.4"
|
|
51
|
+
"typescript": "^5.9.3",
|
|
52
|
+
"zustand": "^5.0.8"
|
|
57
53
|
},
|
|
58
54
|
"scripts": {
|
|
59
55
|
"start": "tsup src/index.ts --watch",
|