@cometh/connect-react-hooks 0.0.10 → 0.0.11-dev.2

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.cjs CHANGED
@@ -77,6 +77,7 @@ async function createSmartAccount(config) {
77
77
 
78
78
 
79
79
  var _react = require('react'); var React2 = _interopRequireWildcard(_react); var React3 = _interopRequireWildcard(_react); var React4 = _interopRequireWildcard(_react); var React5 = _interopRequireWildcard(_react); var React6 = _interopRequireWildcard(_react); var React7 = _interopRequireWildcard(_react);
80
+ var CHAIN_STORAGE_KEY = "currentChain";
80
81
  var ConnectContext = _react.createContext.call(void 0, {
81
82
  queryClient: void 0,
82
83
  smartAccountClient: null,
@@ -84,7 +85,8 @@ var ConnectContext = _react.createContext.call(void 0, {
84
85
  updateSmartAccountClient: async () => {
85
86
  },
86
87
  disconnectSmartAccount: async () => {
87
- }
88
+ },
89
+ networksConfig: void 0
88
90
  });
89
91
  var ConnectProvider = ({
90
92
  children,
@@ -95,9 +97,24 @@ var ConnectProvider = ({
95
97
  const [smartAccountAddress, setSmartAccountAddress] = _react.useState.call(void 0, void 0);
96
98
  const updateSmartAccountClient = _react.useCallback.call(void 0,
97
99
  async (params = {}) => {
100
+ const chain = _nullishCoalesce(_nullishCoalesce(params.chain, () => ( JSON.parse(_nullishCoalesce(localStorage.getItem(CHAIN_STORAGE_KEY), () => ( "null"))))), () => ( config.networksConfig[0].chain));
101
+ const bundlerUrl = _optionalChain([config, 'access', _2 => _2.networksConfig, 'access', _3 => _3.find, 'call', _4 => _4(
102
+ (network) => _optionalChain([network, 'access', _5 => _5.chain, 'optionalAccess', _6 => _6.id]) === chain.id
103
+ ), 'optionalAccess', _7 => _7.bundlerUrl]);
104
+ const paymasterUrl = _optionalChain([config, 'access', _8 => _8.networksConfig, 'access', _9 => _9.find, 'call', _10 => _10(
105
+ (network) => _optionalChain([network, 'access', _11 => _11.chain, 'optionalAccess', _12 => _12.id]) === chain.id
106
+ ), 'optionalAccess', _13 => _13.paymasterUrl]);
107
+ const rpcUrl = _optionalChain([config, 'access', _14 => _14.networksConfig, 'access', _15 => _15.find, 'call', _16 => _16(
108
+ (network) => _optionalChain([network, 'access', _17 => _17.chain, 'optionalAccess', _18 => _18.id]) === chain.id
109
+ ), 'optionalAccess', _19 => _19.rpcUrl]);
110
+ if (!bundlerUrl) throw new Error("Bundler url not found");
98
111
  try {
99
112
  const { client, address: newAddress } = await createSmartAccount({
100
113
  ...config,
114
+ chain,
115
+ bundlerUrl,
116
+ paymasterUrl,
117
+ rpcUrl,
101
118
  smartAccountAddress: params.address,
102
119
  comethSignerConfig: {
103
120
  ...config.comethSignerConfig,
@@ -106,6 +123,7 @@ var ConnectProvider = ({
106
123
  });
107
124
  setSmartAccountClient(client);
108
125
  setSmartAccountAddress(newAddress);
126
+ localStorage.setItem(CHAIN_STORAGE_KEY, JSON.stringify(chain));
109
127
  } catch (e) {
110
128
  console.log(e);
111
129
  }
@@ -115,6 +133,7 @@ var ConnectProvider = ({
115
133
  const disconnectSmartAccount = _react.useCallback.call(void 0, async () => {
116
134
  setSmartAccountClient(null);
117
135
  setSmartAccountAddress(void 0);
136
+ localStorage.removeItem(CHAIN_STORAGE_KEY);
118
137
  }, []);
119
138
  _react.useEffect.call(void 0, () => {
120
139
  if (config.smartAccountAddress) {
@@ -127,14 +146,16 @@ var ConnectProvider = ({
127
146
  smartAccountClient,
128
147
  smartAccountAddress,
129
148
  updateSmartAccountClient,
130
- disconnectSmartAccount
149
+ disconnectSmartAccount,
150
+ networksConfig: config.networksConfig
131
151
  }),
132
152
  [
133
153
  queryClient,
134
154
  smartAccountClient,
135
155
  smartAccountAddress,
136
156
  updateSmartAccountClient,
137
- disconnectSmartAccount
157
+ disconnectSmartAccount,
158
+ config.networksConfig
138
159
  ]
139
160
  );
140
161
  return /* @__PURE__ */ React2.default.createElement(ConnectContext.Provider, { value }, children);
@@ -150,8 +171,8 @@ var useAccount = () => {
150
171
  const { smartAccountClient, smartAccountAddress } = context;
151
172
  const { chain, chainId } = _react.useMemo.call(void 0,
152
173
  () => ({
153
- chain: _optionalChain([smartAccountClient, 'optionalAccess', _2 => _2.chain]),
154
- chainId: _optionalChain([smartAccountClient, 'optionalAccess', _3 => _3.chain, 'optionalAccess', _4 => _4.id])
174
+ chain: _optionalChain([smartAccountClient, 'optionalAccess', _20 => _20.chain]),
175
+ chainId: _optionalChain([smartAccountClient, 'optionalAccess', _21 => _21.chain, 'optionalAccess', _22 => _22.id])
155
176
  }),
156
177
  [smartAccountClient]
157
178
  );
@@ -367,7 +388,7 @@ var FocusManager = (_a = class extends Subscribable {
367
388
  if (typeof __privateGet(this, _focused) === "boolean") {
368
389
  return __privateGet(this, _focused);
369
390
  }
370
- return _optionalChain([globalThis, 'access', _5 => _5.document, 'optionalAccess', _6 => _6.visibilityState]) !== "hidden";
391
+ return _optionalChain([globalThis, 'access', _23 => _23.document, 'optionalAccess', _24 => _24.visibilityState]) !== "hidden";
371
392
  }
372
393
  }, _focused = new WeakMap(), _cleanup = new WeakMap(), _setup = new WeakMap(), _a);
373
394
  var focusManager = new FocusManager();
@@ -657,7 +678,7 @@ var QueryObserver = (_a3 = class extends Subscribable {
657
678
  enumerable: true,
658
679
  get: () => {
659
680
  this.trackProp(key);
660
- _optionalChain([onPropTracked, 'optionalCall', _7 => _7(key)]);
681
+ _optionalChain([onPropTracked, 'optionalCall', _25 => _25(key)]);
661
682
  return result[key];
662
683
  }
663
684
  });
@@ -718,13 +739,13 @@ var QueryObserver = (_a3 = class extends Subscribable {
718
739
  }
719
740
  let { error, errorUpdatedAt, status } = newState;
720
741
  if (options.select && newState.data !== void 0) {
721
- if (prevResult && newState.data === _optionalChain([prevResultState, 'optionalAccess', _8 => _8.data]) && options.select === __privateGet(this, _selectFn)) {
742
+ if (prevResult && newState.data === _optionalChain([prevResultState, 'optionalAccess', _26 => _26.data]) && options.select === __privateGet(this, _selectFn)) {
722
743
  data = __privateGet(this, _selectResult);
723
744
  } else {
724
745
  try {
725
746
  __privateSet(this, _selectFn, options.select);
726
747
  data = options.select(newState.data);
727
- data = replaceData(_optionalChain([prevResult, 'optionalAccess', _9 => _9.data]), data, options);
748
+ data = replaceData(_optionalChain([prevResult, 'optionalAccess', _27 => _27.data]), data, options);
728
749
  __privateSet(this, _selectResult, data);
729
750
  __privateSet(this, _selectError, null);
730
751
  } catch (selectError) {
@@ -736,11 +757,11 @@ var QueryObserver = (_a3 = class extends Subscribable {
736
757
  }
737
758
  if (options.placeholderData !== void 0 && data === void 0 && status === "pending") {
738
759
  let placeholderData;
739
- if (_optionalChain([prevResult, 'optionalAccess', _10 => _10.isPlaceholderData]) && options.placeholderData === _optionalChain([prevResultOptions, 'optionalAccess', _11 => _11.placeholderData])) {
760
+ if (_optionalChain([prevResult, 'optionalAccess', _28 => _28.isPlaceholderData]) && options.placeholderData === _optionalChain([prevResultOptions, 'optionalAccess', _29 => _29.placeholderData])) {
740
761
  placeholderData = prevResult.data;
741
762
  } else {
742
763
  placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(
743
- _optionalChain([__privateGet, 'call', _12 => _12(this, _lastQueryWithDefinedData), 'optionalAccess', _13 => _13.state, 'access', _14 => _14.data]),
764
+ _optionalChain([__privateGet, 'call', _30 => _30(this, _lastQueryWithDefinedData), 'optionalAccess', _31 => _31.state, 'access', _32 => _32.data]),
744
765
  __privateGet(this, _lastQueryWithDefinedData)
745
766
  ) : options.placeholderData;
746
767
  if (options.select && placeholderData !== void 0) {
@@ -755,7 +776,7 @@ var QueryObserver = (_a3 = class extends Subscribable {
755
776
  if (placeholderData !== void 0) {
756
777
  status = "success";
757
778
  data = replaceData(
758
- _optionalChain([prevResult, 'optionalAccess', _15 => _15.data]),
779
+ _optionalChain([prevResult, 'optionalAccess', _33 => _33.data]),
759
780
  placeholderData,
760
781
  options
761
782
  );
@@ -835,7 +856,7 @@ var QueryObserver = (_a3 = class extends Subscribable {
835
856
  return changed && includedProps.has(typedKey);
836
857
  });
837
858
  };
838
- if (_optionalChain([notifyOptions, 'optionalAccess', _16 => _16.listeners]) !== false && shouldNotifyListeners()) {
859
+ if (_optionalChain([notifyOptions, 'optionalAccess', _34 => _34.listeners]) !== false && shouldNotifyListeners()) {
839
860
  defaultNotifyOptions.listeners = true;
840
861
  }
841
862
  __privateMethod(this, _QueryObserver_instances, notify_fn).call(this, { ...defaultNotifyOptions, ...notifyOptions });
@@ -852,7 +873,7 @@ var QueryObserver = (_a3 = class extends Subscribable {
852
873
  this.options,
853
874
  fetchOptions
854
875
  );
855
- if (!_optionalChain([fetchOptions, 'optionalAccess', _17 => _17.throwOnError])) {
876
+ if (!_optionalChain([fetchOptions, 'optionalAccess', _35 => _35.throwOnError])) {
856
877
  promise = promise.catch(noop);
857
878
  }
858
879
  return promise;
@@ -907,7 +928,7 @@ var QueryObserver = (_a3 = class extends Subscribable {
907
928
  __privateSet(this, _currentQuery, query);
908
929
  __privateSet(this, _currentQueryInitialState, query.state);
909
930
  if (this.hasListeners()) {
910
- _optionalChain([prevQuery, 'optionalAccess', _18 => _18.removeObserver, 'call', _19 => _19(this)]);
931
+ _optionalChain([prevQuery, 'optionalAccess', _36 => _36.removeObserver, 'call', _37 => _37(this)]);
911
932
  query.addObserver(this);
912
933
  }
913
934
  }, notify_fn = function(notifyOptions) {
@@ -978,15 +999,15 @@ var MutationObserver = (_a4 = class extends Subscribable {
978
999
  observer: this
979
1000
  });
980
1001
  }
981
- if (_optionalChain([prevOptions, 'optionalAccess', _20 => _20.mutationKey]) && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) {
1002
+ if (_optionalChain([prevOptions, 'optionalAccess', _38 => _38.mutationKey]) && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) {
982
1003
  this.reset();
983
- } else if (_optionalChain([__privateGet, 'call', _21 => _21(this, _currentMutation), 'optionalAccess', _22 => _22.state, 'access', _23 => _23.status]) === "pending") {
1004
+ } else if (_optionalChain([__privateGet, 'call', _39 => _39(this, _currentMutation), 'optionalAccess', _40 => _40.state, 'access', _41 => _41.status]) === "pending") {
984
1005
  __privateGet(this, _currentMutation).setOptions(this.options);
985
1006
  }
986
1007
  }
987
1008
  onUnsubscribe() {
988
1009
  if (!this.hasListeners()) {
989
- _optionalChain([__privateGet, 'call', _24 => _24(this, _currentMutation), 'optionalAccess', _25 => _25.removeObserver, 'call', _26 => _26(this)]);
1010
+ _optionalChain([__privateGet, 'call', _42 => _42(this, _currentMutation), 'optionalAccess', _43 => _43.removeObserver, 'call', _44 => _44(this)]);
990
1011
  }
991
1012
  }
992
1013
  onMutationUpdate(action) {
@@ -997,20 +1018,20 @@ var MutationObserver = (_a4 = class extends Subscribable {
997
1018
  return __privateGet(this, _currentResult2);
998
1019
  }
999
1020
  reset() {
1000
- _optionalChain([__privateGet, 'call', _27 => _27(this, _currentMutation), 'optionalAccess', _28 => _28.removeObserver, 'call', _29 => _29(this)]);
1021
+ _optionalChain([__privateGet, 'call', _45 => _45(this, _currentMutation), 'optionalAccess', _46 => _46.removeObserver, 'call', _47 => _47(this)]);
1001
1022
  __privateSet(this, _currentMutation, void 0);
1002
1023
  __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
1003
1024
  __privateMethod(this, _MutationObserver_instances, notify_fn2).call(this);
1004
1025
  }
1005
1026
  mutate(variables, options) {
1006
1027
  __privateSet(this, _mutateOptions, options);
1007
- _optionalChain([__privateGet, 'call', _30 => _30(this, _currentMutation), 'optionalAccess', _31 => _31.removeObserver, 'call', _32 => _32(this)]);
1028
+ _optionalChain([__privateGet, 'call', _48 => _48(this, _currentMutation), 'optionalAccess', _49 => _49.removeObserver, 'call', _50 => _50(this)]);
1008
1029
  __privateSet(this, _currentMutation, __privateGet(this, _client2).getMutationCache().build(__privateGet(this, _client2), this.options));
1009
1030
  __privateGet(this, _currentMutation).addObserver(this);
1010
1031
  return __privateGet(this, _currentMutation).execute(variables);
1011
1032
  }
1012
1033
  }, _client2 = new WeakMap(), _currentResult2 = new WeakMap(), _currentMutation = new WeakMap(), _mutateOptions = new WeakMap(), _MutationObserver_instances = new WeakSet(), updateResult_fn = function() {
1013
- const state = _nullishCoalesce(_optionalChain([__privateGet, 'call', _33 => _33(this, _currentMutation), 'optionalAccess', _34 => _34.state]), () => ( getDefaultState()));
1034
+ const state = _nullishCoalesce(_optionalChain([__privateGet, 'call', _51 => _51(this, _currentMutation), 'optionalAccess', _52 => _52.state]), () => ( getDefaultState()));
1014
1035
  __privateSet(this, _currentResult2, {
1015
1036
  ...state,
1016
1037
  isPending: state.status === "pending",
@@ -1025,12 +1046,12 @@ var MutationObserver = (_a4 = class extends Subscribable {
1025
1046
  if (__privateGet(this, _mutateOptions) && this.hasListeners()) {
1026
1047
  const variables = __privateGet(this, _currentResult2).variables;
1027
1048
  const context = __privateGet(this, _currentResult2).context;
1028
- if (_optionalChain([action, 'optionalAccess', _35 => _35.type]) === "success") {
1029
- _optionalChain([__privateGet, 'call', _36 => _36(this, _mutateOptions), 'access', _37 => _37.onSuccess, 'optionalCall', _38 => _38(action.data, variables, context)]);
1030
- _optionalChain([__privateGet, 'call', _39 => _39(this, _mutateOptions), 'access', _40 => _40.onSettled, 'optionalCall', _41 => _41(action.data, null, variables, context)]);
1031
- } else if (_optionalChain([action, 'optionalAccess', _42 => _42.type]) === "error") {
1032
- _optionalChain([__privateGet, 'call', _43 => _43(this, _mutateOptions), 'access', _44 => _44.onError, 'optionalCall', _45 => _45(action.error, variables, context)]);
1033
- _optionalChain([__privateGet, 'call', _46 => _46(this, _mutateOptions), 'access', _47 => _47.onSettled, 'optionalCall', _48 => _48(
1049
+ if (_optionalChain([action, 'optionalAccess', _53 => _53.type]) === "success") {
1050
+ _optionalChain([__privateGet, 'call', _54 => _54(this, _mutateOptions), 'access', _55 => _55.onSuccess, 'optionalCall', _56 => _56(action.data, variables, context)]);
1051
+ _optionalChain([__privateGet, 'call', _57 => _57(this, _mutateOptions), 'access', _58 => _58.onSettled, 'optionalCall', _59 => _59(action.data, null, variables, context)]);
1052
+ } else if (_optionalChain([action, 'optionalAccess', _60 => _60.type]) === "error") {
1053
+ _optionalChain([__privateGet, 'call', _61 => _61(this, _mutateOptions), 'access', _62 => _62.onError, 'optionalCall', _63 => _63(action.error, variables, context)]);
1054
+ _optionalChain([__privateGet, 'call', _64 => _64(this, _mutateOptions), 'access', _65 => _65.onSettled, 'optionalCall', _66 => _66(
1034
1055
  void 0,
1035
1056
  action.error,
1036
1057
  variables,
@@ -1130,7 +1151,7 @@ var ensureStaleTime = (defaultedOptions) => {
1130
1151
  }
1131
1152
  }
1132
1153
  };
1133
- var shouldSuspend = (defaultedOptions, result) => _optionalChain([defaultedOptions, 'optionalAccess', _49 => _49.suspense]) && result.isPending;
1154
+ var shouldSuspend = (defaultedOptions, result) => _optionalChain([defaultedOptions, 'optionalAccess', _67 => _67.suspense]) && result.isPending;
1134
1155
  var fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => {
1135
1156
  errorResetBoundary.clearReset();
1136
1157
  });
@@ -1149,7 +1170,7 @@ function useBaseQuery(options, Observer, queryClient) {
1149
1170
  const isRestoring = useIsRestoring();
1150
1171
  const errorResetBoundary = useQueryErrorResetBoundary();
1151
1172
  const defaultedOptions = client.defaultQueryOptions(options);
1152
- _optionalChain([client, 'access', _50 => _50.getDefaultOptions, 'call', _51 => _51(), 'access', _52 => _52.queries, 'optionalAccess', _53 => _53._experimental_beforeQuery, 'optionalCall', _54 => _54(
1173
+ _optionalChain([client, 'access', _68 => _68.getDefaultOptions, 'call', _69 => _69(), 'access', _70 => _70.queries, 'optionalAccess', _71 => _71._experimental_beforeQuery, 'optionalCall', _72 => _72(
1153
1174
  defaultedOptions
1154
1175
  )]);
1155
1176
  defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic";
@@ -1190,7 +1211,7 @@ function useBaseQuery(options, Observer, queryClient) {
1190
1211
  throw result.error;
1191
1212
  }
1192
1213
  ;
1193
- _optionalChain([client, 'access', _55 => _55.getDefaultOptions, 'call', _56 => _56(), 'access', _57 => _57.queries, 'optionalAccess', _58 => _58._experimental_afterQuery, 'optionalCall', _59 => _59(
1214
+ _optionalChain([client, 'access', _73 => _73.getDefaultOptions, 'call', _74 => _74(), 'access', _75 => _75.queries, 'optionalAccess', _76 => _76._experimental_afterQuery, 'optionalCall', _77 => _77(
1194
1215
  defaultedOptions,
1195
1216
  result
1196
1217
  )]);
@@ -1394,7 +1415,7 @@ var useConnect = () => {
1394
1415
  setIsPending(true);
1395
1416
  setError(null);
1396
1417
  updateSmartAccountClient(params).then(() => {
1397
- _optionalChain([queryClient, 'optionalAccess', _60 => _60.invalidateQueries, 'call', _61 => _61({
1418
+ _optionalChain([queryClient, 'optionalAccess', _78 => _78.invalidateQueries, 'call', _79 => _79({
1398
1419
  queryKey: ["connect"]
1399
1420
  })]);
1400
1421
  }).catch((e) => {
@@ -1412,7 +1433,7 @@ var useConnect = () => {
1412
1433
  setError(null);
1413
1434
  try {
1414
1435
  await updateSmartAccountClient(params);
1415
- _optionalChain([queryClient, 'optionalAccess', _62 => _62.invalidateQueries, 'call', _63 => _63({ queryKey: ["connect"] })]);
1436
+ _optionalChain([queryClient, 'optionalAccess', _80 => _80.invalidateQueries, 'call', _81 => _81({ queryKey: ["connect"] })]);
1416
1437
  } catch (e) {
1417
1438
  const err = e instanceof Error ? e : new Error("An error occurred");
1418
1439
  setError(err);
@@ -1445,7 +1466,7 @@ var useDisconnect = () => {
1445
1466
  setIsPending(true);
1446
1467
  setError(null);
1447
1468
  disconnectSmartAccount().then(() => {
1448
- _optionalChain([queryClient, 'optionalAccess', _64 => _64.invalidateQueries, 'call', _65 => _65({
1469
+ _optionalChain([queryClient, 'optionalAccess', _82 => _82.invalidateQueries, 'call', _83 => _83({
1449
1470
  queryKey: ["connect"]
1450
1471
  })]);
1451
1472
  }).catch((e) => {
@@ -1460,7 +1481,7 @@ var useDisconnect = () => {
1460
1481
  setError(null);
1461
1482
  try {
1462
1483
  await disconnectSmartAccount();
1463
- _optionalChain([queryClient, 'optionalAccess', _66 => _66.invalidateQueries, 'call', _67 => _67({ queryKey: ["connect"] })]);
1484
+ _optionalChain([queryClient, 'optionalAccess', _84 => _84.invalidateQueries, 'call', _85 => _85({ queryKey: ["connect"] })]);
1464
1485
  } catch (e) {
1465
1486
  const err = e instanceof Error ? e : new Error("An error occurred during disconnection");
1466
1487
  setError(err);
@@ -1897,7 +1918,7 @@ var useCreateNewSigner = (apiKey, baseUrl) => {
1897
1918
  setIsPending(true);
1898
1919
  setError(null);
1899
1920
  _connectsdk4337.createNewSigner.call(void 0, { apiKey, baseUrl, params }).then((signer) => {
1900
- _optionalChain([queryClient, 'optionalAccess', _68 => _68.invalidateQueries, 'call', _69 => _69({ queryKey: ["signer"] })]);
1921
+ _optionalChain([queryClient, 'optionalAccess', _86 => _86.invalidateQueries, 'call', _87 => _87({ queryKey: ["signer"] })]);
1901
1922
  return signer;
1902
1923
  }).catch((e) => {
1903
1924
  const err = e instanceof Error ? e : new Error("An error occurred");
@@ -1918,7 +1939,7 @@ var useCreateNewSigner = (apiKey, baseUrl) => {
1918
1939
  baseUrl,
1919
1940
  params
1920
1941
  });
1921
- _optionalChain([queryClient, 'optionalAccess', _70 => _70.invalidateQueries, 'call', _71 => _71({ queryKey: ["signer"] })]);
1942
+ _optionalChain([queryClient, 'optionalAccess', _88 => _88.invalidateQueries, 'call', _89 => _89({ queryKey: ["signer"] })]);
1922
1943
  return signer;
1923
1944
  } catch (e) {
1924
1945
  const err = e instanceof Error ? e : new Error("An error occurred");
@@ -2162,6 +2183,90 @@ function useCancelRecoveryRequest() {
2162
2183
  };
2163
2184
  }
2164
2185
 
2186
+ // src/hooks/useSwitchChain.ts
2187
+
2188
+
2189
+ var useSwitchChain = () => {
2190
+ const { address } = _wagmi.useAccount.call(void 0, );
2191
+ const context = _react.useContext.call(void 0, ConnectContext);
2192
+ if (context === void 0) {
2193
+ throw new Error("useSwitchChain must be used within a ConnectProvider");
2194
+ }
2195
+ const {
2196
+ queryClient,
2197
+ smartAccountClient,
2198
+ updateSmartAccountClient,
2199
+ networksConfig
2200
+ } = context;
2201
+ const [isPending, setIsPending] = _react.useState.call(void 0, false);
2202
+ const [error, setError] = _react.useState.call(void 0, null);
2203
+ const switchChainInternal = _react.useCallback.call(void 0,
2204
+ async (params) => {
2205
+ const { chain } = params;
2206
+ if (!networksConfig) {
2207
+ throw new Error("No current configuration found");
2208
+ }
2209
+ try {
2210
+ await updateSmartAccountClient({
2211
+ address: _optionalChain([smartAccountClient, 'optionalAccess', _90 => _90.account, 'access', _91 => _91.address]),
2212
+ chain
2213
+ });
2214
+ _optionalChain([queryClient, 'optionalAccess', _92 => _92.invalidateQueries, 'call', _93 => _93({
2215
+ queryKey: ["switchChain"]
2216
+ })]);
2217
+ } catch (e) {
2218
+ throw e instanceof Error ? e : new Error("An error occurred while switching chain");
2219
+ }
2220
+ },
2221
+ [
2222
+ smartAccountClient,
2223
+ updateSmartAccountClient,
2224
+ queryClient,
2225
+ networksConfig
2226
+ ]
2227
+ );
2228
+ const switchChain = _react.useCallback.call(void 0,
2229
+ (params) => {
2230
+ if (!address) throw new Error("Wallet is not connected");
2231
+ setIsPending(true);
2232
+ setError(null);
2233
+ switchChainInternal(params).catch((e) => {
2234
+ const err = e instanceof Error ? e : new Error(
2235
+ "An error occurred while switching chain"
2236
+ );
2237
+ setError(err);
2238
+ }).finally(() => {
2239
+ setIsPending(false);
2240
+ });
2241
+ },
2242
+ [switchChainInternal]
2243
+ );
2244
+ const switchChainAsync = _react.useCallback.call(void 0,
2245
+ async (params) => {
2246
+ if (!address) throw new Error("Wallet is not connected");
2247
+ setIsPending(true);
2248
+ setError(null);
2249
+ try {
2250
+ await switchChainInternal(params);
2251
+ } catch (e) {
2252
+ const err = e instanceof Error ? e : new Error("An error occurred while switching chain");
2253
+ setError(err);
2254
+ throw err;
2255
+ } finally {
2256
+ setIsPending(false);
2257
+ }
2258
+ },
2259
+ [switchChainInternal]
2260
+ );
2261
+ return {
2262
+ switchChain,
2263
+ switchChainAsync,
2264
+ isPending,
2265
+ error
2266
+ };
2267
+ };
2268
+
2269
+
2165
2270
 
2166
2271
 
2167
2272
 
@@ -2193,4 +2298,4 @@ function useCancelRecoveryRequest() {
2193
2298
 
2194
2299
 
2195
2300
 
2196
- exports.ConnectProvider = ConnectProvider; exports.useAccount = useAccount; exports.useAddOwner = useAddOwner; exports.useAddSessionKey = useAddSessionKey; exports.useAddWhitelistDestination = useAddWhitelistDestination; exports.useCancelRecoveryRequest = useCancelRecoveryRequest; exports.useConnect = useConnect; exports.useCreateNewSigner = useCreateNewSigner; exports.useDisconnect = useDisconnect; exports.useGenerateQRCodeUrl = useGenerateQRCodeUrl; exports.useGetEnrichedOwners = useGetEnrichedOwners; exports.useGetGasPrice = useGetGasPrice; exports.useGetOwners = useGetOwners; exports.useGetRecoveryRequest = useGetRecoveryRequest; exports.useGetSessionFromAddress = useGetSessionFromAddress; exports.useIsAddressWhitelistDestination = useIsAddressWhitelistDestination; exports.useIsRecoveryActive = useIsRecoveryActive; exports.useRemoveOwner = useRemoveOwner; exports.useRemoveWhitelistDestination = useRemoveWhitelistDestination; exports.useRetrieveAccountAddressFromPasskeyId = useRetrieveAccountAddressFromPasskeyId; exports.useRetrieveAccountAddressFromPasskeys = useRetrieveAccountAddressFromPasskeys; exports.useRevokeSessionKey = useRevokeSessionKey; exports.useSendTransaction = useSendTransaction; exports.useSendTransactionWithSessionKey = useSendTransactionWithSessionKey; exports.useSerializeUrlWithSignerPayload = useSerializeUrlWithSignerPayload; exports.useSetUpRecovery = useSetUpRecovery; exports.useSignMessage = useSignMessage; exports.useValidateAddDevice = useValidateAddDevice; exports.useVerifyMessage = useVerifyMessage; exports.useWriteContract = useWriteContract; exports.useWriteContractWithSessionKey = useWriteContractWithSessionKey;
2301
+ exports.ConnectProvider = ConnectProvider; exports.useAccount = useAccount; exports.useAddOwner = useAddOwner; exports.useAddSessionKey = useAddSessionKey; exports.useAddWhitelistDestination = useAddWhitelistDestination; exports.useCancelRecoveryRequest = useCancelRecoveryRequest; exports.useConnect = useConnect; exports.useCreateNewSigner = useCreateNewSigner; exports.useDisconnect = useDisconnect; exports.useGenerateQRCodeUrl = useGenerateQRCodeUrl; exports.useGetEnrichedOwners = useGetEnrichedOwners; exports.useGetGasPrice = useGetGasPrice; exports.useGetOwners = useGetOwners; exports.useGetRecoveryRequest = useGetRecoveryRequest; exports.useGetSessionFromAddress = useGetSessionFromAddress; exports.useIsAddressWhitelistDestination = useIsAddressWhitelistDestination; exports.useIsRecoveryActive = useIsRecoveryActive; exports.useRemoveOwner = useRemoveOwner; exports.useRemoveWhitelistDestination = useRemoveWhitelistDestination; exports.useRetrieveAccountAddressFromPasskeyId = useRetrieveAccountAddressFromPasskeyId; exports.useRetrieveAccountAddressFromPasskeys = useRetrieveAccountAddressFromPasskeys; exports.useRevokeSessionKey = useRevokeSessionKey; exports.useSendTransaction = useSendTransaction; exports.useSendTransactionWithSessionKey = useSendTransactionWithSessionKey; exports.useSerializeUrlWithSignerPayload = useSerializeUrlWithSignerPayload; exports.useSetUpRecovery = useSetUpRecovery; exports.useSignMessage = useSignMessage; exports.useSwitchChain = useSwitchChain; exports.useValidateAddDevice = useValidateAddDevice; exports.useVerifyMessage = useVerifyMessage; exports.useWriteContract = useWriteContract; exports.useWriteContractWithSessionKey = useWriteContractWithSessionKey;
package/dist/index.d.cts CHANGED
@@ -41,10 +41,16 @@ type Override<TTargetA, TTargetB> = {
41
41
 
42
42
  declare function useMutation<TData = unknown, TError = y, TVariables = void, TContext = unknown>(options: UseMutationOptions<TData, TError, TVariables, TContext>, queryClient?: b): UseMutationResult<TData, TError, TVariables, TContext>;
43
43
 
44
- type ConnectConfig = createSafeSmartAccountParameters<ENTRYPOINT_ADDRESS_V07_TYPE> & {
45
- bundlerUrl: string;
44
+ type NetworkParams = {
45
+ chain?: Chain;
46
+ bundlerUrl?: string;
46
47
  paymasterUrl?: string;
48
+ rpcUrl?: string;
47
49
  };
50
+ type OmitConfig<T> = Omit<T, "chain" | "paymasterUrl" | "bundlerUrl" | "rpcUrl"> & {
51
+ networksConfig: NetworkParams[];
52
+ };
53
+ type ConnectConfig = OmitConfig<createSafeSmartAccountParameters<ENTRYPOINT_ADDRESS_V07_TYPE>>;
48
54
  type ContextComethSmartAccountClient = ComethSmartAccountClient<SafeSmartAccount<ENTRYPOINT_ADDRESS_V07_TYPE, Transport, Chain>, Transport, Chain, ENTRYPOINT_ADDRESS_V07_TYPE>;
49
55
  declare const ConnectProvider: <TConfig extends ConnectConfig, TQueryClient extends b | undefined>({ children, config, queryClient, }: {
50
56
  children: ReactNode;
@@ -931,4 +937,15 @@ type UseCancelRecoveryRequestReturn = QueryResultType & {
931
937
  */
932
938
  declare function useCancelRecoveryRequest(): UseCancelRecoveryRequestReturn;
933
939
 
934
- export { ConnectProvider, type SendTransactionMutate, type SendTransactionMutateAsync, type SendTransactionWithSessionKeyMutate, type SendTransactionWithSessionKeyMutateAsync, type UseAddOwnerReturn, type UseAddSessionKeyReturn, type UseAddWhitelistDestinationReturn, type UseRemoveOwnerReturn, type UseRemoveWhitelistDestinationReturn, type UseRetrieveAccountAddressFromPasskeyOptions, type UseRevokeSessionKeyReturn, type VerifyMessageMutate, type VerifyMessageMutateAsync, type WriteContractMutate, type WriteContractMutateAsync, type WriteContractWithSessionKeyMutate, type WriteContractWithSessionKeyMutateAsync, useAccount, useAddOwner, useAddSessionKey, useAddWhitelistDestination, useCancelRecoveryRequest, useConnect, useCreateNewSigner, useDisconnect, useGenerateQRCodeUrl, useGetEnrichedOwners, useGetGasPrice, useGetOwners, useGetRecoveryRequest, useGetSessionFromAddress, useIsAddressWhitelistDestination, useIsRecoveryActive, useRemoveOwner, useRemoveWhitelistDestination, useRetrieveAccountAddressFromPasskeyId, useRetrieveAccountAddressFromPasskeys, useRevokeSessionKey, useSendTransaction, useSendTransactionWithSessionKey, useSerializeUrlWithSignerPayload, useSetUpRecovery, useSignMessage, useValidateAddDevice, useVerifyMessage, useWriteContract, useWriteContractWithSessionKey };
940
+ declare const useSwitchChain: () => {
941
+ switchChain: (params: {
942
+ chain: Chain;
943
+ }) => void;
944
+ switchChainAsync: (params: {
945
+ chain: Chain;
946
+ }) => Promise<void>;
947
+ isPending: boolean;
948
+ error: Error | null;
949
+ };
950
+
951
+ export { ConnectProvider, type SendTransactionMutate, type SendTransactionMutateAsync, type SendTransactionWithSessionKeyMutate, type SendTransactionWithSessionKeyMutateAsync, type UseAddOwnerReturn, type UseAddSessionKeyReturn, type UseAddWhitelistDestinationReturn, type UseRemoveOwnerReturn, type UseRemoveWhitelistDestinationReturn, type UseRetrieveAccountAddressFromPasskeyOptions, type UseRevokeSessionKeyReturn, type VerifyMessageMutate, type VerifyMessageMutateAsync, type WriteContractMutate, type WriteContractMutateAsync, type WriteContractWithSessionKeyMutate, type WriteContractWithSessionKeyMutateAsync, useAccount, useAddOwner, useAddSessionKey, useAddWhitelistDestination, useCancelRecoveryRequest, useConnect, useCreateNewSigner, useDisconnect, useGenerateQRCodeUrl, useGetEnrichedOwners, useGetGasPrice, useGetOwners, useGetRecoveryRequest, useGetSessionFromAddress, useIsAddressWhitelistDestination, useIsRecoveryActive, useRemoveOwner, useRemoveWhitelistDestination, useRetrieveAccountAddressFromPasskeyId, useRetrieveAccountAddressFromPasskeys, useRevokeSessionKey, useSendTransaction, useSendTransactionWithSessionKey, useSerializeUrlWithSignerPayload, useSetUpRecovery, useSignMessage, useSwitchChain, useValidateAddDevice, useVerifyMessage, useWriteContract, useWriteContractWithSessionKey };
package/dist/index.d.ts CHANGED
@@ -41,10 +41,16 @@ type Override<TTargetA, TTargetB> = {
41
41
 
42
42
  declare function useMutation<TData = unknown, TError = y, TVariables = void, TContext = unknown>(options: UseMutationOptions<TData, TError, TVariables, TContext>, queryClient?: b): UseMutationResult<TData, TError, TVariables, TContext>;
43
43
 
44
- type ConnectConfig = createSafeSmartAccountParameters<ENTRYPOINT_ADDRESS_V07_TYPE> & {
45
- bundlerUrl: string;
44
+ type NetworkParams = {
45
+ chain?: Chain;
46
+ bundlerUrl?: string;
46
47
  paymasterUrl?: string;
48
+ rpcUrl?: string;
47
49
  };
50
+ type OmitConfig<T> = Omit<T, "chain" | "paymasterUrl" | "bundlerUrl" | "rpcUrl"> & {
51
+ networksConfig: NetworkParams[];
52
+ };
53
+ type ConnectConfig = OmitConfig<createSafeSmartAccountParameters<ENTRYPOINT_ADDRESS_V07_TYPE>>;
48
54
  type ContextComethSmartAccountClient = ComethSmartAccountClient<SafeSmartAccount<ENTRYPOINT_ADDRESS_V07_TYPE, Transport, Chain>, Transport, Chain, ENTRYPOINT_ADDRESS_V07_TYPE>;
49
55
  declare const ConnectProvider: <TConfig extends ConnectConfig, TQueryClient extends b | undefined>({ children, config, queryClient, }: {
50
56
  children: ReactNode;
@@ -931,4 +937,15 @@ type UseCancelRecoveryRequestReturn = QueryResultType & {
931
937
  */
932
938
  declare function useCancelRecoveryRequest(): UseCancelRecoveryRequestReturn;
933
939
 
934
- export { ConnectProvider, type SendTransactionMutate, type SendTransactionMutateAsync, type SendTransactionWithSessionKeyMutate, type SendTransactionWithSessionKeyMutateAsync, type UseAddOwnerReturn, type UseAddSessionKeyReturn, type UseAddWhitelistDestinationReturn, type UseRemoveOwnerReturn, type UseRemoveWhitelistDestinationReturn, type UseRetrieveAccountAddressFromPasskeyOptions, type UseRevokeSessionKeyReturn, type VerifyMessageMutate, type VerifyMessageMutateAsync, type WriteContractMutate, type WriteContractMutateAsync, type WriteContractWithSessionKeyMutate, type WriteContractWithSessionKeyMutateAsync, useAccount, useAddOwner, useAddSessionKey, useAddWhitelistDestination, useCancelRecoveryRequest, useConnect, useCreateNewSigner, useDisconnect, useGenerateQRCodeUrl, useGetEnrichedOwners, useGetGasPrice, useGetOwners, useGetRecoveryRequest, useGetSessionFromAddress, useIsAddressWhitelistDestination, useIsRecoveryActive, useRemoveOwner, useRemoveWhitelistDestination, useRetrieveAccountAddressFromPasskeyId, useRetrieveAccountAddressFromPasskeys, useRevokeSessionKey, useSendTransaction, useSendTransactionWithSessionKey, useSerializeUrlWithSignerPayload, useSetUpRecovery, useSignMessage, useValidateAddDevice, useVerifyMessage, useWriteContract, useWriteContractWithSessionKey };
940
+ declare const useSwitchChain: () => {
941
+ switchChain: (params: {
942
+ chain: Chain;
943
+ }) => void;
944
+ switchChainAsync: (params: {
945
+ chain: Chain;
946
+ }) => Promise<void>;
947
+ isPending: boolean;
948
+ error: Error | null;
949
+ };
950
+
951
+ export { ConnectProvider, type SendTransactionMutate, type SendTransactionMutateAsync, type SendTransactionWithSessionKeyMutate, type SendTransactionWithSessionKeyMutateAsync, type UseAddOwnerReturn, type UseAddSessionKeyReturn, type UseAddWhitelistDestinationReturn, type UseRemoveOwnerReturn, type UseRemoveWhitelistDestinationReturn, type UseRetrieveAccountAddressFromPasskeyOptions, type UseRevokeSessionKeyReturn, type VerifyMessageMutate, type VerifyMessageMutateAsync, type WriteContractMutate, type WriteContractMutateAsync, type WriteContractWithSessionKeyMutate, type WriteContractWithSessionKeyMutateAsync, useAccount, useAddOwner, useAddSessionKey, useAddWhitelistDestination, useCancelRecoveryRequest, useConnect, useCreateNewSigner, useDisconnect, useGenerateQRCodeUrl, useGetEnrichedOwners, useGetGasPrice, useGetOwners, useGetRecoveryRequest, useGetSessionFromAddress, useIsAddressWhitelistDestination, useIsRecoveryActive, useRemoveOwner, useRemoveWhitelistDestination, useRetrieveAccountAddressFromPasskeyId, useRetrieveAccountAddressFromPasskeys, useRevokeSessionKey, useSendTransaction, useSendTransactionWithSessionKey, useSerializeUrlWithSignerPayload, useSetUpRecovery, useSignMessage, useSwitchChain, useValidateAddDevice, useVerifyMessage, useWriteContract, useWriteContractWithSessionKey };
package/dist/index.js CHANGED
@@ -77,6 +77,7 @@ import React, {
77
77
  useEffect,
78
78
  useCallback
79
79
  } from "react";
80
+ var CHAIN_STORAGE_KEY = "currentChain";
80
81
  var ConnectContext = createContext({
81
82
  queryClient: void 0,
82
83
  smartAccountClient: null,
@@ -84,7 +85,8 @@ var ConnectContext = createContext({
84
85
  updateSmartAccountClient: async () => {
85
86
  },
86
87
  disconnectSmartAccount: async () => {
87
- }
88
+ },
89
+ networksConfig: void 0
88
90
  });
89
91
  var ConnectProvider = ({
90
92
  children,
@@ -95,9 +97,24 @@ var ConnectProvider = ({
95
97
  const [smartAccountAddress, setSmartAccountAddress] = useState(void 0);
96
98
  const updateSmartAccountClient = useCallback(
97
99
  async (params = {}) => {
100
+ const chain = params.chain ?? JSON.parse(localStorage.getItem(CHAIN_STORAGE_KEY) ?? "null") ?? config.networksConfig[0].chain;
101
+ const bundlerUrl = config.networksConfig.find(
102
+ (network) => network.chain?.id === chain.id
103
+ )?.bundlerUrl;
104
+ const paymasterUrl = config.networksConfig.find(
105
+ (network) => network.chain?.id === chain.id
106
+ )?.paymasterUrl;
107
+ const rpcUrl = config.networksConfig.find(
108
+ (network) => network.chain?.id === chain.id
109
+ )?.rpcUrl;
110
+ if (!bundlerUrl) throw new Error("Bundler url not found");
98
111
  try {
99
112
  const { client, address: newAddress } = await createSmartAccount({
100
113
  ...config,
114
+ chain,
115
+ bundlerUrl,
116
+ paymasterUrl,
117
+ rpcUrl,
101
118
  smartAccountAddress: params.address,
102
119
  comethSignerConfig: {
103
120
  ...config.comethSignerConfig,
@@ -106,6 +123,7 @@ var ConnectProvider = ({
106
123
  });
107
124
  setSmartAccountClient(client);
108
125
  setSmartAccountAddress(newAddress);
126
+ localStorage.setItem(CHAIN_STORAGE_KEY, JSON.stringify(chain));
109
127
  } catch (e) {
110
128
  console.log(e);
111
129
  }
@@ -115,6 +133,7 @@ var ConnectProvider = ({
115
133
  const disconnectSmartAccount = useCallback(async () => {
116
134
  setSmartAccountClient(null);
117
135
  setSmartAccountAddress(void 0);
136
+ localStorage.removeItem(CHAIN_STORAGE_KEY);
118
137
  }, []);
119
138
  useEffect(() => {
120
139
  if (config.smartAccountAddress) {
@@ -127,14 +146,16 @@ var ConnectProvider = ({
127
146
  smartAccountClient,
128
147
  smartAccountAddress,
129
148
  updateSmartAccountClient,
130
- disconnectSmartAccount
149
+ disconnectSmartAccount,
150
+ networksConfig: config.networksConfig
131
151
  }),
132
152
  [
133
153
  queryClient,
134
154
  smartAccountClient,
135
155
  smartAccountAddress,
136
156
  updateSmartAccountClient,
137
- disconnectSmartAccount
157
+ disconnectSmartAccount,
158
+ config.networksConfig
138
159
  ]
139
160
  );
140
161
  return /* @__PURE__ */ React.createElement(ConnectContext.Provider, { value }, children);
@@ -2161,6 +2182,89 @@ function useCancelRecoveryRequest() {
2161
2182
  data: result.data
2162
2183
  };
2163
2184
  }
2185
+
2186
+ // src/hooks/useSwitchChain.ts
2187
+ import { useCallback as useCallback8, useContext as useContext8, useState as useState9 } from "react";
2188
+ import { useAccount as useAccount2 } from "wagmi";
2189
+ var useSwitchChain = () => {
2190
+ const { address } = useAccount2();
2191
+ const context = useContext8(ConnectContext);
2192
+ if (context === void 0) {
2193
+ throw new Error("useSwitchChain must be used within a ConnectProvider");
2194
+ }
2195
+ const {
2196
+ queryClient,
2197
+ smartAccountClient,
2198
+ updateSmartAccountClient,
2199
+ networksConfig
2200
+ } = context;
2201
+ const [isPending, setIsPending] = useState9(false);
2202
+ const [error, setError] = useState9(null);
2203
+ const switchChainInternal = useCallback8(
2204
+ async (params) => {
2205
+ const { chain } = params;
2206
+ if (!networksConfig) {
2207
+ throw new Error("No current configuration found");
2208
+ }
2209
+ try {
2210
+ await updateSmartAccountClient({
2211
+ address: smartAccountClient?.account.address,
2212
+ chain
2213
+ });
2214
+ queryClient?.invalidateQueries({
2215
+ queryKey: ["switchChain"]
2216
+ });
2217
+ } catch (e) {
2218
+ throw e instanceof Error ? e : new Error("An error occurred while switching chain");
2219
+ }
2220
+ },
2221
+ [
2222
+ smartAccountClient,
2223
+ updateSmartAccountClient,
2224
+ queryClient,
2225
+ networksConfig
2226
+ ]
2227
+ );
2228
+ const switchChain = useCallback8(
2229
+ (params) => {
2230
+ if (!address) throw new Error("Wallet is not connected");
2231
+ setIsPending(true);
2232
+ setError(null);
2233
+ switchChainInternal(params).catch((e) => {
2234
+ const err = e instanceof Error ? e : new Error(
2235
+ "An error occurred while switching chain"
2236
+ );
2237
+ setError(err);
2238
+ }).finally(() => {
2239
+ setIsPending(false);
2240
+ });
2241
+ },
2242
+ [switchChainInternal]
2243
+ );
2244
+ const switchChainAsync = useCallback8(
2245
+ async (params) => {
2246
+ if (!address) throw new Error("Wallet is not connected");
2247
+ setIsPending(true);
2248
+ setError(null);
2249
+ try {
2250
+ await switchChainInternal(params);
2251
+ } catch (e) {
2252
+ const err = e instanceof Error ? e : new Error("An error occurred while switching chain");
2253
+ setError(err);
2254
+ throw err;
2255
+ } finally {
2256
+ setIsPending(false);
2257
+ }
2258
+ },
2259
+ [switchChainInternal]
2260
+ );
2261
+ return {
2262
+ switchChain,
2263
+ switchChainAsync,
2264
+ isPending,
2265
+ error
2266
+ };
2267
+ };
2164
2268
  export {
2165
2269
  ConnectProvider,
2166
2270
  useAccount,
@@ -2189,6 +2293,7 @@ export {
2189
2293
  useSerializeUrlWithSignerPayload,
2190
2294
  useSetUpRecovery,
2191
2295
  useSignMessage,
2296
+ useSwitchChain,
2192
2297
  useValidateAddDevice,
2193
2298
  useVerifyMessage,
2194
2299
  useWriteContract,
package/package.json CHANGED
@@ -7,7 +7,7 @@
7
7
  "url": "https://twitter.com/slovaye"
8
8
  }
9
9
  ],
10
- "version": "0.0.10",
10
+ "version": "0.0.11-dev.2",
11
11
  "description": "React hooks Connect 4337",
12
12
  "repository": "https://github.com/cometh-hq/connect-sdk-4337.git",
13
13
  "keywords": [