@tuwaio/satellite-core 1.0.0-fix-packages-alpha.2.a842786 → 1.0.0-fix-packages-alpha.3.bf8071b
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 +9 -5
- package/dist/index.d.ts +9 -5
- 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 +1 -1
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
|
@@ -70,7 +70,7 @@ type SatelliteAdapter<C, W extends BaseWallet = BaseWallet> = BaseAdapter & {
|
|
|
70
70
|
* @param currentChainId - Current chain ID
|
|
71
71
|
* @param updateActiveWallet - Callback to update wallet state
|
|
72
72
|
*/
|
|
73
|
-
checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number,
|
|
73
|
+
checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number, updateActiveConnection?: (wallet: Partial<Wallet<W>>) => void) => Promise<void>;
|
|
74
74
|
getBalance: (address: string, chainId: number | string) => Promise<{
|
|
75
75
|
value: string;
|
|
76
76
|
symbol: string;
|
|
@@ -99,7 +99,7 @@ type ISatelliteConnectStore<C, W extends BaseWallet = BaseWallet> = {
|
|
|
99
99
|
chainId: number | string;
|
|
100
100
|
}) => Promise<void>;
|
|
101
101
|
/** Disconnects active wallet */
|
|
102
|
-
disconnect: () => Promise<void>;
|
|
102
|
+
disconnect: (walletType?: WalletType) => Promise<void>;
|
|
103
103
|
/** Disconnects all wallets, used for initialize application */
|
|
104
104
|
disconnectAll: () => Promise<void>;
|
|
105
105
|
/** Indicates ongoing connection attempt */
|
|
@@ -109,13 +109,17 @@ type ISatelliteConnectStore<C, W extends BaseWallet = BaseWallet> = {
|
|
|
109
109
|
/** Sets error message if connection failed or form validation failed */
|
|
110
110
|
setWalletConnectionError: (error: string) => void;
|
|
111
111
|
/** Currently connected wallet */
|
|
112
|
-
|
|
112
|
+
activeConnection?: Wallet<W>;
|
|
113
|
+
/** List of all connected wallets */
|
|
114
|
+
connections: Record<WalletType, Wallet<W>>;
|
|
113
115
|
/** Clears connection error state */
|
|
114
116
|
resetWalletConnectionError: () => void;
|
|
115
117
|
/** Updates active wallet properties */
|
|
116
|
-
|
|
118
|
+
updateActiveConnection: (wallet: Partial<Wallet<W>>) => void;
|
|
119
|
+
/** Switches active connection from the list of connections */
|
|
120
|
+
switchConnection: (walletType: WalletType) => void;
|
|
117
121
|
/** Switches network for connected wallet */
|
|
118
|
-
switchNetwork: (chainId: string | number) => Promise<void>;
|
|
122
|
+
switchNetwork: (chainId: string | number, walletType?: WalletType) => Promise<void>;
|
|
119
123
|
/** Contains error message if network switch failed */
|
|
120
124
|
switchNetworkError?: string;
|
|
121
125
|
/** Clears network switch error state */
|
package/dist/index.d.ts
CHANGED
|
@@ -70,7 +70,7 @@ type SatelliteAdapter<C, W extends BaseWallet = BaseWallet> = BaseAdapter & {
|
|
|
70
70
|
* @param currentChainId - Current chain ID
|
|
71
71
|
* @param updateActiveWallet - Callback to update wallet state
|
|
72
72
|
*/
|
|
73
|
-
checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number,
|
|
73
|
+
checkAndSwitchNetwork: (chainId: string | number, currentChainId?: string | number, updateActiveConnection?: (wallet: Partial<Wallet<W>>) => void) => Promise<void>;
|
|
74
74
|
getBalance: (address: string, chainId: number | string) => Promise<{
|
|
75
75
|
value: string;
|
|
76
76
|
symbol: string;
|
|
@@ -99,7 +99,7 @@ type ISatelliteConnectStore<C, W extends BaseWallet = BaseWallet> = {
|
|
|
99
99
|
chainId: number | string;
|
|
100
100
|
}) => Promise<void>;
|
|
101
101
|
/** Disconnects active wallet */
|
|
102
|
-
disconnect: () => Promise<void>;
|
|
102
|
+
disconnect: (walletType?: WalletType) => Promise<void>;
|
|
103
103
|
/** Disconnects all wallets, used for initialize application */
|
|
104
104
|
disconnectAll: () => Promise<void>;
|
|
105
105
|
/** Indicates ongoing connection attempt */
|
|
@@ -109,13 +109,17 @@ type ISatelliteConnectStore<C, W extends BaseWallet = BaseWallet> = {
|
|
|
109
109
|
/** Sets error message if connection failed or form validation failed */
|
|
110
110
|
setWalletConnectionError: (error: string) => void;
|
|
111
111
|
/** Currently connected wallet */
|
|
112
|
-
|
|
112
|
+
activeConnection?: Wallet<W>;
|
|
113
|
+
/** List of all connected wallets */
|
|
114
|
+
connections: Record<WalletType, Wallet<W>>;
|
|
113
115
|
/** Clears connection error state */
|
|
114
116
|
resetWalletConnectionError: () => void;
|
|
115
117
|
/** Updates active wallet properties */
|
|
116
|
-
|
|
118
|
+
updateActiveConnection: (wallet: Partial<Wallet<W>>) => void;
|
|
119
|
+
/** Switches active connection from the list of connections */
|
|
120
|
+
switchConnection: (walletType: WalletType) => void;
|
|
117
121
|
/** Switches network for connected wallet */
|
|
118
|
-
switchNetwork: (chainId: string | number) => Promise<void>;
|
|
122
|
+
switchNetwork: (chainId: string | number, walletType?: WalletType) => Promise<void>;
|
|
119
123
|
/** Contains error message if network switch failed */
|
|
120
124
|
switchNetworkError?: string;
|
|
121
125
|
/** Clears network switch error state */
|
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 S({adapter:l,callbackAfterConnected:w}){return vanilla.createStore()((c,a)=>({getAdapter:e=>orbitCore.selectAdapterByKey({adapter:l,adapterKey:e}),getConnectors:()=>{let e;return Array.isArray(l)?e=l.map(n=>n.getConnectors()):e=[l.getConnectors()],e.reduce((n,t)=>{let i=t.adapter,o=t.connectors;return {...n,[i]:o}},{})},initializeAutoConnect:async e=>{if(e){let n=orbitCore.lastConnectedWalletHelpers.getLastConnectedWallet();n&&!["impersonatedwallet","walletconnect","coinbasewallet","bitgetwallet"].includes(n.walletType.split(":")[1])&&(await orbitCore.delay(null,200),await a().connect({walletType:n.walletType,chainId:n.chainId}));}else if(orbitCore.isSafeApp){await orbitCore.delay(null,200);let n=a().getAdapter(orbitCore.OrbitAdapter.EVM);if(n&&n.getSafeConnectorChainId){let t=await n.getSafeConnectorChainId();t&&await a().connect({walletType:`${orbitCore.OrbitAdapter.EVM}:safewallet`,chainId:t});}}},walletConnecting:false,walletConnectionError:void 0,switchNetworkError:void 0,activeConnection:void 0,connections:{},setWalletConnectionError:e=>c({walletConnectionError:e}),connect:async({walletType:e,chainId:n})=>{c({walletConnecting:true,walletConnectionError:void 0});let t=a().getAdapter(orbitCore.getAdapterFromWalletType(e));if(!t){c({walletConnecting:false,walletConnectionError:`No adapter found for wallet type: ${e}`});return}try{if(a().connections[e])return;let o=await t.connect({walletType:e,chainId:n});if(c(r=>({activeConnection:o,connections:{...r.connections,[o.walletType]:o}})),t.checkIsContractWallet){let r=await t.checkIsContractWallet({address:o.address,chainId:n});a().updateActiveConnection({...o,isContractAddress:r});}if(w){let r=a().activeConnection;r&&r.walletType===e&&await w(r);}c({walletConnecting:!1}),orbitCore.lastConnectedWalletHelpers.setLastConnectedWallet({walletType:e,chainId:n,address:a().activeConnection?.address}),orbitCore.recentConnectedWalletHelpers.setRecentConnectedWallet({[orbitCore.getAdapterFromWalletType(e)]:{[e.split(":")[1]]:!0}});}catch(i){c({walletConnecting:false,walletConnectionError:"Wallet connection failed: "+(i instanceof Error?i.message:String(i))});}},disconnect:async e=>{if(e){let n=a().connections[e];n&&(await a().getAdapter(orbitCore.getAdapterFromWalletType(n.walletType))?.disconnect(n),c(i=>{let o={...i.connections};delete o[e];let r=i.activeConnection?.walletType===e?void 0:i.activeConnection;return {connections:o,activeConnection:r,walletConnectionError:void 0,switchNetworkError:void 0}}));}else await a().disconnectAll();if(Object.keys(a().connections).length===0)orbitCore.lastConnectedWalletHelpers.removeLastConnectedWallet(),orbitCore.impersonatedHelpers.removeImpersonated();else {let n=a().activeConnection;n&&orbitCore.lastConnectedWalletHelpers.setLastConnectedWallet({walletType:n.walletType,chainId:n.chainId,address:n.address});}},disconnectAll:async()=>{if(await orbitCore.delay(null,150),Array.isArray(l))await Promise.allSettled(l.map(async e=>{try{await e.disconnect();}catch{}}));else try{await l.disconnect();}catch{}c({activeConnection:void 0,connections:{},walletConnectionError:void 0,switchNetworkError:void 0}),orbitCore.impersonatedHelpers.removeImpersonated();},resetWalletConnectionError:()=>{c({walletConnectionError:void 0});},updateActiveConnection:e=>{let n=a().activeConnection,t=e.walletType??n?.walletType;t?(e.chainId&&t===n?.walletType&&orbitCore.lastConnectedWalletHelpers.setLastConnectedWallet({walletType:t,chainId:e.chainId,address:e.address??n?.address}),c(i=>immer.produce(i,o=>{o.connections[t]&&(o.connections[t]={...o.connections[t],...e},o.activeConnection?.walletType===t&&(o.activeConnection=o.connections[t]));}))):e.walletType!==void 0&&e.chainId!==void 0&&e.address!==void 0?(orbitCore.lastConnectedWalletHelpers.setLastConnectedWallet({walletType:e.walletType,chainId:e.chainId,address:e.address}),c(o=>{let r=e;return {activeConnection:r,connections:{...o.connections,[r.walletType]:r}}})):console.warn("Attempted to set activeConnection with incomplete data while activeConnection was undefined.");},switchConnection:e=>{let n=a().connections[e];n&&(c({activeConnection:n}),orbitCore.lastConnectedWalletHelpers.setLastConnectedWallet({walletType:n.walletType,chainId:n.chainId,address:n.address}));},switchNetwork:async(e,n)=>{c({switchNetworkError:void 0});let t=n?a().connections[n]:a().activeConnection;if(t){let i=a().getAdapter(orbitCore.getAdapterFromWalletType(t.walletType));if(!i){c({switchNetworkError:`No adapter found for active wallet type: ${t.walletType}`});return}try{await i.checkAndSwitchNetwork(e,t.chainId,a().updateActiveConnection);}catch(o){c({switchNetworkError:"Switch network failed: "+(o instanceof Error?o.message:String(o))});}}},resetSwitchNetworkError:()=>c({switchNetworkError:void 0})}))}exports.createSatelliteConnectStore=S;//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/store/satelliteConnectStore.ts"],"names":["createSatelliteConnectStore","adapter","callbackAfterConnected","createStore","set","get","adapterKey","selectAdapterByKey","results","a","accumulator","currentResult","key","value","autoConnect","lastConnectedWallet","lastConnectedWalletHelpers","delay","isSafeApp","foundAdapter","OrbitAdapter","safeConnectorChainId","error","walletType","chainId","getAdapterFromWalletType","wallet","isContractAddress","updatedWallet","recentConnectedWalletHelpers","e","activeWallet","impersonatedHelpers","state","produce","draft"],"mappings":"mHAyBO,SAASA,CAAAA,CAAkE,CAChF,OAAA,CAAAC,CAAAA,CACA,uBAAAC,CACF,CAAA,CAAiD,CAC/C,OAAOC,mBAAAA,GAA4C,CAACC,CAAAA,CAAKC,CAAAA,IAAS,CAIhE,WAAaC,CAAAA,EAAeC,4BAAAA,CAAmB,CAAE,OAAA,CAAAN,EAAS,UAAA,CAAAK,CAAW,CAAC,CAAA,CAKtE,cAAe,IAAM,CACnB,IAAIE,CAAAA,CAEJ,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,EAAQ,MAAA,CACb,CAACE,EAAaC,CAAAA,GAAkB,CAC9B,IAAMC,CAAAA,CAAMD,EAAc,OAAA,CACpBE,CAAAA,CAAQF,CAAAA,CAAc,UAAA,CAC5B,OAAO,CACL,GAAGD,CAAAA,CACH,CAACE,CAAG,EAAGC,CACT,CACF,CAAA,CACA,EACF,CACF,CAAA,CAEA,qBAAA,CAAuB,MAAOC,CAAAA,EAAgB,CAC5C,GAAIA,CAAAA,CAAa,CACf,IAAMC,CAAAA,CAAsBC,oCAAAA,CAA2B,sBAAA,GAErDD,CAAAA,EACA,CAAC,CAAC,oBAAA,CAAsB,eAAA,CAAiB,iBAAkB,cAAc,CAAA,CAAE,QAAA,CACzEA,CAAAA,CAAoB,WAAW,KAAA,CAAM,GAAG,CAAA,CAAE,CA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,CAAAA,YAAa,KAAA,CAAQA,CAAAA,CAAE,OAAA,CAAU,OAAOA,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,CAAA,CAUA,uBAAA,CAAyB,IAAM1B,EAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CACtE,EAAE,CACJ","file":"index.js","sourcesContent":["import {\n delay,\n getAdapterFromWalletType,\n impersonatedHelpers,\n isSafeApp,\n lastConnectedWalletHelpers,\n OrbitAdapter,\n RecentConnectedWallet,\n recentConnectedWalletHelpers,\n selectAdapterByKey,\n} from '@tuwaio/orbit-core';\nimport { produce } from 'immer';\nimport { createStore } from 'zustand/vanilla';\n\nimport { BaseWallet, ISatelliteConnectStore, SatelliteConnectStoreInitialParameters, Wallet } from '../types';\n\n/**\n * Creates a Satellite Connect store instance for managing wallet connections and state\n *\n * @param params - Configuration parameters for the store\n * @param params.adapter - Single adapter or array of adapters for different chains\n * @param params.callbackAfterConnected - Optional callback function called after successful wallet connection\n *\n * @returns A Zustand store instance with wallet connection state and methods\n */\nexport function createSatelliteConnectStore<C, W extends BaseWallet = BaseWallet>({\n adapter,\n callbackAfterConnected,\n}: SatelliteConnectStoreInitialParameters<C, W>) {\n return createStore<ISatelliteConnectStore<C, W>>()((set, get) => ({\n /**\n * Returns active adapter\n */\n getAdapter: (adapterKey) => selectAdapterByKey({ adapter, adapterKey }),\n\n /**\n * Get wallet connectors for all configured adapters\n */\n getConnectors: () => {\n let results: { adapter: OrbitAdapter; connectors: C[] }[];\n\n if (Array.isArray(adapter)) {\n results = adapter.map((a) => a.getConnectors());\n } else {\n // Ensure the single adapter result is wrapped in an array for consistent processing\n results = [adapter.getConnectors()];\n }\n\n return results.reduce(\n (accumulator, currentResult) => {\n const key = currentResult.adapter;\n const value = currentResult.connectors;\n return {\n ...accumulator,\n [key]: value,\n };\n },\n {} as Partial<Record<OrbitAdapter, C[]>>,\n );\n },\n\n initializeAutoConnect: async (autoConnect) => {\n if (autoConnect) {\n const lastConnectedWallet = lastConnectedWalletHelpers.getLastConnectedWallet();\n if (\n lastConnectedWallet &&\n !['impersonatedwallet', 'walletconnect', 'coinbasewallet', 'bitgetwallet'].includes(\n lastConnectedWallet.walletType.split(':')[1],\n )\n ) {\n await delay(null, 200);\n await get().connect({ walletType: lastConnectedWallet.walletType, chainId: lastConnectedWallet.chainId });\n }\n } else if (isSafeApp) {\n await delay(null, 200);\n const foundAdapter = get().getAdapter(OrbitAdapter.EVM);\n if (foundAdapter && foundAdapter.getSafeConnectorChainId) {\n const safeConnectorChainId = await foundAdapter.getSafeConnectorChainId();\n if (safeConnectorChainId) {\n await get().connect({ walletType: `${OrbitAdapter.EVM}:safewallet`, chainId: safeConnectorChainId });\n }\n }\n }\n },\n\n walletConnecting: false,\n walletConnectionError: undefined,\n switchNetworkError: undefined,\n activeWallet: undefined,\n\n setWalletConnectionError: (error) => set({ walletConnectionError: error }),\n\n /**\n * Connects to a wallet\n * @param walletType - Type of wallet to connect to\n * @param chainId - Chain ID to connect on\n */\n connect: async ({ walletType, chainId }) => {\n set({ walletConnecting: true, walletConnectionError: undefined });\n const foundAdapter = get().getAdapter(getAdapterFromWalletType(walletType));\n\n if (!foundAdapter) {\n set({\n walletConnecting: false,\n walletConnectionError: `No adapter found for wallet type: ${walletType}`,\n });\n return;\n }\n\n try {\n // 1. Check if wallet is already connected, case when you reconnect by another wallet\n if (get().activeWallet?.isConnected) {\n await get().disconnectAll();\n }\n const wallet = await foundAdapter.connect({\n walletType,\n chainId,\n });\n\n // 2. Set initial wallet state\n set({ activeWallet: wallet });\n\n // 3. Check for contract address if the adapter supports it\n if (foundAdapter.checkIsContractWallet) {\n const isContractAddress = await foundAdapter.checkIsContractWallet({\n address: wallet.address,\n chainId,\n });\n\n // Update only the isContractAddress property\n get().updateActiveWallet({ isContractAddress });\n }\n\n // 4. Run callback if provided\n if (callbackAfterConnected) {\n // Use the latest wallet state after potential updates (like isContractAddress)\n const updatedWallet = get().activeWallet;\n if (updatedWallet) {\n await callbackAfterConnected(updatedWallet);\n }\n }\n\n // 5. Final state updates\n set({ walletConnecting: false });\n lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType,\n chainId,\n address: get().activeWallet?.address,\n });\n recentConnectedWalletHelpers.setRecentConnectedWallet({\n [getAdapterFromWalletType(walletType)]: {\n [walletType.split(':')[1]]: true,\n },\n } as RecentConnectedWallet);\n } catch (e) {\n await get().disconnectAll();\n lastConnectedWalletHelpers.removeLastConnectedWallet();\n set({\n walletConnecting: false,\n walletConnectionError: 'Wallet connection failed: ' + (e instanceof Error ? e.message : String(e)),\n });\n }\n },\n\n /**\n * Disconnects the currently active wallet\n */\n disconnect: async () => {\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n // Clear all states and storages\n set({ activeWallet: undefined, walletConnectionError: undefined, switchNetworkError: undefined });\n lastConnectedWalletHelpers.removeLastConnectedWallet();\n impersonatedHelpers.removeImpersonated();\n const foundAdapter = get().getAdapter(getAdapterFromWalletType(activeWallet.walletType));\n // Call disconnect only if adapter is found\n await foundAdapter?.disconnect(activeWallet);\n }\n },\n\n disconnectAll: async () => {\n await delay(null, 150);\n\n if (Array.isArray(adapter)) {\n await Promise.allSettled(\n adapter.map(async (a) => {\n try {\n await a.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }),\n );\n } else {\n try {\n await adapter.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }\n\n set({ activeWallet: undefined, walletConnectionError: undefined, switchNetworkError: undefined });\n impersonatedHelpers.removeImpersonated();\n },\n\n /**\n * Contains error message if connection failed\n */\n // walletConnectionError is declared above with an initial value\n\n /**\n * Resets any wallet connection errors\n */\n resetWalletConnectionError: () => {\n set({ walletConnectionError: undefined });\n },\n\n /**\n * Updates the active wallet's properties\n * @param wallet - Partial wallet object with properties to update\n */\n updateActiveWallet: (wallet: Partial<Wallet<W>>) => {\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n // If chainId is updated, update storage\n if (wallet.chainId) {\n // Update lastConnectedWallet storage if chainId changes\n lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: wallet.walletType ?? activeWallet.walletType,\n chainId: wallet.chainId ?? activeWallet.chainId,\n address: wallet.address ?? activeWallet.address,\n });\n }\n\n // Use produce for immutable state update\n set((state) =>\n produce(state, (draft) => {\n if (draft.activeWallet) {\n // Ensure we merge partial properties into the existing activeWallet object\n draft.activeWallet = {\n ...draft.activeWallet,\n ...wallet,\n } as W; // Cast ensures type compatibility after merging\n }\n }),\n );\n } else {\n const isWalletCanChange =\n wallet.walletType !== undefined && wallet.chainId !== undefined && wallet.address !== undefined;\n\n if (isWalletCanChange) {\n lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: wallet.walletType!,\n chainId: wallet.chainId!,\n address: wallet.address!,\n });\n set({ activeWallet: wallet as W });\n } else {\n console.warn('Attempted to set activeWallet with incomplete data while activeWallet was undefined.');\n }\n }\n },\n\n /**\n * Switches the connected wallet to a different network\n * @param chainId - Target chain ID to switch to\n */\n switchNetwork: async (chainId: string | number) => {\n set({ switchNetworkError: undefined });\n const activeWallet = get().activeWallet;\n if (activeWallet) {\n const foundAdapter = get().getAdapter(getAdapterFromWalletType(activeWallet.walletType));\n\n if (!foundAdapter) {\n set({ switchNetworkError: `No adapter found for active wallet type: ${activeWallet.walletType}` });\n return;\n }\n\n try {\n // Pass the local updateActiveWallet method from 'get()' to the adapter\n await foundAdapter.checkAndSwitchNetwork(chainId, activeWallet.chainId, get().updateActiveWallet);\n } catch (e) {\n set({ switchNetworkError: 'Switch network failed: ' + (e instanceof Error ? e.message : String(e)) });\n }\n }\n },\n\n /**\n * Contains error message if network switch failed\n */\n // switchNetworkError is declared above with an initial value\n\n /**\n * Resets any network switching errors\n */\n resetSwitchNetworkError: () => set({ switchNetworkError: undefined }),\n }));\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/store/satelliteConnectStore.ts"],"names":["createSatelliteConnectStore","adapter","callbackAfterConnected","createStore","set","get","adapterKey","selectAdapterByKey","results","a","accumulator","currentResult","key","value","autoConnect","lastConnectedWallet","lastConnectedWalletHelpers","delay","isSafeApp","foundAdapter","OrbitAdapter","safeConnectorChainId","error","walletType","chainId","getAdapterFromWalletType","wallet","state","isContractAddress","updatedWallet","recentConnectedWalletHelpers","e","walletToDisconnect","newConnections","newActiveConnection","impersonatedHelpers","currentActive","activeConnection","targetWalletType","produce","draft","newWallet","targetWallet"],"mappings":"mHA0BO,SAASA,EAAkE,CAChF,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,EAAsBC,oCAAAA,CAA2B,sBAAA,GAErDD,CAAAA,EACA,CAAC,CAAC,oBAAA,CAAsB,eAAA,CAAiB,iBAAkB,cAAc,CAAA,CAAE,QAAA,CACzEA,CAAAA,CAAoB,UAAA,CAAW,KAAA,CAAM,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AAE,UAAA,CAAWoB,mCAAyBiB,CAAAA,CAAa,UAAU,CAAC,CAAA,CAEvF,GAAI,CAACvB,CAAAA,CAAc,CACjBf,CAAAA,CAAI,CAAE,kBAAA,CAAoB,CAAA,yCAAA,EAA4CsC,EAAa,UAAU,CAAA,CAAG,CAAC,CAAA,CACjG,MACF,CAEA,GAAI,CAEF,MAAMvB,EAAa,qBAAA,CAAsBK,CAAAA,CAASkB,EAAa,OAAA,CAASrC,CAAAA,GAAM,sBAAsB,EACtG,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 delay,\n getAdapterFromWalletType,\n impersonatedHelpers,\n isSafeApp,\n lastConnectedWalletHelpers,\n OrbitAdapter,\n RecentConnectedWallet,\n recentConnectedWalletHelpers,\n selectAdapterByKey,\n WalletType,\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 activeConnection: undefined,\n connections: {},\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\n const existingWallet = get().connections[walletType as WalletType];\n if (existingWallet) {\n return;\n }\n\n const wallet = await foundAdapter.connect({\n walletType,\n chainId,\n });\n\n // 2. Set initial wallet state\n set((state) => {\n return {\n activeConnection: wallet,\n connections: {\n ...state.connections,\n [wallet.walletType]: wallet,\n },\n };\n });\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().updateActiveConnection({ ...wallet, 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().activeConnection;\n if (updatedWallet && updatedWallet.walletType === walletType) {\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().activeConnection?.address,\n });\n recentConnectedWalletHelpers.setRecentConnectedWallet({\n [getAdapterFromWalletType(walletType)]: {\n [walletType.split(':')[1]]: true,\n },\n } as RecentConnectedWallet);\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 or a specific wallet\n */\n /**\n * Disconnects the currently active wallet or a specific wallet\n */\n disconnect: async (walletType?: string) => {\n if (walletType) {\n // Disconnect specific wallet\n const walletToDisconnect = get().connections[walletType as WalletType];\n\n if (walletToDisconnect) {\n const foundAdapter = get().getAdapter(getAdapterFromWalletType(walletToDisconnect.walletType));\n await foundAdapter?.disconnect(walletToDisconnect);\n\n set((state) => {\n const newConnections = { ...state.connections };\n delete newConnections[walletType as WalletType];\n\n // If the disconnected wallet was the active one, set activeConnection to undefined\n const newActiveConnection =\n state.activeConnection?.walletType === walletType ? undefined : state.activeConnection;\n\n return {\n connections: newConnections,\n activeConnection: newActiveConnection,\n walletConnectionError: undefined,\n switchNetworkError: undefined,\n };\n });\n }\n } else {\n // Disconnect ALL wallets\n await get().disconnectAll();\n }\n\n if (Object.keys(get().connections).length === 0) {\n lastConnectedWalletHelpers.removeLastConnectedWallet();\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 lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: currentActive.walletType,\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 walletConnectionError: undefined,\n switchNetworkError: undefined,\n });\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 /**\n * Updates the active connection's properties\n * @param wallet - Partial wallet object with properties to update\n */\n updateActiveConnection: (wallet: Partial<Wallet<W>>) => {\n const activeConnection = get().activeConnection;\n // Determine which wallet to update. If walletType is provided, use it. Otherwise use activeConnection.\n const targetWalletType = wallet.walletType ?? activeConnection?.walletType;\n\n if (targetWalletType) {\n // If chainId is updated, update storage\n if (wallet.chainId && targetWalletType === activeConnection?.walletType) {\n // Update lastConnectedWallet storage if chainId changes and it's the active wallet\n lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: targetWalletType,\n chainId: wallet.chainId,\n address: wallet.address ?? activeConnection?.address,\n });\n }\n\n // Use produce for immutable state update\n set((state) =>\n produce(state, (draft) => {\n if (draft.connections[targetWalletType as WalletType]) {\n draft.connections[targetWalletType as WalletType] = {\n ...draft.connections[targetWalletType as WalletType],\n ...wallet,\n } as Wallet<W>;\n\n // Also update activeConnection if it matches\n if (draft.activeConnection?.walletType === targetWalletType) {\n draft.activeConnection = draft.connections[targetWalletType as WalletType];\n }\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 // It's a new wallet or full replacement\n set((state) => {\n const newWallet = wallet as W;\n return {\n activeConnection: newWallet,\n connections: {\n ...state.connections,\n [newWallet.walletType]: newWallet,\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: (walletType: string) => {\n const targetWallet = get().connections[walletType as WalletType];\n if (targetWallet) {\n set({ activeConnection: targetWallet });\n lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: targetWallet.walletType,\n chainId: targetWallet.chainId,\n address: targetWallet.address,\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, walletType?: string) => {\n set({ switchNetworkError: undefined });\n const targetWallet = walletType ? get().connections[walletType as WalletType] : get().activeConnection;\n\n if (targetWallet) {\n const foundAdapter = get().getAdapter(getAdapterFromWalletType(targetWallet.walletType));\n\n if (!foundAdapter) {\n set({ switchNetworkError: `No adapter found for active wallet type: ${targetWallet.walletType}` });\n return;\n }\n\n try {\n // Pass the local updateActiveConnection method from 'get()' to the adapter\n await foundAdapter.checkAndSwitchNetwork(chainId, targetWallet.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,getAdapterFromWalletType,lastConnectedWalletHelpers,delay,impersonatedHelpers,recentConnectedWalletHelpers,isSafeApp,OrbitAdapter}from'@tuwaio/orbit-core';import {produce}from'immer';import {createStore}from'zustand/vanilla';function
|
|
1
|
+
import {selectAdapterByKey,getAdapterFromWalletType,lastConnectedWalletHelpers,delay,impersonatedHelpers,recentConnectedWalletHelpers,isSafeApp,OrbitAdapter}from'@tuwaio/orbit-core';import {produce}from'immer';import {createStore}from'zustand/vanilla';function S({adapter:l,callbackAfterConnected:w}){return createStore()((c,a)=>({getAdapter:e=>selectAdapterByKey({adapter:l,adapterKey:e}),getConnectors:()=>{let e;return Array.isArray(l)?e=l.map(n=>n.getConnectors()):e=[l.getConnectors()],e.reduce((n,t)=>{let i=t.adapter,o=t.connectors;return {...n,[i]:o}},{})},initializeAutoConnect:async e=>{if(e){let n=lastConnectedWalletHelpers.getLastConnectedWallet();n&&!["impersonatedwallet","walletconnect","coinbasewallet","bitgetwallet"].includes(n.walletType.split(":")[1])&&(await delay(null,200),await a().connect({walletType:n.walletType,chainId:n.chainId}));}else if(isSafeApp){await delay(null,200);let n=a().getAdapter(OrbitAdapter.EVM);if(n&&n.getSafeConnectorChainId){let t=await n.getSafeConnectorChainId();t&&await a().connect({walletType:`${OrbitAdapter.EVM}:safewallet`,chainId:t});}}},walletConnecting:false,walletConnectionError:void 0,switchNetworkError:void 0,activeConnection:void 0,connections:{},setWalletConnectionError:e=>c({walletConnectionError:e}),connect:async({walletType:e,chainId:n})=>{c({walletConnecting:true,walletConnectionError:void 0});let t=a().getAdapter(getAdapterFromWalletType(e));if(!t){c({walletConnecting:false,walletConnectionError:`No adapter found for wallet type: ${e}`});return}try{if(a().connections[e])return;let o=await t.connect({walletType:e,chainId:n});if(c(r=>({activeConnection:o,connections:{...r.connections,[o.walletType]:o}})),t.checkIsContractWallet){let r=await t.checkIsContractWallet({address:o.address,chainId:n});a().updateActiveConnection({...o,isContractAddress:r});}if(w){let r=a().activeConnection;r&&r.walletType===e&&await w(r);}c({walletConnecting:!1}),lastConnectedWalletHelpers.setLastConnectedWallet({walletType:e,chainId:n,address:a().activeConnection?.address}),recentConnectedWalletHelpers.setRecentConnectedWallet({[getAdapterFromWalletType(e)]:{[e.split(":")[1]]:!0}});}catch(i){c({walletConnecting:false,walletConnectionError:"Wallet connection failed: "+(i instanceof Error?i.message:String(i))});}},disconnect:async e=>{if(e){let n=a().connections[e];n&&(await a().getAdapter(getAdapterFromWalletType(n.walletType))?.disconnect(n),c(i=>{let o={...i.connections};delete o[e];let r=i.activeConnection?.walletType===e?void 0:i.activeConnection;return {connections:o,activeConnection:r,walletConnectionError:void 0,switchNetworkError:void 0}}));}else await a().disconnectAll();if(Object.keys(a().connections).length===0)lastConnectedWalletHelpers.removeLastConnectedWallet(),impersonatedHelpers.removeImpersonated();else {let n=a().activeConnection;n&&lastConnectedWalletHelpers.setLastConnectedWallet({walletType:n.walletType,chainId:n.chainId,address:n.address});}},disconnectAll:async()=>{if(await delay(null,150),Array.isArray(l))await Promise.allSettled(l.map(async e=>{try{await e.disconnect();}catch{}}));else try{await l.disconnect();}catch{}c({activeConnection:void 0,connections:{},walletConnectionError:void 0,switchNetworkError:void 0}),impersonatedHelpers.removeImpersonated();},resetWalletConnectionError:()=>{c({walletConnectionError:void 0});},updateActiveConnection:e=>{let n=a().activeConnection,t=e.walletType??n?.walletType;t?(e.chainId&&t===n?.walletType&&lastConnectedWalletHelpers.setLastConnectedWallet({walletType:t,chainId:e.chainId,address:e.address??n?.address}),c(i=>produce(i,o=>{o.connections[t]&&(o.connections[t]={...o.connections[t],...e},o.activeConnection?.walletType===t&&(o.activeConnection=o.connections[t]));}))):e.walletType!==void 0&&e.chainId!==void 0&&e.address!==void 0?(lastConnectedWalletHelpers.setLastConnectedWallet({walletType:e.walletType,chainId:e.chainId,address:e.address}),c(o=>{let r=e;return {activeConnection:r,connections:{...o.connections,[r.walletType]:r}}})):console.warn("Attempted to set activeConnection with incomplete data while activeConnection was undefined.");},switchConnection:e=>{let n=a().connections[e];n&&(c({activeConnection:n}),lastConnectedWalletHelpers.setLastConnectedWallet({walletType:n.walletType,chainId:n.chainId,address:n.address}));},switchNetwork:async(e,n)=>{c({switchNetworkError:void 0});let t=n?a().connections[n]:a().activeConnection;if(t){let i=a().getAdapter(getAdapterFromWalletType(t.walletType));if(!i){c({switchNetworkError:`No adapter found for active wallet type: ${t.walletType}`});return}try{await i.checkAndSwitchNetwork(e,t.chainId,a().updateActiveConnection);}catch(o){c({switchNetworkError:"Switch network failed: "+(o instanceof Error?o.message:String(o))});}}},resetSwitchNetworkError:()=>c({switchNetworkError:void 0})}))}export{S 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,IA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AA,CAAuB,CAChD,UAAA,CAAYU,CAAAA,CAAO,UAAA,CACnB,OAAA,CAASA,EAAO,OAAA,CAChB,OAAA,CAASA,CAAAA,CAAO,OAClB,CAAC,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,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","lastConnectedWallet","lastConnectedWalletHelpers","delay","isSafeApp","foundAdapter","OrbitAdapter","safeConnectorChainId","error","walletType","chainId","getAdapterFromWalletType","wallet","state","isContractAddress","updatedWallet","recentConnectedWalletHelpers","e","walletToDisconnect","newConnections","newActiveConnection","impersonatedHelpers","currentActive","activeConnection","targetWalletType","produce","draft","newWallet","targetWallet"],"mappings":"4PA0BO,SAASA,EAAkE,CAChF,OAAA,CAAAC,EACA,sBAAA,CAAAC,CACF,CAAA,CAAiD,CAC/C,OAAOC,W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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 delay,\n getAdapterFromWalletType,\n impersonatedHelpers,\n isSafeApp,\n lastConnectedWalletHelpers,\n OrbitAdapter,\n RecentConnectedWallet,\n recentConnectedWalletHelpers,\n selectAdapterByKey,\n WalletType,\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 activeConnection: undefined,\n connections: {},\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\n const existingWallet = get().connections[walletType as WalletType];\n if (existingWallet) {\n return;\n }\n\n const wallet = await foundAdapter.connect({\n walletType,\n chainId,\n });\n\n // 2. Set initial wallet state\n set((state) => {\n return {\n activeConnection: wallet,\n connections: {\n ...state.connections,\n [wallet.walletType]: wallet,\n },\n };\n });\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().updateActiveConnection({ ...wallet, 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().activeConnection;\n if (updatedWallet && updatedWallet.walletType === walletType) {\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().activeConnection?.address,\n });\n recentConnectedWalletHelpers.setRecentConnectedWallet({\n [getAdapterFromWalletType(walletType)]: {\n [walletType.split(':')[1]]: true,\n },\n } as RecentConnectedWallet);\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 or a specific wallet\n */\n /**\n * Disconnects the currently active wallet or a specific wallet\n */\n disconnect: async (walletType?: string) => {\n if (walletType) {\n // Disconnect specific wallet\n const walletToDisconnect = get().connections[walletType as WalletType];\n\n if (walletToDisconnect) {\n const foundAdapter = get().getAdapter(getAdapterFromWalletType(walletToDisconnect.walletType));\n await foundAdapter?.disconnect(walletToDisconnect);\n\n set((state) => {\n const newConnections = { ...state.connections };\n delete newConnections[walletType as WalletType];\n\n // If the disconnected wallet was the active one, set activeConnection to undefined\n const newActiveConnection =\n state.activeConnection?.walletType === walletType ? undefined : state.activeConnection;\n\n return {\n connections: newConnections,\n activeConnection: newActiveConnection,\n walletConnectionError: undefined,\n switchNetworkError: undefined,\n };\n });\n }\n } else {\n // Disconnect ALL wallets\n await get().disconnectAll();\n }\n\n if (Object.keys(get().connections).length === 0) {\n lastConnectedWalletHelpers.removeLastConnectedWallet();\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 lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: currentActive.walletType,\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 walletConnectionError: undefined,\n switchNetworkError: undefined,\n });\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 /**\n * Updates the active connection's properties\n * @param wallet - Partial wallet object with properties to update\n */\n updateActiveConnection: (wallet: Partial<Wallet<W>>) => {\n const activeConnection = get().activeConnection;\n // Determine which wallet to update. If walletType is provided, use it. Otherwise use activeConnection.\n const targetWalletType = wallet.walletType ?? activeConnection?.walletType;\n\n if (targetWalletType) {\n // If chainId is updated, update storage\n if (wallet.chainId && targetWalletType === activeConnection?.walletType) {\n // Update lastConnectedWallet storage if chainId changes and it's the active wallet\n lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: targetWalletType,\n chainId: wallet.chainId,\n address: wallet.address ?? activeConnection?.address,\n });\n }\n\n // Use produce for immutable state update\n set((state) =>\n produce(state, (draft) => {\n if (draft.connections[targetWalletType as WalletType]) {\n draft.connections[targetWalletType as WalletType] = {\n ...draft.connections[targetWalletType as WalletType],\n ...wallet,\n } as Wallet<W>;\n\n // Also update activeConnection if it matches\n if (draft.activeConnection?.walletType === targetWalletType) {\n draft.activeConnection = draft.connections[targetWalletType as WalletType];\n }\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 // It's a new wallet or full replacement\n set((state) => {\n const newWallet = wallet as W;\n return {\n activeConnection: newWallet,\n connections: {\n ...state.connections,\n [newWallet.walletType]: newWallet,\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: (walletType: string) => {\n const targetWallet = get().connections[walletType as WalletType];\n if (targetWallet) {\n set({ activeConnection: targetWallet });\n lastConnectedWalletHelpers.setLastConnectedWallet({\n walletType: targetWallet.walletType,\n chainId: targetWallet.chainId,\n address: targetWallet.address,\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, walletType?: string) => {\n set({ switchNetworkError: undefined });\n const targetWallet = walletType ? get().connections[walletType as WalletType] : get().activeConnection;\n\n if (targetWallet) {\n const foundAdapter = get().getAdapter(getAdapterFromWalletType(targetWallet.walletType));\n\n if (!foundAdapter) {\n set({ switchNetworkError: `No adapter found for active wallet type: ${targetWallet.walletType}` });\n return;\n }\n\n try {\n // Pass the local updateActiveConnection method from 'get()' to the adapter\n await foundAdapter.checkAndSwitchNetwork(chainId, targetWallet.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"]}
|