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

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,21 @@ 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
+ if (!bundlerUrl || !paymasterUrl)
108
+ throw new Error("Bundler or paymaster url not found");
98
109
  try {
99
110
  const { client, address: newAddress } = await createSmartAccount({
100
111
  ...config,
112
+ chain,
113
+ bundlerUrl,
114
+ paymasterUrl,
101
115
  smartAccountAddress: params.address,
102
116
  comethSignerConfig: {
103
117
  ...config.comethSignerConfig,
@@ -106,6 +120,7 @@ var ConnectProvider = ({
106
120
  });
107
121
  setSmartAccountClient(client);
108
122
  setSmartAccountAddress(newAddress);
123
+ localStorage.setItem(CHAIN_STORAGE_KEY, JSON.stringify(chain));
109
124
  } catch (e) {
110
125
  console.log(e);
111
126
  }
@@ -115,6 +130,7 @@ var ConnectProvider = ({
115
130
  const disconnectSmartAccount = _react.useCallback.call(void 0, async () => {
116
131
  setSmartAccountClient(null);
117
132
  setSmartAccountAddress(void 0);
133
+ localStorage.removeItem(CHAIN_STORAGE_KEY);
118
134
  }, []);
119
135
  _react.useEffect.call(void 0, () => {
120
136
  if (config.smartAccountAddress) {
@@ -127,14 +143,16 @@ var ConnectProvider = ({
127
143
  smartAccountClient,
128
144
  smartAccountAddress,
129
145
  updateSmartAccountClient,
130
- disconnectSmartAccount
146
+ disconnectSmartAccount,
147
+ networksConfig: config.networksConfig
131
148
  }),
132
149
  [
133
150
  queryClient,
134
151
  smartAccountClient,
135
152
  smartAccountAddress,
136
153
  updateSmartAccountClient,
137
- disconnectSmartAccount
154
+ disconnectSmartAccount,
155
+ config.networksConfig
138
156
  ]
139
157
  );
140
158
  return /* @__PURE__ */ React2.default.createElement(ConnectContext.Provider, { value }, children);
@@ -150,8 +168,8 @@ var useAccount = () => {
150
168
  const { smartAccountClient, smartAccountAddress } = context;
151
169
  const { chain, chainId } = _react.useMemo.call(void 0,
152
170
  () => ({
153
- chain: _optionalChain([smartAccountClient, 'optionalAccess', _2 => _2.chain]),
154
- chainId: _optionalChain([smartAccountClient, 'optionalAccess', _3 => _3.chain, 'optionalAccess', _4 => _4.id])
171
+ chain: _optionalChain([smartAccountClient, 'optionalAccess', _14 => _14.chain]),
172
+ chainId: _optionalChain([smartAccountClient, 'optionalAccess', _15 => _15.chain, 'optionalAccess', _16 => _16.id])
155
173
  }),
156
174
  [smartAccountClient]
157
175
  );
@@ -367,7 +385,7 @@ var FocusManager = (_a = class extends Subscribable {
367
385
  if (typeof __privateGet(this, _focused) === "boolean") {
368
386
  return __privateGet(this, _focused);
369
387
  }
370
- return _optionalChain([globalThis, 'access', _5 => _5.document, 'optionalAccess', _6 => _6.visibilityState]) !== "hidden";
388
+ return _optionalChain([globalThis, 'access', _17 => _17.document, 'optionalAccess', _18 => _18.visibilityState]) !== "hidden";
371
389
  }
372
390
  }, _focused = new WeakMap(), _cleanup = new WeakMap(), _setup = new WeakMap(), _a);
373
391
  var focusManager = new FocusManager();
@@ -657,7 +675,7 @@ var QueryObserver = (_a3 = class extends Subscribable {
657
675
  enumerable: true,
658
676
  get: () => {
659
677
  this.trackProp(key);
660
- _optionalChain([onPropTracked, 'optionalCall', _7 => _7(key)]);
678
+ _optionalChain([onPropTracked, 'optionalCall', _19 => _19(key)]);
661
679
  return result[key];
662
680
  }
663
681
  });
@@ -718,13 +736,13 @@ var QueryObserver = (_a3 = class extends Subscribable {
718
736
  }
719
737
  let { error, errorUpdatedAt, status } = newState;
720
738
  if (options.select && newState.data !== void 0) {
721
- if (prevResult && newState.data === _optionalChain([prevResultState, 'optionalAccess', _8 => _8.data]) && options.select === __privateGet(this, _selectFn)) {
739
+ if (prevResult && newState.data === _optionalChain([prevResultState, 'optionalAccess', _20 => _20.data]) && options.select === __privateGet(this, _selectFn)) {
722
740
  data = __privateGet(this, _selectResult);
723
741
  } else {
724
742
  try {
725
743
  __privateSet(this, _selectFn, options.select);
726
744
  data = options.select(newState.data);
727
- data = replaceData(_optionalChain([prevResult, 'optionalAccess', _9 => _9.data]), data, options);
745
+ data = replaceData(_optionalChain([prevResult, 'optionalAccess', _21 => _21.data]), data, options);
728
746
  __privateSet(this, _selectResult, data);
729
747
  __privateSet(this, _selectError, null);
730
748
  } catch (selectError) {
@@ -736,11 +754,11 @@ var QueryObserver = (_a3 = class extends Subscribable {
736
754
  }
737
755
  if (options.placeholderData !== void 0 && data === void 0 && status === "pending") {
738
756
  let placeholderData;
739
- if (_optionalChain([prevResult, 'optionalAccess', _10 => _10.isPlaceholderData]) && options.placeholderData === _optionalChain([prevResultOptions, 'optionalAccess', _11 => _11.placeholderData])) {
757
+ if (_optionalChain([prevResult, 'optionalAccess', _22 => _22.isPlaceholderData]) && options.placeholderData === _optionalChain([prevResultOptions, 'optionalAccess', _23 => _23.placeholderData])) {
740
758
  placeholderData = prevResult.data;
741
759
  } else {
742
760
  placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(
743
- _optionalChain([__privateGet, 'call', _12 => _12(this, _lastQueryWithDefinedData), 'optionalAccess', _13 => _13.state, 'access', _14 => _14.data]),
761
+ _optionalChain([__privateGet, 'call', _24 => _24(this, _lastQueryWithDefinedData), 'optionalAccess', _25 => _25.state, 'access', _26 => _26.data]),
744
762
  __privateGet(this, _lastQueryWithDefinedData)
745
763
  ) : options.placeholderData;
746
764
  if (options.select && placeholderData !== void 0) {
@@ -755,7 +773,7 @@ var QueryObserver = (_a3 = class extends Subscribable {
755
773
  if (placeholderData !== void 0) {
756
774
  status = "success";
757
775
  data = replaceData(
758
- _optionalChain([prevResult, 'optionalAccess', _15 => _15.data]),
776
+ _optionalChain([prevResult, 'optionalAccess', _27 => _27.data]),
759
777
  placeholderData,
760
778
  options
761
779
  );
@@ -835,7 +853,7 @@ var QueryObserver = (_a3 = class extends Subscribable {
835
853
  return changed && includedProps.has(typedKey);
836
854
  });
837
855
  };
838
- if (_optionalChain([notifyOptions, 'optionalAccess', _16 => _16.listeners]) !== false && shouldNotifyListeners()) {
856
+ if (_optionalChain([notifyOptions, 'optionalAccess', _28 => _28.listeners]) !== false && shouldNotifyListeners()) {
839
857
  defaultNotifyOptions.listeners = true;
840
858
  }
841
859
  __privateMethod(this, _QueryObserver_instances, notify_fn).call(this, { ...defaultNotifyOptions, ...notifyOptions });
@@ -852,7 +870,7 @@ var QueryObserver = (_a3 = class extends Subscribable {
852
870
  this.options,
853
871
  fetchOptions
854
872
  );
855
- if (!_optionalChain([fetchOptions, 'optionalAccess', _17 => _17.throwOnError])) {
873
+ if (!_optionalChain([fetchOptions, 'optionalAccess', _29 => _29.throwOnError])) {
856
874
  promise = promise.catch(noop);
857
875
  }
858
876
  return promise;
@@ -907,7 +925,7 @@ var QueryObserver = (_a3 = class extends Subscribable {
907
925
  __privateSet(this, _currentQuery, query);
908
926
  __privateSet(this, _currentQueryInitialState, query.state);
909
927
  if (this.hasListeners()) {
910
- _optionalChain([prevQuery, 'optionalAccess', _18 => _18.removeObserver, 'call', _19 => _19(this)]);
928
+ _optionalChain([prevQuery, 'optionalAccess', _30 => _30.removeObserver, 'call', _31 => _31(this)]);
911
929
  query.addObserver(this);
912
930
  }
913
931
  }, notify_fn = function(notifyOptions) {
@@ -978,15 +996,15 @@ var MutationObserver = (_a4 = class extends Subscribable {
978
996
  observer: this
979
997
  });
980
998
  }
981
- if (_optionalChain([prevOptions, 'optionalAccess', _20 => _20.mutationKey]) && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) {
999
+ if (_optionalChain([prevOptions, 'optionalAccess', _32 => _32.mutationKey]) && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) {
982
1000
  this.reset();
983
- } else if (_optionalChain([__privateGet, 'call', _21 => _21(this, _currentMutation), 'optionalAccess', _22 => _22.state, 'access', _23 => _23.status]) === "pending") {
1001
+ } else if (_optionalChain([__privateGet, 'call', _33 => _33(this, _currentMutation), 'optionalAccess', _34 => _34.state, 'access', _35 => _35.status]) === "pending") {
984
1002
  __privateGet(this, _currentMutation).setOptions(this.options);
985
1003
  }
986
1004
  }
987
1005
  onUnsubscribe() {
988
1006
  if (!this.hasListeners()) {
989
- _optionalChain([__privateGet, 'call', _24 => _24(this, _currentMutation), 'optionalAccess', _25 => _25.removeObserver, 'call', _26 => _26(this)]);
1007
+ _optionalChain([__privateGet, 'call', _36 => _36(this, _currentMutation), 'optionalAccess', _37 => _37.removeObserver, 'call', _38 => _38(this)]);
990
1008
  }
991
1009
  }
992
1010
  onMutationUpdate(action) {
@@ -997,20 +1015,20 @@ var MutationObserver = (_a4 = class extends Subscribable {
997
1015
  return __privateGet(this, _currentResult2);
998
1016
  }
999
1017
  reset() {
1000
- _optionalChain([__privateGet, 'call', _27 => _27(this, _currentMutation), 'optionalAccess', _28 => _28.removeObserver, 'call', _29 => _29(this)]);
1018
+ _optionalChain([__privateGet, 'call', _39 => _39(this, _currentMutation), 'optionalAccess', _40 => _40.removeObserver, 'call', _41 => _41(this)]);
1001
1019
  __privateSet(this, _currentMutation, void 0);
1002
1020
  __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
1003
1021
  __privateMethod(this, _MutationObserver_instances, notify_fn2).call(this);
1004
1022
  }
1005
1023
  mutate(variables, options) {
1006
1024
  __privateSet(this, _mutateOptions, options);
1007
- _optionalChain([__privateGet, 'call', _30 => _30(this, _currentMutation), 'optionalAccess', _31 => _31.removeObserver, 'call', _32 => _32(this)]);
1025
+ _optionalChain([__privateGet, 'call', _42 => _42(this, _currentMutation), 'optionalAccess', _43 => _43.removeObserver, 'call', _44 => _44(this)]);
1008
1026
  __privateSet(this, _currentMutation, __privateGet(this, _client2).getMutationCache().build(__privateGet(this, _client2), this.options));
1009
1027
  __privateGet(this, _currentMutation).addObserver(this);
1010
1028
  return __privateGet(this, _currentMutation).execute(variables);
1011
1029
  }
1012
1030
  }, _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()));
1031
+ const state = _nullishCoalesce(_optionalChain([__privateGet, 'call', _45 => _45(this, _currentMutation), 'optionalAccess', _46 => _46.state]), () => ( getDefaultState()));
1014
1032
  __privateSet(this, _currentResult2, {
1015
1033
  ...state,
1016
1034
  isPending: state.status === "pending",
@@ -1025,12 +1043,12 @@ var MutationObserver = (_a4 = class extends Subscribable {
1025
1043
  if (__privateGet(this, _mutateOptions) && this.hasListeners()) {
1026
1044
  const variables = __privateGet(this, _currentResult2).variables;
1027
1045
  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(
1046
+ if (_optionalChain([action, 'optionalAccess', _47 => _47.type]) === "success") {
1047
+ _optionalChain([__privateGet, 'call', _48 => _48(this, _mutateOptions), 'access', _49 => _49.onSuccess, 'optionalCall', _50 => _50(action.data, variables, context)]);
1048
+ _optionalChain([__privateGet, 'call', _51 => _51(this, _mutateOptions), 'access', _52 => _52.onSettled, 'optionalCall', _53 => _53(action.data, null, variables, context)]);
1049
+ } else if (_optionalChain([action, 'optionalAccess', _54 => _54.type]) === "error") {
1050
+ _optionalChain([__privateGet, 'call', _55 => _55(this, _mutateOptions), 'access', _56 => _56.onError, 'optionalCall', _57 => _57(action.error, variables, context)]);
1051
+ _optionalChain([__privateGet, 'call', _58 => _58(this, _mutateOptions), 'access', _59 => _59.onSettled, 'optionalCall', _60 => _60(
1034
1052
  void 0,
1035
1053
  action.error,
1036
1054
  variables,
@@ -1130,7 +1148,7 @@ var ensureStaleTime = (defaultedOptions) => {
1130
1148
  }
1131
1149
  }
1132
1150
  };
1133
- var shouldSuspend = (defaultedOptions, result) => _optionalChain([defaultedOptions, 'optionalAccess', _49 => _49.suspense]) && result.isPending;
1151
+ var shouldSuspend = (defaultedOptions, result) => _optionalChain([defaultedOptions, 'optionalAccess', _61 => _61.suspense]) && result.isPending;
1134
1152
  var fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => {
1135
1153
  errorResetBoundary.clearReset();
1136
1154
  });
@@ -1149,7 +1167,7 @@ function useBaseQuery(options, Observer, queryClient) {
1149
1167
  const isRestoring = useIsRestoring();
1150
1168
  const errorResetBoundary = useQueryErrorResetBoundary();
1151
1169
  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(
1170
+ _optionalChain([client, 'access', _62 => _62.getDefaultOptions, 'call', _63 => _63(), 'access', _64 => _64.queries, 'optionalAccess', _65 => _65._experimental_beforeQuery, 'optionalCall', _66 => _66(
1153
1171
  defaultedOptions
1154
1172
  )]);
1155
1173
  defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic";
@@ -1190,7 +1208,7 @@ function useBaseQuery(options, Observer, queryClient) {
1190
1208
  throw result.error;
1191
1209
  }
1192
1210
  ;
1193
- _optionalChain([client, 'access', _55 => _55.getDefaultOptions, 'call', _56 => _56(), 'access', _57 => _57.queries, 'optionalAccess', _58 => _58._experimental_afterQuery, 'optionalCall', _59 => _59(
1211
+ _optionalChain([client, 'access', _67 => _67.getDefaultOptions, 'call', _68 => _68(), 'access', _69 => _69.queries, 'optionalAccess', _70 => _70._experimental_afterQuery, 'optionalCall', _71 => _71(
1194
1212
  defaultedOptions,
1195
1213
  result
1196
1214
  )]);
@@ -1394,7 +1412,7 @@ var useConnect = () => {
1394
1412
  setIsPending(true);
1395
1413
  setError(null);
1396
1414
  updateSmartAccountClient(params).then(() => {
1397
- _optionalChain([queryClient, 'optionalAccess', _60 => _60.invalidateQueries, 'call', _61 => _61({
1415
+ _optionalChain([queryClient, 'optionalAccess', _72 => _72.invalidateQueries, 'call', _73 => _73({
1398
1416
  queryKey: ["connect"]
1399
1417
  })]);
1400
1418
  }).catch((e) => {
@@ -1412,7 +1430,7 @@ var useConnect = () => {
1412
1430
  setError(null);
1413
1431
  try {
1414
1432
  await updateSmartAccountClient(params);
1415
- _optionalChain([queryClient, 'optionalAccess', _62 => _62.invalidateQueries, 'call', _63 => _63({ queryKey: ["connect"] })]);
1433
+ _optionalChain([queryClient, 'optionalAccess', _74 => _74.invalidateQueries, 'call', _75 => _75({ queryKey: ["connect"] })]);
1416
1434
  } catch (e) {
1417
1435
  const err = e instanceof Error ? e : new Error("An error occurred");
1418
1436
  setError(err);
@@ -1445,7 +1463,7 @@ var useDisconnect = () => {
1445
1463
  setIsPending(true);
1446
1464
  setError(null);
1447
1465
  disconnectSmartAccount().then(() => {
1448
- _optionalChain([queryClient, 'optionalAccess', _64 => _64.invalidateQueries, 'call', _65 => _65({
1466
+ _optionalChain([queryClient, 'optionalAccess', _76 => _76.invalidateQueries, 'call', _77 => _77({
1449
1467
  queryKey: ["connect"]
1450
1468
  })]);
1451
1469
  }).catch((e) => {
@@ -1460,7 +1478,7 @@ var useDisconnect = () => {
1460
1478
  setError(null);
1461
1479
  try {
1462
1480
  await disconnectSmartAccount();
1463
- _optionalChain([queryClient, 'optionalAccess', _66 => _66.invalidateQueries, 'call', _67 => _67({ queryKey: ["connect"] })]);
1481
+ _optionalChain([queryClient, 'optionalAccess', _78 => _78.invalidateQueries, 'call', _79 => _79({ queryKey: ["connect"] })]);
1464
1482
  } catch (e) {
1465
1483
  const err = e instanceof Error ? e : new Error("An error occurred during disconnection");
1466
1484
  setError(err);
@@ -1897,7 +1915,7 @@ var useCreateNewSigner = (apiKey, baseUrl) => {
1897
1915
  setIsPending(true);
1898
1916
  setError(null);
1899
1917
  _connectsdk4337.createNewSigner.call(void 0, { apiKey, baseUrl, params }).then((signer) => {
1900
- _optionalChain([queryClient, 'optionalAccess', _68 => _68.invalidateQueries, 'call', _69 => _69({ queryKey: ["signer"] })]);
1918
+ _optionalChain([queryClient, 'optionalAccess', _80 => _80.invalidateQueries, 'call', _81 => _81({ queryKey: ["signer"] })]);
1901
1919
  return signer;
1902
1920
  }).catch((e) => {
1903
1921
  const err = e instanceof Error ? e : new Error("An error occurred");
@@ -1918,7 +1936,7 @@ var useCreateNewSigner = (apiKey, baseUrl) => {
1918
1936
  baseUrl,
1919
1937
  params
1920
1938
  });
1921
- _optionalChain([queryClient, 'optionalAccess', _70 => _70.invalidateQueries, 'call', _71 => _71({ queryKey: ["signer"] })]);
1939
+ _optionalChain([queryClient, 'optionalAccess', _82 => _82.invalidateQueries, 'call', _83 => _83({ queryKey: ["signer"] })]);
1922
1940
  return signer;
1923
1941
  } catch (e) {
1924
1942
  const err = e instanceof Error ? e : new Error("An error occurred");
@@ -2162,6 +2180,90 @@ function useCancelRecoveryRequest() {
2162
2180
  };
2163
2181
  }
2164
2182
 
2183
+ // src/hooks/useSwitchChain.ts
2184
+
2185
+
2186
+ var useSwitchChain = () => {
2187
+ const { address } = _wagmi.useAccount.call(void 0, );
2188
+ const context = _react.useContext.call(void 0, ConnectContext);
2189
+ if (context === void 0) {
2190
+ throw new Error("useSwitchChain must be used within a ConnectProvider");
2191
+ }
2192
+ const {
2193
+ queryClient,
2194
+ smartAccountClient,
2195
+ updateSmartAccountClient,
2196
+ networksConfig
2197
+ } = context;
2198
+ const [isPending, setIsPending] = _react.useState.call(void 0, false);
2199
+ const [error, setError] = _react.useState.call(void 0, null);
2200
+ const switchChainInternal = _react.useCallback.call(void 0,
2201
+ async (params) => {
2202
+ const { chain } = params;
2203
+ if (!networksConfig) {
2204
+ throw new Error("No current configuration found");
2205
+ }
2206
+ try {
2207
+ await updateSmartAccountClient({
2208
+ address: _optionalChain([smartAccountClient, 'optionalAccess', _84 => _84.account, 'access', _85 => _85.address]),
2209
+ chain
2210
+ });
2211
+ _optionalChain([queryClient, 'optionalAccess', _86 => _86.invalidateQueries, 'call', _87 => _87({
2212
+ queryKey: ["switchChain"]
2213
+ })]);
2214
+ } catch (e) {
2215
+ throw e instanceof Error ? e : new Error("An error occurred while switching chain");
2216
+ }
2217
+ },
2218
+ [
2219
+ smartAccountClient,
2220
+ updateSmartAccountClient,
2221
+ queryClient,
2222
+ networksConfig
2223
+ ]
2224
+ );
2225
+ const switchChain = _react.useCallback.call(void 0,
2226
+ (params) => {
2227
+ if (!address) throw new Error("No connected wallet");
2228
+ setIsPending(true);
2229
+ setError(null);
2230
+ switchChainInternal(params).catch((e) => {
2231
+ const err = e instanceof Error ? e : new Error(
2232
+ "An error occurred while switching chain"
2233
+ );
2234
+ setError(err);
2235
+ }).finally(() => {
2236
+ setIsPending(false);
2237
+ });
2238
+ },
2239
+ [switchChainInternal]
2240
+ );
2241
+ const switchChainAsync = _react.useCallback.call(void 0,
2242
+ async (params) => {
2243
+ if (!address) throw new Error("No connected wallet");
2244
+ setIsPending(true);
2245
+ setError(null);
2246
+ try {
2247
+ await switchChainInternal(params);
2248
+ } catch (e) {
2249
+ const err = e instanceof Error ? e : new Error("An error occurred while switching chain");
2250
+ setError(err);
2251
+ throw err;
2252
+ } finally {
2253
+ setIsPending(false);
2254
+ }
2255
+ },
2256
+ [switchChainInternal]
2257
+ );
2258
+ return {
2259
+ switchChain,
2260
+ switchChainAsync,
2261
+ isPending,
2262
+ error
2263
+ };
2264
+ };
2265
+
2266
+
2165
2267
 
2166
2268
 
2167
2269
 
@@ -2193,4 +2295,4 @@ function useCancelRecoveryRequest() {
2193
2295
 
2194
2296
 
2195
2297
 
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;
2298
+ 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,18 @@ 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;
47
48
  };
49
+ type OmitConfig<T> = Omit<T, "chain" | "paymasterUrl" | "bundlerUrl"> & {
50
+ networksConfig: NetworkParams[];
51
+ };
52
+ type ConnectConfig = OmitConfig<createSafeSmartAccountParameters<ENTRYPOINT_ADDRESS_V07_TYPE> & {
53
+ bundlerUrl: string;
54
+ paymasterUrl?: string;
55
+ }>;
48
56
  type ContextComethSmartAccountClient = ComethSmartAccountClient<SafeSmartAccount<ENTRYPOINT_ADDRESS_V07_TYPE, Transport, Chain>, Transport, Chain, ENTRYPOINT_ADDRESS_V07_TYPE>;
49
57
  declare const ConnectProvider: <TConfig extends ConnectConfig, TQueryClient extends b | undefined>({ children, config, queryClient, }: {
50
58
  children: ReactNode;
@@ -931,4 +939,15 @@ type UseCancelRecoveryRequestReturn = QueryResultType & {
931
939
  */
932
940
  declare function useCancelRecoveryRequest(): UseCancelRecoveryRequestReturn;
933
941
 
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 };
942
+ declare const useSwitchChain: () => {
943
+ switchChain: (params: {
944
+ chain: Chain;
945
+ }) => void;
946
+ switchChainAsync: (params: {
947
+ chain: Chain;
948
+ }) => Promise<void>;
949
+ isPending: boolean;
950
+ error: Error | null;
951
+ };
952
+
953
+ 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,18 @@ 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;
47
48
  };
49
+ type OmitConfig<T> = Omit<T, "chain" | "paymasterUrl" | "bundlerUrl"> & {
50
+ networksConfig: NetworkParams[];
51
+ };
52
+ type ConnectConfig = OmitConfig<createSafeSmartAccountParameters<ENTRYPOINT_ADDRESS_V07_TYPE> & {
53
+ bundlerUrl: string;
54
+ paymasterUrl?: string;
55
+ }>;
48
56
  type ContextComethSmartAccountClient = ComethSmartAccountClient<SafeSmartAccount<ENTRYPOINT_ADDRESS_V07_TYPE, Transport, Chain>, Transport, Chain, ENTRYPOINT_ADDRESS_V07_TYPE>;
49
57
  declare const ConnectProvider: <TConfig extends ConnectConfig, TQueryClient extends b | undefined>({ children, config, queryClient, }: {
50
58
  children: ReactNode;
@@ -931,4 +939,15 @@ type UseCancelRecoveryRequestReturn = QueryResultType & {
931
939
  */
932
940
  declare function useCancelRecoveryRequest(): UseCancelRecoveryRequestReturn;
933
941
 
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 };
942
+ declare const useSwitchChain: () => {
943
+ switchChain: (params: {
944
+ chain: Chain;
945
+ }) => void;
946
+ switchChainAsync: (params: {
947
+ chain: Chain;
948
+ }) => Promise<void>;
949
+ isPending: boolean;
950
+ error: Error | null;
951
+ };
952
+
953
+ 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,21 @@ 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
+ if (!bundlerUrl || !paymasterUrl)
108
+ throw new Error("Bundler or paymaster url not found");
98
109
  try {
99
110
  const { client, address: newAddress } = await createSmartAccount({
100
111
  ...config,
112
+ chain,
113
+ bundlerUrl,
114
+ paymasterUrl,
101
115
  smartAccountAddress: params.address,
102
116
  comethSignerConfig: {
103
117
  ...config.comethSignerConfig,
@@ -106,6 +120,7 @@ var ConnectProvider = ({
106
120
  });
107
121
  setSmartAccountClient(client);
108
122
  setSmartAccountAddress(newAddress);
123
+ localStorage.setItem(CHAIN_STORAGE_KEY, JSON.stringify(chain));
109
124
  } catch (e) {
110
125
  console.log(e);
111
126
  }
@@ -115,6 +130,7 @@ var ConnectProvider = ({
115
130
  const disconnectSmartAccount = useCallback(async () => {
116
131
  setSmartAccountClient(null);
117
132
  setSmartAccountAddress(void 0);
133
+ localStorage.removeItem(CHAIN_STORAGE_KEY);
118
134
  }, []);
119
135
  useEffect(() => {
120
136
  if (config.smartAccountAddress) {
@@ -127,14 +143,16 @@ var ConnectProvider = ({
127
143
  smartAccountClient,
128
144
  smartAccountAddress,
129
145
  updateSmartAccountClient,
130
- disconnectSmartAccount
146
+ disconnectSmartAccount,
147
+ networksConfig: config.networksConfig
131
148
  }),
132
149
  [
133
150
  queryClient,
134
151
  smartAccountClient,
135
152
  smartAccountAddress,
136
153
  updateSmartAccountClient,
137
- disconnectSmartAccount
154
+ disconnectSmartAccount,
155
+ config.networksConfig
138
156
  ]
139
157
  );
140
158
  return /* @__PURE__ */ React.createElement(ConnectContext.Provider, { value }, children);
@@ -2161,6 +2179,89 @@ function useCancelRecoveryRequest() {
2161
2179
  data: result.data
2162
2180
  };
2163
2181
  }
2182
+
2183
+ // src/hooks/useSwitchChain.ts
2184
+ import { useCallback as useCallback8, useContext as useContext8, useState as useState9 } from "react";
2185
+ import { useAccount as useAccount2 } from "wagmi";
2186
+ var useSwitchChain = () => {
2187
+ const { address } = useAccount2();
2188
+ const context = useContext8(ConnectContext);
2189
+ if (context === void 0) {
2190
+ throw new Error("useSwitchChain must be used within a ConnectProvider");
2191
+ }
2192
+ const {
2193
+ queryClient,
2194
+ smartAccountClient,
2195
+ updateSmartAccountClient,
2196
+ networksConfig
2197
+ } = context;
2198
+ const [isPending, setIsPending] = useState9(false);
2199
+ const [error, setError] = useState9(null);
2200
+ const switchChainInternal = useCallback8(
2201
+ async (params) => {
2202
+ const { chain } = params;
2203
+ if (!networksConfig) {
2204
+ throw new Error("No current configuration found");
2205
+ }
2206
+ try {
2207
+ await updateSmartAccountClient({
2208
+ address: smartAccountClient?.account.address,
2209
+ chain
2210
+ });
2211
+ queryClient?.invalidateQueries({
2212
+ queryKey: ["switchChain"]
2213
+ });
2214
+ } catch (e) {
2215
+ throw e instanceof Error ? e : new Error("An error occurred while switching chain");
2216
+ }
2217
+ },
2218
+ [
2219
+ smartAccountClient,
2220
+ updateSmartAccountClient,
2221
+ queryClient,
2222
+ networksConfig
2223
+ ]
2224
+ );
2225
+ const switchChain = useCallback8(
2226
+ (params) => {
2227
+ if (!address) throw new Error("No connected wallet");
2228
+ setIsPending(true);
2229
+ setError(null);
2230
+ switchChainInternal(params).catch((e) => {
2231
+ const err = e instanceof Error ? e : new Error(
2232
+ "An error occurred while switching chain"
2233
+ );
2234
+ setError(err);
2235
+ }).finally(() => {
2236
+ setIsPending(false);
2237
+ });
2238
+ },
2239
+ [switchChainInternal]
2240
+ );
2241
+ const switchChainAsync = useCallback8(
2242
+ async (params) => {
2243
+ if (!address) throw new Error("No connected wallet");
2244
+ setIsPending(true);
2245
+ setError(null);
2246
+ try {
2247
+ await switchChainInternal(params);
2248
+ } catch (e) {
2249
+ const err = e instanceof Error ? e : new Error("An error occurred while switching chain");
2250
+ setError(err);
2251
+ throw err;
2252
+ } finally {
2253
+ setIsPending(false);
2254
+ }
2255
+ },
2256
+ [switchChainInternal]
2257
+ );
2258
+ return {
2259
+ switchChain,
2260
+ switchChainAsync,
2261
+ isPending,
2262
+ error
2263
+ };
2264
+ };
2164
2265
  export {
2165
2266
  ConnectProvider,
2166
2267
  useAccount,
@@ -2189,6 +2290,7 @@ export {
2189
2290
  useSerializeUrlWithSignerPayload,
2190
2291
  useSetUpRecovery,
2191
2292
  useSignMessage,
2293
+ useSwitchChain,
2192
2294
  useValidateAddDevice,
2193
2295
  useVerifyMessage,
2194
2296
  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.1",
11
11
  "description": "React hooks Connect 4337",
12
12
  "repository": "https://github.com/cometh-hq/connect-sdk-4337.git",
13
13
  "keywords": [