@zerodev/wallet-react 0.0.1-alpha.0 → 0.0.1-alpha.10

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 (54) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +282 -0
  3. package/dist/_cjs/actions.js +62 -24
  4. package/dist/_cjs/connector.js +86 -52
  5. package/dist/_cjs/constants.js +1 -1
  6. package/dist/_cjs/hooks/useExportPrivateKey.js +18 -0
  7. package/dist/_cjs/hooks/useGetUserEmail.js +19 -0
  8. package/dist/_cjs/index.js +8 -1
  9. package/dist/_cjs/oauth.js +60 -55
  10. package/dist/_cjs/provider.js +5 -2
  11. package/dist/_cjs/store.js +4 -9
  12. package/dist/_cjs/utils/aaUtils.js +2 -2
  13. package/dist/_esm/actions.js +74 -27
  14. package/dist/_esm/connector.js +102 -59
  15. package/dist/_esm/constants.js +1 -1
  16. package/dist/_esm/hooks/useExportPrivateKey.js +18 -0
  17. package/dist/_esm/hooks/useGetUserEmail.js +19 -0
  18. package/dist/_esm/index.js +3 -1
  19. package/dist/_esm/oauth.js +71 -53
  20. package/dist/_esm/provider.js +5 -2
  21. package/dist/_esm/store.js +4 -10
  22. package/dist/_esm/utils/aaUtils.js +2 -2
  23. package/dist/_types/actions.d.ts +35 -6
  24. package/dist/_types/actions.d.ts.map +1 -1
  25. package/dist/_types/connector.d.ts +1 -3
  26. package/dist/_types/connector.d.ts.map +1 -1
  27. package/dist/_types/constants.d.ts +1 -1
  28. package/dist/_types/constants.d.ts.map +1 -1
  29. package/dist/_types/hooks/useExportPrivateKey.d.ts +18 -0
  30. package/dist/_types/hooks/useExportPrivateKey.d.ts.map +1 -0
  31. package/dist/_types/hooks/useGetUserEmail.d.ts +18 -0
  32. package/dist/_types/hooks/useGetUserEmail.d.ts.map +1 -0
  33. package/dist/_types/index.d.ts +4 -2
  34. package/dist/_types/index.d.ts.map +1 -1
  35. package/dist/_types/oauth.d.ts +25 -12
  36. package/dist/_types/oauth.d.ts.map +1 -1
  37. package/dist/_types/provider.d.ts.map +1 -1
  38. package/dist/_types/store.d.ts +11 -7
  39. package/dist/_types/store.d.ts.map +1 -1
  40. package/dist/_types/utils/aaUtils.d.ts +1 -1
  41. package/dist/_types/utils/aaUtils.d.ts.map +1 -1
  42. package/dist/tsconfig.build.tsbuildinfo +1 -1
  43. package/package.json +2 -2
  44. package/src/actions.ts +124 -44
  45. package/src/connector.ts +130 -70
  46. package/src/constants.ts +2 -1
  47. package/src/hooks/useExportPrivateKey.ts +57 -0
  48. package/src/hooks/useGetUserEmail.ts +52 -0
  49. package/src/index.ts +9 -2
  50. package/src/oauth.ts +97 -78
  51. package/src/provider.ts +5 -2
  52. package/src/store.ts +15 -16
  53. package/src/utils/aaUtils.ts +2 -2
  54. package/tsconfig.build.tsbuildinfo +1 -1
@@ -6,51 +6,86 @@ const sdk_1 = require("@zerodev/sdk");
6
6
  const constants_1 = require("@zerodev/sdk/constants");
7
7
  const wallet_core_1 = require("@zerodev/wallet-core");
8
8
  const viem_1 = require("viem");
9
+ const oauth_js_1 = require("./oauth.js");
9
10
  const provider_js_1 = require("./provider.js");
10
11
  const store_js_1 = require("./store.js");
11
12
  const aaUtils_js_1 = require("./utils/aaUtils.js");
13
+ const OAUTH_SUCCESS_PARAM = 'oauth_success';
14
+ const OAUTH_PROVIDER_PARAM = 'oauth_provider';
15
+ async function detectAndHandleOAuthCallback(wallet, store) {
16
+ if (typeof window === 'undefined')
17
+ return false;
18
+ const params = new URLSearchParams(window.location.search);
19
+ const isOAuthCallback = params.get(OAUTH_SUCCESS_PARAM) === 'true';
20
+ if (!isOAuthCallback)
21
+ return false;
22
+ if (window.opener) {
23
+ (0, oauth_js_1.handleOAuthCallback)(OAUTH_SUCCESS_PARAM);
24
+ return true;
25
+ }
26
+ console.log('OAuth callback detected, completing authentication...');
27
+ const provider = (params.get(OAUTH_PROVIDER_PARAM) ||
28
+ 'google');
29
+ try {
30
+ await wallet.auth({ type: 'oauth', provider });
31
+ const [session, eoaAccount] = await Promise.all([
32
+ wallet.getSession(),
33
+ wallet.toAccount(),
34
+ ]);
35
+ store.getState().setEoaAccount(eoaAccount);
36
+ store.getState().setSession(session || null);
37
+ params.delete(OAUTH_SUCCESS_PARAM);
38
+ params.delete(OAUTH_PROVIDER_PARAM);
39
+ const newUrl = params.toString()
40
+ ? `${window.location.pathname}?${params.toString()}`
41
+ : window.location.pathname;
42
+ window.history.replaceState({}, '', newUrl);
43
+ console.log('OAuth authentication completed');
44
+ return true;
45
+ }
46
+ catch (error) {
47
+ console.error('OAuth authentication failed:', error);
48
+ return false;
49
+ }
50
+ }
12
51
  function zeroDevWallet(params) {
13
52
  return (0, core_1.createConnector)((wagmiConfig) => {
14
53
  let store;
15
54
  let provider;
16
- let initPromise;
17
55
  const transports = wagmiConfig.transports;
18
56
  const initialize = async () => {
19
- initPromise ??= (async () => {
20
- console.log('Initializing ZeroDevWallet connector...');
21
- const wallet = await (0, wallet_core_1.createZeroDevWallet)({
22
- projectId: params.projectId,
23
- ...(params.organizationId && {
24
- organizationId: params.organizationId,
25
- }),
26
- ...(params.proxyBaseUrl && { proxyBaseUrl: params.proxyBaseUrl }),
27
- ...(params.sessionStorage && {
28
- sessionStorage: params.sessionStorage,
29
- }),
30
- ...(params.rpId && { rpId: params.rpId }),
31
- });
32
- store = (0, store_js_1.createZeroDevWalletStore)();
33
- store.getState().setWallet(wallet);
34
- const chainIds = params.chains.map((c) => c.id);
35
- store.setState({ chainIds });
36
- if (params.oauthConfig) {
37
- store.getState().setOAuthConfig(params.oauthConfig);
38
- }
39
- provider = (0, provider_js_1.createProvider)({
40
- store,
41
- config: params,
42
- chains: Array.from(params.chains),
43
- });
44
- const session = await wallet.getSession();
45
- if (session) {
46
- console.log('Found existing session, restoring...');
47
- const eoaAccount = await wallet.toAccount();
48
- store.getState().setEoaAccount(eoaAccount);
49
- store.getState().setSession(session);
50
- }
51
- console.log('ZeroDevWallet connector initialized');
52
- })();
53
- return initPromise;
57
+ console.log('Initializing ZeroDevWallet connector...');
58
+ const wallet = await (0, wallet_core_1.createZeroDevWallet)({
59
+ projectId: params.projectId,
60
+ ...(params.organizationId && {
61
+ organizationId: params.organizationId,
62
+ }),
63
+ ...(params.proxyBaseUrl && { proxyBaseUrl: params.proxyBaseUrl }),
64
+ ...(params.sessionStorage && {
65
+ sessionStorage: params.sessionStorage,
66
+ }),
67
+ ...(params.rpId && { rpId: params.rpId }),
68
+ });
69
+ store = (0, store_js_1.createZeroDevWalletStore)();
70
+ store.getState().setWallet(wallet);
71
+ store.getState().setOAuthConfig({
72
+ backendUrl: params.proxyBaseUrl || `${wallet_core_1.KMS_SERVER_URL}/api/v1`,
73
+ projectId: params.projectId,
74
+ });
75
+ provider = (0, provider_js_1.createProvider)({
76
+ store,
77
+ config: params,
78
+ chains: Array.from(params.chains),
79
+ });
80
+ const session = await wallet.getSession();
81
+ if (session) {
82
+ console.log('Found existing session, restoring...');
83
+ const eoaAccount = await wallet.toAccount();
84
+ store.getState().setEoaAccount(eoaAccount);
85
+ store.getState().setSession(session);
86
+ }
87
+ await detectAndHandleOAuthCallback(wallet, store);
88
+ console.log('ZeroDevWallet connector initialized');
54
89
  };
55
90
  return {
56
91
  id: 'zerodev-wallet',
@@ -69,10 +104,7 @@ function zeroDevWallet(params) {
69
104
  ? 'Reconnecting ZeroDevWallet...'
70
105
  : 'Connecting ZeroDevWallet...');
71
106
  const state = store.getState();
72
- const activeChainId = chainId || state.chainIds[0];
73
- if (!activeChainId) {
74
- throw new Error('No chain configured');
75
- }
107
+ const activeChainId = chainId ?? state.activeChainId ?? params.chains[0].id;
76
108
  if (isReconnecting && state.kernelAccounts.has(activeChainId)) {
77
109
  const kernelAccount = state.kernelAccounts.get(activeChainId);
78
110
  if (kernelAccount?.address) {
@@ -105,17 +137,17 @@ function zeroDevWallet(params) {
105
137
  store.getState().setKernelAccount(activeChainId, kernelAccount);
106
138
  const kernelClient = (0, sdk_1.createKernelAccountClient)({
107
139
  account: kernelAccount,
108
- bundlerTransport: (0, viem_1.http)((0, aaUtils_js_1.getAAUrl)(activeChainId, params.aaUrl)),
140
+ bundlerTransport: (0, viem_1.http)((0, aaUtils_js_1.getAAUrl)(params.projectId, activeChainId, params.aaUrl)),
109
141
  chain,
110
142
  client: publicClient,
111
143
  paymaster: (0, sdk_1.createZeroDevPaymasterClient)({
112
144
  chain,
113
- transport: (0, viem_1.http)((0, aaUtils_js_1.getAAUrl)(activeChainId, params.aaUrl)),
145
+ transport: (0, viem_1.http)((0, aaUtils_js_1.getAAUrl)(params.projectId, activeChainId, params.aaUrl)),
114
146
  }),
115
147
  });
116
148
  store.getState().setKernelClient(activeChainId, kernelClient);
117
149
  }
118
- store.getState().setActiveChain(activeChainId);
150
+ store.getState().setActiveChainId(activeChainId);
119
151
  const freshState = store.getState();
120
152
  const kernelAccount = freshState.kernelAccounts.get(activeChainId);
121
153
  console.log('ZeroDevWallet connected:', kernelAccount.address);
@@ -139,32 +171,33 @@ function zeroDevWallet(params) {
139
171
  async getAccounts() {
140
172
  if (!store)
141
173
  return [];
142
- const { eoaAccount, kernelAccounts, chainIds } = store.getState();
174
+ const { eoaAccount, kernelAccounts, activeChainId } = store.getState();
143
175
  if (eoaAccount) {
144
176
  return [eoaAccount.address];
145
177
  }
146
- const activeAccount = chainIds[0]
147
- ? kernelAccounts.get(chainIds[0])
178
+ const activeAccount = activeChainId
179
+ ? kernelAccounts.get(activeChainId)
148
180
  : null;
149
181
  return activeAccount ? [activeAccount.address] : [];
150
182
  },
151
183
  async getChainId() {
152
184
  if (!store)
153
185
  return params.chains[0].id;
154
- return store.getState().chainIds[0] || params.chains[0].id;
186
+ return store.getState().activeChainId ?? params.chains[0].id;
155
187
  },
156
188
  async getProvider() {
157
- await initialize();
189
+ if (!provider) {
190
+ await initialize();
191
+ }
158
192
  return provider;
159
193
  },
160
194
  async switchChain({ chainId }) {
161
- await initialize();
162
195
  console.log(`Switching to chain ${chainId}...`);
163
196
  const state = store.getState();
164
197
  if (!state.eoaAccount) {
165
198
  throw new Error('Not authenticated');
166
199
  }
167
- store.getState().setActiveChain(chainId);
200
+ store.getState().setActiveChainId(chainId);
168
201
  if (!state.kernelAccounts.has(chainId)) {
169
202
  const chain = params.chains.find((c) => c.id === chainId);
170
203
  if (!chain) {
@@ -184,16 +217,17 @@ function zeroDevWallet(params) {
184
217
  store.getState().setKernelAccount(chainId, kernelAccount);
185
218
  const kernelClient = (0, sdk_1.createKernelAccountClient)({
186
219
  account: kernelAccount,
187
- bundlerTransport: (0, viem_1.http)((0, aaUtils_js_1.getAAUrl)(chainId, params.aaUrl)),
220
+ bundlerTransport: (0, viem_1.http)((0, aaUtils_js_1.getAAUrl)(params.projectId, chainId, params.aaUrl)),
188
221
  chain,
189
222
  client: publicClient,
190
223
  paymaster: (0, sdk_1.createZeroDevPaymasterClient)({
191
224
  chain,
192
- transport: (0, viem_1.http)((0, aaUtils_js_1.getAAUrl)(chainId, params.aaUrl)),
225
+ transport: (0, viem_1.http)((0, aaUtils_js_1.getAAUrl)(params.projectId, chainId, params.aaUrl)),
193
226
  }),
194
227
  });
195
228
  store.getState().setKernelClient(chainId, kernelClient);
196
229
  }
230
+ wagmiConfig.emitter.emit('change', { chainId });
197
231
  return params.chains.find((c) => c.id === chainId);
198
232
  },
199
233
  async isAuthorized() {
@@ -1,4 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ZERODEV_AA_URL = void 0;
4
- exports.ZERODEV_AA_URL = 'https://rpc.zerodev.app/api/v3/';
4
+ exports.ZERODEV_AA_URL = 'https://staging-meta-aa-provider.onrender.com/api/v3/';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ 'use client';
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.useExportPrivateKey = useExportPrivateKey;
5
+ const react_query_1 = require("@tanstack/react-query");
6
+ const wagmi_1 = require("wagmi");
7
+ const actions_js_1 = require("../actions.js");
8
+ function useExportPrivateKey(parameters = {}) {
9
+ const { mutation } = parameters;
10
+ const config = (0, wagmi_1.useConfig)(parameters);
11
+ return (0, react_query_1.useMutation)({
12
+ ...mutation,
13
+ async mutationFn(variables) {
14
+ return (0, actions_js_1.exportPrivateKey)(config, variables);
15
+ },
16
+ mutationKey: ['exportPrivateKey'],
17
+ });
18
+ }
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ 'use client';
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.useGetUserEmail = useGetUserEmail;
5
+ const react_query_1 = require("@tanstack/react-query");
6
+ const wagmi_1 = require("wagmi");
7
+ const actions_js_1 = require("../actions.js");
8
+ function useGetUserEmail(parameters) {
9
+ const { query } = parameters;
10
+ const config = (0, wagmi_1.useConfig)(parameters);
11
+ return (0, react_query_1.useQuery)({
12
+ ...query,
13
+ queryKey: ['getUserEmail'],
14
+ queryFn: async () => {
15
+ return (0, actions_js_1.getUserEmail)(config);
16
+ },
17
+ enabled: Boolean(config),
18
+ });
19
+ }
@@ -1,12 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createZeroDevWalletStore = exports.OAUTH_PROVIDERS = exports.useVerifyOTP = exports.useSendOTP = exports.useRegisterPasskey = exports.useRefreshSession = exports.useLoginPasskey = exports.useExportWallet = exports.useAuthenticateOAuth = exports.zeroDevWallet = void 0;
3
+ exports.createZeroDevWalletStore = exports.OAUTH_PROVIDERS = exports.listenForOAuthMessage = exports.handleOAuthCallback = exports.buildBackendOAuthUrl = exports.useVerifyOTP = exports.useSendOTP = exports.useRegisterPasskey = exports.useRefreshSession = exports.useLoginPasskey = exports.useGetUserEmail = exports.useExportWallet = exports.useExportPrivateKey = exports.useAuthenticateOAuth = exports.zeroDevWallet = void 0;
4
4
  var connector_js_1 = require("./connector.js");
5
5
  Object.defineProperty(exports, "zeroDevWallet", { enumerable: true, get: function () { return connector_js_1.zeroDevWallet; } });
6
6
  var useAuthenticateOAuth_js_1 = require("./hooks/useAuthenticateOAuth.js");
7
7
  Object.defineProperty(exports, "useAuthenticateOAuth", { enumerable: true, get: function () { return useAuthenticateOAuth_js_1.useAuthenticateOAuth; } });
8
+ var useExportPrivateKey_js_1 = require("./hooks/useExportPrivateKey.js");
9
+ Object.defineProperty(exports, "useExportPrivateKey", { enumerable: true, get: function () { return useExportPrivateKey_js_1.useExportPrivateKey; } });
8
10
  var useExportWallet_js_1 = require("./hooks/useExportWallet.js");
9
11
  Object.defineProperty(exports, "useExportWallet", { enumerable: true, get: function () { return useExportWallet_js_1.useExportWallet; } });
12
+ var useGetUserEmail_js_1 = require("./hooks/useGetUserEmail.js");
13
+ Object.defineProperty(exports, "useGetUserEmail", { enumerable: true, get: function () { return useGetUserEmail_js_1.useGetUserEmail; } });
10
14
  var useLoginPasskey_js_1 = require("./hooks/useLoginPasskey.js");
11
15
  Object.defineProperty(exports, "useLoginPasskey", { enumerable: true, get: function () { return useLoginPasskey_js_1.useLoginPasskey; } });
12
16
  var useRefreshSession_js_1 = require("./hooks/useRefreshSession.js");
@@ -18,6 +22,9 @@ Object.defineProperty(exports, "useSendOTP", { enumerable: true, get: function (
18
22
  var useVerifyOTP_js_1 = require("./hooks/useVerifyOTP.js");
19
23
  Object.defineProperty(exports, "useVerifyOTP", { enumerable: true, get: function () { return useVerifyOTP_js_1.useVerifyOTP; } });
20
24
  var oauth_js_1 = require("./oauth.js");
25
+ Object.defineProperty(exports, "buildBackendOAuthUrl", { enumerable: true, get: function () { return oauth_js_1.buildBackendOAuthUrl; } });
26
+ Object.defineProperty(exports, "handleOAuthCallback", { enumerable: true, get: function () { return oauth_js_1.handleOAuthCallback; } });
27
+ Object.defineProperty(exports, "listenForOAuthMessage", { enumerable: true, get: function () { return oauth_js_1.listenForOAuthMessage; } });
21
28
  Object.defineProperty(exports, "OAUTH_PROVIDERS", { enumerable: true, get: function () { return oauth_js_1.OAUTH_PROVIDERS; } });
22
29
  var store_js_1 = require("./store.js");
23
30
  Object.defineProperty(exports, "createZeroDevWalletStore", { enumerable: true, get: function () { return store_js_1.createZeroDevWalletStore; } });
@@ -1,42 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.OAUTH_PROVIDERS = void 0;
4
- exports.buildOAuthUrl = buildOAuthUrl;
5
4
  exports.openOAuthPopup = openOAuthPopup;
6
- exports.extractOAuthToken = extractOAuthToken;
7
- exports.pollOAuthPopup = pollOAuthPopup;
8
5
  exports.generateOAuthNonce = generateOAuthNonce;
6
+ exports.buildBackendOAuthUrl = buildBackendOAuthUrl;
7
+ exports.listenForOAuthMessage = listenForOAuthMessage;
8
+ exports.handleOAuthCallback = handleOAuthCallback;
9
9
  const viem_1 = require("viem");
10
10
  exports.OAUTH_PROVIDERS = {
11
11
  GOOGLE: 'google',
12
12
  };
13
- const GOOGLE_AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth';
14
13
  const POPUP_WIDTH = 500;
15
14
  const POPUP_HEIGHT = 600;
16
- function buildOAuthUrl(params) {
17
- const { provider, clientId, redirectUri, nonce, state } = params;
18
- if (provider !== exports.OAUTH_PROVIDERS.GOOGLE) {
19
- throw new Error(`Unsupported OAuth provider: ${provider}`);
20
- }
21
- const authUrl = new URL(GOOGLE_AUTH_URL);
22
- authUrl.searchParams.set('client_id', clientId);
23
- authUrl.searchParams.set('redirect_uri', redirectUri);
24
- authUrl.searchParams.set('response_type', 'id_token');
25
- authUrl.searchParams.set('scope', 'openid email profile');
26
- authUrl.searchParams.set('nonce', nonce);
27
- authUrl.searchParams.set('prompt', 'select_account');
28
- let stateParam = `provider=${provider}`;
29
- if (state) {
30
- const additionalState = Object.entries(state)
31
- .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
32
- .join('&');
33
- if (additionalState) {
34
- stateParam += `&${additionalState}`;
35
- }
36
- }
37
- authUrl.searchParams.set('state', stateParam);
38
- return authUrl.toString();
39
- }
40
15
  function openOAuthPopup(url) {
41
16
  const width = POPUP_WIDTH;
42
17
  const height = POPUP_HEIGHT;
@@ -48,37 +23,67 @@ function openOAuthPopup(url) {
48
23
  }
49
24
  return authWindow;
50
25
  }
51
- function extractOAuthToken(url) {
52
- const hashParams = new URLSearchParams(url.split('#')[1]);
53
- let idToken = hashParams.get('id_token');
54
- if (!idToken) {
55
- const queryParams = new URLSearchParams(url.split('?')[1]);
56
- idToken = queryParams.get('id_token');
26
+ function generateOAuthNonce(publicKey) {
27
+ return (0, viem_1.sha256)(publicKey).replace(/^0x/, '');
28
+ }
29
+ function buildBackendOAuthUrl(params) {
30
+ const { provider, backendUrl, projectId, publicKey, returnTo } = params;
31
+ if (provider !== exports.OAUTH_PROVIDERS.GOOGLE) {
32
+ throw new Error(`Unsupported OAuth provider: ${provider}`);
57
33
  }
58
- return idToken;
34
+ const oauthUrl = new URL(`${backendUrl}/oauth/google/login`);
35
+ oauthUrl.searchParams.set('project_id', projectId);
36
+ oauthUrl.searchParams.set('pub_key', publicKey.replace(/^0x/, ''));
37
+ oauthUrl.searchParams.set('return_to', returnTo);
38
+ return oauthUrl.toString();
59
39
  }
60
- function pollOAuthPopup(authWindow, originUrl, onSuccess, onError) {
61
- const interval = setInterval(() => {
62
- try {
63
- if (authWindow.closed) {
64
- clearInterval(interval);
65
- onError(new Error('Authentication window was closed'));
66
- return;
67
- }
68
- const url = authWindow.location.href || '';
69
- if (url.startsWith(originUrl)) {
70
- const token = extractOAuthToken(url);
71
- if (token) {
72
- authWindow.close();
73
- clearInterval(interval);
74
- onSuccess(token);
75
- }
76
- }
40
+ function listenForOAuthMessage(authWindow, expectedOrigin, onSuccess, onError) {
41
+ let cleaned = false;
42
+ const handleMessage = (event) => {
43
+ if (event.origin !== expectedOrigin)
44
+ return;
45
+ if (!event.data || typeof event.data !== 'object')
46
+ return;
47
+ if (event.data.type === 'oauth_success') {
48
+ cleanup();
49
+ onSuccess();
77
50
  }
78
- catch {
51
+ else if (event.data.type === 'oauth_error') {
52
+ cleanup();
53
+ onError(new Error(event.data.error || 'OAuth authentication failed'));
54
+ }
55
+ };
56
+ const checkWindowClosed = setInterval(() => {
57
+ if (authWindow.closed) {
58
+ cleanup();
59
+ onError(new Error('Authentication window was closed'));
79
60
  }
80
61
  }, 500);
62
+ const cleanup = () => {
63
+ if (cleaned)
64
+ return;
65
+ cleaned = true;
66
+ window.removeEventListener('message', handleMessage);
67
+ clearInterval(checkWindowClosed);
68
+ };
69
+ window.addEventListener('message', handleMessage);
70
+ return cleanup;
81
71
  }
82
- function generateOAuthNonce(publicKey) {
83
- return (0, viem_1.sha256)(publicKey).replace(/^0x/, '');
72
+ function handleOAuthCallback(successParam = 'oauth_success') {
73
+ const urlParams = new URLSearchParams(window.location.search);
74
+ const isSuccess = urlParams.get(successParam) === 'true';
75
+ const error = urlParams.get('error');
76
+ if (window.opener) {
77
+ if (isSuccess) {
78
+ window.opener.postMessage({ type: 'oauth_success' }, window.location.origin);
79
+ window.close();
80
+ return true;
81
+ }
82
+ if (error) {
83
+ window.opener.postMessage({ type: 'oauth_error', error }, window.location.origin);
84
+ window.close();
85
+ return false;
86
+ }
87
+ }
88
+ return false;
84
89
  }
@@ -77,7 +77,10 @@ function createProvider({ store, config, }) {
77
77
  },
78
78
  async request({ method, params }) {
79
79
  const state = store.getState();
80
- const activeChainId = state.chainIds[0];
80
+ const activeChainId = state.activeChainId;
81
+ if (!activeChainId) {
82
+ throw new Error('No active chain');
83
+ }
81
84
  switch (method) {
82
85
  case 'eth_accounts': {
83
86
  const account = state.kernelAccounts.get(activeChainId);
@@ -151,7 +154,7 @@ function createProvider({ store, config, }) {
151
154
  }
152
155
  const [{ chainId }] = params;
153
156
  const chainId_number = parseInt(chainId, 16);
154
- store.getState().setActiveChain(chainId_number);
157
+ store.getState().setActiveChainId(chainId_number);
155
158
  emitter.emit('chainChanged', chainId);
156
159
  return null;
157
160
  }
@@ -7,7 +7,7 @@ const createZeroDevWalletStore = () => (0, zustand_1.create)()((0, middleware_1.
7
7
  wallet: null,
8
8
  eoaAccount: null,
9
9
  session: null,
10
- chainIds: [],
10
+ activeChainId: null,
11
11
  kernelAccounts: new Map(),
12
12
  kernelClients: new Map(),
13
13
  isExpiring: false,
@@ -25,12 +25,7 @@ const createZeroDevWalletStore = () => (0, zustand_1.create)()((0, middleware_1.
25
25
  set({ kernelClients: clients });
26
26
  },
27
27
  setSession: (session) => set({ session }),
28
- setActiveChain: (chainId) => {
29
- const { chainIds } = get();
30
- set({
31
- chainIds: [chainId, ...chainIds.filter((id) => id !== chainId)],
32
- });
33
- },
28
+ setActiveChainId: (chainId) => set({ activeChainId: chainId }),
34
29
  setIsExpiring: (isExpiring) => set({ isExpiring }),
35
30
  setOAuthConfig: (config) => set({ oauthConfig: config }),
36
31
  clear: () => set({
@@ -39,13 +34,13 @@ const createZeroDevWalletStore = () => (0, zustand_1.create)()((0, middleware_1.
39
34
  kernelAccounts: new Map(),
40
35
  kernelClients: new Map(),
41
36
  isExpiring: false,
42
- chainIds: [],
37
+ activeChainId: null,
43
38
  }),
44
39
  }), {
45
40
  name: 'zerodev-wallet',
46
41
  partialize: (state) => ({
47
42
  session: state.session,
48
- chainIds: state.chainIds,
43
+ activeChainId: state.activeChainId,
49
44
  }),
50
45
  })));
51
46
  exports.createZeroDevWalletStore = createZeroDevWalletStore;
@@ -2,6 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getAAUrl = getAAUrl;
4
4
  const constants_js_1 = require("../constants.js");
5
- function getAAUrl(chainId, aaUrl) {
6
- return aaUrl || `${constants_js_1.ZERODEV_AA_URL}${chainId}/chain/${chainId}`;
5
+ function getAAUrl(projectId, chainId, aaUrl) {
6
+ return aaUrl || `${constants_js_1.ZERODEV_AA_URL}${projectId}/chain/${chainId}`;
7
7
  }