@moon-x/react-native-sdk 0.12.0 → 0.13.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.
package/dist/index.js CHANGED
@@ -30,27 +30,34 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ MoonKeyProvider: () => MoonXProvider,
33
34
  MoonXProvider: () => MoonXProvider,
34
- PostMessageMethod: () => import_utils9.PostMessageMethod,
35
- PostMessageType: () => import_utils9.PostMessageType,
36
- useAddPasskey: () => import_react6.useAddPasskey,
35
+ PostMessageMethod: () => import_utils10.PostMessageMethod,
36
+ PostMessageType: () => import_utils10.PostMessageType,
37
+ connectWalletConnect: () => connectWalletConnect,
38
+ listWalletConnectSessions: () => listWalletConnectSessions,
39
+ restoreWalletConnectSession: () => restoreWalletConnectSession,
40
+ useAddPasskey: () => import_react8.useAddPasskey,
37
41
  useAppConfig: () => useAppConfig,
38
42
  useAttachOAuth: () => useAttachOAuth,
39
- useCreateWallet: () => import_react6.useCreateWallet,
43
+ useCreateWallet: () => import_react8.useCreateWallet,
40
44
  useDetachOAuth: () => useDetachOAuth,
41
- useEphemeralSigner: () => import_react6.useEphemeralSigner,
45
+ useEphemeralSigner: () => import_react8.useEphemeralSigner,
42
46
  useExportKey: () => useExportKey,
43
- useImportKey: () => import_react6.useImportKey,
44
- useLoginWithEmail: () => import_react6.useLoginWithEmail,
47
+ useExternalWallets: () => useExternalWallets,
48
+ useFundWallet: () => useFundWallet,
49
+ useImportKey: () => import_react8.useImportKey,
50
+ useLoginWithEmail: () => useLoginWithEmail,
45
51
  useLoginWithOAuth: () => useLoginWithOAuth,
46
- useLogout: () => import_react6.useLogout,
52
+ useLogout: () => import_react8.useLogout,
53
+ useMoonKey: () => useMoonX,
47
54
  useMoonX: () => useMoonX,
48
55
  useMoonXContext: () => useMoonXContext,
49
- usePasskeyStatus: () => import_react6.usePasskeyStatus,
50
- useRegisterPasskey: () => import_react6.useRegisterPasskey,
51
- useRemovePasskey: () => import_react6.useRemovePasskey,
52
- useUser: () => import_react6.useUser,
53
- useWallets: () => import_react6.useWallets
56
+ usePasskeyStatus: () => import_react8.usePasskeyStatus,
57
+ useRegisterPasskey: () => import_react8.useRegisterPasskey,
58
+ useRemovePasskey: () => import_react8.useRemovePasskey,
59
+ useUser: () => import_react8.useUser,
60
+ useWallets: () => import_react8.useWallets
54
61
  });
55
62
  module.exports = __toCommonJS(index_exports);
56
63
 
@@ -64,12 +71,24 @@ var import_utils2 = require("@moon-x/core/utils");
64
71
 
65
72
  // src/sdk/sdk-authentication-methods.ts
66
73
  var import_sdk = require("@moon-x/core/sdk");
67
- var getAuthenticationMethods = (bridge, publishableKey, setIsAuthenticated, setUser) => (0, import_sdk.getHeadlessAuthenticationMethods)({
68
- transport: bridge,
69
- publishableKey,
70
- setIsAuthenticated,
71
- setUser
72
- });
74
+ var getAuthenticationMethods = (bridge, publishableKey, setIsAuthenticated, setUser) => {
75
+ const headless = (0, import_sdk.getHeadlessAuthenticationMethods)({
76
+ transport: bridge,
77
+ publishableKey,
78
+ setIsAuthenticated,
79
+ setUser
80
+ });
81
+ return {
82
+ ...headless,
83
+ // The verification response contains session credentials that belong
84
+ // inside the WebView. Keep the public RN contract aligned with the web
85
+ // SDK: callers only observe successful completion, never the raw token
86
+ // bundle returned by VERIFY_EMAIL_OTP.
87
+ loginWithCode: async (params) => {
88
+ await headless.loginWithCode(params);
89
+ }
90
+ };
91
+ };
73
92
 
74
93
  // src/sdk/sdk-ethereum-methods.ts
75
94
  var import_sdk2 = require("@moon-x/core/sdk");
@@ -162,13 +181,20 @@ var getEthereumSDKMethods = (bridge, publishableKey, relyingPartyOrigin) => (0,
162
181
  relyingPartyOrigin
163
182
  });
164
183
 
184
+ // src/sdk/sdk-funding-methods.ts
185
+ var import_sdk3 = require("@moon-x/core/sdk");
186
+ var getFundingSDKMethods = (bridge, publishableKey) => (0, import_sdk3.getHeadlessFundingMethods)({
187
+ transport: bridge,
188
+ publishableKey
189
+ });
190
+
165
191
  // src/sdk/sdk-passkey-methods.ts
166
192
  var import_lib = require("@moon-x/core/lib");
167
- var import_sdk3 = require("@moon-x/core/sdk");
193
+ var import_sdk4 = require("@moon-x/core/sdk");
168
194
  var import_utils = require("@moon-x/core/utils");
169
195
  var import_react_native_passkeys2 = require("react-native-passkeys");
170
- var getPasskeyMethods = (bridge, publishableKey) => ({
171
- registerPasskey: async (params) => {
196
+ var getPasskeyMethods = (bridge, publishableKey) => {
197
+ const enrollPasskey = async (params) => {
172
198
  const dekInfo = await bridge.send(
173
199
  import_utils.PostMessageType.AUTH,
174
200
  import_utils.PostMessageMethod.GET_DEK_INFO,
@@ -182,12 +208,12 @@ var getPasskeyMethods = (bridge, publishableKey) => ({
182
208
  const isAdditional = (dekInfo.allow_credential_ids_b64url ?? []).length > 0;
183
209
  let unlock = null;
184
210
  if (isAdditional) {
185
- const result = await (0, import_sdk3.getInternalPresenceTokens)({
211
+ const result = await (0, import_sdk4.getInternalPresenceTokens)({
186
212
  transport: bridge,
187
213
  passkey: createRNPasskey(),
188
214
  publishableKey,
189
215
  relyingPartyOrigin,
190
- scopes: import_sdk3.SCOPES_ADD_PASSKEY
216
+ scopes: import_sdk4.SCOPES_ADD_PASSKEY
191
217
  });
192
218
  const allowList = dekInfo.allow_credential_ids_b64url ?? [];
193
219
  if (!allowList.includes(result.credentialIdB64url)) {
@@ -196,7 +222,7 @@ var getPasskeyMethods = (bridge, publishableKey) => ({
196
222
  unlock = {
197
223
  userHandleB64url: result.userHandleB64url,
198
224
  credentialIdB64url: result.credentialIdB64url,
199
- presenceTokens: (0, import_sdk3.flattenPresenceTokens)(result)
225
+ presenceTokens: (0, import_sdk4.flattenPresenceTokens)(result)
200
226
  };
201
227
  }
202
228
  const beginResult = await bridge.send(
@@ -251,42 +277,49 @@ var getPasskeyMethods = (bridge, publishableKey) => ({
251
277
  );
252
278
  }
253
279
  return { credential_id: credential.rawId, passkey_registered: true };
254
- },
255
- // Parent-side passkey step-up. Mirrors the web SDK's
256
- // `sdk.getPresenceToken()` — orchestrator is platform-agnostic; only
257
- // the WebAuthn primitive differs (createRNPasskey() uses
258
- // react-native-passkeys instead of @simplewebauthn/browser).
259
- //
260
- // DEK hygiene strip lives inside `createRNPasskey().assertForServer`,
261
- // so the orchestrator never touches userHandle. Server gate
262
- // (requireUserHandleStripped) catches any regression.
263
- //
264
- // The relying-party origin for RN apps is reconstructed from the
265
- // app's configured rp_id (fetched via the iframe's GET_DEK_INFO) —
266
- // RN has no window.location.origin to use. Same pattern as
267
- // sdk-passkey-methods.ts::registerPasskey.
268
- getPresenceToken: async (options) => {
269
- const dekInfo = await bridge.send(
270
- import_utils.PostMessageType.AUTH,
271
- import_utils.PostMessageMethod.GET_DEK_INFO,
272
- { publishableKey }
273
- );
274
- if (!dekInfo.rp_id) {
275
- throw new Error("webauthn_rp_id_not_configured");
280
+ };
281
+ return {
282
+ registerPasskey: enrollPasskey,
283
+ // Additional and first-time enrollment share the same implementation.
284
+ // The SDK derives which branch is required from GET_DEK_INFO, so exposing
285
+ // both public method names does not duplicate ceremony logic.
286
+ addPasskey: enrollPasskey,
287
+ // Parent-side passkey step-up. Mirrors the web SDK's
288
+ // `sdk.getPresenceToken()` — orchestrator is platform-agnostic; only
289
+ // the WebAuthn primitive differs (createRNPasskey() uses
290
+ // react-native-passkeys instead of @simplewebauthn/browser).
291
+ //
292
+ // DEK hygiene strip lives inside `createRNPasskey().assertForServer`,
293
+ // so the orchestrator never touches userHandle. Server gate
294
+ // (requireUserHandleStripped) catches any regression.
295
+ //
296
+ // The relying-party origin for RN apps is reconstructed from the
297
+ // app's configured rp_id (fetched via the iframe's GET_DEK_INFO) —
298
+ // RN has no window.location.origin to use. Same pattern as
299
+ // sdk-passkey-methods.ts::registerPasskey.
300
+ getPresenceToken: async (options) => {
301
+ const dekInfo = await bridge.send(
302
+ import_utils.PostMessageType.AUTH,
303
+ import_utils.PostMessageMethod.GET_DEK_INFO,
304
+ { publishableKey }
305
+ );
306
+ if (!dekInfo.rp_id) {
307
+ throw new Error("webauthn_rp_id_not_configured");
308
+ }
309
+ return (0, import_sdk4.getPresenceToken)({
310
+ transport: bridge,
311
+ passkey: createRNPasskey(),
312
+ publishableKey,
313
+ relyingPartyOrigin: `https://${dekInfo.rp_id}`,
314
+ expiresInSecs: options?.expiresInSecs
315
+ });
276
316
  }
277
- return (0, import_sdk3.getPresenceToken)({
278
- transport: bridge,
279
- passkey: createRNPasskey(),
280
- publishableKey,
281
- relyingPartyOrigin: `https://${dekInfo.rp_id}`,
282
- expiresInSecs: options?.expiresInSecs
283
- });
284
- }
285
- });
317
+ };
318
+ };
286
319
 
287
320
  // src/sdk/sdk-methods.ts
288
- var import_sdk4 = require("@moon-x/core/sdk");
289
- var getSDKMethods = (bridge, publishableKey, relyingPartyOrigin, setIsAuthenticated, setUser) => (0, import_sdk4.getHeadlessGeneralMethods)({
321
+ var import_sdk5 = require("@moon-x/core/sdk");
322
+ var getSDKMethods = (bridge, publishableKey, relyingPartyOrigin, setIsAuthenticated, setUser) => (0, import_sdk5.getHeadlessGeneralMethods)({
290
323
  transport: bridge,
291
324
  passkey: createRNPasskey(),
292
325
  storage: createAsyncStorageKv(),
@@ -297,8 +330,17 @@ var getSDKMethods = (bridge, publishableKey, relyingPartyOrigin, setIsAuthentica
297
330
  });
298
331
 
299
332
  // src/sdk/sdk-solana-methods.ts
300
- var import_sdk5 = require("@moon-x/core/sdk");
301
- var getSolanaSDKMethods = (bridge, publishableKey, relyingPartyOrigin) => (0, import_sdk5.getHeadlessSolanaMethods)({
333
+ var import_sdk6 = require("@moon-x/core/sdk");
334
+ var getSolanaSDKMethods = (bridge, publishableKey, relyingPartyOrigin) => (0, import_sdk6.getHeadlessSolanaMethods)({
335
+ transport: bridge,
336
+ passkey: createRNPasskey(),
337
+ publishableKey,
338
+ relyingPartyOrigin
339
+ });
340
+
341
+ // src/sdk/sdk-tron-methods.ts
342
+ var import_sdk7 = require("@moon-x/core/sdk");
343
+ var getTronSDKMethods = (bridge, publishableKey, relyingPartyOrigin) => (0, import_sdk7.getHeadlessTronMethods)({
302
344
  transport: bridge,
303
345
  passkey: createRNPasskey(),
304
346
  publishableKey,
@@ -329,12 +371,14 @@ var createSdkInstance = ({
329
371
  isAuthenticated,
330
372
  user,
331
373
  ready,
374
+ revalidatedAt,
332
375
  setIsAuthenticated,
333
376
  setUser,
334
377
  refreshUser
335
378
  }) => ({
336
379
  publishableKey,
337
380
  ready,
381
+ revalidatedAt,
338
382
  isAuthenticated,
339
383
  user,
340
384
  refreshUser,
@@ -353,7 +397,9 @@ var createSdkInstance = ({
353
397
  ),
354
398
  ...getPasskeyMethods(bridge, publishableKey),
355
399
  ...getEthereumSDKMethods(bridge, publishableKey, relyingPartyOrigin),
356
- ...getSolanaSDKMethods(bridge, publishableKey, relyingPartyOrigin)
400
+ ...getFundingSDKMethods(bridge, publishableKey),
401
+ ...getSolanaSDKMethods(bridge, publishableKey, relyingPartyOrigin),
402
+ ...getTronSDKMethods(bridge, publishableKey, relyingPartyOrigin)
357
403
  });
358
404
 
359
405
  // src/provider.tsx
@@ -606,6 +652,32 @@ var MoonXProvider = ({
606
652
  const [ready, setReady] = (0, import_react.useState)(false);
607
653
  const [isAuthenticated, setIsAuthenticated] = (0, import_react.useState)(false);
608
654
  const [user, setUser] = (0, import_react.useState)(null);
655
+ const [revalidatedAt, setRevalidatedAt] = (0, import_react.useState)(0);
656
+ const [restoreNonce, setRestoreNonce] = (0, import_react.useState)(0);
657
+ const authFlowsInFlightRef = (0, import_react.useRef)(0);
658
+ const beginAuthFlow = (0, import_react.useCallback)(() => {
659
+ authFlowsInFlightRef.current += 1;
660
+ let finished = false;
661
+ return () => {
662
+ if (finished) return;
663
+ finished = true;
664
+ authFlowsInFlightRef.current = Math.max(
665
+ 0,
666
+ authFlowsInFlightRef.current - 1
667
+ );
668
+ if (authFlowsInFlightRef.current === 0) {
669
+ setRestoreNonce((value) => value + 1);
670
+ }
671
+ };
672
+ }, []);
673
+ (0, import_react.useEffect)(() => {
674
+ const subscription = import_react_native.AppState.addEventListener("change", (nextState) => {
675
+ if (nextState === "active") {
676
+ setRestoreNonce((value) => value + 1);
677
+ }
678
+ });
679
+ return () => subscription.remove();
680
+ }, []);
609
681
  const { height: screenHeight } = (0, import_react_native.useWindowDimensions)();
610
682
  const SHEET_TOP_OFFSET = 80;
611
683
  const sheetTranslateY = (0, import_react.useRef)(new import_react_native.Animated.Value(screenHeight)).current;
@@ -663,20 +735,37 @@ var MoonXProvider = ({
663
735
  navigateWebView(options.flowPath);
664
736
  return new Promise((resolve) => {
665
737
  let finished = false;
738
+ let result = null;
739
+ let cleanup;
666
740
  const finish = () => {
667
741
  if (finished) return;
668
742
  finished = true;
743
+ cleanup?.();
669
744
  setSensitiveVisible(false);
670
745
  navigateWebView("/");
671
746
  if (cancelRef.current === finish) cancelRef.current = null;
672
- resolve();
747
+ resolve(result ?? { status: "cancelled" });
673
748
  };
674
749
  cancelRef.current = finish;
675
750
  if (options.onMount) {
676
- Promise.resolve(options.onMount({ bridge, cancel: finish })).catch(
677
- () => {
678
- }
679
- );
751
+ Promise.resolve(
752
+ options.onMount({
753
+ bridge,
754
+ setResult: (next) => {
755
+ result = next;
756
+ }
757
+ })
758
+ ).then((onCleanup) => {
759
+ if (typeof onCleanup !== "function") return;
760
+ if (finished) onCleanup();
761
+ else cleanup = onCleanup;
762
+ }).catch((error) => {
763
+ if (finished) return;
764
+ result = {
765
+ status: "failed",
766
+ error: error instanceof Error ? error.message : "sensitive_flow_setup_failed"
767
+ };
768
+ });
680
769
  }
681
770
  });
682
771
  },
@@ -695,6 +784,7 @@ var MoonXProvider = ({
695
784
  isAuthenticated,
696
785
  user,
697
786
  ready,
787
+ revalidatedAt,
698
788
  setIsAuthenticated,
699
789
  setUser,
700
790
  refreshUser
@@ -706,6 +796,7 @@ var MoonXProvider = ({
706
796
  isAuthenticated,
707
797
  user,
708
798
  ready,
799
+ revalidatedAt,
709
800
  refreshUser
710
801
  ]
711
802
  );
@@ -737,16 +828,24 @@ var MoonXProvider = ({
737
828
  };
738
829
  }, [bridge]);
739
830
  (0, import_react.useEffect)(() => {
740
- if (!ready || isAuthenticated) return;
831
+ if (!ready) return;
741
832
  let cancelled = false;
742
833
  let attempt = 0;
743
- const maxAttempts = 4;
834
+ const maxAttempts = 5;
835
+ const timers = /* @__PURE__ */ new Set();
836
+ const schedule = (callback, delay) => {
837
+ const timer = setTimeout(() => {
838
+ timers.delete(timer);
839
+ callback();
840
+ }, delay);
841
+ timers.add(timer);
842
+ };
744
843
  const tryRestore = async () => {
745
- if (cancelled) return;
844
+ if (cancelled || authFlowsInFlightRef.current > 0) return;
746
845
  attempt += 1;
747
846
  try {
748
847
  const session = await sdkRef.current.getCurrentSession();
749
- if (cancelled) return;
848
+ if (cancelled || authFlowsInFlightRef.current > 0) return;
750
849
  if (session) {
751
850
  setIsAuthenticated(true);
752
851
  try {
@@ -754,38 +853,50 @@ var MoonXProvider = ({
754
853
  if (!cancelled && u) setUser(u);
755
854
  } catch {
756
855
  }
856
+ if (!cancelled) setRevalidatedAt(Date.now());
757
857
  return;
758
858
  }
759
859
  if (attempt < maxAttempts) {
760
860
  const delay = 200 * 2 ** (attempt - 1);
761
- setTimeout(tryRestore, delay);
861
+ schedule(tryRestore, delay);
862
+ } else if (!cancelled) {
863
+ setIsAuthenticated(false);
864
+ setUser(null);
865
+ setRevalidatedAt(Date.now());
762
866
  }
763
867
  } catch {
868
+ if (authFlowsInFlightRef.current > 0) return;
764
869
  if (!cancelled && attempt < maxAttempts) {
765
870
  const delay = 200 * 2 ** (attempt - 1);
766
- setTimeout(tryRestore, delay);
871
+ schedule(tryRestore, delay);
872
+ } else if (!cancelled) {
873
+ setRevalidatedAt(Date.now());
767
874
  }
768
875
  }
769
876
  };
770
- tryRestore();
877
+ schedule(tryRestore, restoreNonce > 0 ? 150 : 0);
771
878
  return () => {
772
879
  cancelled = true;
880
+ timers.forEach(clearTimeout);
881
+ timers.clear();
773
882
  };
774
- }, [ready, isAuthenticated]);
883
+ }, [ready, restoreNonce]);
775
884
  const contextValue = (0, import_react.useMemo)(
776
885
  () => ({
777
886
  sdk,
778
887
  _bridge: bridge,
779
888
  _relyingPartyOrigin: relyingPartyOriginResolver,
780
889
  _runSensitiveFlow: runSensitiveFlow,
781
- _oauthRedirectUri: config?.oauthRedirectUri
890
+ _oauthRedirectUri: config?.oauthRedirectUri,
891
+ _beginAuthFlow: beginAuthFlow
782
892
  }),
783
893
  [
784
894
  sdk,
785
895
  bridge,
786
896
  relyingPartyOriginResolver,
787
897
  runSensitiveFlow,
788
- config?.oauthRedirectUri
898
+ config?.oauthRedirectUri,
899
+ beginAuthFlow
789
900
  ]
790
901
  );
791
902
  const closeLabel = config?.sensitiveModalCopy?.closeLabel ?? "Done";
@@ -930,7 +1041,7 @@ var styles = import_react_native.StyleSheet.create({
930
1041
  });
931
1042
 
932
1043
  // src/hooks/index.ts
933
- var import_react6 = require("@moon-x/core/react");
1044
+ var import_react8 = require("@moon-x/core/react");
934
1045
 
935
1046
  // src/hooks/use-app-config.ts
936
1047
  var import_utils5 = require("@moon-x/core/utils");
@@ -1086,51 +1197,102 @@ var useDetachOAuth = () => {
1086
1197
  };
1087
1198
 
1088
1199
  // src/hooks/use-export-key.ts
1089
- var import_sdk6 = require("@moon-x/core/sdk");
1200
+ var import_sdk8 = require("@moon-x/core/sdk");
1201
+ var import_utils8 = require("@moon-x/core/utils");
1202
+ var parseExportKeyResult = (value) => {
1203
+ if (!value || typeof value !== "object" || !("status" in value)) {
1204
+ return { status: "failed", error: "invalid_export_key_result" };
1205
+ }
1206
+ const candidate = value;
1207
+ if (candidate.status === "completed" || candidate.status === "cancelled") {
1208
+ return { status: candidate.status };
1209
+ }
1210
+ if (candidate.status === "failed" && typeof candidate.error === "string") {
1211
+ return { status: "failed", error: candidate.error };
1212
+ }
1213
+ return { status: "failed", error: "invalid_export_key_result" };
1214
+ };
1090
1215
  var useExportKey = () => {
1091
1216
  const { sdk, _bridge, _relyingPartyOrigin, _runSensitiveFlow } = useMoonXContext();
1092
1217
  return {
1093
1218
  exportKey: async (wallet) => {
1094
- const { userHandleB64url, credentialIdB64url, tokens } = await (0, import_sdk6.getInternalPresenceTokens)({
1095
- transport: _bridge,
1096
- passkey: createRNPasskey(),
1097
- publishableKey: sdk.publishableKey,
1098
- relyingPartyOrigin: _relyingPartyOrigin,
1099
- scopes: import_sdk6.SCOPES_EXPORT_KEY
1100
- });
1101
- const keyshareReadToken = tokens.keyshare_read?.token ?? "";
1102
- const params = new URLSearchParams({
1103
- publishableKey: sdk.publishableKey,
1104
- wallet_id: wallet.id ?? "",
1105
- wallet_type: wallet.wallet_type ?? ""
1106
- });
1107
- const secrets = new URLSearchParams({
1108
- user_handle_b64url: userHandleB64url,
1109
- credential_id_b64url: credentialIdB64url,
1110
- keyshare_read_token: keyshareReadToken
1111
- });
1112
- await _runSensitiveFlow({
1113
- title: "Export key",
1114
- flowPath: `/export-key?${params.toString()}#${secrets.toString()}`,
1115
- // No completion postMessage in v1 — the user-tap-Done path
1116
- // resolves the promise via the modal's cancel handler. The
1117
- // promise simply waits for runSensitiveFlow to settle, which
1118
- // happens when the user dismisses.
1119
- onMount: () => Promise.resolve()
1120
- });
1219
+ try {
1220
+ const { userHandleB64url, credentialIdB64url, tokens } = await (0, import_sdk8.getInternalPresenceTokens)({
1221
+ transport: _bridge,
1222
+ passkey: createRNPasskey(),
1223
+ publishableKey: sdk.publishableKey,
1224
+ relyingPartyOrigin: _relyingPartyOrigin,
1225
+ scopes: import_sdk8.SCOPES_EXPORT_KEY
1226
+ });
1227
+ const keyshareReadToken = tokens.keyshare_read?.token ?? "";
1228
+ const params = new URLSearchParams({
1229
+ publishableKey: sdk.publishableKey,
1230
+ wallet_id: wallet.id ?? "",
1231
+ wallet_type: wallet.wallet_type ?? ""
1232
+ });
1233
+ const secrets = new URLSearchParams({
1234
+ user_handle_b64url: userHandleB64url,
1235
+ credential_id_b64url: credentialIdB64url,
1236
+ keyshare_read_token: keyshareReadToken
1237
+ });
1238
+ return await _runSensitiveFlow({
1239
+ title: "Export key",
1240
+ flowPath: `/export-key?${params.toString()}#${secrets.toString()}`,
1241
+ onMount: ({ bridge, setResult }) => bridge.register(
1242
+ import_utils8.PostMessageType.WALLET,
1243
+ import_utils8.PostMessageMethod.EXPORT_KEY_RESULT,
1244
+ (result) => {
1245
+ setResult(parseExportKeyResult(result));
1246
+ }
1247
+ )
1248
+ });
1249
+ } catch (error) {
1250
+ const message = error instanceof Error ? error.message : "export_key_failed";
1251
+ return /cancel/i.test(message) ? { status: "cancelled" } : { status: "failed", error: message };
1252
+ }
1121
1253
  }
1122
1254
  };
1123
1255
  };
1124
1256
 
1257
+ // src/hooks/use-fund-wallet.ts
1258
+ var useFundWallet = () => {
1259
+ const { sdk } = useMoonXContext();
1260
+ return {
1261
+ fundWallet: (params) => sdk.prepareFunding(params)
1262
+ };
1263
+ };
1264
+
1265
+ // src/hooks/use-login-with-email.ts
1266
+ var import_react5 = require("@moon-x/core/react");
1267
+ var import_react6 = require("react");
1268
+ var useLoginWithEmail = (callbacks) => {
1269
+ const login = (0, import_react5.useLoginWithEmail)(callbacks);
1270
+ const { _beginAuthFlow } = useMoonXContext();
1271
+ const coreLoginWithCode = login.loginWithCode;
1272
+ const loginWithCode = (0, import_react6.useCallback)(
1273
+ async (params) => {
1274
+ const finishAuthFlow = _beginAuthFlow();
1275
+ try {
1276
+ return await coreLoginWithCode(params);
1277
+ } finally {
1278
+ finishAuthFlow();
1279
+ }
1280
+ },
1281
+ [_beginAuthFlow, coreLoginWithCode]
1282
+ );
1283
+ return { ...login, loginWithCode };
1284
+ };
1285
+
1125
1286
  // src/hooks/use-login-with-oauth.ts
1126
- var import_utils8 = require("@moon-x/core/utils");
1127
- var import_react5 = require("react");
1287
+ var import_utils9 = require("@moon-x/core/utils");
1288
+ var import_react7 = require("react");
1128
1289
  var useLoginWithOAuth = (params) => {
1129
- const { sdk, _bridge, _oauthRedirectUri } = useMoonXContext();
1130
- const [state, setState] = (0, import_react5.useState)({ status: "idle" });
1290
+ const { sdk, _bridge, _oauthRedirectUri, _beginAuthFlow } = useMoonXContext();
1291
+ const [state, setState] = (0, import_react7.useState)({ status: "idle" });
1131
1292
  return {
1132
1293
  state,
1133
1294
  loginWithOAuth: async (provider) => {
1295
+ const finishAuthFlow = _beginAuthFlow();
1134
1296
  setState({ status: "starting" });
1135
1297
  try {
1136
1298
  const redirectUri = params?.redirectUri || _oauthRedirectUri;
@@ -1138,8 +1300,8 @@ var useLoginWithOAuth = (params) => {
1138
1300
  throw new Error("oauth_redirect_uri_missing");
1139
1301
  }
1140
1302
  const startResult = await _bridge.send(
1141
- import_utils8.PostMessageType.AUTH,
1142
- import_utils8.PostMessageMethod.START_OAUTH,
1303
+ import_utils9.PostMessageType.AUTH,
1304
+ import_utils9.PostMessageMethod.START_OAUTH,
1143
1305
  {
1144
1306
  publishableKey: sdk.publishableKey,
1145
1307
  provider,
@@ -1171,6 +1333,8 @@ var useLoginWithOAuth = (params) => {
1171
1333
  const err = e instanceof Error ? e : new Error(String(e));
1172
1334
  setState({ status: "error", error: err });
1173
1335
  throw err;
1336
+ } finally {
1337
+ finishAuthFlow();
1174
1338
  }
1175
1339
  },
1176
1340
  reset: () => setState({ status: "idle" })
@@ -1180,13 +1344,374 @@ var useLoginWithOAuth = (params) => {
1180
1344
  // src/hooks/use-moonx.ts
1181
1345
  var useMoonX = () => useMoonXContext().sdk;
1182
1346
 
1347
+ // src/external-wallets/use-external-wallets.ts
1348
+ var import_react9 = require("react");
1349
+ var useExternalWallets = (connectors) => {
1350
+ const [wallets, setWallets] = (0, import_react9.useState)([]);
1351
+ const [connected, setConnected] = (0, import_react9.useState)(
1352
+ null
1353
+ );
1354
+ const [status, setStatus] = (0, import_react9.useState)("idle");
1355
+ const [error, setError] = (0, import_react9.useState)(null);
1356
+ const [refreshNonce, setRefreshNonce] = (0, import_react9.useState)(0);
1357
+ const unsubscribeRef = (0, import_react9.useRef)(null);
1358
+ (0, import_react9.useEffect)(() => {
1359
+ let cancelled = false;
1360
+ void Promise.all(
1361
+ connectors.map(async (connector) => ({
1362
+ ...connector.info,
1363
+ available: connector.isAvailable ? await Promise.resolve(connector.isAvailable()).catch(() => false) : true
1364
+ }))
1365
+ ).then((discovered) => {
1366
+ if (!cancelled) setWallets(discovered);
1367
+ });
1368
+ return () => {
1369
+ cancelled = true;
1370
+ };
1371
+ }, [connectors, refreshNonce]);
1372
+ (0, import_react9.useEffect)(
1373
+ () => () => {
1374
+ unsubscribeRef.current?.();
1375
+ },
1376
+ []
1377
+ );
1378
+ const connect = (0, import_react9.useCallback)(
1379
+ async (id) => {
1380
+ const connector = connectors.find((candidate) => candidate.info.id === id);
1381
+ if (!connector) throw new Error(`External wallet "${id}" not found`);
1382
+ setStatus("connecting");
1383
+ setError(null);
1384
+ try {
1385
+ const connection = await connector.connect();
1386
+ unsubscribeRef.current?.();
1387
+ unsubscribeRef.current = connection.subscribeAccounts?.((accounts, activeAccount) => {
1388
+ if (!activeAccount) {
1389
+ setConnected(null);
1390
+ setStatus("idle");
1391
+ return;
1392
+ }
1393
+ setConnected(
1394
+ (current) => current ? { ...current, accounts, activeAccount, chain: activeAccount.chain } : current
1395
+ );
1396
+ }) ?? null;
1397
+ setConnected(connection);
1398
+ setStatus("connected");
1399
+ return connection;
1400
+ } catch (cause) {
1401
+ const nextError = cause instanceof Error ? cause : new Error("Wallet connection failed");
1402
+ setError(nextError);
1403
+ setStatus("error");
1404
+ throw nextError;
1405
+ }
1406
+ },
1407
+ [connectors]
1408
+ );
1409
+ const switchAccount = (0, import_react9.useCallback)(
1410
+ async (address, chainId) => {
1411
+ if (!connected) throw new Error("No external wallet connected");
1412
+ const activeAccount = await connected.switchAccount(address, chainId);
1413
+ setConnected(
1414
+ (current) => current?.id === connected.id ? { ...current, activeAccount, chain: activeAccount.chain } : current
1415
+ );
1416
+ },
1417
+ [connected]
1418
+ );
1419
+ const disconnect = (0, import_react9.useCallback)(async () => {
1420
+ try {
1421
+ await connected?.disconnect();
1422
+ } finally {
1423
+ unsubscribeRef.current?.();
1424
+ unsubscribeRef.current = null;
1425
+ setConnected(null);
1426
+ setStatus("idle");
1427
+ }
1428
+ }, [connected]);
1429
+ return {
1430
+ wallets,
1431
+ connected,
1432
+ status,
1433
+ error,
1434
+ connect,
1435
+ disconnect,
1436
+ switchAccount,
1437
+ refresh: () => setRefreshNonce((value) => value + 1)
1438
+ };
1439
+ };
1440
+
1441
+ // src/external-wallets/wallet-connect.ts
1442
+ var import_lib2 = require("@moon-x/core/lib");
1443
+ var DEFAULT_REQUIRED_NAMESPACES = {
1444
+ eip155: {
1445
+ chains: ["eip155:1"],
1446
+ methods: [
1447
+ "eth_sendTransaction",
1448
+ "eth_signTransaction",
1449
+ "personal_sign",
1450
+ "eth_signTypedData_v4"
1451
+ ],
1452
+ events: ["accountsChanged", "chainChanged"]
1453
+ }
1454
+ };
1455
+ var toExternalAccount = (account) => {
1456
+ const chain = account.namespace === "eip155" ? "ethereum" : account.namespace === "solana" ? "solana" : null;
1457
+ return chain ? { address: account.address, chain, chainId: account.chainId } : null;
1458
+ };
1459
+ var addressesMatch = (left, right, chain) => chain === "ethereum" ? left.toLowerCase() === right.toLowerCase() : left === right;
1460
+ var bytesToHex = (message) => {
1461
+ let result = "0x";
1462
+ for (const byte of message) result += byte.toString(16).padStart(2, "0");
1463
+ return result;
1464
+ };
1465
+ var stringToHex = (message) => {
1466
+ if (message.startsWith("0x")) return message;
1467
+ const encoded = encodeURIComponent(message);
1468
+ let result = "0x";
1469
+ for (let index = 0; index < encoded.length; index += 1) {
1470
+ if (encoded[index] === "%") {
1471
+ result += encoded.slice(index + 1, index + 3).toLowerCase();
1472
+ index += 2;
1473
+ } else {
1474
+ result += encoded.charCodeAt(index).toString(16).padStart(2, "0");
1475
+ }
1476
+ }
1477
+ return result;
1478
+ };
1479
+ var createConnection = ({
1480
+ client,
1481
+ session,
1482
+ walletClientType = "walletconnect",
1483
+ chain,
1484
+ address
1485
+ }) => {
1486
+ let accounts = (0, import_lib2.getWalletConnectAccounts)(session).map(toExternalAccount).filter((account) => account !== null);
1487
+ if (chain) accounts = accounts.filter((account) => account.chain === chain);
1488
+ if (accounts.length === 0) {
1489
+ throw new Error("WalletConnect session has no supported accounts");
1490
+ }
1491
+ let active = accounts.find(
1492
+ (account) => account.address === address && (!chain || account.chain === chain)
1493
+ ) ?? accounts[0];
1494
+ const requireActiveAccount = () => {
1495
+ if (!active) throw new Error("WalletConnect session disconnected");
1496
+ return active;
1497
+ };
1498
+ const listeners = /* @__PURE__ */ new Set();
1499
+ const metadata = session.peer?.metadata;
1500
+ const connection = {
1501
+ id: session.topic,
1502
+ name: metadata?.name ?? "WalletConnect",
1503
+ chain: active.chain,
1504
+ walletClientType,
1505
+ accounts,
1506
+ activeAccount: active,
1507
+ request: async (method, params, chainId) => {
1508
+ const account = requireActiveAccount();
1509
+ return (0, import_lib2.requestWalletConnect)(client, {
1510
+ topic: session.topic,
1511
+ chainId: chainId ?? account.chainId ?? "eip155:1",
1512
+ method,
1513
+ requestParams: params
1514
+ });
1515
+ },
1516
+ signMessage: async (message) => {
1517
+ const account = requireActiveAccount();
1518
+ if (account.chain !== "ethereum") {
1519
+ throw new Error(
1520
+ "Use request() with the wallet's supported Solana signing method"
1521
+ );
1522
+ }
1523
+ return (0, import_lib2.requestWalletConnect)(client, {
1524
+ topic: session.topic,
1525
+ chainId: account.chainId ?? "eip155:1",
1526
+ method: "personal_sign",
1527
+ requestParams: [
1528
+ typeof message === "string" ? stringToHex(message) : bytesToHex(message),
1529
+ account.address
1530
+ ]
1531
+ });
1532
+ },
1533
+ signTypedData: async (typedData) => {
1534
+ const account = requireActiveAccount();
1535
+ if (account.chain !== "ethereum") {
1536
+ throw new Error("Typed-data signing is only available for Ethereum");
1537
+ }
1538
+ return (0, import_lib2.requestWalletConnect)(client, {
1539
+ topic: session.topic,
1540
+ chainId: account.chainId ?? "eip155:1",
1541
+ method: "eth_signTypedData_v4",
1542
+ requestParams: [account.address, JSON.stringify(typedData)]
1543
+ });
1544
+ },
1545
+ signTransaction: async (transaction) => {
1546
+ const account = requireActiveAccount();
1547
+ if (account.chain !== "ethereum") {
1548
+ throw new Error(
1549
+ "Use request() with the wallet's supported Solana signing method"
1550
+ );
1551
+ }
1552
+ return (0, import_lib2.requestWalletConnect)(client, {
1553
+ topic: session.topic,
1554
+ chainId: account.chainId ?? "eip155:1",
1555
+ method: "eth_signTransaction",
1556
+ requestParams: [transaction]
1557
+ });
1558
+ },
1559
+ sendTransaction: async (transaction) => {
1560
+ const account = requireActiveAccount();
1561
+ if (account.chain !== "ethereum") {
1562
+ throw new Error(
1563
+ "Use request() with the wallet's supported Solana send method"
1564
+ );
1565
+ }
1566
+ return (0, import_lib2.requestWalletConnect)(client, {
1567
+ topic: session.topic,
1568
+ chainId: account.chainId ?? "eip155:1",
1569
+ method: "eth_sendTransaction",
1570
+ requestParams: [transaction]
1571
+ });
1572
+ },
1573
+ switchAccount: async (nextAddress, nextChainId) => {
1574
+ requireActiveAccount();
1575
+ const next = accounts.find(
1576
+ (account) => account.address === nextAddress && (!nextChainId || account.chainId === nextChainId)
1577
+ );
1578
+ if (!next) throw new Error("Account is not approved in this session");
1579
+ active = next;
1580
+ connection.activeAccount = next;
1581
+ connection.chain = next.chain;
1582
+ listeners.forEach((listener) => listener(accounts, active));
1583
+ return next;
1584
+ },
1585
+ subscribeAccounts: (listener) => {
1586
+ listeners.add(listener);
1587
+ return () => listeners.delete(listener);
1588
+ },
1589
+ disconnect: async () => {
1590
+ cleanup();
1591
+ publish([]);
1592
+ await (0, import_lib2.disconnectWalletConnectSession)(client, session.topic);
1593
+ },
1594
+ raw: { client, session }
1595
+ };
1596
+ const publish = (nextAccounts) => {
1597
+ accounts = chain ? nextAccounts.filter((account) => account.chain === chain) : nextAccounts;
1598
+ const previousActive = active;
1599
+ const stillApproved = previousActive ? accounts.find(
1600
+ (account) => account.address === previousActive.address && account.chainId === previousActive.chainId
1601
+ ) : void 0;
1602
+ active = stillApproved ?? accounts[0] ?? null;
1603
+ connection.accounts = accounts;
1604
+ connection.activeAccount = active;
1605
+ if (active) {
1606
+ connection.chain = active.chain;
1607
+ }
1608
+ listeners.forEach((listener) => listener(accounts, active ?? null));
1609
+ };
1610
+ const onSessionUpdate = (event) => {
1611
+ if (event.topic !== session.topic || !event.params?.namespaces) return;
1612
+ session.namespaces = event.params.namespaces;
1613
+ publish(
1614
+ (0, import_lib2.getWalletConnectAccounts)(session).map(toExternalAccount).filter((account) => account !== null)
1615
+ );
1616
+ };
1617
+ const onSessionEvent = (event) => {
1618
+ if (event.topic !== session.topic || event.params?.event?.name !== "accountsChanged" || !Array.isArray(event.params.event.data)) {
1619
+ return;
1620
+ }
1621
+ if (!active) return;
1622
+ const currentAccount = active;
1623
+ const values = event.params.event.data;
1624
+ if (!values.every((value) => typeof value === "string")) {
1625
+ return;
1626
+ }
1627
+ if (values.length === 0) {
1628
+ publish([]);
1629
+ return;
1630
+ }
1631
+ const approvedAccounts = (0, import_lib2.getWalletConnectAccounts)(session).map(toExternalAccount).filter(
1632
+ (account) => account !== null && (!chain || account.chain === chain)
1633
+ );
1634
+ const eventChainId = event.params.chainId;
1635
+ const next = values.map((value) => {
1636
+ if (value.includes(":")) {
1637
+ const parsed = (0, import_lib2.parseWalletConnectAccount)(value);
1638
+ const candidate = parsed ? toExternalAccount(parsed) : null;
1639
+ if (!candidate || eventChainId && candidate.chainId !== eventChainId) {
1640
+ return null;
1641
+ }
1642
+ return approvedAccounts.find(
1643
+ (account) => account.chain === candidate.chain && account.chainId === candidate.chainId && addressesMatch(account.address, candidate.address, account.chain)
1644
+ ) ?? null;
1645
+ }
1646
+ return approvedAccounts.find(
1647
+ (account) => (eventChainId ? account.chainId === eventChainId : account.chain === currentAccount.chain && account.chainId === currentAccount.chainId) && addressesMatch(account.address, value, account.chain)
1648
+ ) ?? null;
1649
+ });
1650
+ const validated = next.filter(
1651
+ (account) => account !== null
1652
+ );
1653
+ if (validated.length !== values.length) return;
1654
+ publish(validated);
1655
+ };
1656
+ const onSessionEnded = (event) => {
1657
+ if (event.topic !== session.topic) return;
1658
+ cleanup();
1659
+ publish([]);
1660
+ };
1661
+ const cleanup = () => {
1662
+ client.off?.("session_update", onSessionUpdate);
1663
+ client.off?.("session_event", onSessionEvent);
1664
+ client.off?.("session_delete", onSessionEnded);
1665
+ client.off?.("session_expire", onSessionEnded);
1666
+ };
1667
+ client.on?.("session_update", onSessionUpdate);
1668
+ client.on?.("session_event", onSessionEvent);
1669
+ client.on?.("session_delete", onSessionEnded);
1670
+ client.on?.("session_expire", onSessionEnded);
1671
+ return connection;
1672
+ };
1673
+ var connectWalletConnect = async (options) => {
1674
+ const { uri, approval } = await (0, import_lib2.beginWalletConnectSession)(options.client, {
1675
+ requiredNamespaces: options.requiredNamespaces ?? DEFAULT_REQUIRED_NAMESPACES,
1676
+ optionalNamespaces: options.optionalNamespaces
1677
+ });
1678
+ return {
1679
+ uri,
1680
+ approval: async () => createConnection({
1681
+ client: options.client,
1682
+ session: await approval(),
1683
+ walletClientType: options.walletClientType,
1684
+ chain: options.chain,
1685
+ address: options.address
1686
+ })
1687
+ };
1688
+ };
1689
+ var listWalletConnectSessions = (client) => client.session?.getAll() ?? [];
1690
+ var restoreWalletConnectSession = (options) => {
1691
+ const session = listWalletConnectSessions(options.client).find(
1692
+ (candidate) => candidate.topic === options.topic
1693
+ );
1694
+ if (!session) throw new Error("WalletConnect session not found");
1695
+ return createConnection({
1696
+ client: options.client,
1697
+ session,
1698
+ walletClientType: options.walletClientType,
1699
+ chain: options.chain,
1700
+ address: options.address
1701
+ });
1702
+ };
1703
+
1183
1704
  // src/index.ts
1184
- var import_utils9 = require("@moon-x/core/utils");
1705
+ var import_utils10 = require("@moon-x/core/utils");
1185
1706
  // Annotate the CommonJS export names for ESM import in node:
1186
1707
  0 && (module.exports = {
1708
+ MoonKeyProvider,
1187
1709
  MoonXProvider,
1188
1710
  PostMessageMethod,
1189
1711
  PostMessageType,
1712
+ connectWalletConnect,
1713
+ listWalletConnectSessions,
1714
+ restoreWalletConnectSession,
1190
1715
  useAddPasskey,
1191
1716
  useAppConfig,
1192
1717
  useAttachOAuth,
@@ -1194,10 +1719,13 @@ var import_utils9 = require("@moon-x/core/utils");
1194
1719
  useDetachOAuth,
1195
1720
  useEphemeralSigner,
1196
1721
  useExportKey,
1722
+ useExternalWallets,
1723
+ useFundWallet,
1197
1724
  useImportKey,
1198
1725
  useLoginWithEmail,
1199
1726
  useLoginWithOAuth,
1200
1727
  useLogout,
1728
+ useMoonKey,
1201
1729
  useMoonX,
1202
1730
  useMoonXContext,
1203
1731
  usePasskeyStatus,