Skip to content

Commit

Permalink
fix: Try to switch first in AutoChangeChain
Browse files Browse the repository at this point in the history
  • Loading branch information
ugur-eren committed Jul 29, 2023
1 parent 0c20bc0 commit c578f83
Showing 1 changed file with 31 additions and 24 deletions.
55 changes: 31 additions & 24 deletions src/utils/AutoChangeChain.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,47 @@
/* eslint no-underscore-dangle: "off" */

import {ethers, utils} from 'ethers';
import {Chain, ChainObject, DefaultChains, DefaultChainNames} from '../types';
import {Chain, ChainObject, DefaultChains} from '../types';

const AutoChangeChain = async (provider: ethers.providers.Web3Provider, chains?: Chain[]) => {
await provider._networkPromise;

if (Array.isArray(chains) && chains.length > 0) {
const foundIndex = chains.findIndex(
(chain) =>
(typeof chain === 'object' && chain.chainId === provider.network.chainId) ||
(typeof chain === 'string' && DefaultChains[chain] === provider.network.chainId),
);
if (!provider.network.chainId || !Array.isArray(chains) || chains.length === 0) return;

if (foundIndex === -1) {
const defaultChains = chains.filter(
(chain): chain is DefaultChainNames => typeof chain === 'string',
);
const providerNetwork = utils.hexValue(provider.network.chainId);

if (defaultChains.length > 0) {
const foundIndex = chains.findIndex(
(chain) =>
(typeof chain === 'object' && utils.hexValue(chain.chainId) === providerNetwork) ||
(typeof chain === 'string' && utils.hexValue(DefaultChains[chain]) === providerNetwork),
);

if (foundIndex === -1) {
try {
try {
// Try to switch
await provider.send(
'wallet_switchEthereumChain',
defaultChains.map((chain) => ({chainId: utils.hexValue(DefaultChains[chain])})),
chains.map((chain) => ({
chainId: utils.hexValue(
typeof chain === 'string' ? DefaultChains[chain] : chain.chainId,
),
})),
);
} catch (_) {
// Try to add if switch failed
await provider.send(
'wallet_addEthereumChain',
chains
.filter((chain): chain is ChainObject => typeof chain === 'object')
.map((chain) => ({
...chain,
chainId: utils.hexValue(chain.chainId),
})),
);
return;
}

await provider.send(
'wallet_addEthereumChain',
chains
.filter((chain): chain is ChainObject => typeof chain === 'object')
.map((chain) => ({
...chain,
chainId: utils.hexValue(chain.chainId),
})),
);
} catch (_) {
// Don't do anything if switch and add failed
}
}
};
Expand Down

0 comments on commit c578f83

Please sign in to comment.