@dynamic-labs-sdk/wallet-connect 0.2.4 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/SessionClosedUnexpectedlyError-DiLzuxNr.cjs.js +41 -0
  2. package/dist/SessionClosedUnexpectedlyError-DiLzuxNr.cjs.js.map +1 -0
  3. package/dist/SessionClosedUnexpectedlyError-DtBVy8Mt.esm.js +23 -0
  4. package/dist/SessionClosedUnexpectedlyError-DtBVy8Mt.esm.js.map +1 -0
  5. package/dist/appendWalletConnectUriToDeepLink/appendWalletConnectUriToDeepLink.d.ts +26 -0
  6. package/dist/appendWalletConnectUriToDeepLink/appendWalletConnectUriToDeepLink.d.ts.map +1 -0
  7. package/dist/appendWalletConnectUriToDeepLink/index.d.ts +2 -0
  8. package/dist/appendWalletConnectUriToDeepLink/index.d.ts.map +1 -0
  9. package/dist/core.cjs.js +127 -312
  10. package/dist/core.cjs.js.map +1 -1
  11. package/dist/core.esm.js +127 -310
  12. package/dist/core.esm.js.map +1 -1
  13. package/dist/createWalletAccountsForWalletConnectWalletProvider/createWalletAccountsForWalletConnectWalletProvider.d.ts.map +1 -1
  14. package/dist/createWalletConnectSessionEventEmitter/createWalletConnectSessionEventEmitter.d.ts +30 -0
  15. package/dist/createWalletConnectSessionEventEmitter/createWalletConnectSessionEventEmitter.d.ts.map +1 -0
  16. package/dist/createWalletConnectSessionEventEmitter/index.d.ts +2 -0
  17. package/dist/createWalletConnectSessionEventEmitter/index.d.ts.map +1 -0
  18. package/dist/errors/SessionClosedUnexpectedlyError.d.ts +16 -0
  19. package/dist/errors/SessionClosedUnexpectedlyError.d.ts.map +1 -0
  20. package/dist/exports/core.d.ts +2 -4
  21. package/dist/exports/core.d.ts.map +1 -1
  22. package/dist/exports/index.d.ts +2 -0
  23. package/dist/exports/index.d.ts.map +1 -1
  24. package/dist/importWalletConnectAuthResponse/importWalletConnectAuthResponse.d.ts +6 -1
  25. package/dist/importWalletConnectAuthResponse/importWalletConnectAuthResponse.d.ts.map +1 -1
  26. package/dist/importWalletConnectAuthResponse/verifyWalletConnectAuths/verifyWalletConnectAuths.d.ts.map +1 -1
  27. package/dist/importWalletConnectSession/importWalletConnectSession.d.ts +9 -5
  28. package/dist/importWalletConnectSession/importWalletConnectSession.d.ts.map +1 -1
  29. package/dist/index.cjs.js +39 -3
  30. package/dist/index.cjs.js.map +1 -1
  31. package/dist/index.esm.js +36 -2
  32. package/dist/index.esm.js.map +1 -1
  33. package/dist/isWalletConnectWalletProvider/isWalletConnectWalletProvider.d.ts.map +1 -1
  34. package/dist/signClient/getSignClient/createSignClient/createSignClient.d.ts.map +1 -1
  35. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  36. package/dist/walletConnectWalletProvider.types.d.ts +5 -10
  37. package/dist/walletConnectWalletProvider.types.d.ts.map +1 -1
  38. package/package.json +5 -4
  39. package/dist/initializeWalletConnectExtension/index.d.ts +0 -2
  40. package/dist/initializeWalletConnectExtension/index.d.ts.map +0 -1
  41. package/dist/initializeWalletConnectExtension/initializeWalletConnectExtension.d.ts +0 -3
  42. package/dist/initializeWalletConnectExtension/initializeWalletConnectExtension.d.ts.map +0 -1
  43. package/dist/isWalletConnectWalletProvider-CXVKIbLV.cjs.js +0 -36
  44. package/dist/isWalletConnectWalletProvider-CXVKIbLV.cjs.js.map +0 -1
  45. package/dist/isWalletConnectWalletProvider-DUlbqnZc.esm.js +0 -18
  46. package/dist/isWalletConnectWalletProvider-DUlbqnZc.esm.js.map +0 -1
  47. package/dist/namespaceRegistry/getNamespaceRegistry/createNamespaceRegistry/createNamespaceRegistry.d.ts +0 -3
  48. package/dist/namespaceRegistry/getNamespaceRegistry/createNamespaceRegistry/createNamespaceRegistry.d.ts.map +0 -1
  49. package/dist/namespaceRegistry/getNamespaceRegistry/createNamespaceRegistry/index.d.ts +0 -2
  50. package/dist/namespaceRegistry/getNamespaceRegistry/createNamespaceRegistry/index.d.ts.map +0 -1
  51. package/dist/namespaceRegistry/getNamespaceRegistry/getNamespaceRegistry.d.ts +0 -2
  52. package/dist/namespaceRegistry/getNamespaceRegistry/getNamespaceRegistry.d.ts.map +0 -1
  53. package/dist/namespaceRegistry/getNamespaceRegistry/index.d.ts +0 -2
  54. package/dist/namespaceRegistry/getNamespaceRegistry/index.d.ts.map +0 -1
  55. package/dist/namespaceRegistry/index.d.ts +0 -3
  56. package/dist/namespaceRegistry/index.d.ts.map +0 -1
  57. package/dist/namespaceRegistry/namespaceRegistry.types.d.ts +0 -34
  58. package/dist/namespaceRegistry/namespaceRegistry.types.d.ts.map +0 -1
  59. package/dist/sessionTopicsData/clearTemporarySessions/clearTemporarySessions.d.ts +0 -13
  60. package/dist/sessionTopicsData/clearTemporarySessions/clearTemporarySessions.d.ts.map +0 -1
  61. package/dist/sessionTopicsData/clearTemporarySessions/index.d.ts +0 -2
  62. package/dist/sessionTopicsData/clearTemporarySessions/index.d.ts.map +0 -1
  63. package/dist/sessionTopicsData/getSessionTopicsData/getSessionTopicsData.d.ts +0 -11
  64. package/dist/sessionTopicsData/getSessionTopicsData/getSessionTopicsData.d.ts.map +0 -1
  65. package/dist/sessionTopicsData/getSessionTopicsData/index.d.ts +0 -2
  66. package/dist/sessionTopicsData/getSessionTopicsData/index.d.ts.map +0 -1
  67. package/dist/sessionTopicsData/schema.d.ts +0 -4
  68. package/dist/sessionTopicsData/schema.d.ts.map +0 -1
  69. package/dist/sessionTopicsData/sessionTopicsData.types.d.ts +0 -14
  70. package/dist/sessionTopicsData/sessionTopicsData.types.d.ts.map +0 -1
  71. package/dist/sessionTopicsData/setSessionTopicsData/index.d.ts +0 -2
  72. package/dist/sessionTopicsData/setSessionTopicsData/index.d.ts.map +0 -1
  73. package/dist/sessionTopicsData/setSessionTopicsData/setSessionTopicsData.d.ts +0 -16
  74. package/dist/sessionTopicsData/setSessionTopicsData/setSessionTopicsData.d.ts.map +0 -1
  75. package/dist/syncSessionsToWalletProviders/addMissingWalletProvidersForSessions/addMissingWalletProvidersForSessions.d.ts +0 -12
  76. package/dist/syncSessionsToWalletProviders/addMissingWalletProvidersForSessions/addMissingWalletProvidersForSessions.d.ts.map +0 -1
  77. package/dist/syncSessionsToWalletProviders/addMissingWalletProvidersForSessions/index.d.ts +0 -2
  78. package/dist/syncSessionsToWalletProviders/addMissingWalletProvidersForSessions/index.d.ts.map +0 -1
  79. package/dist/syncSessionsToWalletProviders/index.d.ts +0 -2
  80. package/dist/syncSessionsToWalletProviders/index.d.ts.map +0 -1
  81. package/dist/syncSessionsToWalletProviders/syncSessionsToWalletProviders.d.ts +0 -8
  82. package/dist/syncSessionsToWalletProviders/syncSessionsToWalletProviders.d.ts.map +0 -1
package/dist/core.esm.js CHANGED
@@ -1,11 +1,10 @@
1
- import { n as name, r as version, t as isWalletConnectWalletProvider } from "./isWalletConnectWalletProvider-DUlbqnZc.esm.js";
1
+ import { n as name, r as version, t as SessionClosedUnexpectedlyError } from "./SessionClosedUnexpectedlyError-DtBVy8Mt.esm.js";
2
2
  import { assertPackageVersion } from "@dynamic-labs-sdk/assert-package-version";
3
- import { SDK_ERRORS, formatMessage } from "@walletconnect/utils";
3
+ import { formatMessage } from "@walletconnect/utils";
4
4
  import { getWalletAccounts, verifyWalletAccount } from "@dynamic-labs-sdk/client";
5
- import { WalletProviderPriority, assertDefined, createRuntimeServiceAccessKey, createStorageKeySchema, createVisit, emitWalletAccountsChangedEvent, filterDuplicates, formatWalletAccountId, getCore, getWalletProviderRegistry, getWalletProviders, setUnverifiedWalletAccounts, splitWalletProviderKey, updateAuthFromVerifyResponse, updateWalletProviderKeysForVerifiedCredentials, verifyMessageSignatureOwnership, waitForProjectSettings } from "@dynamic-labs-sdk/client/core";
6
- import * as z from "zod/mini";
7
- import SignClient from "@walletconnect/sign-client";
8
5
  import { WalletProviderEnum } from "@dynamic-labs/sdk-api-core";
6
+ import { WalletProviderPriority, assertDefined, createRuntimeServiceAccessKey, createVisit, createWalletProviderEventEmitter, emitWalletAccountsChangedEvent, filterDuplicates, formatWalletAccountId, getCore, getWalletProviderRegistry, setUnverifiedWalletAccounts, updateAuthFromVerifyResponse, updateWalletProviderKeysForVerifiedCredentials, verifyMessageSignatureOwnership } from "@dynamic-labs-sdk/client/core";
7
+ import SignClient from "@walletconnect/sign-client";
9
8
 
10
9
  //#region src/splitCaip10Token/splitCaip10Token.ts
11
10
  /**
@@ -32,6 +31,53 @@ const splitCaip10Token = (caip10Token) => {
32
31
  };
33
32
  };
34
33
 
34
+ //#endregion
35
+ //#region src/createWalletConnectSessionEventEmitter/createWalletConnectSessionEventEmitter.ts
36
+ /**
37
+ * Creates a WalletConnect session event emitter with common event handling logic.
38
+ *
39
+ * Handles chainChanged, accountsChanged, and disconnected events from WalletConnect sessions.
40
+ *
41
+ * @param params.getSession - Function to get the current session
42
+ * @param params.namespaceKey - The WalletConnect namespace key (e.g., 'eip155', 'solana')
43
+ * @param params.sessionTopic - The session topic to listen for events
44
+ * @param params.signClient - The WalletConnect sign client instance
45
+ * @param params.formatAddress - Optional function to format addresses (e.g., EIP-55 for EVM)
46
+ * @returns An object with cleanupEventEmitter and getEventEmitter functions
47
+ */
48
+ const createWalletConnectSessionEventEmitter = ({ formatAddress, getSession, namespaceKey, sessionTopic, signClient }) => {
49
+ return createWalletProviderEventEmitter({
50
+ removeEventListeners: ({ setupReturnValue: handleSessionEvent }) => {
51
+ signClient.off("session_event", handleSessionEvent);
52
+ },
53
+ setupEventListeners: ({ handleAccountsChanged, handleDisconnected, handleNetworkChanged }) => {
54
+ const handleSessionEvent = ({ params: { event }, topic }) => {
55
+ if (topic !== sessionTopic) return;
56
+ if (event.name === "chainChanged") {
57
+ const networkParam = event.data;
58
+ handleNetworkChanged({ networkId: networkParam.startsWith(`${namespaceKey}:`) ? networkParam.split(":")[1] : networkParam });
59
+ return;
60
+ }
61
+ if (event.name === "accountsChanged") {
62
+ const accountsParam = event.data;
63
+ handleAccountsChanged({ addresses: filterDuplicates(accountsParam.map((account) => {
64
+ if (account.startsWith(`${namespaceKey}:`)) return splitCaip10Token(account).address;
65
+ return account;
66
+ })).map((address) => formatAddress ? formatAddress(address) : address) });
67
+ return;
68
+ }
69
+ if (event.name === "disconnected") {
70
+ handleDisconnected();
71
+ return;
72
+ }
73
+ };
74
+ getSession();
75
+ signClient.on("session_event", handleSessionEvent);
76
+ return handleSessionEvent;
77
+ }
78
+ });
79
+ };
80
+
35
81
  //#endregion
36
82
  //#region src/createWalletAccountsForWalletConnectWalletProvider/createWalletAccountsForWalletConnectWalletProvider.ts
37
83
  const createWalletAccountsForWalletConnectWalletProvider = ({ walletProvider }) => {
@@ -43,8 +89,9 @@ const createWalletAccountsForWalletConnectWalletProvider = ({ walletProvider })
43
89
  * and they have attributed to them the methods, events and networks that are expected
44
90
  * to be supported by the wallet application, as well as which accounts are connected.
45
91
  */
46
- const namespace = walletProvider.session.namespaces[walletProvider.namespaceKey];
47
- assertDefined(namespace, `Namespace key ${walletProvider.namespaceKey} of wallet provider ${walletProvider.key} not found in its session ${walletProvider.topic}`);
92
+ const session = walletProvider.getSession();
93
+ const namespace = session.namespaces[walletProvider.namespaceKey];
94
+ assertDefined(namespace, `Namespace key ${walletProvider.namespaceKey} of wallet provider ${walletProvider.key} not found in its session ${session.topic}`);
48
95
  const accountAddresses = filterDuplicates(namespace.accounts.map((account) => splitCaip10Token(account).address));
49
96
  const formatAddress = walletProvider.formatWalletAddress ?? (({ address }) => address);
50
97
  return accountAddresses.map((address) => ({
@@ -61,253 +108,18 @@ const createWalletAccountsForWalletConnectWalletProvider = ({ walletProvider })
61
108
  }));
62
109
  };
63
110
 
64
- //#endregion
65
- //#region src/sessionTopicsData/schema.ts
66
- const sessionTopicsStorageKeySchema = createStorageKeySchema({
67
- key: "sessionTopics",
68
- schema: z.record(
69
- /**
70
- * The session topic that identifies this session.
71
- */
72
- z.string(),
73
- /**
74
- * The session data.
75
- */
76
- z.object({ shouldAddToDynamicWalletAccounts: z.boolean() })
77
- )
78
- });
79
-
80
- //#endregion
81
- //#region src/sessionTopicsData/setSessionTopicsData/setSessionTopicsData.ts
82
- /**
83
- * Sets the session topics data.
84
- *
85
- * Read more about it in the sessionTopicsData.types.ts file.
86
- *
87
- * @param update - The function to update the session topics data.
88
- * @param client - The client instance.
89
- */
90
- const setSessionTopicsData = async ({ update }, client) => {
91
- const { storage } = getCore(client);
92
- const newSessionTopicsData = update(await storage.getItem(sessionTopicsStorageKeySchema) ?? {});
93
- if (Object.keys(newSessionTopicsData).length === 0) return storage.removeItem(sessionTopicsStorageKeySchema);
94
- return storage.setItem(sessionTopicsStorageKeySchema, newSessionTopicsData);
95
- };
96
-
97
- //#endregion
98
- //#region src/sessionTopicsData/getSessionTopicsData/getSessionTopicsData.ts
99
- /**
100
- * Gets the session topics data.
101
- *
102
- * Read more about it in the sessionTopicsData.types.ts file.
103
- * @param client - The client instance.
104
- */
105
- const getSessionTopicsData = async (client) => {
106
- const { storage } = getCore(client);
107
- return await storage.getItem(sessionTopicsStorageKeySchema) ?? {};
108
- };
109
-
110
- //#endregion
111
- //#region src/signClient/getSignClient/createSignClient/createSignClient.ts
112
- const createSignClient = async (client) => {
113
- const core = getCore(client);
114
- assertDefined(client.projectSettings, "Project settings not available");
115
- const generalSettings = client.projectSettings.general;
116
- assertDefined(generalSettings.displayName, "Please configure an app name in dashboard to use WalletConnect");
117
- const projectId = client.projectSettings.sdk.walletConnect?.projectId;
118
- assertDefined(projectId, "Please configure a project ID for WalletConnect in dashboard");
119
- const customStoragePrefix = `dynamic_${core.environmentId}_walletconnect`;
120
- const displayName = core.metadata?.name ?? generalSettings.displayName;
121
- const appLogo = core.metadata?.iconUrl ?? generalSettings.appLogo;
122
- return SignClient.init({
123
- customStoragePrefix,
124
- metadata: {
125
- description: "",
126
- icons: appLogo ? [appLogo] : [],
127
- name: displayName,
128
- url: ""
129
- },
130
- projectId
131
- });
132
- };
133
-
134
- //#endregion
135
- //#region src/signClient/getSignClient/getSignClient.ts
136
- const getSignClient = createRuntimeServiceAccessKey("walletConnectSignClient", (client) => createSignClient(client));
137
-
138
- //#endregion
139
- //#region src/namespaceRegistry/getNamespaceRegistry/createNamespaceRegistry/createNamespaceRegistry.ts
140
- const createNamespaceRegistry = () => {
141
- const walletProviderBuilderMap = /* @__PURE__ */ new Map();
142
- return {
143
- getWalletProviderBuilder: (key) => walletProviderBuilderMap.get(key),
144
- registerNamespace: ({ createWalletProviderFromSession, namespaceKey }) => {
145
- walletProviderBuilderMap.set(namespaceKey, createWalletProviderFromSession);
146
- }
147
- };
148
- };
149
-
150
- //#endregion
151
- //#region src/namespaceRegistry/getNamespaceRegistry/getNamespaceRegistry.ts
152
- const getNamespaceRegistry = createRuntimeServiceAccessKey("walletConnectNamespaceRegistry", createNamespaceRegistry);
153
-
154
- //#endregion
155
- //#region src/syncSessionsToWalletProviders/addMissingWalletProvidersForSessions/addMissingWalletProvidersForSessions.ts
156
- const addMissingWalletProvidersForSessions = async ({ sessions, allowOverridingWalletProviders }, client) => {
157
- const namespaceRegistry = getNamespaceRegistry(client);
158
- const walletProviderRegistry = getWalletProviderRegistry(client);
159
- const sessionTopicsData = await getSessionTopicsData(client);
160
- const currentWalletAccounts = getWalletAccounts(client);
161
- sessions.sort((sessionA, sessionB) => sessionA.expiry - sessionB.expiry);
162
- /**
163
- * All the WC wallet providers that are currently registered
164
- */
165
- const currentWalletProviders = walletProviderRegistry.listProviders().filter(isWalletConnectWalletProvider);
166
- /**
167
- * Keep record on which walletProviders are tied to active sessions
168
- */
169
- const walletProvidersWithActiveSession = [];
170
- /**
171
- * Maps the ID of the created wallet accounts to the wallet accounts themselves.
172
- */
173
- const createdWalletAccounts = {};
174
- /**
175
- * Keep record on which wallet account IDs were not in the current wallet accounts
176
- * and are therefore brand new.
177
- */
178
- const brandNewWalletAccounts = /* @__PURE__ */ new Set();
179
- /**
180
- * Keep record on which wallet account IDs already exist but will have
181
- * their wallet provider keys overridden to use the new WC wallet provider key.
182
- *
183
- * This will only ever be the case for unverified wallet accounts, however. That is
184
- * because verified wallets will already override the wallet provider key on the verification
185
- * step, which happens at the call to verifyWalletConnectAuths, which happens before this function.
186
- */
187
- const unverifiedWalletAccountsToOverride = /* @__PURE__ */ new Set();
188
- for (const session of sessions) {
189
- const namespaceKeys = Object.keys(session.namespaces);
190
- for (const namespaceKey of namespaceKeys) {
191
- const existingWalletProvider = currentWalletProviders.find((walletProvider$1) => walletProvider$1.namespaceKey === namespaceKey && walletProvider$1.topic === session.topic);
192
- if (existingWalletProvider) {
193
- walletProvidersWithActiveSession.push(existingWalletProvider);
194
- continue;
195
- }
196
- const walletProviderBuilder = namespaceRegistry.getWalletProviderBuilder(namespaceKey);
197
- /**
198
- * There being no wallet provider builder for this namespace simply means the customer
199
- * didn't add an extension for the corresponding chain.
200
- * For instance, if we get a namespace for Solana but only have an Evm extension,
201
- * the solana namespace would fall here. No need to throw.
202
- */
203
- if (!walletProviderBuilder) continue;
204
- const walletProvider = await walletProviderBuilder({ session }, client);
205
- walletProviderRegistry.register({
206
- priority: WalletProviderPriority.WALLET_SDK,
207
- walletProvider
208
- });
209
- walletProvidersWithActiveSession.push(walletProvider);
210
- if (!sessionTopicsData[session.topic].shouldAddToDynamicWalletAccounts) continue;
211
- const namespaceWalletAccounts = createWalletAccountsForWalletConnectWalletProvider({ walletProvider });
212
- if (namespaceWalletAccounts.length === 0) continue;
213
- for (const createdWalletAccount of namespaceWalletAccounts) {
214
- if (!currentWalletAccounts.some((existingAccount$1) => existingAccount$1.id === createdWalletAccount.id)) {
215
- createdWalletAccounts[createdWalletAccount.id] = createdWalletAccount;
216
- brandNewWalletAccounts.add(createdWalletAccount.id);
217
- continue;
218
- }
219
- const existingAccount = currentWalletAccounts.find((existingAccount$1) => existingAccount$1.id === createdWalletAccount.id);
220
- if (!(existingAccount && existingAccount.walletProviderKey !== createdWalletAccount.walletProviderKey)) continue;
221
- const existingWalletIsWalletConnect = splitWalletProviderKey(existingAccount.walletProviderKey).walletProviderType === WalletProviderEnum.WalletConnect;
222
- if (allowOverridingWalletProviders || existingWalletIsWalletConnect) {
223
- createdWalletAccounts[createdWalletAccount.id] = createdWalletAccount;
224
- if (existingAccount.verifiedCredentialId)
225
- /**
226
- * A verified wallet account only arrives here when its wallet provider key is lacking the suffix,
227
- * which should be the sessionTopic. So we just need to add its entry to the verifiedCredentialId map.
228
- */
229
- updateWalletProviderKeysForVerifiedCredentials({ keysToUpdate: { [existingAccount.verifiedCredentialId]: walletProvider.key } }, client);
230
- else unverifiedWalletAccountsToOverride.add(createdWalletAccount.id);
231
- }
232
- }
233
- }
234
- }
235
- if (unverifiedWalletAccountsToOverride.size === 0 && brandNewWalletAccounts.size === 0) return { walletProvidersWithActiveSession };
236
- setUnverifiedWalletAccounts({ unverifiedWalletAccountsToUpdate: Object.values(createdWalletAccounts) }, client);
237
- if (brandNewWalletAccounts.size > 0) for (const walletAccountId of brandNewWalletAccounts) createVisit({ walletAccount: createdWalletAccounts[walletAccountId] }, client);
238
- emitWalletAccountsChangedEvent(client);
239
- return { walletProvidersWithActiveSession };
240
- };
241
-
242
- //#endregion
243
- //#region src/syncSessionsToWalletProviders/syncSessionsToWalletProviders.ts
244
- const doSyncSessionsToWalletProviders = async ({ allowOverridingWalletProviders }, client) => {
245
- await waitForProjectSettings(client);
246
- const signClient = await getSignClient(client);
247
- const walletProviderRegistry = getWalletProviderRegistry(client);
248
- const sessionTopicsData = await getSessionTopicsData(client);
249
- const sessions = signClient.session.getAll().filter((session) => {
250
- if (sessionTopicsData[session.topic]) return true;
251
- signClient.disconnect({
252
- reason: SDK_ERRORS.USER_DISCONNECTED,
253
- topic: session.topic
254
- });
255
- return false;
256
- });
257
- /**
258
- * All the WC wallet providers that are currently registered
259
- */
260
- const currentWalletProviders = walletProviderRegistry.listProviders().filter(isWalletConnectWalletProvider);
261
- for (const walletProvider of currentWalletProviders) if (!sessions.some((session) => session.topic === walletProvider.topic && walletProvider.namespaceKey in session.namespaces)) walletProviderRegistry.unregister(walletProvider.key);
262
- const { walletProvidersWithActiveSession: updatedWalletProviders } = await addMissingWalletProvidersForSessions({
263
- allowOverridingWalletProviders,
264
- sessions
265
- }, client);
266
- const currentWalletAccounts = getWalletAccounts(client);
267
- /**
268
- * Maps which sessions have wallet accounts associated with them
269
- */
270
- const sessionTopicHasWalletAccountMap = /* @__PURE__ */ new Map();
271
- for (const walletProvider of updatedWalletProviders) {
272
- const sessionTopic = walletProvider.topic;
273
- if (!sessionTopicHasWalletAccountMap.has(sessionTopic)) sessionTopicHasWalletAccountMap.set(sessionTopic, false);
274
- if (sessionTopicHasWalletAccountMap.get(sessionTopic)) continue;
275
- if (currentWalletAccounts.filter((walletAccount) => walletAccount.walletProviderKey === walletProvider.key).length > 0) sessionTopicHasWalletAccountMap.set(sessionTopic, true);
276
- }
277
- for (const [sessionTopic, hasWalletAccount] of sessionTopicHasWalletAccountMap) {
278
- if (hasWalletAccount || !sessionTopicsData[sessionTopic].shouldAddToDynamicWalletAccounts) continue;
279
- const session = sessions.find((session$1) => session$1.topic === sessionTopic);
280
- if (session) signClient.disconnect({
281
- reason: SDK_ERRORS.USER_DISCONNECTED,
282
- topic: session.topic
283
- });
284
- for (const walletProvider of updatedWalletProviders) if (walletProvider.topic === sessionTopic) walletProviderRegistry.unregister(walletProvider.key);
285
- }
286
- const activeSessionTopics = new Set(signClient.session.getAll().map((session) => session.topic));
287
- await setSessionTopicsData({ update: (sessionTopicsData$1) => {
288
- return Object.fromEntries(Object.entries(sessionTopicsData$1).filter(([topic]) => activeSessionTopics.has(topic)));
289
- } }, client);
290
- };
291
- const syncSessionsToWalletProviders = async ({ debounceTime = 0, allowOverridingWalletProviders }, client) => {
292
- return getCore(client).debouncedMutex({
293
- callback: async () => doSyncSessionsToWalletProviders({ allowOverridingWalletProviders }, client),
294
- debounceTime,
295
- lockKey: "wallet-connect-sync-sessions-to-wallet-providers"
296
- });
297
- };
298
-
299
111
  //#endregion
300
112
  //#region src/importWalletConnectSession/importWalletConnectSession.ts
301
113
  /**
302
114
  * This is a lower level function that is used to connect a WalletConnect session to the Dynamic SDK.
303
115
  * It will generate the wallet providers and wallet accounts for all accounts in the session.
304
116
  *
305
- * @param session - The session object created from the approval promise of the signClient.connect method.
117
+ * @param sessionTopic - The session topic of the WalletConnect session.
306
118
  * @param addToDynamicWalletAccounts - Whether to add the wallet accounts to the dynamic's wallet accounts.
307
119
  * @param client - The Dynamic client instance. Only required when using multiple Dynamic clients.
308
120
  * @returns The wallet accounts.
309
121
  */
310
- const importWalletConnectSession = async ({ addToDynamicWalletAccounts = true, session }, client) => {
122
+ const importWalletConnectSession = async ({ addToDynamicWalletAccounts = true, sessionTopic, walletProviderBuilder }, client) => {
311
123
  /**
312
124
  * You would normally get the session from the signClient.connect method. It takes the optionalNamespaces as an argument.
313
125
  *
@@ -340,30 +152,48 @@ const importWalletConnectSession = async ({ addToDynamicWalletAccounts = true, s
340
152
  * Where each chain is a CAIP-2 formatted string, for example: "eip155:1"
341
153
  * — see docs: https://chainagnostic.org/CAIPs/caip-2
342
154
  */
343
- const sessionData = { shouldAddToDynamicWalletAccounts: addToDynamicWalletAccounts };
344
- await setSessionTopicsData({ update: (sessionTopicsData) => ({
345
- ...sessionTopicsData,
346
- [session.topic]: sessionData
347
- }) }, client);
155
+ const walletProviderRegistry = getWalletProviderRegistry(client);
156
+ const walletProvider = await walletProviderBuilder({ sessionTopic }, client);
157
+ walletProviderRegistry.register({
158
+ priority: WalletProviderPriority.WALLET_SDK,
159
+ walletProvider
160
+ });
161
+ const walletAccounts = createWalletAccountsForWalletConnectWalletProvider({ walletProvider });
162
+ const existingWalletAccounts = getWalletAccounts(client);
348
163
  /**
349
- * Once the connection is established, we ensure that all active connections (aka sessions)
350
- * are synced to our WalletConnect wallet providers.
351
- * Each session can be uniquely identified by its topic (a random string generated by WalletConnect).
352
- *
353
- * Each session may have multiple wallet providers, one for each namespace (aka our SDK chains)
164
+ * Keep track of which of the new wallet accounts are unverified to add later.
354
165
  */
355
- await syncSessionsToWalletProviders({ allowOverridingWalletProviders: true }, client);
356
- const sessionWalletProviders = getWalletProviders(client).filter(isWalletConnectWalletProvider).filter((provider) => provider.topic === session.topic);
166
+ const unverifiedWalletAccounts = [];
167
+ let walletAccountsChanged = false;
357
168
  /**
358
- * Upon setting the session data to NOT externally owned, syncSessionsToWalletProviders will have
359
- * already created the wallet accounts for each of this session's wallet providers — so all we need
360
- * to do is retrieve them.
169
+ * For all verified wallet accounts that are tied to this session, we need to update
170
+ * the map of verified credential to wallet provider key
361
171
  */
362
- if (addToDynamicWalletAccounts) {
363
- const sessionWalletProviderKeys = sessionWalletProviders.map((provider) => provider.key);
364
- return { walletAccounts: getWalletAccounts(client).filter((walletAccount) => sessionWalletProviderKeys.includes(walletAccount.walletProviderKey)) };
172
+ const verifiedCredentialIdToWalletProviderKeyMap = {};
173
+ walletAccounts.forEach((walletAccount) => {
174
+ const matchingWalletAccount = existingWalletAccounts.find((existingWalletAccount) => existingWalletAccount.id === walletAccount.id);
175
+ const matchingVerifiedCredentialId = matchingWalletAccount?.verifiedCredentialId;
176
+ if (!matchingVerifiedCredentialId) unverifiedWalletAccounts.push({
177
+ isNew: !matchingWalletAccount,
178
+ walletAccount
179
+ });
180
+ else {
181
+ verifiedCredentialIdToWalletProviderKeyMap[matchingVerifiedCredentialId] = walletProvider.key;
182
+ walletAccount.verifiedCredentialId = matchingVerifiedCredentialId;
183
+ }
184
+ });
185
+ if (Object.keys(verifiedCredentialIdToWalletProviderKeyMap).length > 0) {
186
+ updateWalletProviderKeysForVerifiedCredentials({ keysToUpdate: verifiedCredentialIdToWalletProviderKeyMap }, client);
187
+ walletAccountsChanged = true;
188
+ }
189
+ if (addToDynamicWalletAccounts && unverifiedWalletAccounts.length > 0) {
190
+ walletAccountsChanged = true;
191
+ setUnverifiedWalletAccounts({ unverifiedWalletAccountsToUpdate: unverifiedWalletAccounts.map(({ walletAccount }) => walletAccount) }, client);
192
+ const newWalletAccounts = unverifiedWalletAccounts.filter(({ isNew }) => isNew).map(({ walletAccount }) => walletAccount);
193
+ for (const walletAccount of newWalletAccounts) createVisit({ walletAccount }, client);
365
194
  }
366
- return { walletAccounts: sessionWalletProviders.map((walletProvider) => createWalletAccountsForWalletConnectWalletProvider({ walletProvider })).flat() };
195
+ if (walletAccountsChanged) emitWalletAccountsChangedEvent(client);
196
+ return { walletAccounts };
367
197
  };
368
198
 
369
199
  //#endregion
@@ -379,6 +209,8 @@ const verifyWalletConnectAuths = async ({ auths, chain, walletDisplayName }, cli
379
209
  *
380
210
  * Usually, there will be multiple auths if the wallet app bundles signatures for multiple
381
211
  * networks at once, so the only field that will change among auth iss will be the networkId under iss.
212
+ *
213
+ * Docs on Cacao: https://chainagnostic.org/CAIPs/caip-74
382
214
  */
383
215
  const visitedAddresses = /* @__PURE__ */ new Set();
384
216
  const authsFilteredByAddress = auths.filter((auth) => {
@@ -427,7 +259,7 @@ const verifyWalletConnectAuths = async ({ auths, chain, walletDisplayName }, cli
427
259
  * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
428
260
  * @returns A promise that resolves to the connected and verified wallet account.
429
261
  */
430
- const importWalletConnectAuthResponse = async ({ authResponse, chain }, client) => {
262
+ const importWalletConnectAuthResponse = async ({ authResponse, chain, walletProviderBuilder }, client) => {
431
263
  const { session, auths } = authResponse;
432
264
  /**
433
265
  * Some wallets do not support WC's authenticate method (such as Rainbow).
@@ -435,20 +267,12 @@ const importWalletConnectAuthResponse = async ({ authResponse, chain }, client)
435
267
  * Therefore we must call verify individually.
436
268
  */
437
269
  if (!auths || auths.length === 0) {
438
- /**
439
- * Set addToDynamicWalletAccounts to false to avoid adding the wallet accounts to the dynamic's wallet accounts
440
- * while we are still verifying them.
441
- * After verifying, we set addToDynamicWalletAccounts back to true.
442
- */
443
270
  const { walletAccounts: walletAccounts$1 } = await importWalletConnectSession({
444
271
  addToDynamicWalletAccounts: false,
445
- session
272
+ sessionTopic: session.topic,
273
+ walletProviderBuilder
446
274
  }, client);
447
275
  for (const walletAccount of walletAccounts$1) await verifyWalletAccount({ walletAccount }, client);
448
- await setSessionTopicsData({ update: (sessionTopicsData) => ({
449
- ...sessionTopicsData,
450
- [session.topic]: { shouldAddToDynamicWalletAccounts: true }
451
- }) }, client);
452
276
  return { walletAccounts: walletAccounts$1 };
453
277
  }
454
278
  /**
@@ -462,55 +286,48 @@ const importWalletConnectAuthResponse = async ({ authResponse, chain }, client)
462
286
  }, client);
463
287
  const { walletAccounts } = await importWalletConnectSession({
464
288
  addToDynamicWalletAccounts: true,
465
- session
289
+ sessionTopic: session.topic,
290
+ walletProviderBuilder
466
291
  }, client);
467
- updateWalletProviderKeysForVerifiedCredentials({ keysToUpdate: Object.fromEntries(walletAccounts.map((walletAccount) => {
468
- const { verifiedCredentialId } = walletAccount;
469
- assertDefined(verifiedCredentialId, `Wallet account of ID ${walletAccount.id} still has no verified credential after being verified`);
470
- return [verifiedCredentialId, walletAccount.walletProviderKey];
471
- })) }, client);
472
292
  return { walletAccounts };
473
293
  };
474
294
 
475
295
  //#endregion
476
- //#region src/sessionTopicsData/clearTemporarySessions/clearTemporarySessions.ts
477
- /**
478
- * Clears all temporary sessions and disconnects from them.
479
- *
480
- * External sessions are for WC sessions whose accounts are not supposed to be saved in
481
- * the current dynamic's wallet accounts.
482
- * Since we don't own the created wallet accounts, we must keep their corresponding WC sessions alive
483
- * until the page is refreshed or the customer removes the wallet account.
484
- *
485
- * @param client - The client instance.
486
- */
487
- const clearTemporarySessions = async (client) => {
488
- const signClient = await getSignClient(client);
489
- const sessionTopicsData = await getSessionTopicsData(client);
490
- const temporarySessionTopics = Object.keys(sessionTopicsData).filter((topic) => !sessionTopicsData[topic].shouldAddToDynamicWalletAccounts);
491
- if (temporarySessionTopics.length === 0) return;
492
- for (const topic of temporarySessionTopics) await signClient.disconnect({
493
- reason: SDK_ERRORS.USER_DISCONNECTED,
494
- topic
296
+ //#region src/signClient/getSignClient/createSignClient/createSignClient.ts
297
+ const createSignClient = async (client) => {
298
+ const core = getCore(client);
299
+ assertDefined(client.projectSettings, "Project settings not available");
300
+ const generalSettings = client.projectSettings.general;
301
+ assertDefined(generalSettings.displayName, "Please configure an app name in dashboard to use WalletConnect");
302
+ const projectId = client.projectSettings.sdk.walletConnect?.projectId;
303
+ assertDefined(projectId, "Please configure a project ID for WalletConnect in dashboard");
304
+ const customStoragePrefix = `dynamic_${core.environmentId}_walletconnect`;
305
+ const displayName = core.metadata?.name ?? generalSettings.displayName;
306
+ const appLogo = core.metadata?.iconUrl ?? generalSettings.appLogo;
307
+ return SignClient.init({
308
+ customStoragePrefix,
309
+ metadata: {
310
+ description: "",
311
+ icons: appLogo ? [appLogo] : [],
312
+ name: displayName,
313
+ redirect: {
314
+ native: core.metadata?.nativeLink,
315
+ universal: core.metadata?.universalLink
316
+ },
317
+ url: core.metadata?.universalLink ?? ""
318
+ },
319
+ projectId
495
320
  });
496
- const newSessionTopicsData = Object.fromEntries(Object.entries(sessionTopicsData).filter(([, { shouldAddToDynamicWalletAccounts: isPermanentSession }]) => isPermanentSession));
497
- await setSessionTopicsData({ update: () => newSessionTopicsData }, client);
498
321
  };
499
322
 
500
323
  //#endregion
501
- //#region src/initializeWalletConnectExtension/initializeWalletConnectExtension.ts
502
- const initializeWalletConnectExtension = async (client) => {
503
- await clearTemporarySessions(client);
504
- await syncSessionsToWalletProviders({
505
- allowOverridingWalletProviders: false,
506
- debounceTime: 200
507
- }, client);
508
- };
324
+ //#region src/signClient/getSignClient/getSignClient.ts
325
+ const getSignClient = createRuntimeServiceAccessKey("walletConnectSignClient", (client) => createSignClient(client));
509
326
 
510
327
  //#endregion
511
328
  //#region src/exports/core.ts
512
329
  assertPackageVersion(name, version);
513
330
 
514
331
  //#endregion
515
- export { getNamespaceRegistry, getSignClient, importWalletConnectAuthResponse, importWalletConnectSession, initializeWalletConnectExtension, splitCaip10Token, syncSessionsToWalletProviders };
332
+ export { SessionClosedUnexpectedlyError, createWalletConnectSessionEventEmitter, getSignClient, importWalletConnectAuthResponse, importWalletConnectSession, splitCaip10Token };
516
333
  //# sourceMappingURL=core.esm.js.map