@tuwaio/satellite-core 1.0.0-fix-packages-alpha.17.c720fd6 → 1.0.0-fix-packages-alpha.19.eb3499f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var orbitCore=require('@tuwaio/orbit-core'),immer=require('immer'),vanilla=require('zustand/vanilla');function k({adapter:d,callbackAfterConnected:p}){return immer.setAutoFreeze(false),vanilla.createStore()((i,c)=>({getAdapter:n=>orbitCore.selectAdapterByKey({adapter:d,adapterKey:n}),getConnectors:()=>{let n;return Array.isArray(d)?n=d.map(o=>o.getConnectors()):n=[d.getConnectors()],n.reduce((o,e)=>{let r=e.adapter,t=e.connectors;return {...o,[r]:t}},{})},initializeAutoConnect:async n=>{let o=Date.now()-6048e5;if(orbitCore.recentlyConnectedConnectorsListHelpers.removeConnectorsOlderThan(o),n){let e=orbitCore.lastConnectedConnectorHelpers.getLastConnectedConnector();e&&!["impersonatedwallet","walletconnect","coinbasewallet","bitgetwallet"].includes(e.connectorType.split(":")[1])&&(await orbitCore.delay(null,200),await c().connect({connectorType:e.connectorType,chainId:e.chainId}));}else if(orbitCore.isSafeApp){await orbitCore.delay(null,200);let e=c().getAdapter(orbitCore.OrbitAdapter.EVM);if(e&&e.getSafeConnectorChainId){let r=await e.getSafeConnectorChainId();r&&await c().connect({connectorType:`${orbitCore.OrbitAdapter.EVM}:safewallet`,chainId:r});}}},connecting:false,disconnecting:false,connectionError:void 0,switchNetworkError:void 0,activeConnection:void 0,connections:{},setConnectionError:n=>i({connectionError:n}),connect:async({connectorType:n,chainId:o})=>{i({connecting:true,connectionError:void 0});let e=c().getAdapter(orbitCore.getAdapterFromConnectorType(n));if(!e){i({connecting:false,connectionError:`No adapter found for connector type: ${n}`});return}try{if(c().connections[n])return;let t=await e.connect({connectorType:n,chainId:o});if(i(s=>({activeConnection:t,connections:{...s.connections,[t.connectorType]:t}})),e.checkIsContractAddress){let s=await e.checkIsContractAddress({address:t.address,chainId:o});c().updateActiveConnection({...t,isContractAddress:s});}if(p){let s=c().activeConnection;s&&s.connectorType===n&&await p(s);}i({connecting:!1}),orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:n,chainId:o,address:c().activeConnection?.address});let a=c().activeConnection;a&&a.address&&orbitCore.recentlyConnectedConnectorsListHelpers.addConnector(a.connectorType,{address:a.address,disconnectedTimestamp:Date.now(),icon:a.icon});}catch(r){i({connecting:false,connectionError:"Connector connection failed: "+(r instanceof Error?r.message:String(r))});}},disconnect:async n=>{if(!c().disconnecting){i({disconnecting:true});try{if(n){let o=c().connections[n];o&&(await c().getAdapter(orbitCore.getAdapterFromConnectorType(o.connectorType))?.disconnect(o),i(r=>{let t={...r.connections};delete t[n];let a=r.activeConnection;if(r.activeConnection?.connectorType===n){let s=Object.values(t);s.length>0?a=s[0]:a=void 0;}return {connections:t,activeConnection:a,connectionError:void 0,switchNetworkError:void 0}}));}else await c().disconnectAll();if(Object.keys(c().connections).length===0)orbitCore.lastConnectedConnectorHelpers.removeLastConnectedConnector(),orbitCore.impersonatedHelpers.removeImpersonated();else {let o=c().activeConnection;o&&orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:o.connectorType,chainId:o.chainId,address:o.address});}}finally{i({disconnecting:false});}}},disconnectAll:async()=>{if(await orbitCore.delay(null,150),Array.isArray(d))await Promise.allSettled(d.map(async n=>{try{await n.disconnect();}catch{}}));else try{await d.disconnect();}catch{}i({activeConnection:void 0,connections:{},connectionError:void 0,switchNetworkError:void 0}),orbitCore.impersonatedHelpers.removeImpersonated();},resetConnectionError:()=>{i({connectionError:void 0});},updateActiveConnection:n=>{let o=c().activeConnection,e=n.connectorType??o?.connectorType;e?(n.chainId&&e===o?.connectorType&&orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:e,chainId:n.chainId,address:n.address??o?.address}),i(r=>immer.produce(r,t=>{t.connections[e]&&(t.connections[e]={...t.connections[e],...n},t.activeConnection?.connectorType===e&&(t.activeConnection=t.connections[e]));}))):n.connectorType!==void 0&&n.chainId!==void 0&&n.address!==void 0?(orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:n.connectorType,chainId:n.chainId,address:n.address}),i(t=>{let a=n;return {activeConnection:a,connections:{...t.connections,[a.connectorType]:a}}})):console.warn("Attempted to set activeConnection with incomplete data while activeConnection was undefined.");},switchConnection:async n=>{let o=c().connections[n];if(!o){console.warn(`No connection found for connector type: ${n}`);return}if(c().activeConnection?.connectorType!==n)try{let e=c().getAdapter(orbitCore.getAdapterFromConnectorType(n));e?.switchConnection&&await e.switchConnection(n),i(r=>immer.produce(r,t=>{t.activeConnection=o;})),orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:o.connectorType,chainId:o.chainId,address:o.address});}catch(e){console.error("Failed to switch connection:",e);}},switchNetwork:async(n,o)=>{i({switchNetworkError:void 0});let e=o?c().connections[o]:c().activeConnection;if(e){let r=c().getAdapter(orbitCore.getAdapterFromConnectorType(e.connectorType));if(!r){i({switchNetworkError:`No adapter found for active connector type: ${e.connectorType}`});return}try{await r.checkAndSwitchNetwork(n,e.chainId,c().updateActiveConnection);}catch(t){i({switchNetworkError:"Switch network failed: "+(t instanceof Error?t.message:String(t))});}}},resetSwitchNetworkError:()=>i({switchNetworkError:void 0})}))}exports.createSatelliteConnectStore=k;//# sourceMappingURL=index.js.map
1
+ 'use strict';var orbitCore=require('@tuwaio/orbit-core'),immer=require('immer'),vanilla=require('zustand/vanilla');function b({adapter:l,callbackAfterConnected:h}){return immer.setAutoFreeze(false),vanilla.createStore()((r,c)=>({getAdapter:n=>orbitCore.selectAdapterByKey({adapter:l,adapterKey:n}),getConnectors:()=>{let n;return Array.isArray(l)?n=l.map(o=>o.getConnectors()):n=[l.getConnectors()],n.reduce((o,e)=>{let i=e.adapter,t=e.connectors;return {...o,[i]:t}},{})},initializeAutoConnect:async n=>{let o=Date.now()-6048e5;if(orbitCore.recentlyConnectedConnectorsListHelpers.removeConnectorsOlderThan(o),n){let e=orbitCore.lastConnectedConnectorHelpers.getLastConnectedConnector();e&&!["impersonatedwallet","walletconnect","coinbasewallet","bitgetwallet"].includes(e.connectorType.split(":")[1])&&(await orbitCore.delay(null,200),await c().connect({connectorType:e.connectorType,chainId:e.chainId}));}else if(orbitCore.isSafeApp){await orbitCore.delay(null,200);let e=c().getAdapter(orbitCore.OrbitAdapter.EVM);if(e&&e.getSafeConnectorChainId){let i=await e.getSafeConnectorChainId();i&&await c().connect({connectorType:`${orbitCore.OrbitAdapter.EVM}:safewallet`,chainId:i});}}},connecting:false,disconnecting:false,connectionError:void 0,switchNetworkError:void 0,activeConnection:void 0,connections:{},setConnectionError:n=>r({connectionError:n}),connect:async({connectorType:n,chainId:o})=>{r({connecting:true,connectionError:void 0});let e=c().getAdapter(orbitCore.getAdapterFromConnectorType(n));if(!e){r({connecting:false,connectionError:`No adapter found for connector type: ${n}`});return}try{if(c().connections[n])return;let t=await e.connect({connectorType:n,chainId:o});if(r(s=>({activeConnection:t,connections:{...s.connections,[t.connectorType]:t}})),e.checkIsContractAddress){let s=await e.checkIsContractAddress({address:t.address,chainId:o});c().updateActiveConnection({...t,isContractAddress:s});}if(h){let s=c().activeConnection;s&&s.connectorType===n&&await h(s);}r({connecting:!1}),orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:n,chainId:o,address:c().activeConnection?.address});let a=c().activeConnection;a&&a.address&&orbitCore.recentlyConnectedConnectorsListHelpers.addConnector(a.connectorType,{address:a.address,disconnectedTimestamp:Date.now(),icon:a.icon});}catch(i){r({connecting:false,connectionError:"Connector connection failed: "+(i instanceof Error?i.message:String(i))});}},disconnect:async n=>{if(!c().disconnecting){r({disconnecting:true});try{if(n){let e=c(),i=e.connections[n];if(!i){console.warn(`No connection found for connector type: ${n}`);return}let t=c().getAdapter(orbitCore.getAdapterFromConnectorType(i.connectorType));if(t)try{await t.disconnect(i);}catch(d){console.error(`Failed to disconnect connector ${n}:`,d);}let a=e.activeConnection?.connectorType===n,s=Object.values(e.connections).filter(d=>d.connectorType!==n),w;if(a&&s.length>0){let d=s[0];try{let C=c().getAdapter(orbitCore.getAdapterFromConnectorType(d.connectorType));C?.switchConnection&&await C.switchConnection(d.connectorType),w=d;}catch(C){console.error("Failed to switch to remaining connector:",C),w=void 0;}}else a||(w=e.activeConnection);r(d=>immer.produce(d,C=>{delete C.connections[n],C.activeConnection=w,C.connectionError=void 0,C.switchNetworkError=void 0;}));}else await c().disconnectAll();let o=c();Object.keys(o.connections).length===0?(orbitCore.lastConnectedConnectorHelpers.removeLastConnectedConnector(),orbitCore.impersonatedHelpers.removeImpersonated()):o.activeConnection&&orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:o.activeConnection.connectorType,chainId:o.activeConnection.chainId,address:o.activeConnection.address});}catch(o){console.error("Disconnect operation failed:",o),r(e=>immer.produce(e,i=>{i.connectionError=`Disconnect failed: ${o instanceof Error?o.message:String(o)}`;}));}finally{r({disconnecting:false});}}},disconnectAll:async()=>{if(await orbitCore.delay(null,150),Array.isArray(l))await Promise.allSettled(l.map(async n=>{try{await n.disconnect();}catch{}}));else try{await l.disconnect();}catch{}r({activeConnection:void 0,connections:{},connectionError:void 0,switchNetworkError:void 0}),orbitCore.impersonatedHelpers.removeImpersonated();},resetConnectionError:()=>{r({connectionError:void 0});},updateActiveConnection:n=>{let o=c().activeConnection,e=n.connectorType??o?.connectorType;e?(n.chainId&&e===o?.connectorType&&orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:e,chainId:n.chainId,address:n.address??o?.address}),r(i=>immer.produce(i,t=>{t.connections[e]&&(t.connections[e]={...t.connections[e],...n},t.activeConnection?.connectorType===e&&(t.activeConnection=t.connections[e]));}))):n.connectorType!==void 0&&n.chainId!==void 0&&n.address!==void 0?(orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:n.connectorType,chainId:n.chainId,address:n.address}),r(t=>{let a=n;return {activeConnection:a,connections:{...t.connections,[a.connectorType]:a}}})):console.warn("Attempted to set activeConnection with incomplete data while activeConnection was undefined.");},switchConnection:async n=>{let o=c().connections[n];if(!o){console.warn(`No connection found for connector type: ${n}`);return}if(c().activeConnection?.connectorType!==n)try{let e=c().getAdapter(orbitCore.getAdapterFromConnectorType(n));e?.switchConnection&&await e.switchConnection(n),r(i=>immer.produce(i,t=>{t.activeConnection=o;})),orbitCore.lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:o.connectorType,chainId:o.chainId,address:o.address});}catch(e){console.error("Failed to switch connection:",e);}},switchNetwork:async(n,o)=>{r({switchNetworkError:void 0});let e=o?c().connections[o]:c().activeConnection;if(e){let i=c().getAdapter(orbitCore.getAdapterFromConnectorType(e.connectorType));if(!i){r({switchNetworkError:`No adapter found for active connector type: ${e.connectorType}`});return}try{await i.checkAndSwitchNetwork(n,e.chainId,c().updateActiveConnection);}catch(t){r({switchNetworkError:"Switch network failed: "+(t instanceof Error?t.message:String(t))});}}},resetSwitchNetworkError:()=>r({switchNetworkError:void 0})}))}exports.createSatelliteConnectStore=b;//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/store/satelliteConnectStore.ts"],"names":["createSatelliteConnectStore","adapter","callbackAfterConnected","setAutoFreeze","createStore","set","get","adapterKey","selectAdapterByKey","results","a","accumulator","currentResult","key","value","autoConnect","sevenDaysAgo","recentlyConnectedConnectorsListHelpers","lastConnectedConnector","lastConnectedConnectorHelpers","delay","isSafeApp","foundAdapter","OrbitAdapter","safeConnectorChainId","error","connectorType","chainId","getAdapterFromConnectorType","connector","state","isContractAddress","updatedConnector","activeConnection","e","connectorToDisconnect","newConnections","newActiveConnection","remainingConnectors","impersonatedHelpers","currentActive","targetConnectorType","produce","draft","newConnector","targetConnector"],"mappings":"mHAyBO,SAASA,CAAAA,CAAwE,CACtF,OAAA,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AWsB,qCAAAA,CAA4BiB,CAAAA,CAAgB,aAAa,CAAC,CAAA,CAEhG,GAAI,CAACvB,CAAAA,CAAc,CACjBjB,CAAAA,CAAI,CAAE,kBAAA,CAAoB,CAAA,4CAAA,EAA+CwC,CAAAA,CAAgB,aAAa,CAAA,CAAG,CAAC,EAC1G,MACF,CAEA,GAAI,CAEF,MAAMvB,CAAAA,CAAa,qBAAA,CAAsBK,CAAAA,CAASkB,CAAAA,CAAgB,OAAA,CAASvC,CAAAA,EAAI,CAAE,sBAAsB,EACzG,OAAS4B,CAAAA,CAAG,CACV7B,CAAAA,CAAI,CAAE,kBAAA,CAAoB,yBAAA,EAA6B6B,CAAAA,YAAa,KAAA,CAAQA,CAAAA,CAAE,OAAA,CAAU,MAAA,CAAOA,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,CAAA,CAUA,uBAAA,CAAyB,IAAM7B,CAAAA,CAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CACtE,CAAA,CAAE,CACJ","file":"index.js","sourcesContent":["import {\n ConnectorType,\n delay,\n getAdapterFromConnectorType,\n impersonatedHelpers,\n isSafeApp,\n lastConnectedConnectorHelpers,\n OrbitAdapter,\n recentlyConnectedConnectorsListHelpers,\n selectAdapterByKey,\n} from '@tuwaio/orbit-core';\nimport { produce, setAutoFreeze } from 'immer';\nimport { createStore } from 'zustand/vanilla';\n\nimport { BaseConnector, Connector, ISatelliteConnectStore, SatelliteConnectStoreInitialParameters } from '../types';\n\n/**\n * Creates a Satellite Connect store instance for managing connector connections and state\n *\n * @param params - Initial parameters for the store\n * @param params.adapter - Blockchain adapter(s) to use\n * @param params.callbackAfterConnected - Optional callback function called after successful connection\n *\n * @returns A Zustand store instance with connection state and methods\n */\nexport function createSatelliteConnectStore<C, W extends BaseConnector = BaseConnector>({\n adapter,\n callbackAfterConnected,\n}: SatelliteConnectStoreInitialParameters<C, W>) {\n // Disable autoFreeze for immers in this store, since connectors contain EventEmitter objects that must remain mutable to function correctly\n setAutoFreeze(false);\n\n return createStore<ISatelliteConnectStore<C, W>>()((set, get) => ({\n /**\n * Returns active adapter\n */\n getAdapter: (adapterKey) => selectAdapterByKey({ adapter, adapterKey }),\n\n /**\n * Get connectors for all configured adapters\n */\n getConnectors: () => {\n let results: { adapter: OrbitAdapter; connectors: C[] }[];\n\n if (Array.isArray(adapter)) {\n results = adapter.map((a) => a.getConnectors());\n } else {\n // Ensure the single adapter result is wrapped in an array for consistent processing\n results = [adapter.getConnectors()];\n }\n\n return results.reduce(\n (accumulator, currentResult) => {\n const key = currentResult.adapter;\n const value = currentResult.connectors;\n return {\n ...accumulator,\n [key]: value,\n };\n },\n {} as Partial<Record<OrbitAdapter, C[]>>,\n );\n },\n\n initializeAutoConnect: async (autoConnect) => {\n // Cleanup old recently connected connectors (older than 7 days)\n const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;\n recentlyConnectedConnectorsListHelpers.removeConnectorsOlderThan(sevenDaysAgo);\n\n if (autoConnect) {\n const lastConnectedConnector = lastConnectedConnectorHelpers.getLastConnectedConnector();\n if (\n lastConnectedConnector &&\n !['impersonatedwallet', 'walletconnect', 'coinbasewallet', 'bitgetwallet'].includes(\n lastConnectedConnector.connectorType.split(':')[1],\n )\n ) {\n await delay(null, 200);\n await get().connect({\n connectorType: lastConnectedConnector.connectorType,\n chainId: lastConnectedConnector.chainId,\n });\n }\n } else if (isSafeApp) {\n await delay(null, 200);\n const foundAdapter = get().getAdapter(OrbitAdapter.EVM);\n if (foundAdapter && foundAdapter.getSafeConnectorChainId) {\n const safeConnectorChainId = await foundAdapter.getSafeConnectorChainId();\n if (safeConnectorChainId) {\n await get().connect({ connectorType: `${OrbitAdapter.EVM}:safewallet`, chainId: safeConnectorChainId });\n }\n }\n }\n },\n\n connecting: false,\n disconnecting: false,\n connectionError: undefined,\n switchNetworkError: undefined,\n activeConnection: undefined,\n connections: {},\n\n setConnectionError: (error) => set({ connectionError: error }),\n\n /**\n * Connects to a connector\n * @param connectorType - Type of connector to connect to\n * @param chainId - Chain ID to connect on\n */\n connect: async ({ connectorType, chainId }) => {\n set({ connecting: true, connectionError: undefined });\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorType));\n\n if (!foundAdapter) {\n set({\n connecting: false,\n connectionError: `No adapter found for connector type: ${connectorType}`,\n });\n return;\n }\n\n try {\n // 1. Check if connector is already connected\n const existingConnector = get().connections[connectorType as ConnectorType];\n if (existingConnector) {\n return;\n }\n\n const connector = await foundAdapter.connect({\n connectorType,\n chainId,\n });\n\n // 2. Set initial connector state\n set((state) => {\n return {\n activeConnection: connector,\n connections: {\n ...state.connections,\n [connector.connectorType]: connector,\n },\n };\n });\n\n // 3. Check for contract address if the adapter supports it\n if (foundAdapter.checkIsContractAddress) {\n const isContractAddress = await foundAdapter.checkIsContractAddress({\n address: connector.address,\n chainId,\n });\n\n // Update only the isContractAddress property\n get().updateActiveConnection({ ...connector, isContractAddress });\n }\n\n // 4. Run callback if provided\n if (callbackAfterConnected) {\n // Use the latest connector state after potential updates (like isContractAddress)\n const updatedConnector = get().activeConnection;\n if (updatedConnector && updatedConnector.connectorType === connectorType) {\n await callbackAfterConnected(updatedConnector);\n }\n }\n\n // 5. Final state updates\n set({ connecting: false });\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType,\n chainId,\n address: get().activeConnection?.address,\n });\n\n // Add to recently connected list\n const activeConnection = get().activeConnection;\n if (activeConnection && activeConnection.address) {\n recentlyConnectedConnectorsListHelpers.addConnector(activeConnection.connectorType, {\n address: activeConnection.address,\n disconnectedTimestamp: Date.now(),\n icon: activeConnection.icon,\n });\n }\n } catch (e) {\n set({\n connecting: false,\n connectionError: 'Connector connection failed: ' + (e instanceof Error ? e.message : String(e)),\n });\n }\n },\n\n /**\n * Disconnects the currently active wallet or a specific wallet\n */\n disconnect: async (connectorType?: string) => {\n // Guard against re-entry\n if (get().disconnecting) return;\n set({ disconnecting: true });\n\n try {\n if (connectorType) {\n // Disconnect specific connector\n const connectorToDisconnect = get().connections[connectorType as ConnectorType];\n\n if (connectorToDisconnect) {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorToDisconnect.connectorType));\n await foundAdapter?.disconnect(connectorToDisconnect);\n\n set((state) => {\n const newConnections = { ...state.connections };\n delete newConnections[connectorType as ConnectorType];\n\n // If the disconnected connector was the active one, try to switch to another one\n let newActiveConnection = state.activeConnection;\n if (state.activeConnection?.connectorType === connectorType) {\n const remainingConnectors = Object.values(newConnections);\n if (remainingConnectors.length > 0) {\n newActiveConnection = remainingConnectors[0];\n } else {\n newActiveConnection = undefined;\n }\n }\n\n return {\n connections: newConnections,\n activeConnection: newActiveConnection,\n connectionError: undefined,\n switchNetworkError: undefined,\n };\n });\n }\n } else {\n // Disconnect ALL connectors\n await get().disconnectAll();\n }\n\n if (Object.keys(get().connections).length === 0) {\n lastConnectedConnectorHelpers.removeLastConnectedConnector();\n impersonatedHelpers.removeImpersonated();\n } else {\n // Update last connected to the current active one (if any)\n const currentActive = get().activeConnection;\n if (currentActive) {\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: currentActive.connectorType,\n chainId: currentActive.chainId,\n address: currentActive.address,\n });\n }\n }\n } finally {\n set({ disconnecting: false });\n }\n },\n\n disconnectAll: async () => {\n await delay(null, 150);\n\n if (Array.isArray(adapter)) {\n await Promise.allSettled(\n adapter.map(async (a) => {\n try {\n await a.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }),\n );\n } else {\n try {\n await adapter.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }\n\n set({\n activeConnection: undefined,\n connections: {},\n connectionError: undefined,\n switchNetworkError: undefined,\n });\n impersonatedHelpers.removeImpersonated();\n },\n\n /**\n * Contains error message if connection failed\n */\n // connectionError is declared above with an initial value\n\n /**\n * Resets any connection errors\n */\n resetConnectionError: () => {\n set({ connectionError: undefined });\n },\n\n /**\n * Updates the active connection's properties\n * @param connector - Partial connector object with properties to update\n */\n updateActiveConnection: (connector: Partial<Connector<W>>) => {\n const activeConnection = get().activeConnection;\n // Determine which connector to update. If connectorType is provided, use it. Otherwise use activeConnection.\n const targetConnectorType = connector.connectorType ?? activeConnection?.connectorType;\n\n if (targetConnectorType) {\n // If chainId is updated, update storage\n if (connector.chainId && targetConnectorType === activeConnection?.connectorType) {\n // Update lastConnectedConnector storage if chainId changes and it's the active connector\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: targetConnectorType,\n chainId: connector.chainId,\n address: connector.address ?? activeConnection?.address,\n });\n }\n\n // Use produce for immutable state update\n set((state) =>\n produce(state, (draft) => {\n if (draft.connections[targetConnectorType as ConnectorType]) {\n draft.connections[targetConnectorType as ConnectorType] = {\n ...draft.connections[targetConnectorType as ConnectorType],\n ...connector,\n } as Connector<W>;\n\n // Also update activeConnection if it matches\n if (draft.activeConnection?.connectorType === targetConnectorType) {\n draft.activeConnection = draft.connections[targetConnectorType as ConnectorType];\n }\n }\n }),\n );\n } else {\n const isConnectorCanChange =\n connector.connectorType !== undefined && connector.chainId !== undefined && connector.address !== undefined;\n\n if (isConnectorCanChange) {\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: connector.connectorType!,\n chainId: connector.chainId!,\n address: connector.address!,\n });\n // It's a new connector or full replacement\n set((state) => {\n const newConnector = connector as Connector<W>;\n return {\n activeConnection: newConnector,\n connections: {\n ...state.connections,\n [newConnector.connectorType]: newConnector,\n },\n };\n });\n } else {\n console.warn('Attempted to set activeConnection with incomplete data while activeConnection was undefined.');\n }\n }\n },\n\n /**\n * Switches active connection from the list of connections\n */\n switchConnection: async (connectorType) => {\n const targetConnector = get().connections[connectorType as ConnectorType];\n if (!targetConnector) {\n console.warn(`No connection found for connector type: ${connectorType}`);\n return;\n }\n\n if (get().activeConnection?.connectorType === connectorType) {\n return;\n }\n\n try {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorType));\n if (foundAdapter?.switchConnection) {\n await foundAdapter.switchConnection(connectorType);\n }\n\n set((state) =>\n produce(state, (draft) => {\n draft.activeConnection = targetConnector;\n }),\n );\n\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: targetConnector.connectorType,\n chainId: targetConnector.chainId,\n address: targetConnector.address,\n });\n } catch (e) {\n console.error('Failed to switch connection:', e);\n }\n },\n\n /**\n * Switches the connected connector to a different network\n * @param chainId - Target chain ID to switch to\n * @param connectorType - Optional connector type to switch to. If not provided, will switch to the active connection.\n */\n switchNetwork: async (chainId: string | number, connectorType?: string) => {\n set({ switchNetworkError: undefined });\n const targetConnector = connectorType\n ? get().connections[connectorType as ConnectorType]\n : get().activeConnection;\n\n if (targetConnector) {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(targetConnector.connectorType));\n\n if (!foundAdapter) {\n set({ switchNetworkError: `No adapter found for active connector type: ${targetConnector.connectorType}` });\n return;\n }\n\n try {\n // Pass the local updateActiveConnection method from 'get()' to the adapter\n await foundAdapter.checkAndSwitchNetwork(chainId, targetConnector.chainId, get().updateActiveConnection);\n } catch (e) {\n set({ switchNetworkError: 'Switch network failed: ' + (e instanceof Error ? e.message : String(e)) });\n }\n }\n },\n\n /**\n * Contains error message if network switch failed\n */\n // switchNetworkError is declared above with an initial value\n\n /**\n * Resets any network switching errors\n */\n resetSwitchNetworkError: () => set({ switchNetworkError: undefined }),\n }));\n}\n"]}
1
+ {"version":3,"sources":["../src/store/satelliteConnectStore.ts"],"names":["createSatelliteConnectStore","adapter","callbackAfterConnected","setAutoFreeze","createStore","set","get","adapterKey","selectAdapterByKey","results","a","accumulator","currentResult","key","value","autoConnect","sevenDaysAgo","recentlyConnectedConnectorsListHelpers","lastConnectedConnector","lastConnectedConnectorHelpers","delay","isSafeApp","foundAdapter","OrbitAdapter","safeConnectorChainId","error","connectorType","chainId","getAdapterFromConnectorType","connector","state","isContractAddress","updatedConnector","activeConnection","e","currentState","connectorToDisconnect","wasActiveConnection","remainingConnectors","conn","newActiveConnection","candidateConnection","newAdapter","produce","draft","finalState","impersonatedHelpers","targetConnectorType","newConnector","targetConnector"],"mappings":"mHAyBO,SAASA,CAAAA,CAAwE,CACtF,OAAA,CAAAC,CAAAA,CACA,sBAAA,CAAAC,CACF,CAAA,CAAiD,CAE/C,OAAAC,mBAAAA,CAAc,KAAK,CAAA,CAEZC,mBAAAA,EAA0C,CAAE,CAACC,CAAAA,CAAKC,CAAAA,IAAS,CAIhE,UAAA,CAAaC,CAAAA,EAAeC,4BAAAA,CAAmB,CAAE,OAAA,CAAAP,CAAAA,CAAS,UAAA,CAAAM,CAAW,CAAC,CAAA,CAKtE,aAAA,CAAe,IAAM,CACnB,IAAIE,CAAAA,CAEJ,OAAI,KAAA,CAAM,OAAA,CAAQR,CAAO,CAAA,CACvBQ,CAAAA,CAAUR,CAAAA,CAAQ,GAAA,CAAKS,CAAAA,EAAMA,CAAAA,CAAE,aAAA,EAAe,CAAA,CAG9CD,CAAAA,CAAU,CAACR,CAAAA,CAAQ,aAAA,EAAe,CAAA,CAG7BQ,CAAAA,CAAQ,MAAA,CACb,CAACE,CAAAA,CAAaC,CAAAA,GAAkB,CAC9B,IAAMC,CAAAA,CAAMD,CAAAA,CAAc,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,CAE5C,IAAMC,CAAAA,CAAe,IAAA,CAAK,GAAA,EAAI,CAAI,MAAA,CAGlC,GAFAC,gDAAAA,CAAuC,yBAAA,CAA0BD,CAAY,CAAA,CAEzED,CAAAA,CAAa,CACf,IAAMG,CAAAA,CAAyBC,uCAAAA,CAA8B,yBAAA,EAA0B,CAErFD,CAAAA,EACA,CAAC,CAAC,oBAAA,CAAsB,eAAA,CAAiB,gBAAA,CAAkB,cAAc,CAAA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G,CACV,OAAA,CAAQ,KAAA,CAAM,8BAAA,CAAgC,CAAC,EACjD,CACF,CAAA,CAOA,aAAA,CAAe,MAAOtB,CAAAA,CAA0BD,CAAAA,GAA2B,CACzErB,CAAAA,CAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CAAA,CACrC,IAAM4C,CAAAA,CAAkBvB,CAAAA,CACpBpB,CAAAA,EAAI,CAAE,WAAA,CAAYoB,CAA8B,CAAA,CAChDpB,CAAAA,EAAI,CAAE,gBAAA,CAEV,GAAI2C,CAAAA,CAAiB,CACnB,IAAM3B,CAAAA,CAAehB,CAAAA,EAAI,CAAE,UAAA,CAAWsB,qCAAAA,CAA4BqB,CAAAA,CAAgB,aAAa,CAAC,CAAA,CAEhG,GAAI,CAAC3B,CAAAA,CAAc,CACjBjB,CAAAA,CAAI,CAAE,kBAAA,CAAoB,CAAA,4CAAA,EAA+C4C,CAAAA,CAAgB,aAAa,CAAA,CAAG,CAAC,CAAA,CAC1G,MACF,CAEA,GAAI,CAEF,MAAM3B,CAAAA,CAAa,qBAAA,CAAsBK,CAAAA,CAASsB,CAAAA,CAAgB,OAAA,CAAS3C,CAAAA,EAAI,CAAE,sBAAsB,EACzG,CAAA,MAAS4B,CAAAA,CAAG,CACV7B,CAAAA,CAAI,CAAE,kBAAA,CAAoB,yBAAA,EAA6B6B,CAAAA,YAAa,KAAA,CAAQA,CAAAA,CAAE,OAAA,CAAU,MAAA,CAAOA,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,CAAA,CAUA,uBAAA,CAAyB,IAAM7B,CAAAA,CAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CACtE,EAAE,CACJ","file":"index.js","sourcesContent":["import {\n ConnectorType,\n delay,\n getAdapterFromConnectorType,\n impersonatedHelpers,\n isSafeApp,\n lastConnectedConnectorHelpers,\n OrbitAdapter,\n recentlyConnectedConnectorsListHelpers,\n selectAdapterByKey,\n} from '@tuwaio/orbit-core';\nimport { produce, setAutoFreeze } from 'immer';\nimport { createStore } from 'zustand/vanilla';\n\nimport { BaseConnector, Connector, ISatelliteConnectStore, SatelliteConnectStoreInitialParameters } from '../types';\n\n/**\n * Creates a Satellite Connect store instance for managing connector connections and state\n *\n * @param params - Initial parameters for the store\n * @param params.adapter - Blockchain adapter(s) to use\n * @param params.callbackAfterConnected - Optional callback function called after successful connection\n *\n * @returns A Zustand store instance with connection state and methods\n */\nexport function createSatelliteConnectStore<C, W extends BaseConnector = BaseConnector>({\n adapter,\n callbackAfterConnected,\n}: SatelliteConnectStoreInitialParameters<C, W>) {\n // Disable autoFreeze for immers in this store, since connectors contain EventEmitter objects that must remain mutable to function correctly\n setAutoFreeze(false);\n\n return createStore<ISatelliteConnectStore<C, W>>()((set, get) => ({\n /**\n * Returns active adapter\n */\n getAdapter: (adapterKey) => selectAdapterByKey({ adapter, adapterKey }),\n\n /**\n * Get connectors for all configured adapters\n */\n getConnectors: () => {\n let results: { adapter: OrbitAdapter; connectors: C[] }[];\n\n if (Array.isArray(adapter)) {\n results = adapter.map((a) => a.getConnectors());\n } else {\n // Ensure the single adapter result is wrapped in an array for consistent processing\n results = [adapter.getConnectors()];\n }\n\n return results.reduce(\n (accumulator, currentResult) => {\n const key = currentResult.adapter;\n const value = currentResult.connectors;\n return {\n ...accumulator,\n [key]: value,\n };\n },\n {} as Partial<Record<OrbitAdapter, C[]>>,\n );\n },\n\n initializeAutoConnect: async (autoConnect) => {\n // Cleanup old recently connected connectors (older than 7 days)\n const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;\n recentlyConnectedConnectorsListHelpers.removeConnectorsOlderThan(sevenDaysAgo);\n\n if (autoConnect) {\n const lastConnectedConnector = lastConnectedConnectorHelpers.getLastConnectedConnector();\n if (\n lastConnectedConnector &&\n !['impersonatedwallet', 'walletconnect', 'coinbasewallet', 'bitgetwallet'].includes(\n lastConnectedConnector.connectorType.split(':')[1],\n )\n ) {\n await delay(null, 200);\n await get().connect({\n connectorType: lastConnectedConnector.connectorType,\n chainId: lastConnectedConnector.chainId,\n });\n }\n } else if (isSafeApp) {\n await delay(null, 200);\n const foundAdapter = get().getAdapter(OrbitAdapter.EVM);\n if (foundAdapter && foundAdapter.getSafeConnectorChainId) {\n const safeConnectorChainId = await foundAdapter.getSafeConnectorChainId();\n if (safeConnectorChainId) {\n await get().connect({ connectorType: `${OrbitAdapter.EVM}:safewallet`, chainId: safeConnectorChainId });\n }\n }\n }\n },\n\n connecting: false,\n disconnecting: false,\n connectionError: undefined,\n switchNetworkError: undefined,\n activeConnection: undefined,\n connections: {},\n\n setConnectionError: (error) => set({ connectionError: error }),\n\n /**\n * Connects to a connector\n * @param connectorType - Type of connector to connect to\n * @param chainId - Chain ID to connect on\n */\n connect: async ({ connectorType, chainId }) => {\n set({ connecting: true, connectionError: undefined });\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorType));\n\n if (!foundAdapter) {\n set({\n connecting: false,\n connectionError: `No adapter found for connector type: ${connectorType}`,\n });\n return;\n }\n\n try {\n // 1. Check if connector is already connected\n const existingConnector = get().connections[connectorType as ConnectorType];\n if (existingConnector) {\n return;\n }\n\n const connector = await foundAdapter.connect({\n connectorType,\n chainId,\n });\n\n // 2. Set initial connector state\n set((state) => {\n return {\n activeConnection: connector,\n connections: {\n ...state.connections,\n [connector.connectorType]: connector,\n },\n };\n });\n\n // 3. Check for contract address if the adapter supports it\n if (foundAdapter.checkIsContractAddress) {\n const isContractAddress = await foundAdapter.checkIsContractAddress({\n address: connector.address,\n chainId,\n });\n\n // Update only the isContractAddress property\n get().updateActiveConnection({ ...connector, isContractAddress });\n }\n\n // 4. Run callback if provided\n if (callbackAfterConnected) {\n // Use the latest connector state after potential updates (like isContractAddress)\n const updatedConnector = get().activeConnection;\n if (updatedConnector && updatedConnector.connectorType === connectorType) {\n await callbackAfterConnected(updatedConnector);\n }\n }\n\n // 5. Final state updates\n set({ connecting: false });\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType,\n chainId,\n address: get().activeConnection?.address,\n });\n\n // Add to recently connected list\n const activeConnection = get().activeConnection;\n if (activeConnection && activeConnection.address) {\n recentlyConnectedConnectorsListHelpers.addConnector(activeConnection.connectorType, {\n address: activeConnection.address,\n disconnectedTimestamp: Date.now(),\n icon: activeConnection.icon,\n });\n }\n } catch (e) {\n set({\n connecting: false,\n connectionError: 'Connector connection failed: ' + (e instanceof Error ? e.message : String(e)),\n });\n }\n },\n\n /**\n * Disconnects the currently active wallet or a specific wallet\n */\n disconnect: async (connectorType?: string) => {\n // Guard against re-entry\n if (get().disconnecting) return;\n set({ disconnecting: true });\n\n try {\n if (connectorType) {\n // Disconnect specific connector\n const currentState = get();\n const connectorToDisconnect = currentState.connections[connectorType as ConnectorType];\n\n if (!connectorToDisconnect) {\n console.warn(`No connection found for connector type: ${connectorType}`);\n return;\n }\n\n // 1. Disconnect at adapter level\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorToDisconnect.connectorType));\n if (foundAdapter) {\n try {\n await foundAdapter.disconnect(connectorToDisconnect);\n } catch (e) {\n console.error(`Failed to disconnect connector ${connectorType}:`, e);\n // Continue with state cleanup even if adapter disconnect fails\n }\n }\n\n // 2. Determine if we need to switch to another connector\n const wasActiveConnection = currentState.activeConnection?.connectorType === connectorType;\n const remainingConnectors = Object.values(currentState.connections).filter(\n (conn) => conn.connectorType !== connectorType,\n );\n\n let newActiveConnection: typeof currentState.activeConnection = undefined;\n\n // 3. If the disconnected connector was active and there are remaining ones, switch first\n if (wasActiveConnection && remainingConnectors.length > 0) {\n const candidateConnection = remainingConnectors[0];\n\n try {\n const newAdapter = get().getAdapter(getAdapterFromConnectorType(candidateConnection.connectorType));\n if (newAdapter?.switchConnection) {\n await newAdapter.switchConnection(candidateConnection.connectorType);\n }\n // Only set as active if switchConnection succeeded\n newActiveConnection = candidateConnection;\n } catch (e) {\n console.error('Failed to switch to remaining connector:', e);\n // If switching fails, we'll leave activeConnection as undefined\n newActiveConnection = undefined;\n }\n } else if (!wasActiveConnection) {\n // If the disconnected connector wasn't active, keep the current active connection\n newActiveConnection = currentState.activeConnection;\n }\n\n // 4. Update state atomically using produce\n set((state) =>\n produce(state, (draft) => {\n // Remove the disconnected connector\n delete draft.connections[connectorType as ConnectorType];\n\n // Set the new active connection (could be undefined, another connector, or unchanged)\n draft.activeConnection = newActiveConnection;\n\n // Clear errors\n draft.connectionError = undefined;\n draft.switchNetworkError = undefined;\n }),\n );\n } else {\n // Disconnect ALL connectors\n await get().disconnectAll();\n }\n\n // 5. Handle storage updates\n const finalState = get();\n if (Object.keys(finalState.connections).length === 0) {\n lastConnectedConnectorHelpers.removeLastConnectedConnector();\n impersonatedHelpers.removeImpersonated();\n } else if (finalState.activeConnection) {\n // Update last connected to the current active one\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: finalState.activeConnection.connectorType,\n chainId: finalState.activeConnection.chainId,\n address: finalState.activeConnection.address,\n });\n }\n } catch (e) {\n console.error('Disconnect operation failed:', e);\n // Set error state if needed\n set((state) =>\n produce(state, (draft) => {\n draft.connectionError = `Disconnect failed: ${e instanceof Error ? e.message : String(e)}`;\n }),\n );\n } finally {\n set({ disconnecting: false });\n }\n },\n\n disconnectAll: async () => {\n await delay(null, 150);\n\n if (Array.isArray(adapter)) {\n await Promise.allSettled(\n adapter.map(async (a) => {\n try {\n await a.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }),\n );\n } else {\n try {\n await adapter.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }\n\n set({\n activeConnection: undefined,\n connections: {},\n connectionError: undefined,\n switchNetworkError: undefined,\n });\n impersonatedHelpers.removeImpersonated();\n },\n\n /**\n * Contains error message if connection failed\n */\n // connectionError is declared above with an initial value\n\n /**\n * Resets any connection errors\n */\n resetConnectionError: () => {\n set({ connectionError: undefined });\n },\n\n /**\n * Updates the active connection's properties\n * @param connector - Partial connector object with properties to update\n */\n updateActiveConnection: (connector: Partial<Connector<W>>) => {\n const activeConnection = get().activeConnection;\n // Determine which connector to update. If connectorType is provided, use it. Otherwise use activeConnection.\n const targetConnectorType = connector.connectorType ?? activeConnection?.connectorType;\n\n if (targetConnectorType) {\n // If chainId is updated, update storage\n if (connector.chainId && targetConnectorType === activeConnection?.connectorType) {\n // Update lastConnectedConnector storage if chainId changes and it's the active connector\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: targetConnectorType,\n chainId: connector.chainId,\n address: connector.address ?? activeConnection?.address,\n });\n }\n\n // Use produce for immutable state update\n set((state) =>\n produce(state, (draft) => {\n if (draft.connections[targetConnectorType as ConnectorType]) {\n draft.connections[targetConnectorType as ConnectorType] = {\n ...draft.connections[targetConnectorType as ConnectorType],\n ...connector,\n } as Connector<W>;\n\n // Also update activeConnection if it matches\n if (draft.activeConnection?.connectorType === targetConnectorType) {\n draft.activeConnection = draft.connections[targetConnectorType as ConnectorType];\n }\n }\n }),\n );\n } else {\n const isConnectorCanChange =\n connector.connectorType !== undefined && connector.chainId !== undefined && connector.address !== undefined;\n\n if (isConnectorCanChange) {\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: connector.connectorType!,\n chainId: connector.chainId!,\n address: connector.address!,\n });\n // It's a new connector or full replacement\n set((state) => {\n const newConnector = connector as Connector<W>;\n return {\n activeConnection: newConnector,\n connections: {\n ...state.connections,\n [newConnector.connectorType]: newConnector,\n },\n };\n });\n } else {\n console.warn('Attempted to set activeConnection with incomplete data while activeConnection was undefined.');\n }\n }\n },\n\n /**\n * Switches active connection from the list of connections\n */\n switchConnection: async (connectorType) => {\n const targetConnector = get().connections[connectorType as ConnectorType];\n if (!targetConnector) {\n console.warn(`No connection found for connector type: ${connectorType}`);\n return;\n }\n\n if (get().activeConnection?.connectorType === connectorType) {\n return;\n }\n\n try {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorType));\n if (foundAdapter?.switchConnection) {\n await foundAdapter.switchConnection(connectorType);\n }\n\n set((state) =>\n produce(state, (draft) => {\n draft.activeConnection = targetConnector;\n }),\n );\n\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: targetConnector.connectorType,\n chainId: targetConnector.chainId,\n address: targetConnector.address,\n });\n } catch (e) {\n console.error('Failed to switch connection:', e);\n }\n },\n\n /**\n * Switches the connected connector to a different network\n * @param chainId - Target chain ID to switch to\n * @param connectorType - Optional connector type to switch to. If not provided, will switch to the active connection.\n */\n switchNetwork: async (chainId: string | number, connectorType?: string) => {\n set({ switchNetworkError: undefined });\n const targetConnector = connectorType\n ? get().connections[connectorType as ConnectorType]\n : get().activeConnection;\n\n if (targetConnector) {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(targetConnector.connectorType));\n\n if (!foundAdapter) {\n set({ switchNetworkError: `No adapter found for active connector type: ${targetConnector.connectorType}` });\n return;\n }\n\n try {\n // Pass the local updateActiveConnection method from 'get()' to the adapter\n await foundAdapter.checkAndSwitchNetwork(chainId, targetConnector.chainId, get().updateActiveConnection);\n } catch (e) {\n set({ switchNetworkError: 'Switch network failed: ' + (e instanceof Error ? e.message : String(e)) });\n }\n }\n },\n\n /**\n * Contains error message if network switch failed\n */\n // switchNetworkError is declared above with an initial value\n\n /**\n * Resets any network switching errors\n */\n resetSwitchNetworkError: () => set({ switchNetworkError: undefined }),\n }));\n}\n"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import {selectAdapterByKey,getAdapterFromConnectorType,lastConnectedConnectorHelpers,delay,impersonatedHelpers,recentlyConnectedConnectorsListHelpers,isSafeApp,OrbitAdapter}from'@tuwaio/orbit-core';import {setAutoFreeze,produce}from'immer';import {createStore}from'zustand/vanilla';function k({adapter:d,callbackAfterConnected:p}){return setAutoFreeze(false),createStore()((i,c)=>({getAdapter:n=>selectAdapterByKey({adapter:d,adapterKey:n}),getConnectors:()=>{let n;return Array.isArray(d)?n=d.map(o=>o.getConnectors()):n=[d.getConnectors()],n.reduce((o,e)=>{let r=e.adapter,t=e.connectors;return {...o,[r]:t}},{})},initializeAutoConnect:async n=>{let o=Date.now()-6048e5;if(recentlyConnectedConnectorsListHelpers.removeConnectorsOlderThan(o),n){let e=lastConnectedConnectorHelpers.getLastConnectedConnector();e&&!["impersonatedwallet","walletconnect","coinbasewallet","bitgetwallet"].includes(e.connectorType.split(":")[1])&&(await delay(null,200),await c().connect({connectorType:e.connectorType,chainId:e.chainId}));}else if(isSafeApp){await delay(null,200);let e=c().getAdapter(OrbitAdapter.EVM);if(e&&e.getSafeConnectorChainId){let r=await e.getSafeConnectorChainId();r&&await c().connect({connectorType:`${OrbitAdapter.EVM}:safewallet`,chainId:r});}}},connecting:false,disconnecting:false,connectionError:void 0,switchNetworkError:void 0,activeConnection:void 0,connections:{},setConnectionError:n=>i({connectionError:n}),connect:async({connectorType:n,chainId:o})=>{i({connecting:true,connectionError:void 0});let e=c().getAdapter(getAdapterFromConnectorType(n));if(!e){i({connecting:false,connectionError:`No adapter found for connector type: ${n}`});return}try{if(c().connections[n])return;let t=await e.connect({connectorType:n,chainId:o});if(i(s=>({activeConnection:t,connections:{...s.connections,[t.connectorType]:t}})),e.checkIsContractAddress){let s=await e.checkIsContractAddress({address:t.address,chainId:o});c().updateActiveConnection({...t,isContractAddress:s});}if(p){let s=c().activeConnection;s&&s.connectorType===n&&await p(s);}i({connecting:!1}),lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:n,chainId:o,address:c().activeConnection?.address});let a=c().activeConnection;a&&a.address&&recentlyConnectedConnectorsListHelpers.addConnector(a.connectorType,{address:a.address,disconnectedTimestamp:Date.now(),icon:a.icon});}catch(r){i({connecting:false,connectionError:"Connector connection failed: "+(r instanceof Error?r.message:String(r))});}},disconnect:async n=>{if(!c().disconnecting){i({disconnecting:true});try{if(n){let o=c().connections[n];o&&(await c().getAdapter(getAdapterFromConnectorType(o.connectorType))?.disconnect(o),i(r=>{let t={...r.connections};delete t[n];let a=r.activeConnection;if(r.activeConnection?.connectorType===n){let s=Object.values(t);s.length>0?a=s[0]:a=void 0;}return {connections:t,activeConnection:a,connectionError:void 0,switchNetworkError:void 0}}));}else await c().disconnectAll();if(Object.keys(c().connections).length===0)lastConnectedConnectorHelpers.removeLastConnectedConnector(),impersonatedHelpers.removeImpersonated();else {let o=c().activeConnection;o&&lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:o.connectorType,chainId:o.chainId,address:o.address});}}finally{i({disconnecting:false});}}},disconnectAll:async()=>{if(await delay(null,150),Array.isArray(d))await Promise.allSettled(d.map(async n=>{try{await n.disconnect();}catch{}}));else try{await d.disconnect();}catch{}i({activeConnection:void 0,connections:{},connectionError:void 0,switchNetworkError:void 0}),impersonatedHelpers.removeImpersonated();},resetConnectionError:()=>{i({connectionError:void 0});},updateActiveConnection:n=>{let o=c().activeConnection,e=n.connectorType??o?.connectorType;e?(n.chainId&&e===o?.connectorType&&lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:e,chainId:n.chainId,address:n.address??o?.address}),i(r=>produce(r,t=>{t.connections[e]&&(t.connections[e]={...t.connections[e],...n},t.activeConnection?.connectorType===e&&(t.activeConnection=t.connections[e]));}))):n.connectorType!==void 0&&n.chainId!==void 0&&n.address!==void 0?(lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:n.connectorType,chainId:n.chainId,address:n.address}),i(t=>{let a=n;return {activeConnection:a,connections:{...t.connections,[a.connectorType]:a}}})):console.warn("Attempted to set activeConnection with incomplete data while activeConnection was undefined.");},switchConnection:async n=>{let o=c().connections[n];if(!o){console.warn(`No connection found for connector type: ${n}`);return}if(c().activeConnection?.connectorType!==n)try{let e=c().getAdapter(getAdapterFromConnectorType(n));e?.switchConnection&&await e.switchConnection(n),i(r=>produce(r,t=>{t.activeConnection=o;})),lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:o.connectorType,chainId:o.chainId,address:o.address});}catch(e){console.error("Failed to switch connection:",e);}},switchNetwork:async(n,o)=>{i({switchNetworkError:void 0});let e=o?c().connections[o]:c().activeConnection;if(e){let r=c().getAdapter(getAdapterFromConnectorType(e.connectorType));if(!r){i({switchNetworkError:`No adapter found for active connector type: ${e.connectorType}`});return}try{await r.checkAndSwitchNetwork(n,e.chainId,c().updateActiveConnection);}catch(t){i({switchNetworkError:"Switch network failed: "+(t instanceof Error?t.message:String(t))});}}},resetSwitchNetworkError:()=>i({switchNetworkError:void 0})}))}export{k as createSatelliteConnectStore};//# sourceMappingURL=index.mjs.map
1
+ import {selectAdapterByKey,getAdapterFromConnectorType,lastConnectedConnectorHelpers,delay,impersonatedHelpers,recentlyConnectedConnectorsListHelpers,isSafeApp,OrbitAdapter}from'@tuwaio/orbit-core';import {setAutoFreeze,produce}from'immer';import {createStore}from'zustand/vanilla';function b({adapter:l,callbackAfterConnected:h}){return setAutoFreeze(false),createStore()((r,c)=>({getAdapter:n=>selectAdapterByKey({adapter:l,adapterKey:n}),getConnectors:()=>{let n;return Array.isArray(l)?n=l.map(o=>o.getConnectors()):n=[l.getConnectors()],n.reduce((o,e)=>{let i=e.adapter,t=e.connectors;return {...o,[i]:t}},{})},initializeAutoConnect:async n=>{let o=Date.now()-6048e5;if(recentlyConnectedConnectorsListHelpers.removeConnectorsOlderThan(o),n){let e=lastConnectedConnectorHelpers.getLastConnectedConnector();e&&!["impersonatedwallet","walletconnect","coinbasewallet","bitgetwallet"].includes(e.connectorType.split(":")[1])&&(await delay(null,200),await c().connect({connectorType:e.connectorType,chainId:e.chainId}));}else if(isSafeApp){await delay(null,200);let e=c().getAdapter(OrbitAdapter.EVM);if(e&&e.getSafeConnectorChainId){let i=await e.getSafeConnectorChainId();i&&await c().connect({connectorType:`${OrbitAdapter.EVM}:safewallet`,chainId:i});}}},connecting:false,disconnecting:false,connectionError:void 0,switchNetworkError:void 0,activeConnection:void 0,connections:{},setConnectionError:n=>r({connectionError:n}),connect:async({connectorType:n,chainId:o})=>{r({connecting:true,connectionError:void 0});let e=c().getAdapter(getAdapterFromConnectorType(n));if(!e){r({connecting:false,connectionError:`No adapter found for connector type: ${n}`});return}try{if(c().connections[n])return;let t=await e.connect({connectorType:n,chainId:o});if(r(s=>({activeConnection:t,connections:{...s.connections,[t.connectorType]:t}})),e.checkIsContractAddress){let s=await e.checkIsContractAddress({address:t.address,chainId:o});c().updateActiveConnection({...t,isContractAddress:s});}if(h){let s=c().activeConnection;s&&s.connectorType===n&&await h(s);}r({connecting:!1}),lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:n,chainId:o,address:c().activeConnection?.address});let a=c().activeConnection;a&&a.address&&recentlyConnectedConnectorsListHelpers.addConnector(a.connectorType,{address:a.address,disconnectedTimestamp:Date.now(),icon:a.icon});}catch(i){r({connecting:false,connectionError:"Connector connection failed: "+(i instanceof Error?i.message:String(i))});}},disconnect:async n=>{if(!c().disconnecting){r({disconnecting:true});try{if(n){let e=c(),i=e.connections[n];if(!i){console.warn(`No connection found for connector type: ${n}`);return}let t=c().getAdapter(getAdapterFromConnectorType(i.connectorType));if(t)try{await t.disconnect(i);}catch(d){console.error(`Failed to disconnect connector ${n}:`,d);}let a=e.activeConnection?.connectorType===n,s=Object.values(e.connections).filter(d=>d.connectorType!==n),w;if(a&&s.length>0){let d=s[0];try{let C=c().getAdapter(getAdapterFromConnectorType(d.connectorType));C?.switchConnection&&await C.switchConnection(d.connectorType),w=d;}catch(C){console.error("Failed to switch to remaining connector:",C),w=void 0;}}else a||(w=e.activeConnection);r(d=>produce(d,C=>{delete C.connections[n],C.activeConnection=w,C.connectionError=void 0,C.switchNetworkError=void 0;}));}else await c().disconnectAll();let o=c();Object.keys(o.connections).length===0?(lastConnectedConnectorHelpers.removeLastConnectedConnector(),impersonatedHelpers.removeImpersonated()):o.activeConnection&&lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:o.activeConnection.connectorType,chainId:o.activeConnection.chainId,address:o.activeConnection.address});}catch(o){console.error("Disconnect operation failed:",o),r(e=>produce(e,i=>{i.connectionError=`Disconnect failed: ${o instanceof Error?o.message:String(o)}`;}));}finally{r({disconnecting:false});}}},disconnectAll:async()=>{if(await delay(null,150),Array.isArray(l))await Promise.allSettled(l.map(async n=>{try{await n.disconnect();}catch{}}));else try{await l.disconnect();}catch{}r({activeConnection:void 0,connections:{},connectionError:void 0,switchNetworkError:void 0}),impersonatedHelpers.removeImpersonated();},resetConnectionError:()=>{r({connectionError:void 0});},updateActiveConnection:n=>{let o=c().activeConnection,e=n.connectorType??o?.connectorType;e?(n.chainId&&e===o?.connectorType&&lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:e,chainId:n.chainId,address:n.address??o?.address}),r(i=>produce(i,t=>{t.connections[e]&&(t.connections[e]={...t.connections[e],...n},t.activeConnection?.connectorType===e&&(t.activeConnection=t.connections[e]));}))):n.connectorType!==void 0&&n.chainId!==void 0&&n.address!==void 0?(lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:n.connectorType,chainId:n.chainId,address:n.address}),r(t=>{let a=n;return {activeConnection:a,connections:{...t.connections,[a.connectorType]:a}}})):console.warn("Attempted to set activeConnection with incomplete data while activeConnection was undefined.");},switchConnection:async n=>{let o=c().connections[n];if(!o){console.warn(`No connection found for connector type: ${n}`);return}if(c().activeConnection?.connectorType!==n)try{let e=c().getAdapter(getAdapterFromConnectorType(n));e?.switchConnection&&await e.switchConnection(n),r(i=>produce(i,t=>{t.activeConnection=o;})),lastConnectedConnectorHelpers.setLastConnectedConnector({connectorType:o.connectorType,chainId:o.chainId,address:o.address});}catch(e){console.error("Failed to switch connection:",e);}},switchNetwork:async(n,o)=>{r({switchNetworkError:void 0});let e=o?c().connections[o]:c().activeConnection;if(e){let i=c().getAdapter(getAdapterFromConnectorType(e.connectorType));if(!i){r({switchNetworkError:`No adapter found for active connector type: ${e.connectorType}`});return}try{await i.checkAndSwitchNetwork(n,e.chainId,c().updateActiveConnection);}catch(t){r({switchNetworkError:"Switch network failed: "+(t instanceof Error?t.message:String(t))});}}},resetSwitchNetworkError:()=>r({switchNetworkError:void 0})}))}export{b as createSatelliteConnectStore};//# sourceMappingURL=index.mjs.map
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/store/satelliteConnectStore.ts"],"names":["createSatelliteConnectStore","adapter","callbackAfterConnected","setAutoFreeze","createStore","set","get","adapterKey","selectAdapterByKey","results","a","accumulator","currentResult","key","value","autoConnect","sevenDaysAgo","recentlyConnectedConnectorsListHelpers","lastConnectedConnector","lastConnectedConnectorHelpers","delay","isSafeApp","foundAdapter","OrbitAdapter","safeConnectorChainId","error","connectorType","chainId","getAdapterFromConnectorType","connector","state","isContractAddress","updatedConnector","activeConnection","e","connectorToDisconnect","newConnections","newActiveConnection","remainingConnectors","impersonatedHelpers","currentActive","targetConnectorType","produce","draft","newConnector","targetConnector"],"mappings":"0RAyBO,SAASA,CAAAA,CAAwE,CACtF,OAAA,CAAAC,CAAAA,CACA,sBAAA,CAAAC,CACF,EAAiD,CAE/C,OAAAC,aAAAA,CAAc,KAAK,CAAA,CAEZC,WAAAA,GAA4C,CAACC,CAAAA,CAAKC,CAAAA,IAAS,CAIhE,UAAA,CAAaC,CAAAA,EAAeC,kBAAAA,CAAmB,CAAE,OAAA,CAAAP,CAAAA,CAAS,UAAA,CAAAM,CAAW,CAAC,CAAA,CAKtE,cAAe,IAAM,CACnB,IAAIE,CAAAA,CAEJ,OAAI,KAAA,CAAM,QAAQR,CAAO,CAAA,CACvBQ,CAAAA,CAAUR,CAAAA,CAAQ,GAAA,CAAKS,CAAAA,EAAMA,EAAE,aAAA,EAAe,CAAA,CAG9CD,CAAAA,CAAU,CAACR,CAAAA,CAAQ,aAAA,EAAe,CAAA,CAG7BQ,CAAAA,CAAQ,MAAA,CACb,CAACE,CAAAA,CAAaC,CAAAA,GAAkB,CAC9B,IAAMC,CAAAA,CAAMD,CAAAA,CAAc,OAAA,CACpBE,CAAAA,CAAQF,CAAAA,CAAc,UAAA,CAC5B,OAAO,CACL,GAAGD,CAAAA,CACH,CAACE,CAAG,EAAGC,CACT,CACF,CAAA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B,aAAA,CAC/B,QAASA,CAAAA,CAAgB,OAAA,CACzB,OAAA,CAASA,CAAAA,CAAgB,OAC3B,CAAC,EACH,CAAA,MAAS,CAAA,CAAG,CACV,OAAA,CAAQ,KAAA,CAAM,8BAAA,CAAgC,CAAC,EACjD,CACF,CAAA,CAOA,aAAA,CAAe,MAAOlB,CAAAA,CAA0BD,CAAAA,GAA2B,CACzErB,CAAAA,CAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CAAA,CACrC,IAAMwC,CAAAA,CAAkBnB,CAAAA,CACpBpB,CAAAA,EAAI,CAAE,WAAA,CAAYoB,CAA8B,EAChDpB,CAAAA,EAAI,CAAE,gBAAA,CAEV,GAAIuC,CAAAA,CAAiB,CACnB,IAAMvB,CAAAA,CAAehB,CAAAA,EAAI,CAAE,UAAA,CAAWsB,2BAAAA,CAA4BiB,CAAAA,CAAgB,aAAa,CAAC,CAAA,CAEhG,GAAI,CAACvB,CAAAA,CAAc,CACjBjB,CAAAA,CAAI,CAAE,kBAAA,CAAoB,CAAA,4CAAA,EAA+CwC,CAAAA,CAAgB,aAAa,CAAA,CAAG,CAAC,EAC1G,MACF,CAEA,GAAI,CAEF,MAAMvB,CAAAA,CAAa,qBAAA,CAAsBK,CAAAA,CAASkB,CAAAA,CAAgB,OAAA,CAASvC,CAAAA,EAAI,CAAE,sBAAsB,EACzG,OAAS4B,CAAAA,CAAG,CACV7B,CAAAA,CAAI,CAAE,kBAAA,CAAoB,yBAAA,EAA6B6B,CAAAA,YAAa,KAAA,CAAQA,CAAAA,CAAE,OAAA,CAAU,MAAA,CAAOA,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,CAAA,CAUA,uBAAA,CAAyB,IAAM7B,CAAAA,CAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CACtE,CAAA,CAAE,CACJ","file":"index.mjs","sourcesContent":["import {\n ConnectorType,\n delay,\n getAdapterFromConnectorType,\n impersonatedHelpers,\n isSafeApp,\n lastConnectedConnectorHelpers,\n OrbitAdapter,\n recentlyConnectedConnectorsListHelpers,\n selectAdapterByKey,\n} from '@tuwaio/orbit-core';\nimport { produce, setAutoFreeze } from 'immer';\nimport { createStore } from 'zustand/vanilla';\n\nimport { BaseConnector, Connector, ISatelliteConnectStore, SatelliteConnectStoreInitialParameters } from '../types';\n\n/**\n * Creates a Satellite Connect store instance for managing connector connections and state\n *\n * @param params - Initial parameters for the store\n * @param params.adapter - Blockchain adapter(s) to use\n * @param params.callbackAfterConnected - Optional callback function called after successful connection\n *\n * @returns A Zustand store instance with connection state and methods\n */\nexport function createSatelliteConnectStore<C, W extends BaseConnector = BaseConnector>({\n adapter,\n callbackAfterConnected,\n}: SatelliteConnectStoreInitialParameters<C, W>) {\n // Disable autoFreeze for immers in this store, since connectors contain EventEmitter objects that must remain mutable to function correctly\n setAutoFreeze(false);\n\n return createStore<ISatelliteConnectStore<C, W>>()((set, get) => ({\n /**\n * Returns active adapter\n */\n getAdapter: (adapterKey) => selectAdapterByKey({ adapter, adapterKey }),\n\n /**\n * Get connectors for all configured adapters\n */\n getConnectors: () => {\n let results: { adapter: OrbitAdapter; connectors: C[] }[];\n\n if (Array.isArray(adapter)) {\n results = adapter.map((a) => a.getConnectors());\n } else {\n // Ensure the single adapter result is wrapped in an array for consistent processing\n results = [adapter.getConnectors()];\n }\n\n return results.reduce(\n (accumulator, currentResult) => {\n const key = currentResult.adapter;\n const value = currentResult.connectors;\n return {\n ...accumulator,\n [key]: value,\n };\n },\n {} as Partial<Record<OrbitAdapter, C[]>>,\n );\n },\n\n initializeAutoConnect: async (autoConnect) => {\n // Cleanup old recently connected connectors (older than 7 days)\n const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;\n recentlyConnectedConnectorsListHelpers.removeConnectorsOlderThan(sevenDaysAgo);\n\n if (autoConnect) {\n const lastConnectedConnector = lastConnectedConnectorHelpers.getLastConnectedConnector();\n if (\n lastConnectedConnector &&\n !['impersonatedwallet', 'walletconnect', 'coinbasewallet', 'bitgetwallet'].includes(\n lastConnectedConnector.connectorType.split(':')[1],\n )\n ) {\n await delay(null, 200);\n await get().connect({\n connectorType: lastConnectedConnector.connectorType,\n chainId: lastConnectedConnector.chainId,\n });\n }\n } else if (isSafeApp) {\n await delay(null, 200);\n const foundAdapter = get().getAdapter(OrbitAdapter.EVM);\n if (foundAdapter && foundAdapter.getSafeConnectorChainId) {\n const safeConnectorChainId = await foundAdapter.getSafeConnectorChainId();\n if (safeConnectorChainId) {\n await get().connect({ connectorType: `${OrbitAdapter.EVM}:safewallet`, chainId: safeConnectorChainId });\n }\n }\n }\n },\n\n connecting: false,\n disconnecting: false,\n connectionError: undefined,\n switchNetworkError: undefined,\n activeConnection: undefined,\n connections: {},\n\n setConnectionError: (error) => set({ connectionError: error }),\n\n /**\n * Connects to a connector\n * @param connectorType - Type of connector to connect to\n * @param chainId - Chain ID to connect on\n */\n connect: async ({ connectorType, chainId }) => {\n set({ connecting: true, connectionError: undefined });\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorType));\n\n if (!foundAdapter) {\n set({\n connecting: false,\n connectionError: `No adapter found for connector type: ${connectorType}`,\n });\n return;\n }\n\n try {\n // 1. Check if connector is already connected\n const existingConnector = get().connections[connectorType as ConnectorType];\n if (existingConnector) {\n return;\n }\n\n const connector = await foundAdapter.connect({\n connectorType,\n chainId,\n });\n\n // 2. Set initial connector state\n set((state) => {\n return {\n activeConnection: connector,\n connections: {\n ...state.connections,\n [connector.connectorType]: connector,\n },\n };\n });\n\n // 3. Check for contract address if the adapter supports it\n if (foundAdapter.checkIsContractAddress) {\n const isContractAddress = await foundAdapter.checkIsContractAddress({\n address: connector.address,\n chainId,\n });\n\n // Update only the isContractAddress property\n get().updateActiveConnection({ ...connector, isContractAddress });\n }\n\n // 4. Run callback if provided\n if (callbackAfterConnected) {\n // Use the latest connector state after potential updates (like isContractAddress)\n const updatedConnector = get().activeConnection;\n if (updatedConnector && updatedConnector.connectorType === connectorType) {\n await callbackAfterConnected(updatedConnector);\n }\n }\n\n // 5. Final state updates\n set({ connecting: false });\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType,\n chainId,\n address: get().activeConnection?.address,\n });\n\n // Add to recently connected list\n const activeConnection = get().activeConnection;\n if (activeConnection && activeConnection.address) {\n recentlyConnectedConnectorsListHelpers.addConnector(activeConnection.connectorType, {\n address: activeConnection.address,\n disconnectedTimestamp: Date.now(),\n icon: activeConnection.icon,\n });\n }\n } catch (e) {\n set({\n connecting: false,\n connectionError: 'Connector connection failed: ' + (e instanceof Error ? e.message : String(e)),\n });\n }\n },\n\n /**\n * Disconnects the currently active wallet or a specific wallet\n */\n disconnect: async (connectorType?: string) => {\n // Guard against re-entry\n if (get().disconnecting) return;\n set({ disconnecting: true });\n\n try {\n if (connectorType) {\n // Disconnect specific connector\n const connectorToDisconnect = get().connections[connectorType as ConnectorType];\n\n if (connectorToDisconnect) {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorToDisconnect.connectorType));\n await foundAdapter?.disconnect(connectorToDisconnect);\n\n set((state) => {\n const newConnections = { ...state.connections };\n delete newConnections[connectorType as ConnectorType];\n\n // If the disconnected connector was the active one, try to switch to another one\n let newActiveConnection = state.activeConnection;\n if (state.activeConnection?.connectorType === connectorType) {\n const remainingConnectors = Object.values(newConnections);\n if (remainingConnectors.length > 0) {\n newActiveConnection = remainingConnectors[0];\n } else {\n newActiveConnection = undefined;\n }\n }\n\n return {\n connections: newConnections,\n activeConnection: newActiveConnection,\n connectionError: undefined,\n switchNetworkError: undefined,\n };\n });\n }\n } else {\n // Disconnect ALL connectors\n await get().disconnectAll();\n }\n\n if (Object.keys(get().connections).length === 0) {\n lastConnectedConnectorHelpers.removeLastConnectedConnector();\n impersonatedHelpers.removeImpersonated();\n } else {\n // Update last connected to the current active one (if any)\n const currentActive = get().activeConnection;\n if (currentActive) {\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: currentActive.connectorType,\n chainId: currentActive.chainId,\n address: currentActive.address,\n });\n }\n }\n } finally {\n set({ disconnecting: false });\n }\n },\n\n disconnectAll: async () => {\n await delay(null, 150);\n\n if (Array.isArray(adapter)) {\n await Promise.allSettled(\n adapter.map(async (a) => {\n try {\n await a.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }),\n );\n } else {\n try {\n await adapter.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }\n\n set({\n activeConnection: undefined,\n connections: {},\n connectionError: undefined,\n switchNetworkError: undefined,\n });\n impersonatedHelpers.removeImpersonated();\n },\n\n /**\n * Contains error message if connection failed\n */\n // connectionError is declared above with an initial value\n\n /**\n * Resets any connection errors\n */\n resetConnectionError: () => {\n set({ connectionError: undefined });\n },\n\n /**\n * Updates the active connection's properties\n * @param connector - Partial connector object with properties to update\n */\n updateActiveConnection: (connector: Partial<Connector<W>>) => {\n const activeConnection = get().activeConnection;\n // Determine which connector to update. If connectorType is provided, use it. Otherwise use activeConnection.\n const targetConnectorType = connector.connectorType ?? activeConnection?.connectorType;\n\n if (targetConnectorType) {\n // If chainId is updated, update storage\n if (connector.chainId && targetConnectorType === activeConnection?.connectorType) {\n // Update lastConnectedConnector storage if chainId changes and it's the active connector\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: targetConnectorType,\n chainId: connector.chainId,\n address: connector.address ?? activeConnection?.address,\n });\n }\n\n // Use produce for immutable state update\n set((state) =>\n produce(state, (draft) => {\n if (draft.connections[targetConnectorType as ConnectorType]) {\n draft.connections[targetConnectorType as ConnectorType] = {\n ...draft.connections[targetConnectorType as ConnectorType],\n ...connector,\n } as Connector<W>;\n\n // Also update activeConnection if it matches\n if (draft.activeConnection?.connectorType === targetConnectorType) {\n draft.activeConnection = draft.connections[targetConnectorType as ConnectorType];\n }\n }\n }),\n );\n } else {\n const isConnectorCanChange =\n connector.connectorType !== undefined && connector.chainId !== undefined && connector.address !== undefined;\n\n if (isConnectorCanChange) {\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: connector.connectorType!,\n chainId: connector.chainId!,\n address: connector.address!,\n });\n // It's a new connector or full replacement\n set((state) => {\n const newConnector = connector as Connector<W>;\n return {\n activeConnection: newConnector,\n connections: {\n ...state.connections,\n [newConnector.connectorType]: newConnector,\n },\n };\n });\n } else {\n console.warn('Attempted to set activeConnection with incomplete data while activeConnection was undefined.');\n }\n }\n },\n\n /**\n * Switches active connection from the list of connections\n */\n switchConnection: async (connectorType) => {\n const targetConnector = get().connections[connectorType as ConnectorType];\n if (!targetConnector) {\n console.warn(`No connection found for connector type: ${connectorType}`);\n return;\n }\n\n if (get().activeConnection?.connectorType === connectorType) {\n return;\n }\n\n try {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorType));\n if (foundAdapter?.switchConnection) {\n await foundAdapter.switchConnection(connectorType);\n }\n\n set((state) =>\n produce(state, (draft) => {\n draft.activeConnection = targetConnector;\n }),\n );\n\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: targetConnector.connectorType,\n chainId: targetConnector.chainId,\n address: targetConnector.address,\n });\n } catch (e) {\n console.error('Failed to switch connection:', e);\n }\n },\n\n /**\n * Switches the connected connector to a different network\n * @param chainId - Target chain ID to switch to\n * @param connectorType - Optional connector type to switch to. If not provided, will switch to the active connection.\n */\n switchNetwork: async (chainId: string | number, connectorType?: string) => {\n set({ switchNetworkError: undefined });\n const targetConnector = connectorType\n ? get().connections[connectorType as ConnectorType]\n : get().activeConnection;\n\n if (targetConnector) {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(targetConnector.connectorType));\n\n if (!foundAdapter) {\n set({ switchNetworkError: `No adapter found for active connector type: ${targetConnector.connectorType}` });\n return;\n }\n\n try {\n // Pass the local updateActiveConnection method from 'get()' to the adapter\n await foundAdapter.checkAndSwitchNetwork(chainId, targetConnector.chainId, get().updateActiveConnection);\n } catch (e) {\n set({ switchNetworkError: 'Switch network failed: ' + (e instanceof Error ? e.message : String(e)) });\n }\n }\n },\n\n /**\n * Contains error message if network switch failed\n */\n // switchNetworkError is declared above with an initial value\n\n /**\n * Resets any network switching errors\n */\n resetSwitchNetworkError: () => set({ switchNetworkError: undefined }),\n }));\n}\n"]}
1
+ {"version":3,"sources":["../src/store/satelliteConnectStore.ts"],"names":["createSatelliteConnectStore","adapter","callbackAfterConnected","setAutoFreeze","createStore","set","get","adapterKey","selectAdapterByKey","results","a","accumulator","currentResult","key","value","autoConnect","sevenDaysAgo","recentlyConnectedConnectorsListHelpers","lastConnectedConnector","lastConnectedConnectorHelpers","delay","isSafeApp","foundAdapter","OrbitAdapter","safeConnectorChainId","error","connectorType","chainId","getAdapterFromConnectorType","connector","state","isContractAddress","updatedConnector","activeConnection","e","currentState","connectorToDisconnect","wasActiveConnection","remainingConnectors","conn","newActiveConnection","candidateConnection","newAdapter","produce","draft","finalState","impersonatedHelpers","targetConnectorType","newConnector","targetConnector"],"mappings":"0RAyBO,SAASA,CAAAA,CAAwE,CACtF,OAAA,CAAAC,CAAAA,CACA,sBAAA,CAAAC,CACF,CAAA,CAAiD,CAE/C,OAAAC,aAAAA,CAAc,KAAK,CAAA,CAEZC,WAAAA,EAA0C,CAAE,CAACC,CAAAA,CAAKC,CAAAA,IAAS,CAIhE,UAAA,CAAaC,CAAAA,EAAeC,kBAAAA,CAAmB,CAAE,OAAA,CAAAP,CAAAA,CAAS,UAAA,CAAAM,CAAW,CAAC,CAAA,CAKtE,aAAA,CAAe,IAAM,CACnB,IAAIE,CAAAA,CAEJ,OAAI,KAAA,CAAM,OAAA,CAAQR,CAAO,CAAA,CACvBQ,CAAAA,CAAUR,CAAAA,CAAQ,GAAA,CAAKS,CAAAA,EAAMA,CAAAA,CAAE,aAAA,EAAe,CAAA,CAG9CD,CAAAA,CAAU,CAACR,CAAAA,CAAQ,aAAA,EAAe,CAAA,CAG7BQ,CAAAA,CAAQ,MAAA,CACb,CAACE,CAAAA,CAAaC,CAAAA,GAAkB,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E,sBAAsB,EACzG,CAAA,MAAS4B,CAAAA,CAAG,CACV7B,CAAAA,CAAI,CAAE,kBAAA,CAAoB,yBAAA,EAA6B6B,CAAAA,YAAa,KAAA,CAAQA,CAAAA,CAAE,OAAA,CAAU,MAAA,CAAOA,CAAC,CAAA,CAAG,CAAC,EACtG,CACF,CACF,CAAA,CAUA,uBAAA,CAAyB,IAAM7B,CAAAA,CAAI,CAAE,kBAAA,CAAoB,MAAU,CAAC,CACtE,EAAE,CACJ","file":"index.mjs","sourcesContent":["import {\n ConnectorType,\n delay,\n getAdapterFromConnectorType,\n impersonatedHelpers,\n isSafeApp,\n lastConnectedConnectorHelpers,\n OrbitAdapter,\n recentlyConnectedConnectorsListHelpers,\n selectAdapterByKey,\n} from '@tuwaio/orbit-core';\nimport { produce, setAutoFreeze } from 'immer';\nimport { createStore } from 'zustand/vanilla';\n\nimport { BaseConnector, Connector, ISatelliteConnectStore, SatelliteConnectStoreInitialParameters } from '../types';\n\n/**\n * Creates a Satellite Connect store instance for managing connector connections and state\n *\n * @param params - Initial parameters for the store\n * @param params.adapter - Blockchain adapter(s) to use\n * @param params.callbackAfterConnected - Optional callback function called after successful connection\n *\n * @returns A Zustand store instance with connection state and methods\n */\nexport function createSatelliteConnectStore<C, W extends BaseConnector = BaseConnector>({\n adapter,\n callbackAfterConnected,\n}: SatelliteConnectStoreInitialParameters<C, W>) {\n // Disable autoFreeze for immers in this store, since connectors contain EventEmitter objects that must remain mutable to function correctly\n setAutoFreeze(false);\n\n return createStore<ISatelliteConnectStore<C, W>>()((set, get) => ({\n /**\n * Returns active adapter\n */\n getAdapter: (adapterKey) => selectAdapterByKey({ adapter, adapterKey }),\n\n /**\n * Get connectors for all configured adapters\n */\n getConnectors: () => {\n let results: { adapter: OrbitAdapter; connectors: C[] }[];\n\n if (Array.isArray(adapter)) {\n results = adapter.map((a) => a.getConnectors());\n } else {\n // Ensure the single adapter result is wrapped in an array for consistent processing\n results = [adapter.getConnectors()];\n }\n\n return results.reduce(\n (accumulator, currentResult) => {\n const key = currentResult.adapter;\n const value = currentResult.connectors;\n return {\n ...accumulator,\n [key]: value,\n };\n },\n {} as Partial<Record<OrbitAdapter, C[]>>,\n );\n },\n\n initializeAutoConnect: async (autoConnect) => {\n // Cleanup old recently connected connectors (older than 7 days)\n const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;\n recentlyConnectedConnectorsListHelpers.removeConnectorsOlderThan(sevenDaysAgo);\n\n if (autoConnect) {\n const lastConnectedConnector = lastConnectedConnectorHelpers.getLastConnectedConnector();\n if (\n lastConnectedConnector &&\n !['impersonatedwallet', 'walletconnect', 'coinbasewallet', 'bitgetwallet'].includes(\n lastConnectedConnector.connectorType.split(':')[1],\n )\n ) {\n await delay(null, 200);\n await get().connect({\n connectorType: lastConnectedConnector.connectorType,\n chainId: lastConnectedConnector.chainId,\n });\n }\n } else if (isSafeApp) {\n await delay(null, 200);\n const foundAdapter = get().getAdapter(OrbitAdapter.EVM);\n if (foundAdapter && foundAdapter.getSafeConnectorChainId) {\n const safeConnectorChainId = await foundAdapter.getSafeConnectorChainId();\n if (safeConnectorChainId) {\n await get().connect({ connectorType: `${OrbitAdapter.EVM}:safewallet`, chainId: safeConnectorChainId });\n }\n }\n }\n },\n\n connecting: false,\n disconnecting: false,\n connectionError: undefined,\n switchNetworkError: undefined,\n activeConnection: undefined,\n connections: {},\n\n setConnectionError: (error) => set({ connectionError: error }),\n\n /**\n * Connects to a connector\n * @param connectorType - Type of connector to connect to\n * @param chainId - Chain ID to connect on\n */\n connect: async ({ connectorType, chainId }) => {\n set({ connecting: true, connectionError: undefined });\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorType));\n\n if (!foundAdapter) {\n set({\n connecting: false,\n connectionError: `No adapter found for connector type: ${connectorType}`,\n });\n return;\n }\n\n try {\n // 1. Check if connector is already connected\n const existingConnector = get().connections[connectorType as ConnectorType];\n if (existingConnector) {\n return;\n }\n\n const connector = await foundAdapter.connect({\n connectorType,\n chainId,\n });\n\n // 2. Set initial connector state\n set((state) => {\n return {\n activeConnection: connector,\n connections: {\n ...state.connections,\n [connector.connectorType]: connector,\n },\n };\n });\n\n // 3. Check for contract address if the adapter supports it\n if (foundAdapter.checkIsContractAddress) {\n const isContractAddress = await foundAdapter.checkIsContractAddress({\n address: connector.address,\n chainId,\n });\n\n // Update only the isContractAddress property\n get().updateActiveConnection({ ...connector, isContractAddress });\n }\n\n // 4. Run callback if provided\n if (callbackAfterConnected) {\n // Use the latest connector state after potential updates (like isContractAddress)\n const updatedConnector = get().activeConnection;\n if (updatedConnector && updatedConnector.connectorType === connectorType) {\n await callbackAfterConnected(updatedConnector);\n }\n }\n\n // 5. Final state updates\n set({ connecting: false });\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType,\n chainId,\n address: get().activeConnection?.address,\n });\n\n // Add to recently connected list\n const activeConnection = get().activeConnection;\n if (activeConnection && activeConnection.address) {\n recentlyConnectedConnectorsListHelpers.addConnector(activeConnection.connectorType, {\n address: activeConnection.address,\n disconnectedTimestamp: Date.now(),\n icon: activeConnection.icon,\n });\n }\n } catch (e) {\n set({\n connecting: false,\n connectionError: 'Connector connection failed: ' + (e instanceof Error ? e.message : String(e)),\n });\n }\n },\n\n /**\n * Disconnects the currently active wallet or a specific wallet\n */\n disconnect: async (connectorType?: string) => {\n // Guard against re-entry\n if (get().disconnecting) return;\n set({ disconnecting: true });\n\n try {\n if (connectorType) {\n // Disconnect specific connector\n const currentState = get();\n const connectorToDisconnect = currentState.connections[connectorType as ConnectorType];\n\n if (!connectorToDisconnect) {\n console.warn(`No connection found for connector type: ${connectorType}`);\n return;\n }\n\n // 1. Disconnect at adapter level\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorToDisconnect.connectorType));\n if (foundAdapter) {\n try {\n await foundAdapter.disconnect(connectorToDisconnect);\n } catch (e) {\n console.error(`Failed to disconnect connector ${connectorType}:`, e);\n // Continue with state cleanup even if adapter disconnect fails\n }\n }\n\n // 2. Determine if we need to switch to another connector\n const wasActiveConnection = currentState.activeConnection?.connectorType === connectorType;\n const remainingConnectors = Object.values(currentState.connections).filter(\n (conn) => conn.connectorType !== connectorType,\n );\n\n let newActiveConnection: typeof currentState.activeConnection = undefined;\n\n // 3. If the disconnected connector was active and there are remaining ones, switch first\n if (wasActiveConnection && remainingConnectors.length > 0) {\n const candidateConnection = remainingConnectors[0];\n\n try {\n const newAdapter = get().getAdapter(getAdapterFromConnectorType(candidateConnection.connectorType));\n if (newAdapter?.switchConnection) {\n await newAdapter.switchConnection(candidateConnection.connectorType);\n }\n // Only set as active if switchConnection succeeded\n newActiveConnection = candidateConnection;\n } catch (e) {\n console.error('Failed to switch to remaining connector:', e);\n // If switching fails, we'll leave activeConnection as undefined\n newActiveConnection = undefined;\n }\n } else if (!wasActiveConnection) {\n // If the disconnected connector wasn't active, keep the current active connection\n newActiveConnection = currentState.activeConnection;\n }\n\n // 4. Update state atomically using produce\n set((state) =>\n produce(state, (draft) => {\n // Remove the disconnected connector\n delete draft.connections[connectorType as ConnectorType];\n\n // Set the new active connection (could be undefined, another connector, or unchanged)\n draft.activeConnection = newActiveConnection;\n\n // Clear errors\n draft.connectionError = undefined;\n draft.switchNetworkError = undefined;\n }),\n );\n } else {\n // Disconnect ALL connectors\n await get().disconnectAll();\n }\n\n // 5. Handle storage updates\n const finalState = get();\n if (Object.keys(finalState.connections).length === 0) {\n lastConnectedConnectorHelpers.removeLastConnectedConnector();\n impersonatedHelpers.removeImpersonated();\n } else if (finalState.activeConnection) {\n // Update last connected to the current active one\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: finalState.activeConnection.connectorType,\n chainId: finalState.activeConnection.chainId,\n address: finalState.activeConnection.address,\n });\n }\n } catch (e) {\n console.error('Disconnect operation failed:', e);\n // Set error state if needed\n set((state) =>\n produce(state, (draft) => {\n draft.connectionError = `Disconnect failed: ${e instanceof Error ? e.message : String(e)}`;\n }),\n );\n } finally {\n set({ disconnecting: false });\n }\n },\n\n disconnectAll: async () => {\n await delay(null, 150);\n\n if (Array.isArray(adapter)) {\n await Promise.allSettled(\n adapter.map(async (a) => {\n try {\n await a.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }),\n );\n } else {\n try {\n await adapter.disconnect();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n /* empty */\n }\n }\n\n set({\n activeConnection: undefined,\n connections: {},\n connectionError: undefined,\n switchNetworkError: undefined,\n });\n impersonatedHelpers.removeImpersonated();\n },\n\n /**\n * Contains error message if connection failed\n */\n // connectionError is declared above with an initial value\n\n /**\n * Resets any connection errors\n */\n resetConnectionError: () => {\n set({ connectionError: undefined });\n },\n\n /**\n * Updates the active connection's properties\n * @param connector - Partial connector object with properties to update\n */\n updateActiveConnection: (connector: Partial<Connector<W>>) => {\n const activeConnection = get().activeConnection;\n // Determine which connector to update. If connectorType is provided, use it. Otherwise use activeConnection.\n const targetConnectorType = connector.connectorType ?? activeConnection?.connectorType;\n\n if (targetConnectorType) {\n // If chainId is updated, update storage\n if (connector.chainId && targetConnectorType === activeConnection?.connectorType) {\n // Update lastConnectedConnector storage if chainId changes and it's the active connector\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: targetConnectorType,\n chainId: connector.chainId,\n address: connector.address ?? activeConnection?.address,\n });\n }\n\n // Use produce for immutable state update\n set((state) =>\n produce(state, (draft) => {\n if (draft.connections[targetConnectorType as ConnectorType]) {\n draft.connections[targetConnectorType as ConnectorType] = {\n ...draft.connections[targetConnectorType as ConnectorType],\n ...connector,\n } as Connector<W>;\n\n // Also update activeConnection if it matches\n if (draft.activeConnection?.connectorType === targetConnectorType) {\n draft.activeConnection = draft.connections[targetConnectorType as ConnectorType];\n }\n }\n }),\n );\n } else {\n const isConnectorCanChange =\n connector.connectorType !== undefined && connector.chainId !== undefined && connector.address !== undefined;\n\n if (isConnectorCanChange) {\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: connector.connectorType!,\n chainId: connector.chainId!,\n address: connector.address!,\n });\n // It's a new connector or full replacement\n set((state) => {\n const newConnector = connector as Connector<W>;\n return {\n activeConnection: newConnector,\n connections: {\n ...state.connections,\n [newConnector.connectorType]: newConnector,\n },\n };\n });\n } else {\n console.warn('Attempted to set activeConnection with incomplete data while activeConnection was undefined.');\n }\n }\n },\n\n /**\n * Switches active connection from the list of connections\n */\n switchConnection: async (connectorType) => {\n const targetConnector = get().connections[connectorType as ConnectorType];\n if (!targetConnector) {\n console.warn(`No connection found for connector type: ${connectorType}`);\n return;\n }\n\n if (get().activeConnection?.connectorType === connectorType) {\n return;\n }\n\n try {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(connectorType));\n if (foundAdapter?.switchConnection) {\n await foundAdapter.switchConnection(connectorType);\n }\n\n set((state) =>\n produce(state, (draft) => {\n draft.activeConnection = targetConnector;\n }),\n );\n\n lastConnectedConnectorHelpers.setLastConnectedConnector({\n connectorType: targetConnector.connectorType,\n chainId: targetConnector.chainId,\n address: targetConnector.address,\n });\n } catch (e) {\n console.error('Failed to switch connection:', e);\n }\n },\n\n /**\n * Switches the connected connector to a different network\n * @param chainId - Target chain ID to switch to\n * @param connectorType - Optional connector type to switch to. If not provided, will switch to the active connection.\n */\n switchNetwork: async (chainId: string | number, connectorType?: string) => {\n set({ switchNetworkError: undefined });\n const targetConnector = connectorType\n ? get().connections[connectorType as ConnectorType]\n : get().activeConnection;\n\n if (targetConnector) {\n const foundAdapter = get().getAdapter(getAdapterFromConnectorType(targetConnector.connectorType));\n\n if (!foundAdapter) {\n set({ switchNetworkError: `No adapter found for active connector type: ${targetConnector.connectorType}` });\n return;\n }\n\n try {\n // Pass the local updateActiveConnection method from 'get()' to the adapter\n await foundAdapter.checkAndSwitchNetwork(chainId, targetConnector.chainId, get().updateActiveConnection);\n } catch (e) {\n set({ switchNetworkError: 'Switch network failed: ' + (e instanceof Error ? e.message : String(e)) });\n }\n }\n },\n\n /**\n * Contains error message if network switch failed\n */\n // switchNetworkError is declared above with an initial value\n\n /**\n * Resets any network switching errors\n */\n resetSwitchNetworkError: () => set({ switchNetworkError: undefined }),\n }));\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuwaio/satellite-core",
3
- "version": "1.0.0-fix-packages-alpha.17.c720fd6",
3
+ "version": "1.0.0-fix-packages-alpha.19.eb3499f",
4
4
  "private": false,
5
5
  "author": "Oleksandr Tkach",
6
6
  "license": "Apache-2.0",