Skip to content

Commit

Permalink
fix: better handle chain switch rejection
Browse files Browse the repository at this point in the history
  • Loading branch information
chybisov committed Sep 2, 2022
1 parent dc77cf3 commit 48d34ce
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions packages/wallet-management/src/browserWallets.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,37 @@
/* eslint-disable radix */
import type { Token } from '@lifi/sdk';
import { getChainById, prefixChainId } from '@lifi/sdk';
import {
getChainById,
MetaMaskProviderErrorCode,
prefixChainId,
} from '@lifi/sdk';

export const switchChain = async (chainId: number): Promise<boolean> => {
return new Promise((resolve, reject) => {
const { ethereum } = window as any;
if (!ethereum) resolve(false);

try {
ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: getChainById(chainId).metamask?.chainId }],
});
ethereum
.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: getChainById(chainId).metamask?.chainId }],
})
.catch((error: any) => {
if (error.code !== MetaMaskProviderErrorCode.userRejectedRequest) {
addChain(chainId).then((result) => resolve(result));
} else {
reject(error);
}
});
ethereum.once('chainChanged', (id: string) => {
if (parseInt(id) === chainId) {
resolve(true);
}
});
} catch (error: any) {
// const ERROR_CODE_UNKNOWN_CHAIN = 4902
const ERROR_CODE_USER_REJECTED = 4001;
if (error.code !== ERROR_CODE_USER_REJECTED) {
if (error.code !== MetaMaskProviderErrorCode.userRejectedRequest) {
addChain(chainId).then((result) => resolve(result));
} else {
resolve(false);
Expand Down

0 comments on commit 48d34ce

Please sign in to comment.