Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: testnet fixes #1106

Merged
merged 4 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/core/resources/_selectors/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
import { ChainId } from '~/core/types/chains';
import { deriveAddressAndChainWithUniqueId } from '~/core/utils/address';
import { add } from '~/core/utils/numbers';
import { chainIdMap } from '~/core/utils/userChains';

// selectors
export function selectorFilterByUserChains<T>({
Expand All @@ -18,9 +19,12 @@ export function selectorFilterByUserChains<T>({
selector: (data: ParsedAssetsDictByChain) => T;
}): T {
const { userChains } = userChainsStore.getState();
const allUserChainIds = Object.keys(userChains)
.map((chainId) => chainIdMap[Number(chainId)])
.flat();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TIL!

const filteredAssetsDictByChain = Object.keys(data).reduce((acc, key) => {
const chainKey = Number(key);
if (userChains[chainKey]) {
if (allUserChainIds.includes(chainKey)) {
acc[chainKey] = data[chainKey];
}
return acc;
Expand Down
41 changes: 29 additions & 12 deletions src/core/state/userChains/index.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,60 @@
import create from 'zustand';

import { ChainId } from '~/core/types/chains';
import { SUPPORTED_CHAINS } from '~/core/utils/chains';
import { SUPPORTED_MAINNET_CHAINS } from '~/core/utils/chains';

import { createStore } from '../internal/createStore';

type MainnetChainId =
| ChainId.mainnet
| ChainId.optimism
| ChainId.polygon
| ChainId.arbitrum
| ChainId.bsc
| ChainId.zora
| ChainId.base;

export interface UserChainsState {
userChains: Record<ChainId, boolean>;
userChainsOrder: ChainId[];
/**
* Mainnet chains in network settings
*/
userChains: Record<MainnetChainId, boolean>;
/**
* Mainnet chains ordered from network settings
*/
userChainsOrder: MainnetChainId[];
updateUserChain: ({
chainId,
enabled,
}: {
chainId: ChainId;
chainId: MainnetChainId;
enabled: boolean;
}) => void;
updateUserChains: ({
chainIds,
enabled,
}: {
chainIds: ChainId[];
chainIds: MainnetChainId[];
enabled: boolean;
}) => void;
updateUserChainsOrder: ({
userChainsOrder,
}: {
userChainsOrder: ChainId[];
userChainsOrder: MainnetChainId[];
}) => void;
}

const chains = SUPPORTED_CHAINS.reduce(
const chains = SUPPORTED_MAINNET_CHAINS.reduce(
(acc, chain) => ({
...acc,
[chain.id]: true,
}),
{} as Record<ChainId, boolean>,
{} as Record<MainnetChainId, boolean>,
);

const userChainsOrder = Object.keys(chains).map((id) => Number(id) as ChainId);
const userChainsOrder = Object.keys(chains).map(
(id) => Number(id) as MainnetChainId,
);

export const userChainsStore = createStore<UserChainsState>(
(set, get) => ({
Expand All @@ -50,8 +67,8 @@ export const userChainsStore = createStore<UserChainsState>(
acc[chainId] = enabled;
return acc;
},
{} as Record<ChainId, boolean>,
) satisfies Record<ChainId, boolean>;
{} as Record<MainnetChainId, boolean>,
) satisfies Record<MainnetChainId, boolean>;
set({
userChains: {
...userChains,
Expand All @@ -77,7 +94,7 @@ export const userChainsStore = createStore<UserChainsState>(
{
persist: {
name: 'userChains',
version: 0,
version: 1,
},
},
);
Expand Down
12 changes: 11 additions & 1 deletion src/core/utils/chains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@ import { AddressOrEth } from '../types/assets';
import { getDappHost } from './connectedApps';
import { isLowerCaseMatch } from './strings';

export const SUPPORTED_MAINNET_CHAINS: Chain[] = [
mainnet,
polygon,
optimism,
arbitrum,
base,
zora,
bsc,
].map((chain) => ({ ...chain, name: ChainNameDisplay[chain.id] }));

export const SUPPORTED_CHAINS: Chain[] = [
mainnet,
polygon,
Expand Down Expand Up @@ -63,7 +73,7 @@ export const getSupportedChainIds = () =>

export const getSupportedTestnetChains = () => {
const { chains } = getNetwork();
return chains.filter((chain) => chain.testnet);
return chains.filter((chain) => !!chain.testnet);
};

export const getSupportedTestnetChainIds = () =>
Expand Down
36 changes: 35 additions & 1 deletion src/core/utils/userChains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ import { Chain, goerli, mainnet, sepolia } from 'wagmi';

import { ChainId, ChainNameDisplay } from '../types/chains';

import {
getSupportedChainsWithHardhat,
getSupportedTestnetChains,
} from './chains';

export const chainIdMap: Record<
| ChainId.mainnet
| ChainId.optimism
Expand Down Expand Up @@ -57,11 +62,40 @@ export const chainLabelMap: Record<

export const sortNetworks = (order: ChainId[], chains: Chain[]) => {
const allChainsOrder = order.map((chainId) => chainIdMap[chainId]).flat();
return chains.sort((a, b) => {
const ordered = chains.sort((a, b) => {
const aIndex = allChainsOrder.indexOf(a.id);
const bIndex = allChainsOrder.indexOf(b.id);
if (aIndex === -1) return bIndex === -1 ? 0 : 1;
if (bIndex === -1) return -1;
return aIndex - bIndex;
});
return ordered;
};

export const filterUserNetworks = ({
testnetMode,
userChains,
userChainsOrder,
}: {
testnetMode: boolean;
userChains: Record<ChainId, boolean>;
userChainsOrder: ChainId[];
}) => {
const supportedChains = testnetMode
? getSupportedTestnetChains()
: getSupportedChainsWithHardhat();

const availableChains = Object.keys(userChains)
.filter((chainId) => userChains[Number(chainId)] === true)
.map((chainId) => Number(chainId));

const allAvailableUserChains = availableChains
.map((chainId) => chainIdMap[chainId])
.flat();

const chains = supportedChains.filter((chain) =>
allAvailableUserChains.includes(chain.id),
);

return sortNetworks(userChainsOrder, chains);
};
54 changes: 10 additions & 44 deletions src/entries/popup/components/SwitchMenu/SwitchNetworkMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,7 @@ import { Chain } from 'wagmi';

import { i18n } from '~/core/languages';
import { shortcuts } from '~/core/references/shortcuts';
import { useTestnetModeStore } from '~/core/state/currentSettings/testnetMode';
import { useUserChainsStore } from '~/core/state/userChains';
import { ChainId } from '~/core/types/chains';
import {
getSupportedChainsWithHardhat,
getSupportedTestnetChains,
} from '~/core/utils/chains';
import { sortNetworks } from '~/core/utils/userChains';
import {
Box,
Column,
Expand All @@ -24,6 +17,7 @@ import { Space } from '~/design-system/styles/designTokens';

import useKeyboardAnalytics from '../../hooks/useKeyboardAnalytics';
import { useKeyboardShortcut } from '../../hooks/useKeyboardShortcut';
import { useUserChains } from '../../hooks/useUserChains';
import { simulateClick } from '../../utils/simulateClick';
import { ChainBadge } from '../ChainBadge/ChainBadge';
import {
Expand Down Expand Up @@ -64,22 +58,8 @@ export const SwitchNetworkMenuSelector = ({
onNetworkSelect?: (event?: Event) => void;
onShortcutPress: (chainId: string) => void;
}) => {
const { userChains } = useUserChainsStore();
const { trackShortcut } = useKeyboardAnalytics();
const { userChainsOrder } = useUserChainsStore();
const { testnetMode } = useTestnetModeStore();

const availableChains = useMemo(() => {
const supportedChains = testnetMode
? getSupportedTestnetChains()
: getSupportedChainsWithHardhat();
return sortNetworks(
userChainsOrder,
supportedChains.filter(
(chain) => userChains[chain.id] || chain.id === ChainId.hardhat,
),
);
}, [testnetMode, userChains, userChainsOrder]);
const { chains } = useUserChains();

const { MenuRadioItem } = useMemo(() => {
return type === 'dropdown'
Expand All @@ -95,18 +75,15 @@ export const SwitchNetworkMenuSelector = ({
(e: KeyboardEvent) => {
const chainNumber = Number(e.key);
if (chainNumber) {
const chain = availableChains[chainNumber - 1];
const chain = chains[chainNumber - 1];
if (chain) {
trackShortcut({
key: chainNumber.toString(),
type: 'switchNetworkMenu.selectChain',
});
onShortcutPress(String(chain.id));
onNetworkSelect?.();
} else if (
showDisconnect &&
chainNumber === availableChains.length + 1
) {
} else if (showDisconnect && chainNumber === chains.length + 1) {
trackShortcut({
key: chainNumber.toString(),
type: 'switchNetworkMenu.disconnect',
Expand All @@ -116,7 +93,7 @@ export const SwitchNetworkMenuSelector = ({
}
},
[
availableChains,
chains,
disconnect,
onNetworkSelect,
onShortcutPress,
Expand All @@ -131,7 +108,7 @@ export const SwitchNetworkMenuSelector = ({

return (
<Box id="switch-network-menu-selector">
{availableChains.map((chain, i) => {
{chains.map((chain, i) => {
const { id: chainId, name } = chain;
return (
<MenuRadioItem
Expand Down Expand Up @@ -175,7 +152,7 @@ export const SwitchNetworkMenuSelector = ({
{showDisconnect && disconnect && (
<SwitchNetworkMenuDisconnect
onDisconnect={disconnect}
shortcutLabel={String(availableChains.length + 1)}
shortcutLabel={String(chains.length + 1)}
/>
)}
</Box>
Expand Down Expand Up @@ -245,18 +222,7 @@ export const SwitchNetworkMenu = ({
onOpenChange,
}: SwitchNetworkMenuProps) => {
const triggerRef = useRef<HTMLDivElement>(null);
const { userChainsOrder, userChains } = useUserChainsStore();
const { testnetMode } = useTestnetModeStore();

const availableChains = useMemo(() => {
return sortNetworks(
userChainsOrder,
(testnetMode
? getSupportedTestnetChains()
: getSupportedChainsWithHardhat()
).filter((chain) => userChains[chain.id] || chain.id === ChainId.hardhat),
);
}, [testnetMode, userChains, userChainsOrder]);
const { chains } = useUserChains();

useKeyboardShortcut({
handler: (e: KeyboardEvent) => {
Expand Down Expand Up @@ -318,7 +284,7 @@ export const SwitchNetworkMenu = ({
<MenuRadioGroup
value={String(chainId)}
onValueChange={(chainId: string) => {
const chain = availableChains.find(
const chain = chains.find(
({ id }) => String(id) === chainId,
) as Chain;
onChainChanged(chain?.id, chain);
Expand All @@ -328,7 +294,7 @@ export const SwitchNetworkMenu = ({
type={type}
selectedValue={String(chainId)}
onShortcutPress={(chainId) => {
const chain = availableChains.find(
const chain = chains.find(
({ id }) => String(id) === chainId,
) as Chain;
onChainChanged(chain?.id, chain);
Expand Down
8 changes: 4 additions & 4 deletions src/entries/popup/hooks/useInfiniteTransactionList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import {
useCurrentCurrencyStore,
usePendingTransactionsStore,
} from '~/core/state';
import { useUserChainsStore } from '~/core/state/userChains';
import { ChainId } from '~/core/types/chains';
import {
PendingTransaction,
Expand All @@ -27,6 +26,7 @@ import { isLowerCaseMatch } from '~/core/utils/strings';

import useComponentWillUnmount from './useComponentWillUnmount';
import { useKeyboardShortcut } from './useKeyboardShortcut';
import { useUserChains } from './useUserChains';

const PAGES_TO_CACHE_LIMIT = 2;

Expand All @@ -39,7 +39,7 @@ export default function ({
}: UseInfiniteTransactionListParams) {
const { currentAddress: address } = useCurrentAddressStore();
const { currentCurrency: currency } = useCurrentCurrencyStore();
const { userChains } = useUserChainsStore();
const { chains } = useUserChains();
const { getPendingTransactions } = usePendingTransactionsStore();
const [manuallyRefetching, setManuallyRefetching] = useState(false);
const pendingTransactions = getPendingTransactions({ address });
Expand All @@ -61,8 +61,8 @@ export default function ({
const selectedPages = data.pages.map((page) => {
return {
...page,
transactions: page.transactions.filter(
(transaction) => userChains[transaction.chainId],
transactions: page.transactions.filter((transaction) =>
chains.map((chain) => chain.id).includes(transaction.chainId),
),
};
});
Expand Down
Loading
Loading