@injectivelabs/wallet-evm 1.19.22 → 1.19.24

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.
@@ -222,6 +222,38 @@ const getEvmProvider = async (wallet) => {
222
222
  throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`Please install ${(0, __injectivelabs_utils.capitalize)(wallet)} Extension`));
223
223
  }
224
224
  };
225
+ const switchEthereumChainWithTimeout = async (provider, chainIdHex, timeoutMs = 3e4) => {
226
+ let timeoutId;
227
+ let handleChainChanged;
228
+ const cleanup = () => {
229
+ if (handleChainChanged) {
230
+ provider.removeListener("chainChanged", handleChainChanged);
231
+ handleChainChanged = void 0;
232
+ }
233
+ if (timeoutId !== void 0) {
234
+ clearTimeout(timeoutId);
235
+ timeoutId = void 0;
236
+ }
237
+ };
238
+ const switchRequest = provider.request({
239
+ method: "wallet_switchEthereumChain",
240
+ params: [{ chainId: chainIdHex }]
241
+ }).finally(cleanup);
242
+ const chainChangedWaiter = new Promise((resolve, reject) => {
243
+ handleChainChanged = (newChainId) => {
244
+ if (newChainId.toLowerCase() === chainIdHex.toLowerCase()) {
245
+ cleanup();
246
+ resolve();
247
+ }
248
+ };
249
+ timeoutId = setTimeout(() => {
250
+ cleanup();
251
+ reject(/* @__PURE__ */ new Error("Chain switch timed out"));
252
+ }, timeoutMs);
253
+ provider.on("chainChanged", handleChainChanged);
254
+ });
255
+ await Promise.race([switchRequest, chainChangedWaiter]);
256
+ };
225
257
  const updateEvmNetwork = async (wallet, chainId) => {
226
258
  if (!(0, __injectivelabs_wallet_base.isEvmBrowserWallet)(wallet)) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`Evm Wallet for ${(0, __injectivelabs_utils.capitalize)(wallet)} is not supported.`));
227
259
  const provider = await getEvmProvider(wallet);
@@ -229,50 +261,48 @@ const updateEvmNetwork = async (wallet, chainId) => {
229
261
  const chainIdToHex = `0x${chainId.toString(16)}`;
230
262
  const TIMEOUT_MS = 3e4;
231
263
  try {
232
- return await Promise.race([provider.request({
233
- method: "wallet_switchEthereumChain",
234
- params: [{ chainId: chainIdToHex }]
235
- }), new Promise((resolve, reject) => {
236
- const handleChainChanged = (newChainId) => {
237
- if (newChainId.toLowerCase() === chainIdToHex.toLowerCase()) {
238
- cleanup();
239
- resolve();
240
- }
241
- };
242
- const timeoutId = setTimeout(() => {
243
- cleanup();
244
- reject(/* @__PURE__ */ new Error("Chain switch timed out"));
245
- }, TIMEOUT_MS);
246
- const cleanup = () => {
247
- provider.removeListener("chainChanged", handleChainChanged);
248
- clearTimeout(timeoutId);
249
- };
250
- provider.on("chainChanged", handleChainChanged);
251
- })]);
264
+ await switchEthereumChainWithTimeout(provider, chainIdToHex, TIMEOUT_MS);
252
265
  } catch (switchError) {
253
- var _switchError$code, _switchError$data;
254
- if (((_switchError$code = switchError === null || switchError === void 0 ? void 0 : switchError.code) !== null && _switchError$code !== void 0 ? _switchError$code : switchError === null || switchError === void 0 || (_switchError$data = switchError.data) === null || _switchError$data === void 0 || (_switchError$data = _switchError$data.originalError) === null || _switchError$data === void 0 ? void 0 : _switchError$data.code) === 4902) {
255
- const chainConfig = (0, __injectivelabs_wallet_base.getEvmChainConfig)(chainId);
256
- try {
257
- var _chainConfig$rpcUrls, _chainConfig$blockExp;
258
- const rpcUrl = (_chainConfig$rpcUrls = chainConfig.rpcUrls) === null || _chainConfig$rpcUrls === void 0 || (_chainConfig$rpcUrls = _chainConfig$rpcUrls.default) === null || _chainConfig$rpcUrls === void 0 || (_chainConfig$rpcUrls = _chainConfig$rpcUrls.http) === null || _chainConfig$rpcUrls === void 0 ? void 0 : _chainConfig$rpcUrls[0];
259
- const explorerUrl = ((_chainConfig$blockExp = chainConfig.blockExplorers) === null || _chainConfig$blockExp === void 0 || (_chainConfig$blockExp = _chainConfig$blockExp.default) === null || _chainConfig$blockExp === void 0 ? void 0 : _chainConfig$blockExp.url) || void 0;
260
- await provider.request({
261
- method: "wallet_addEthereumChain",
262
- params: [{
263
- chainId: chainIdToHex,
264
- chainName: chainConfig.name,
265
- nativeCurrency: chainConfig.nativeCurrency,
266
- rpcUrls: rpcUrl ? [rpcUrl] : [],
267
- blockExplorerUrls: explorerUrl ? [explorerUrl] : void 0
268
- }]
269
- });
270
- return;
271
- } catch (_unused2) {
272
- throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`Failed to add ${chainConfig.name} network to ${(0, __injectivelabs_utils.capitalize)(wallet)}`));
273
- }
266
+ var _switchError$code, _switchError$data, _chainConfig$rpcUrls, _chainConfig$blockExp;
267
+ const rawCode = (_switchError$code = switchError === null || switchError === void 0 ? void 0 : switchError.code) !== null && _switchError$code !== void 0 ? _switchError$code : switchError === null || switchError === void 0 || (_switchError$data = switchError.data) === null || _switchError$data === void 0 || (_switchError$data = _switchError$data.originalError) === null || _switchError$data === void 0 ? void 0 : _switchError$data.code;
268
+ const parsed = rawCode != null ? Number(rawCode) : NaN;
269
+ const errorCode = !isNaN(parsed) ? parsed : void 0;
270
+ if (errorCode === 4001) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`${(0, __injectivelabs_utils.capitalize)(wallet)} chain switch was rejected`));
271
+ if (switchError.message === "Chain switch timed out") throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Chain switch timed out"));
272
+ if (errorCode !== 4902) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`Please update your ${(0, __injectivelabs_utils.capitalize)(wallet)} network`));
273
+ const chainConfig = (0, __injectivelabs_wallet_base.getEvmChainConfig)(chainId);
274
+ const rpcUrl = (_chainConfig$rpcUrls = chainConfig.rpcUrls) === null || _chainConfig$rpcUrls === void 0 || (_chainConfig$rpcUrls = _chainConfig$rpcUrls.default) === null || _chainConfig$rpcUrls === void 0 || (_chainConfig$rpcUrls = _chainConfig$rpcUrls.http) === null || _chainConfig$rpcUrls === void 0 ? void 0 : _chainConfig$rpcUrls[0];
275
+ const explorerUrl = ((_chainConfig$blockExp = chainConfig.blockExplorers) === null || _chainConfig$blockExp === void 0 || (_chainConfig$blockExp = _chainConfig$blockExp.default) === null || _chainConfig$blockExp === void 0 ? void 0 : _chainConfig$blockExp.url) || void 0;
276
+ try {
277
+ await provider.request({
278
+ method: "wallet_addEthereumChain",
279
+ params: [{
280
+ chainId: chainIdToHex,
281
+ chainName: chainConfig.name,
282
+ nativeCurrency: chainConfig.nativeCurrency,
283
+ rpcUrls: rpcUrl ? [rpcUrl] : [],
284
+ blockExplorerUrls: explorerUrl ? [explorerUrl] : []
285
+ }]
286
+ });
287
+ } catch (_unused2) {
288
+ throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`Failed to add ${chainConfig.name} network to ${(0, __injectivelabs_utils.capitalize)(wallet)}`));
289
+ }
290
+ let currentChainId;
291
+ try {
292
+ currentChainId = await provider.request({ method: "eth_chainId" });
293
+ } catch (_unused3) {
294
+ throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`Failed to get current chain ID from ${(0, __injectivelabs_utils.capitalize)(wallet)} wallet`));
295
+ }
296
+ if (typeof currentChainId !== "string" || !currentChainId.startsWith("0x")) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`Invalid chain ID response from ${(0, __injectivelabs_utils.capitalize)(wallet)}: ${String(currentChainId)}`));
297
+ if (currentChainId.toLowerCase() !== chainIdToHex.toLowerCase()) try {
298
+ await switchEthereumChainWithTimeout(provider, chainIdToHex, TIMEOUT_MS);
299
+ } catch (postAddError) {
300
+ var _postAddError$code, _postAddError$data;
301
+ const rawCode$1 = (_postAddError$code = postAddError === null || postAddError === void 0 ? void 0 : postAddError.code) !== null && _postAddError$code !== void 0 ? _postAddError$code : postAddError === null || postAddError === void 0 || (_postAddError$data = postAddError.data) === null || _postAddError$data === void 0 || (_postAddError$data = _postAddError$data.originalError) === null || _postAddError$data === void 0 ? void 0 : _postAddError$data.code;
302
+ const parsed$1 = rawCode$1 != null ? Number(rawCode$1) : NaN;
303
+ if ((!isNaN(parsed$1) ? parsed$1 : void 0) === 4001) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`${(0, __injectivelabs_utils.capitalize)(wallet)} chain switch after add was rejected`));
304
+ throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`Failed to switch to ${chainConfig.name} network after adding it: ${postAddError.message}`));
274
305
  }
275
- throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`Please update your ${(0, __injectivelabs_utils.capitalize)(wallet)} network`));
276
306
  }
277
307
  };
278
308
 
@@ -548,63 +578,71 @@ var EvmWallet = class extends __injectivelabs_wallet_base.BaseConcreteStrategy {
548
578
  };
549
579
  const TIMEOUT_MS = 3e4;
550
580
  try {
551
- let timeoutId;
552
- let handleChainChanged;
553
- const cleanup = () => {
554
- if (handleChainChanged) {
555
- ethereum.removeListener("chainChanged", handleChainChanged);
556
- handleChainChanged = void 0;
557
- }
558
- if (timeoutId !== void 0) {
559
- clearTimeout(timeoutId);
560
- timeoutId = void 0;
561
- }
562
- };
563
- const switchRequest = ethereum.request({
564
- method: "wallet_switchEthereumChain",
565
- params: [{ chainId: chainIdHex }]
566
- }).finally(cleanup);
567
- const chainChangedWaiter = new Promise((resolve, reject) => {
568
- handleChainChanged = (newChainId) => {
569
- if (newChainId.toLowerCase() === chainIdHex.toLowerCase()) {
570
- cleanup();
571
- resolve();
572
- }
573
- };
574
- timeoutId = setTimeout(() => {
575
- cleanup();
576
- reject(/* @__PURE__ */ new Error("Chain switch timed out"));
577
- }, TIMEOUT_MS);
578
- ethereum.on("chainChanged", handleChainChanged);
579
- });
580
- await Promise.race([switchRequest, chainChangedWaiter]);
581
+ await switchEthereumChainWithTimeout(ethereum, chainIdHex, TIMEOUT_MS);
581
582
  } catch (error) {
582
583
  var _code, _data;
583
- if (((_code = error.code) !== null && _code !== void 0 ? _code : error === null || error === void 0 || (_data = error.data) === null || _data === void 0 || (_data = _data.originalError) === null || _data === void 0 ? void 0 : _data.code) === 4902) {
584
- await ethereum.request({
585
- method: "wallet_addEthereumChain",
586
- params: [params]
587
- });
588
- try {
589
- await ethereum.request({
590
- method: "wallet_switchEthereumChain",
591
- params: [{ chainId: chainIdHex }]
592
- });
593
- } catch (switchError) {
594
- console.warn(`Failed to switch to chain ${chainIdHex} after adding it:`, switchError);
595
- }
596
- return;
597
- }
584
+ const rawCode = (_code = error.code) !== null && _code !== void 0 ? _code : error === null || error === void 0 || (_data = error.data) === null || _data === void 0 || (_data = _data.originalError) === null || _data === void 0 ? void 0 : _data.code;
585
+ const parsed = rawCode != null ? Number(rawCode) : NaN;
586
+ const errorCode = !isNaN(parsed) ? parsed : void 0;
587
+ if (errorCode === 4001) throw this.EvmWalletException(/* @__PURE__ */ new Error(`${(0, __injectivelabs_utils.capitalize)(this.wallet || "wallet")} chain switch was rejected`), {
588
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
589
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
590
+ contextModule: __injectivelabs_wallet_base.WalletAction.GetChainId
591
+ });
598
592
  if (error.message === "Chain switch timed out") throw this.EvmWalletException(/* @__PURE__ */ new Error("Chain switch timed out"), {
599
593
  code: __injectivelabs_exceptions.UnspecifiedErrorCode,
600
594
  type: __injectivelabs_exceptions.ErrorType.WalletError,
601
595
  contextModule: __injectivelabs_wallet_base.WalletAction.GetChainId
602
596
  });
603
- throw this.EvmWalletException(/* @__PURE__ */ new Error(`Something went wrong while adding ${(0, __injectivelabs_utils.capitalize)(this.wallet || "wallet")} network`), {
597
+ if (errorCode !== 4902) throw this.EvmWalletException(/* @__PURE__ */ new Error(`Something went wrong while switching ${(0, __injectivelabs_utils.capitalize)(this.wallet || "wallet")} network`), {
604
598
  code: __injectivelabs_exceptions.UnspecifiedErrorCode,
605
599
  type: __injectivelabs_exceptions.ErrorType.WalletError,
606
600
  contextModule: __injectivelabs_wallet_base.WalletAction.GetChainId
607
601
  });
602
+ try {
603
+ await ethereum.request({
604
+ method: "wallet_addEthereumChain",
605
+ params: [params]
606
+ });
607
+ } catch (_unused2) {
608
+ throw this.EvmWalletException(/* @__PURE__ */ new Error(`Something went wrong while adding ${(0, __injectivelabs_utils.capitalize)(this.wallet || "wallet")} network`), {
609
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
610
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
611
+ contextModule: __injectivelabs_wallet_base.WalletAction.GetChainId
612
+ });
613
+ }
614
+ let currentChainId;
615
+ try {
616
+ currentChainId = await ethereum.request({ method: "eth_chainId" });
617
+ } catch (_unused3) {
618
+ throw this.EvmWalletException(/* @__PURE__ */ new Error(`Failed to get current chain ID from ${(0, __injectivelabs_utils.capitalize)(this.wallet || "wallet")}`), {
619
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
620
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
621
+ contextModule: __injectivelabs_wallet_base.WalletAction.GetChainId
622
+ });
623
+ }
624
+ if (typeof currentChainId !== "string" || !currentChainId.startsWith("0x")) throw this.EvmWalletException(/* @__PURE__ */ new Error(`Invalid chain ID response from ${(0, __injectivelabs_utils.capitalize)(this.wallet || "wallet")}: ${String(currentChainId)}`), {
625
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
626
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
627
+ contextModule: __injectivelabs_wallet_base.WalletAction.GetChainId
628
+ });
629
+ if (currentChainId.toLowerCase() !== chainIdHex.toLowerCase()) try {
630
+ await switchEthereumChainWithTimeout(ethereum, chainIdHex, TIMEOUT_MS);
631
+ } catch (postAddError) {
632
+ var _postAddError$code, _postAddError$data;
633
+ const postAddRawCode = (_postAddError$code = postAddError === null || postAddError === void 0 ? void 0 : postAddError.code) !== null && _postAddError$code !== void 0 ? _postAddError$code : postAddError === null || postAddError === void 0 || (_postAddError$data = postAddError.data) === null || _postAddError$data === void 0 || (_postAddError$data = _postAddError$data.originalError) === null || _postAddError$data === void 0 ? void 0 : _postAddError$data.code;
634
+ const postAddParsed = postAddRawCode != null ? Number(postAddRawCode) : NaN;
635
+ if ((!isNaN(postAddParsed) ? postAddParsed : void 0) === 4001) throw this.EvmWalletException(/* @__PURE__ */ new Error(`${(0, __injectivelabs_utils.capitalize)(this.wallet || "wallet")} chain switch after add was rejected`), {
636
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
637
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
638
+ contextModule: __injectivelabs_wallet_base.WalletAction.GetChainId
639
+ });
640
+ throw this.EvmWalletException(/* @__PURE__ */ new Error(`Failed to switch to ${chain.name} network after adding it: ${postAddError.message}`), {
641
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
642
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
643
+ contextModule: __injectivelabs_wallet_base.WalletAction.GetChainId
644
+ });
645
+ }
608
646
  }
609
647
  }
610
648
  async getEthereum() {
@@ -631,4 +669,5 @@ exports.getPhantomProvider = getPhantomProvider;
631
669
  exports.getRabbyProvider = getRabbyProvider;
632
670
  exports.getRainbowProvider = getRainbowProvider;
633
671
  exports.getTrustWalletProvider = getTrustWalletProvider;
672
+ exports.switchEthereumChainWithTimeout = switchEthereumChainWithTimeout;
634
673
  exports.updateEvmNetwork = updateEvmNetwork;
@@ -6,7 +6,8 @@ import { AminoSignResponse, DirectSignResponse, TxRaw } from "@injectivelabs/sdk
6
6
 
7
7
  //#region src/utils/index.d.ts
8
8
  declare const getEvmProvider: (wallet: Wallet) => Promise<BrowserEip1993Provider>;
9
- declare const updateEvmNetwork: (wallet: Wallet, chainId: EvmChainId) => Promise<unknown>;
9
+ declare const switchEthereumChainWithTimeout: (provider: BrowserEip1993Provider, chainIdHex: string, timeoutMs?: number) => Promise<void>;
10
+ declare const updateEvmNetwork: (wallet: Wallet, chainId: EvmChainId) => Promise<void>;
10
11
  //#endregion
11
12
  //#region src/strategy/utils/rabby.d.ts
12
13
  declare function getRabbyProvider({
@@ -109,4 +110,4 @@ declare class EvmWallet extends BaseConcreteStrategy implements ConcreteWalletSt
109
110
  private getEthereum;
110
111
  }
111
112
  //#endregion
112
- export { EvmWallet as EvmWalletStrategy, getBitGetProvider, getEvmProvider, getKeplrEvmProvider, getMetamaskProvider, getOkxWalletProvider, getPhantomProvider, getRabbyProvider, getRainbowProvider, getTrustWalletProvider, updateEvmNetwork };
113
+ export { EvmWallet as EvmWalletStrategy, getBitGetProvider, getEvmProvider, getKeplrEvmProvider, getMetamaskProvider, getOkxWalletProvider, getPhantomProvider, getRabbyProvider, getRainbowProvider, getTrustWalletProvider, switchEthereumChainWithTimeout, updateEvmNetwork };
@@ -6,7 +6,8 @@ import { AminoSignResponse, DirectSignResponse, TxRaw } from "@injectivelabs/sdk
6
6
 
7
7
  //#region src/utils/index.d.ts
8
8
  declare const getEvmProvider: (wallet: Wallet) => Promise<BrowserEip1993Provider>;
9
- declare const updateEvmNetwork: (wallet: Wallet, chainId: EvmChainId) => Promise<unknown>;
9
+ declare const switchEthereumChainWithTimeout: (provider: BrowserEip1993Provider, chainIdHex: string, timeoutMs?: number) => Promise<void>;
10
+ declare const updateEvmNetwork: (wallet: Wallet, chainId: EvmChainId) => Promise<void>;
10
11
  //#endregion
11
12
  //#region src/strategy/utils/rabby.d.ts
12
13
  declare function getRabbyProvider({
@@ -109,4 +110,4 @@ declare class EvmWallet extends BaseConcreteStrategy implements ConcreteWalletSt
109
110
  private getEthereum;
110
111
  }
111
112
  //#endregion
112
- export { EvmWallet as EvmWalletStrategy, getBitGetProvider, getEvmProvider, getKeplrEvmProvider, getMetamaskProvider, getOkxWalletProvider, getPhantomProvider, getRabbyProvider, getRainbowProvider, getTrustWalletProvider, updateEvmNetwork };
113
+ export { EvmWallet as EvmWalletStrategy, getBitGetProvider, getEvmProvider, getKeplrEvmProvider, getMetamaskProvider, getOkxWalletProvider, getPhantomProvider, getRabbyProvider, getRainbowProvider, getTrustWalletProvider, switchEthereumChainWithTimeout, updateEvmNetwork };
package/dist/esm/index.js CHANGED
@@ -222,6 +222,38 @@ const getEvmProvider = async (wallet) => {
222
222
  throw new WalletException(/* @__PURE__ */ new Error(`Please install ${capitalize(wallet)} Extension`));
223
223
  }
224
224
  };
225
+ const switchEthereumChainWithTimeout = async (provider, chainIdHex, timeoutMs = 3e4) => {
226
+ let timeoutId;
227
+ let handleChainChanged;
228
+ const cleanup = () => {
229
+ if (handleChainChanged) {
230
+ provider.removeListener("chainChanged", handleChainChanged);
231
+ handleChainChanged = void 0;
232
+ }
233
+ if (timeoutId !== void 0) {
234
+ clearTimeout(timeoutId);
235
+ timeoutId = void 0;
236
+ }
237
+ };
238
+ const switchRequest = provider.request({
239
+ method: "wallet_switchEthereumChain",
240
+ params: [{ chainId: chainIdHex }]
241
+ }).finally(cleanup);
242
+ const chainChangedWaiter = new Promise((resolve, reject) => {
243
+ handleChainChanged = (newChainId) => {
244
+ if (newChainId.toLowerCase() === chainIdHex.toLowerCase()) {
245
+ cleanup();
246
+ resolve();
247
+ }
248
+ };
249
+ timeoutId = setTimeout(() => {
250
+ cleanup();
251
+ reject(/* @__PURE__ */ new Error("Chain switch timed out"));
252
+ }, timeoutMs);
253
+ provider.on("chainChanged", handleChainChanged);
254
+ });
255
+ await Promise.race([switchRequest, chainChangedWaiter]);
256
+ };
225
257
  const updateEvmNetwork = async (wallet, chainId) => {
226
258
  if (!isEvmBrowserWallet(wallet)) throw new WalletException(/* @__PURE__ */ new Error(`Evm Wallet for ${capitalize(wallet)} is not supported.`));
227
259
  const provider = await getEvmProvider(wallet);
@@ -229,50 +261,48 @@ const updateEvmNetwork = async (wallet, chainId) => {
229
261
  const chainIdToHex = `0x${chainId.toString(16)}`;
230
262
  const TIMEOUT_MS = 3e4;
231
263
  try {
232
- return await Promise.race([provider.request({
233
- method: "wallet_switchEthereumChain",
234
- params: [{ chainId: chainIdToHex }]
235
- }), new Promise((resolve, reject) => {
236
- const handleChainChanged = (newChainId) => {
237
- if (newChainId.toLowerCase() === chainIdToHex.toLowerCase()) {
238
- cleanup();
239
- resolve();
240
- }
241
- };
242
- const timeoutId = setTimeout(() => {
243
- cleanup();
244
- reject(/* @__PURE__ */ new Error("Chain switch timed out"));
245
- }, TIMEOUT_MS);
246
- const cleanup = () => {
247
- provider.removeListener("chainChanged", handleChainChanged);
248
- clearTimeout(timeoutId);
249
- };
250
- provider.on("chainChanged", handleChainChanged);
251
- })]);
264
+ await switchEthereumChainWithTimeout(provider, chainIdToHex, TIMEOUT_MS);
252
265
  } catch (switchError) {
253
- var _switchError$code, _switchError$data;
254
- if (((_switchError$code = switchError === null || switchError === void 0 ? void 0 : switchError.code) !== null && _switchError$code !== void 0 ? _switchError$code : switchError === null || switchError === void 0 || (_switchError$data = switchError.data) === null || _switchError$data === void 0 || (_switchError$data = _switchError$data.originalError) === null || _switchError$data === void 0 ? void 0 : _switchError$data.code) === 4902) {
255
- const chainConfig = getEvmChainConfig(chainId);
256
- try {
257
- var _chainConfig$rpcUrls, _chainConfig$blockExp;
258
- const rpcUrl = (_chainConfig$rpcUrls = chainConfig.rpcUrls) === null || _chainConfig$rpcUrls === void 0 || (_chainConfig$rpcUrls = _chainConfig$rpcUrls.default) === null || _chainConfig$rpcUrls === void 0 || (_chainConfig$rpcUrls = _chainConfig$rpcUrls.http) === null || _chainConfig$rpcUrls === void 0 ? void 0 : _chainConfig$rpcUrls[0];
259
- const explorerUrl = ((_chainConfig$blockExp = chainConfig.blockExplorers) === null || _chainConfig$blockExp === void 0 || (_chainConfig$blockExp = _chainConfig$blockExp.default) === null || _chainConfig$blockExp === void 0 ? void 0 : _chainConfig$blockExp.url) || void 0;
260
- await provider.request({
261
- method: "wallet_addEthereumChain",
262
- params: [{
263
- chainId: chainIdToHex,
264
- chainName: chainConfig.name,
265
- nativeCurrency: chainConfig.nativeCurrency,
266
- rpcUrls: rpcUrl ? [rpcUrl] : [],
267
- blockExplorerUrls: explorerUrl ? [explorerUrl] : void 0
268
- }]
269
- });
270
- return;
271
- } catch (_unused2) {
272
- throw new WalletException(/* @__PURE__ */ new Error(`Failed to add ${chainConfig.name} network to ${capitalize(wallet)}`));
273
- }
266
+ var _switchError$code, _switchError$data, _chainConfig$rpcUrls, _chainConfig$blockExp;
267
+ const rawCode = (_switchError$code = switchError === null || switchError === void 0 ? void 0 : switchError.code) !== null && _switchError$code !== void 0 ? _switchError$code : switchError === null || switchError === void 0 || (_switchError$data = switchError.data) === null || _switchError$data === void 0 || (_switchError$data = _switchError$data.originalError) === null || _switchError$data === void 0 ? void 0 : _switchError$data.code;
268
+ const parsed = rawCode != null ? Number(rawCode) : NaN;
269
+ const errorCode = !isNaN(parsed) ? parsed : void 0;
270
+ if (errorCode === 4001) throw new WalletException(/* @__PURE__ */ new Error(`${capitalize(wallet)} chain switch was rejected`));
271
+ if (switchError.message === "Chain switch timed out") throw new WalletException(/* @__PURE__ */ new Error("Chain switch timed out"));
272
+ if (errorCode !== 4902) throw new WalletException(/* @__PURE__ */ new Error(`Please update your ${capitalize(wallet)} network`));
273
+ const chainConfig = getEvmChainConfig(chainId);
274
+ const rpcUrl = (_chainConfig$rpcUrls = chainConfig.rpcUrls) === null || _chainConfig$rpcUrls === void 0 || (_chainConfig$rpcUrls = _chainConfig$rpcUrls.default) === null || _chainConfig$rpcUrls === void 0 || (_chainConfig$rpcUrls = _chainConfig$rpcUrls.http) === null || _chainConfig$rpcUrls === void 0 ? void 0 : _chainConfig$rpcUrls[0];
275
+ const explorerUrl = ((_chainConfig$blockExp = chainConfig.blockExplorers) === null || _chainConfig$blockExp === void 0 || (_chainConfig$blockExp = _chainConfig$blockExp.default) === null || _chainConfig$blockExp === void 0 ? void 0 : _chainConfig$blockExp.url) || void 0;
276
+ try {
277
+ await provider.request({
278
+ method: "wallet_addEthereumChain",
279
+ params: [{
280
+ chainId: chainIdToHex,
281
+ chainName: chainConfig.name,
282
+ nativeCurrency: chainConfig.nativeCurrency,
283
+ rpcUrls: rpcUrl ? [rpcUrl] : [],
284
+ blockExplorerUrls: explorerUrl ? [explorerUrl] : []
285
+ }]
286
+ });
287
+ } catch (_unused2) {
288
+ throw new WalletException(/* @__PURE__ */ new Error(`Failed to add ${chainConfig.name} network to ${capitalize(wallet)}`));
289
+ }
290
+ let currentChainId;
291
+ try {
292
+ currentChainId = await provider.request({ method: "eth_chainId" });
293
+ } catch (_unused3) {
294
+ throw new WalletException(/* @__PURE__ */ new Error(`Failed to get current chain ID from ${capitalize(wallet)} wallet`));
295
+ }
296
+ if (typeof currentChainId !== "string" || !currentChainId.startsWith("0x")) throw new WalletException(/* @__PURE__ */ new Error(`Invalid chain ID response from ${capitalize(wallet)}: ${String(currentChainId)}`));
297
+ if (currentChainId.toLowerCase() !== chainIdToHex.toLowerCase()) try {
298
+ await switchEthereumChainWithTimeout(provider, chainIdToHex, TIMEOUT_MS);
299
+ } catch (postAddError) {
300
+ var _postAddError$code, _postAddError$data;
301
+ const rawCode$1 = (_postAddError$code = postAddError === null || postAddError === void 0 ? void 0 : postAddError.code) !== null && _postAddError$code !== void 0 ? _postAddError$code : postAddError === null || postAddError === void 0 || (_postAddError$data = postAddError.data) === null || _postAddError$data === void 0 || (_postAddError$data = _postAddError$data.originalError) === null || _postAddError$data === void 0 ? void 0 : _postAddError$data.code;
302
+ const parsed$1 = rawCode$1 != null ? Number(rawCode$1) : NaN;
303
+ if ((!isNaN(parsed$1) ? parsed$1 : void 0) === 4001) throw new WalletException(/* @__PURE__ */ new Error(`${capitalize(wallet)} chain switch after add was rejected`));
304
+ throw new WalletException(/* @__PURE__ */ new Error(`Failed to switch to ${chainConfig.name} network after adding it: ${postAddError.message}`));
274
305
  }
275
- throw new WalletException(/* @__PURE__ */ new Error(`Please update your ${capitalize(wallet)} network`));
276
306
  }
277
307
  };
278
308
 
@@ -548,63 +578,71 @@ var EvmWallet = class extends BaseConcreteStrategy {
548
578
  };
549
579
  const TIMEOUT_MS = 3e4;
550
580
  try {
551
- let timeoutId;
552
- let handleChainChanged;
553
- const cleanup = () => {
554
- if (handleChainChanged) {
555
- ethereum.removeListener("chainChanged", handleChainChanged);
556
- handleChainChanged = void 0;
557
- }
558
- if (timeoutId !== void 0) {
559
- clearTimeout(timeoutId);
560
- timeoutId = void 0;
561
- }
562
- };
563
- const switchRequest = ethereum.request({
564
- method: "wallet_switchEthereumChain",
565
- params: [{ chainId: chainIdHex }]
566
- }).finally(cleanup);
567
- const chainChangedWaiter = new Promise((resolve, reject) => {
568
- handleChainChanged = (newChainId) => {
569
- if (newChainId.toLowerCase() === chainIdHex.toLowerCase()) {
570
- cleanup();
571
- resolve();
572
- }
573
- };
574
- timeoutId = setTimeout(() => {
575
- cleanup();
576
- reject(/* @__PURE__ */ new Error("Chain switch timed out"));
577
- }, TIMEOUT_MS);
578
- ethereum.on("chainChanged", handleChainChanged);
579
- });
580
- await Promise.race([switchRequest, chainChangedWaiter]);
581
+ await switchEthereumChainWithTimeout(ethereum, chainIdHex, TIMEOUT_MS);
581
582
  } catch (error) {
582
583
  var _code, _data;
583
- if (((_code = error.code) !== null && _code !== void 0 ? _code : error === null || error === void 0 || (_data = error.data) === null || _data === void 0 || (_data = _data.originalError) === null || _data === void 0 ? void 0 : _data.code) === 4902) {
584
- await ethereum.request({
585
- method: "wallet_addEthereumChain",
586
- params: [params]
587
- });
588
- try {
589
- await ethereum.request({
590
- method: "wallet_switchEthereumChain",
591
- params: [{ chainId: chainIdHex }]
592
- });
593
- } catch (switchError) {
594
- console.warn(`Failed to switch to chain ${chainIdHex} after adding it:`, switchError);
595
- }
596
- return;
597
- }
584
+ const rawCode = (_code = error.code) !== null && _code !== void 0 ? _code : error === null || error === void 0 || (_data = error.data) === null || _data === void 0 || (_data = _data.originalError) === null || _data === void 0 ? void 0 : _data.code;
585
+ const parsed = rawCode != null ? Number(rawCode) : NaN;
586
+ const errorCode = !isNaN(parsed) ? parsed : void 0;
587
+ if (errorCode === 4001) throw this.EvmWalletException(/* @__PURE__ */ new Error(`${capitalize(this.wallet || "wallet")} chain switch was rejected`), {
588
+ code: UnspecifiedErrorCode,
589
+ type: ErrorType.WalletError,
590
+ contextModule: WalletAction.GetChainId
591
+ });
598
592
  if (error.message === "Chain switch timed out") throw this.EvmWalletException(/* @__PURE__ */ new Error("Chain switch timed out"), {
599
593
  code: UnspecifiedErrorCode,
600
594
  type: ErrorType.WalletError,
601
595
  contextModule: WalletAction.GetChainId
602
596
  });
603
- throw this.EvmWalletException(/* @__PURE__ */ new Error(`Something went wrong while adding ${capitalize(this.wallet || "wallet")} network`), {
597
+ if (errorCode !== 4902) throw this.EvmWalletException(/* @__PURE__ */ new Error(`Something went wrong while switching ${capitalize(this.wallet || "wallet")} network`), {
604
598
  code: UnspecifiedErrorCode,
605
599
  type: ErrorType.WalletError,
606
600
  contextModule: WalletAction.GetChainId
607
601
  });
602
+ try {
603
+ await ethereum.request({
604
+ method: "wallet_addEthereumChain",
605
+ params: [params]
606
+ });
607
+ } catch (_unused2) {
608
+ throw this.EvmWalletException(/* @__PURE__ */ new Error(`Something went wrong while adding ${capitalize(this.wallet || "wallet")} network`), {
609
+ code: UnspecifiedErrorCode,
610
+ type: ErrorType.WalletError,
611
+ contextModule: WalletAction.GetChainId
612
+ });
613
+ }
614
+ let currentChainId;
615
+ try {
616
+ currentChainId = await ethereum.request({ method: "eth_chainId" });
617
+ } catch (_unused3) {
618
+ throw this.EvmWalletException(/* @__PURE__ */ new Error(`Failed to get current chain ID from ${capitalize(this.wallet || "wallet")}`), {
619
+ code: UnspecifiedErrorCode,
620
+ type: ErrorType.WalletError,
621
+ contextModule: WalletAction.GetChainId
622
+ });
623
+ }
624
+ if (typeof currentChainId !== "string" || !currentChainId.startsWith("0x")) throw this.EvmWalletException(/* @__PURE__ */ new Error(`Invalid chain ID response from ${capitalize(this.wallet || "wallet")}: ${String(currentChainId)}`), {
625
+ code: UnspecifiedErrorCode,
626
+ type: ErrorType.WalletError,
627
+ contextModule: WalletAction.GetChainId
628
+ });
629
+ if (currentChainId.toLowerCase() !== chainIdHex.toLowerCase()) try {
630
+ await switchEthereumChainWithTimeout(ethereum, chainIdHex, TIMEOUT_MS);
631
+ } catch (postAddError) {
632
+ var _postAddError$code, _postAddError$data;
633
+ const postAddRawCode = (_postAddError$code = postAddError === null || postAddError === void 0 ? void 0 : postAddError.code) !== null && _postAddError$code !== void 0 ? _postAddError$code : postAddError === null || postAddError === void 0 || (_postAddError$data = postAddError.data) === null || _postAddError$data === void 0 || (_postAddError$data = _postAddError$data.originalError) === null || _postAddError$data === void 0 ? void 0 : _postAddError$data.code;
634
+ const postAddParsed = postAddRawCode != null ? Number(postAddRawCode) : NaN;
635
+ if ((!isNaN(postAddParsed) ? postAddParsed : void 0) === 4001) throw this.EvmWalletException(/* @__PURE__ */ new Error(`${capitalize(this.wallet || "wallet")} chain switch after add was rejected`), {
636
+ code: UnspecifiedErrorCode,
637
+ type: ErrorType.WalletError,
638
+ contextModule: WalletAction.GetChainId
639
+ });
640
+ throw this.EvmWalletException(/* @__PURE__ */ new Error(`Failed to switch to ${chain.name} network after adding it: ${postAddError.message}`), {
641
+ code: UnspecifiedErrorCode,
642
+ type: ErrorType.WalletError,
643
+ contextModule: WalletAction.GetChainId
644
+ });
645
+ }
608
646
  }
609
647
  }
610
648
  async getEthereum() {
@@ -621,4 +659,4 @@ var EvmWallet = class extends BaseConcreteStrategy {
621
659
  };
622
660
 
623
661
  //#endregion
624
- export { EvmWallet as EvmWalletStrategy, getBitGetProvider, getEvmProvider, getKeplrEvmProvider, getMetamaskProvider, getOkxWalletProvider, getPhantomProvider, getRabbyProvider, getRainbowProvider, getTrustWalletProvider, updateEvmNetwork };
662
+ export { EvmWallet as EvmWalletStrategy, getBitGetProvider, getEvmProvider, getKeplrEvmProvider, getMetamaskProvider, getOkxWalletProvider, getPhantomProvider, getRabbyProvider, getRainbowProvider, getTrustWalletProvider, switchEthereumChainWithTimeout, updateEvmNetwork };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@injectivelabs/wallet-evm",
3
- "version": "1.19.22",
3
+ "version": "1.19.24",
4
4
  "description": "EVM wallet strategies for use with @injectivelabs/wallet-core.",
5
5
  "license": "Apache-2.0",
6
6
  "author": {
@@ -42,11 +42,11 @@
42
42
  "dist"
43
43
  ],
44
44
  "dependencies": {
45
- "@injectivelabs/exceptions": "1.19.22",
46
- "@injectivelabs/ts-types": "1.19.22",
47
- "@injectivelabs/utils": "1.19.22",
48
- "@injectivelabs/wallet-base": "1.19.22",
49
- "@injectivelabs/sdk-ts": "1.19.22"
45
+ "@injectivelabs/exceptions": "1.19.24",
46
+ "@injectivelabs/sdk-ts": "1.19.24",
47
+ "@injectivelabs/ts-types": "1.19.24",
48
+ "@injectivelabs/utils": "1.19.24",
49
+ "@injectivelabs/wallet-base": "1.19.24"
50
50
  },
51
51
  "publishConfig": {
52
52
  "access": "public"