From 5d5dfed90bbef1b9b39534c7528f09f095997a3d Mon Sep 17 00:00:00 2001 From: Matthew Wall Date: Mon, 21 Oct 2024 10:01:55 -0400 Subject: [PATCH 01/11] convert network accessors to functions --- ios/Podfile.lock | 2 +- package.json | 2 +- .../screens/Swap/components/CoinRow.tsx | 4 +- .../screens/Swap/components/ReviewPanel.tsx | 4 +- .../components/TokenList/ChainSelection.tsx | 10 +- .../screens/Swap/providers/swap-provider.tsx | 6 +- .../Swap/resources/assets/userAssets.ts | 4 +- src/__swaps__/utils/assets.ts | 10 +- src/__swaps__/utils/chains.ts | 4 +- src/__swaps__/utils/swaps.ts | 6 +- src/__swaps__/utils/userChains.ts | 18 +- src/chains/index.ts | 216 +++++++++++------- .../control-panel/ControlPanel.tsx | 6 +- .../DappBrowser/handleProviderRequest.ts | 10 +- src/components/L2Disclaimer.js | 4 +- .../Transactions/TransactionDetailsCard.tsx | 4 +- .../TransactionSimulatedEventRow.tsx | 4 +- .../TransactionSimulationCard.tsx | 4 +- src/components/cards/NFTOffersCard/Offer.tsx | 4 +- .../context-menu-buttons/ChainContextMenu.tsx | 8 +- .../discover/DiscoverSearchInput.js | 4 +- .../exchange/ConfirmExchangeButton.js | 4 +- .../exchange/CurrencySelectModalHeader.tsx | 4 +- src/components/exchange/NetworkSwitcher.js | 10 +- src/components/exchange/NetworkSwitcherv2.tsx | 6 +- .../exchangeAssetRowContextMenuProps.ts | 10 +- .../expanded-state/AvailableNetworks.js | 4 +- .../expanded-state/AvailableNetworksv2.tsx | 14 +- .../expanded-state/SwapDetailsState.js | 6 +- .../asset/ChartExpandedState.js | 4 +- .../swap-details/SwapDetailsExchangeRow.js | 4 +- .../swap-details/SwapDetailsRewardRow.tsx | 4 +- src/components/gas/GasSpeedButton.tsx | 4 +- src/components/positions/PositionsCard.tsx | 4 +- .../check-fns/hasSwapTxn.ts | 4 +- .../sheet-action-buttons/SwapActionButton.tsx | 10 +- src/components/toasts/TestnetToast.js | 6 +- .../WalletConnectListItem.js | 8 +- .../WalletConnectV2ListItem.tsx | 4 +- src/featuresToUnlock/tokenGatedUtils.ts | 4 +- src/handlers/assets.ts | 4 +- src/handlers/gasFees.ts | 5 +- src/handlers/tokenSearch.ts | 4 +- src/handlers/web3.ts | 8 +- src/helpers/walletConnectNetworks.ts | 10 +- src/hooks/useAccountTransactions.ts | 6 +- src/hooks/useCalculateGasLimit.ts | 4 +- src/hooks/useSearchCurrencyList.ts | 4 +- src/hooks/useSwapCurrencyList.ts | 4 +- src/hooks/useSwapDerivedOutputs.ts | 4 +- src/hooks/useWatchPendingTxs.ts | 6 +- src/navigation/config.tsx | 4 +- src/raps/actions/claimBridge.ts | 10 +- src/raps/actions/crosschainSwap.ts | 8 +- src/raps/actions/swap.ts | 8 +- src/raps/actions/unlock.ts | 6 +- .../claimTransactionClaimableAction.ts | 4 +- src/redux/gas.ts | 8 +- src/redux/walletconnect.ts | 4 +- src/resources/addys/claimables/query.ts | 4 +- src/resources/addys/claimables/utils.ts | 4 +- src/resources/assets/UserAssetsQuery.ts | 4 +- src/resources/assets/assets.ts | 4 +- src/resources/assets/hardhatAssets.ts | 4 +- src/resources/assets/useUserAsset.ts | 4 +- src/resources/defi/PositionsQuery.ts | 4 +- src/resources/defi/utils.ts | 4 +- src/resources/favorites.ts | 6 +- src/resources/nfts/simplehash/index.ts | 10 +- src/resources/nfts/simplehash/utils.ts | 4 +- .../transactions/consolidatedTransactions.ts | 8 +- src/resources/transactions/transaction.ts | 4 +- src/screens/CurrencySelectModal.tsx | 6 +- src/screens/ExchangeModal.tsx | 16 +- src/screens/ExplainSheet.js | 20 +- src/screens/MintsSheet/card/Card.tsx | 4 +- src/screens/NFTOffersSheet/OfferRow.tsx | 4 +- src/screens/NFTSingleOfferSheet/index.tsx | 8 +- src/screens/SendConfirmationSheet.tsx | 6 +- src/screens/SendSheet.tsx | 12 +- .../components/NetworkSection.tsx | 4 +- src/screens/SignTransactionSheet.tsx | 12 +- src/screens/WalletConnectApprovalSheet.tsx | 12 +- .../claimables/ClaimingClaimableSharedUI.tsx | 4 +- .../ClaimingTransactionClaimable.tsx | 4 +- .../discover/components/DiscoverSearch.js | 4 +- src/screens/mints/MintSheet.tsx | 14 +- .../points/claim-flow/ClaimRewardsPanel.tsx | 16 +- src/screens/positions/SubPositionListItem.tsx | 4 +- src/state/assets/userAssets.ts | 6 +- src/state/nonces/index.ts | 4 +- src/utils/ethereumUtils.ts | 30 +-- src/utils/getUrlForTrustIconFallback.ts | 4 +- src/utils/requestNavigationHandlers.ts | 10 +- src/walletConnect/index.tsx | 6 +- 95 files changed, 439 insertions(+), 394 deletions(-) diff --git a/ios/Podfile.lock b/ios/Podfile.lock index 10d554bc320..af7eb5f5407 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -2525,7 +2525,7 @@ SPEC CHECKSUMS: TOCropViewController: 80b8985ad794298fb69d3341de183f33d1853654 ToolTipMenu: 8ac61aded0fbc4acfe7e84a7d0c9479d15a9a382 VisionCamera: 2af28201c3de77245f8c58b7a5274d5979df70df - Yoga: 88480008ccacea6301ff7bf58726e27a72931c8d + Yoga: 04f1db30bb810187397fa4c37dd1868a27af229c PODFILE CHECKSUM: 98c3fc206d7041ac7388693bb0753109d1884b57 diff --git a/package.json b/package.json index 44f1186cef1..2a78840269b 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,7 @@ "install-pods-fast": "cd ios && bundle exec pod install && cd ..", "install-pods-fast-jsc": "cd ios && bundle exec env USE_HERMES=NO pod install && cd ..", "install-pods-no-flipper": "cd ios && bundle exec env SKIP_FLIPPER=true pod install --repo-update && cd ..", - "ios": "react-native run-ios --simulator='iPhone 16 Pro'", + "ios": "react-native run-ios --simulator='iPhone 15 Pro'", "format": "prettier --write .", "format:check": "prettier --check .", "lint": "yarn format:check && yarn lint:ts && yarn lint:js", diff --git a/src/__swaps__/screens/Swap/components/CoinRow.tsx b/src/__swaps__/screens/Swap/components/CoinRow.tsx index 1d8fcddd91c..f1020deaf40 100644 --- a/src/__swaps__/screens/Swap/components/CoinRow.tsx +++ b/src/__swaps__/screens/Swap/components/CoinRow.tsx @@ -17,7 +17,7 @@ import React, { useCallback, useMemo } from 'react'; import { GestureResponderEvent } from 'react-native'; import { OnPressMenuItemEventObject } from 'react-native-ios-context-menu'; import { SwapCoinIcon } from './SwapCoinIcon'; -import { SUPPORTED_CHAIN_IDS } from '@/chains'; +import { getSupportedChainIds } from '@/chains'; export const COIN_ROW_WITH_PADDING_HEIGHT = 56; @@ -185,7 +185,7 @@ export function CoinRow({ isFavorite, onPress, output, uniqueId, testID, ...asse } const InfoButton = ({ address, chainId }: { address: string; chainId: ChainId }) => { - const supportedChain = SUPPORTED_CHAIN_IDS.includes(chainId); + const supportedChain = getSupportedChainIds().includes(chainId); const handleCopy = useCallback(() => { haptics.selection(); diff --git a/src/__swaps__/screens/Swap/components/ReviewPanel.tsx b/src/__swaps__/screens/Swap/components/ReviewPanel.tsx index eca49b3f12f..44a8c2d3622 100644 --- a/src/__swaps__/screens/Swap/components/ReviewPanel.tsx +++ b/src/__swaps__/screens/Swap/components/ReviewPanel.tsx @@ -48,7 +48,7 @@ import { NavigationSteps, useSwapContext } from '../providers/swap-provider'; import { AnimatedSwitch } from './AnimatedSwitch'; import { EstimatedSwapGasFee, EstimatedSwapGasFeeSlot } from './EstimatedSwapGasFee'; import { UnmountOnAnimatedReaction } from './UnmountOnAnimatedReaction'; -import { chainsLabel } from '@/chains'; +import { getChainsLabel } from '@/chains'; import { ChainId } from '@/chains/types'; const UNKNOWN_LABEL = i18n.t(i18n.l.swap.unknown); @@ -325,7 +325,7 @@ export function ReviewPanel() { const unknown = i18n.t(i18n.l.swap.unknown); - const chainName = useDerivedValue(() => chainsLabel[internalSelectedInputAsset.value?.chainId ?? ChainId.mainnet]); + const chainName = useDerivedValue(() => getChainsLabel()[internalSelectedInputAsset.value?.chainId ?? ChainId.mainnet]); const minReceivedOrMaxSoldLabel = useDerivedValue(() => { const isInputBasedTrade = lastTypedInput.value === 'inputAmount' || lastTypedInput.value === 'inputNativeValue'; diff --git a/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx b/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx index 2fb3f5a389d..26c171c59cf 100644 --- a/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx +++ b/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx @@ -18,7 +18,7 @@ import { userAssetsStore, useUserAssetsStore } from '@/state/assets/userAssets'; import { swapsStore } from '@/state/swaps/swapsStore'; import { showActionSheetWithOptions } from '@/utils'; import { OnPressMenuItemEventObject } from 'react-native-ios-context-menu'; -import { chainsLabel, chainsName } from '@/chains'; +import { getChainsLabel, getChainsName } from '@/chains'; type ChainSelectionProps = { allText?: string; @@ -48,10 +48,10 @@ export const ChainSelection = memo(function ChainSelection({ allText, output }: const chainName = useDerivedValue(() => { return output - ? chainsLabel[selectedOutputChainId.value] + ? getChainsLabel()[selectedOutputChainId.value] : inputListFilter.value === 'all' ? allText - : chainsLabel[inputListFilter.value as ChainId]; + : getChainsLabel()[inputListFilter.value as ChainId]; }); const handleSelectChain = useCallback( @@ -78,11 +78,11 @@ export const ChainSelection = memo(function ChainSelection({ allText, output }: const supportedChains = balanceSortedChainList.map(chainId => { return { actionKey: `${chainId}`, - actionTitle: chainsLabel[chainId], + actionTitle: getChainsLabel()[chainId], icon: { iconType: 'ASSET', // NOTE: chainsName[chainId] for mainnet is 'mainnet' and we need it to be 'ethereum' - iconValue: chainId === ChainId.mainnet ? 'ethereumBadge' : `${chainsName[chainId]}BadgeNoShadow`, + iconValue: chainId === ChainId.mainnet ? 'ethereumBadge' : `${getChainsName()[chainId]}BadgeNoShadow`, }, }; }); diff --git a/src/__swaps__/screens/Swap/providers/swap-provider.tsx b/src/__swaps__/screens/Swap/providers/swap-provider.tsx index bbc534d55cc..41190c5c650 100644 --- a/src/__swaps__/screens/Swap/providers/swap-provider.tsx +++ b/src/__swaps__/screens/Swap/providers/swap-provider.tsx @@ -50,13 +50,13 @@ import { CrosschainQuote, Quote, QuoteError, SwapType } from '@rainbow-me/swaps' import { IS_IOS } from '@/env'; import { Address } from 'viem'; import { clearCustomGasSettings } from '../hooks/useCustomGas'; -import { getGasSettingsBySpeed, getSelectedGas, getSelectedGasSpeed } from '../hooks/useSelectedGas'; +import { getGasSettingsBySpeed, getSelectedGas } from '../hooks/useSelectedGas'; import { useSwapOutputQuotesDisabled } from '../hooks/useSwapOutputQuotesDisabled'; import { SyncGasStateToSharedValues, SyncQuoteSharedValuesToState } from './SyncSwapStateAndSharedValues'; import { performanceTracking, Screens, TimeToSignOperation } from '@/state/performance/performance'; import { getRemoteConfig } from '@/model/remoteConfig'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; -import { chainsNativeAsset, supportedFlashbotsChainIds } from '@/chains'; +import { getChainsNativeAsset, supportedFlashbotsChainIds } from '@/chains'; const swapping = i18n.t(i18n.l.swap.actions.swapping); const holdToSwap = i18n.t(i18n.l.swap.actions.hold_to_swap); @@ -748,7 +748,7 @@ export const SwapProvider = ({ children }: SwapProviderProps) => { } if (hasEnoughFundsForGas.value === false) { - const nativeCurrency = chainsNativeAsset[sellAsset?.chainId || ChainId.mainnet]; + const nativeCurrency = getChainsNativeAsset()[sellAsset?.chainId || ChainId.mainnet]; return { label: `${insufficient} ${nativeCurrency.symbol}`, disabled: true, diff --git a/src/__swaps__/screens/Swap/resources/assets/userAssets.ts b/src/__swaps__/screens/Swap/resources/assets/userAssets.ts index 8fbe3f35a91..1a85ffcdf21 100644 --- a/src/__swaps__/screens/Swap/resources/assets/userAssets.ts +++ b/src/__swaps__/screens/Swap/resources/assets/userAssets.ts @@ -15,7 +15,7 @@ import { greaterThan } from '@/__swaps__/utils/numbers'; import { fetchUserAssetsByChain } from './userAssetsByChain'; import { fetchHardhatBalancesByChainId } from '@/resources/assets/hardhatAssets'; -import { SUPPORTED_CHAIN_IDS } from '@/chains'; +import { getSupportedChainIds } from '@/chains'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; const addysHttp = new RainbowFetchClient({ @@ -113,7 +113,7 @@ async function userAssetsQueryFunction({ const cachedUserAssets = (cache.find(userAssetsQueryKey({ address, currency, testnetMode }))?.state?.data || {}) as ParsedAssetsDictByChain; try { - const url = `/${SUPPORTED_CHAIN_IDS.join(',')}/${address}/assets`; + const url = `/${getSupportedChainIds().join(',')}/${address}/assets`; const res = await addysHttp.get(url, { params: { currency: currency.toLowerCase(), diff --git a/src/__swaps__/utils/assets.ts b/src/__swaps__/utils/assets.ts index 7f5d6f0bb9b..ccf787969bc 100644 --- a/src/__swaps__/utils/assets.ts +++ b/src/__swaps__/utils/assets.ts @@ -26,7 +26,7 @@ import { convertRawAmountToDecimalFormat, } from '@/__swaps__/utils/numbers'; import { isLowerCaseMatch, isLowerCaseMatchWorklet } from '@/__swaps__/utils/strings'; -import { chainsIdByName, chainsName } from '@/chains'; +import { getChainsIdByName, getChainsName } from '@/chains'; export const isSameAsset = (a1: Pick, a2: Pick) => +a1.chainId === +a2.chainId && isLowerCaseMatch(a1.address, a2.address); @@ -80,7 +80,7 @@ const getUniqueIdForAsset = ({ asset }: { asset: ZerionAsset | AssetApiResponse const address = asset.asset_code; const chainName = asset.network ?? ChainName.mainnet; const networks = 'networks' in asset ? asset.networks || {} : {}; - const chainId = ('chain_id' in asset && asset.chain_id) || chainsIdByName[chainName] || Number(Object.keys(networks)[0]); + const chainId = ('chain_id' in asset && asset.chain_id) || getChainsIdByName()[chainName] || Number(Object.keys(networks)[0]); // ZerionAsset should be removed when we move fully away from websckets/refraction api const mainnetAddress = isZerionAsset(asset) @@ -94,7 +94,7 @@ export function parseAsset({ asset, currency }: { asset: ZerionAsset | AssetApiR const address = asset.asset_code; const chainName = asset.network ?? ChainName.mainnet; const networks = 'networks' in asset ? asset.networks || {} : {}; - const chainId = ('chain_id' in asset && asset.chain_id) || chainsIdByName[chainName] || Number(Object.keys(networks)[0]); + const chainId = ('chain_id' in asset && asset.chain_id) || getChainsIdByName()[chainName] || Number(Object.keys(networks)[0]); // ZerionAsset should be removed when we move fully away from websckets/refraction api const mainnetAddress = isZerionAsset(asset) @@ -172,7 +172,7 @@ export function parseAssetMetadata({ const parsedAsset = { address, chainId, - chainName: chainsName[chainId], + chainName: getChainsName()[chainId], colors: asset?.colors, decimals: asset?.decimals, icon_url: asset?.iconUrl, @@ -290,7 +290,7 @@ export const parseSearchAsset = ({ isNativeAsset: isNativeAsset(searchAsset.address, searchAsset.chainId), address: searchAsset.address, chainId: searchAsset.chainId, - chainName: chainsName[searchAsset.chainId], + chainName: getChainsName()[searchAsset.chainId], native: { balance: userAsset?.native.balance || { amount: '0', diff --git a/src/__swaps__/utils/chains.ts b/src/__swaps__/utils/chains.ts index 63b1748d97a..0d25aecc938 100644 --- a/src/__swaps__/utils/chains.ts +++ b/src/__swaps__/utils/chains.ts @@ -2,7 +2,7 @@ import { celo, fantom, harmonyOne, moonbeam } from 'viem/chains'; import { AddressOrEth } from '@/__swaps__/types/assets'; import { ChainId } from '@/chains/types'; import { isLowerCaseMatch } from '@/__swaps__/utils/strings'; -import { chainsNativeAsset } from '@/chains'; +import { getChainsNativeAsset } from '@/chains'; // @ts-expect-error Property '[ChainId.hardhat]' is missing export const customChainIdsToAssetNames: Record = { @@ -44,7 +44,7 @@ export const customChainIdsToAssetNames: Record = { }; export function isNativeAsset(address: AddressOrEth, chainId: ChainId) { - return isLowerCaseMatch(chainsNativeAsset[chainId].address, address); + return isLowerCaseMatch(getChainsNativeAsset()[chainId].address, address); } export const chainIdToUse = (connectedToHardhat: boolean, connectedToHardhatOp: boolean, activeSessionChainId: number) => { diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index d61abbfd6db..ad4b4e0c439 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -38,7 +38,7 @@ import { AddressOrEth, ExtendedAnimatedAssetWithColors, ParsedSearchAsset } from import { inputKeys } from '../types/swap'; import { valueBasedDecimalFormatter } from './decimalFormatter'; import { convertAmountToRawAmount } from './numbers'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; // /---- 🎨 Color functions 🎨 ----/ // // @@ -363,7 +363,7 @@ export const slippageInBipsToStringWorklet = (slippageInBips: number) => { export const getDefaultSlippage = (chainId: ChainId, config: RainbowConfig) => { return slippageInBipsToString( // NOTE: JSON.parse doesn't type the result as a Record - (config.default_slippage_bips as unknown as Record)[chainsName[chainId]] || DEFAULT_SLIPPAGE_BIPS[chainId] + (config.default_slippage_bips as unknown as Record)[getChainsName()[chainId]] || DEFAULT_SLIPPAGE_BIPS[chainId] ); }; @@ -371,7 +371,7 @@ export const getDefaultSlippageWorklet = (chainId: ChainId, config: RainbowConfi 'worklet'; return slippageInBipsToStringWorklet( - (config.default_slippage_bips as unknown as { [key: string]: number })[chainsName[chainId]] || DEFAULT_SLIPPAGE_BIPS[chainId] + (config.default_slippage_bips as unknown as { [key: string]: number })[getChainsName()[chainId]] || DEFAULT_SLIPPAGE_BIPS[chainId] ); }; diff --git a/src/__swaps__/utils/userChains.ts b/src/__swaps__/utils/userChains.ts index d10e850fe4f..bb8c8922f9e 100644 --- a/src/__swaps__/utils/userChains.ts +++ b/src/__swaps__/utils/userChains.ts @@ -22,7 +22,7 @@ import { } from 'viem/chains'; import { ChainId } from '@/chains/types'; -import { chainsLabel } from '@/chains'; +import { getChainsLabel } from '@/chains'; export const chainIdMap: Record< ChainId.mainnet | ChainId.optimism | ChainId.polygon | ChainId.base | ChainId.bsc | ChainId.zora | ChainId.avalanche, @@ -42,14 +42,14 @@ export const chainLabelMap: Record< ChainId.mainnet | ChainId.optimism | ChainId.polygon | ChainId.base | ChainId.bsc | ChainId.zora | ChainId.avalanche, string[] > = { - [ChainId.mainnet]: [chainsLabel[goerli.id], chainsLabel[sepolia.id], chainsLabel[holesky.id]], - [ChainId.optimism]: [chainsLabel[optimismSepolia.id]], - [ChainId.arbitrum]: [chainsLabel[arbitrumGoerli.id], chainsLabel[arbitrumSepolia.id]], - [ChainId.polygon]: [chainsLabel[polygonMumbai.id]], - [ChainId.base]: [chainsLabel[baseSepolia.id]], - [ChainId.bsc]: [chainsLabel[bscTestnet.id]], - [ChainId.zora]: [chainsLabel[zoraSepolia.id]], - [ChainId.avalanche]: [chainsLabel[avalancheFuji.id]], + [ChainId.mainnet]: [getChainsLabel()[goerli.id], getChainsLabel()[sepolia.id], getChainsLabel()[holesky.id]], + [ChainId.optimism]: [getChainsLabel()[optimismSepolia.id]], + [ChainId.arbitrum]: [getChainsLabel()[arbitrumGoerli.id], getChainsLabel()[arbitrumSepolia.id]], + [ChainId.polygon]: [getChainsLabel()[polygonMumbai.id]], + [ChainId.base]: [getChainsLabel()[baseSepolia.id]], + [ChainId.bsc]: [getChainsLabel()[bscTestnet.id]], + [ChainId.zora]: [getChainsLabel()[zoraSepolia.id]], + [ChainId.avalanche]: [getChainsLabel()[avalancheFuji.id]], }; export const sortNetworks = (order: ChainId[], chains: Chain[]) => { diff --git a/src/chains/index.ts b/src/chains/index.ts index 04b4e4eab01..69ffd94341d 100644 --- a/src/chains/index.ts +++ b/src/chains/index.ts @@ -8,62 +8,93 @@ import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; import { IS_TEST } from '@/env'; import buildTimeNetworks from '@/references/networks.json'; -// NOTE: Prefer runtime data from backendNetworksQueryKey, but fallback to buildTimeNetworks if needed -const backendNetworks = queryClient.getQueryData(backendNetworksQueryKey()) ?? buildTimeNetworks; - -const BACKEND_CHAINS = transformBackendNetworksToChains(backendNetworks.networks); - -export const SUPPORTED_CHAINS: Chain[] = IS_TEST ? [...BACKEND_CHAINS, chainHardhat, chainHardhatOptimism] : BACKEND_CHAINS; - -export const defaultChains: Record = SUPPORTED_CHAINS.reduce( - (acc, chain) => { - acc[chain.id] = chain; - return acc; - }, - {} as Record -); - -export const SUPPORTED_CHAIN_IDS = SUPPORTED_CHAINS.map(chain => chain.id); - -export const SUPPORTED_MAINNET_CHAINS: Chain[] = SUPPORTED_CHAINS.filter(chain => !chain.testnet); - -export const SUPPORTED_MAINNET_CHAIN_IDS: ChainId[] = SUPPORTED_MAINNET_CHAINS.map(chain => chain.id); - -export const needsL1SecurityFeeChains = backendNetworks.networks - .filter((backendNetwork: BackendNetwork) => backendNetwork.opStack) - .map((backendNetwork: BackendNetwork) => parseInt(backendNetwork.id, 10)); - -export const chainsNativeAsset: Record = backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = backendNetwork.nativeAsset; - return acc; - }, - {} as Record -); - -export const chainsLabel: Record = backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = backendNetwork.label; - return acc; - }, - {} as Record -); - -export const chainsName: Record = backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = backendNetwork.name; - return acc; - }, - {} as Record -); - -export const chainsIdByName: Record = backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[backendNetwork.name] = parseInt(backendNetwork.id, 10); - return acc; - }, - {} as Record -); +const getBackendNetworks = (): BackendNetworksResponse => { + return queryClient.getQueryData(backendNetworksQueryKey()) ?? buildTimeNetworks; +}; + +const getBackendChains = (): Chain[] => { + const backendNetworks = getBackendNetworks(); + return transformBackendNetworksToChains(backendNetworks.networks); +}; + +export const getSupportedChains = (): Chain[] => { + const backendChains = getBackendChains(); + return IS_TEST ? [...backendChains, chainHardhat, chainHardhatOptimism] : backendChains; +}; + +export const getDefaultChains = (): Record => { + const supportedChains = getSupportedChains(); + return supportedChains.reduce( + (acc, chain) => { + acc[chain.id] = chain; + return acc; + }, + {} as Record + ); +}; + +export const getSupportedChainIds = (): ChainId[] => { + return getSupportedChains().map(chain => chain.id); +}; + +export const getSupportedMainnetChains = (): Chain[] => { + return getSupportedChains().filter(chain => !chain.testnet); +}; + +export const getSupportedMainnetChainIds = (): ChainId[] => { + return getSupportedMainnetChains().map(chain => chain.id); +}; + +export const getNeedsL1SecurityFeeChains = (): ChainId[] => { + const backendNetworks = getBackendNetworks(); + return backendNetworks.networks + .filter((backendNetwork: BackendNetwork) => backendNetwork.opStack) + .map((backendNetwork: BackendNetwork) => parseInt(backendNetwork.id, 10)); +}; + +export const getChainsNativeAsset = (): Record => { + const backendNetworks = getBackendNetworks(); + return backendNetworks.networks.reduce( + (acc, backendNetwork: BackendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = backendNetwork.nativeAsset; + return acc; + }, + {} as Record + ); +}; + +export const getChainsLabel = (): Record => { + const backendNetworks = getBackendNetworks(); + return backendNetworks.networks.reduce( + (acc, backendNetwork: BackendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = backendNetwork.label; + return acc; + }, + {} as Record + ); +}; + +export const getChainsName = (): Record => { + const backendNetworks = getBackendNetworks(); + return backendNetworks.networks.reduce( + (acc, backendNetwork: BackendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = backendNetwork.name; + return acc; + }, + {} as Record + ); +}; + +export const getChainsIdByName = (): Record => { + const backendNetworks = getBackendNetworks(); + return backendNetworks.networks.reduce( + (acc, backendNetwork: BackendNetwork) => { + acc[backendNetwork.name] = parseInt(backendNetwork.id, 10); + return acc; + }, + {} as Record + ); +}; const defaultGasSpeeds = (chainId: ChainId) => { switch (chainId) { @@ -78,13 +109,16 @@ const defaultGasSpeeds = (chainId: ChainId) => { } }; -export const chainsGasSpeeds: Record = backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = defaultGasSpeeds(parseInt(backendNetwork.id, 10)); - return acc; - }, - {} as Record -); +export const getChainsGasSpeeds = (): Record => { + const backendNetworks = getBackendNetworks(); + return backendNetworks.networks.reduce( + (acc, backendNetwork: BackendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = defaultGasSpeeds(parseInt(backendNetwork.id, 10)); + return acc; + }, + {} as Record + ); +}; const defaultPollingIntervals = (chainId: ChainId) => { switch (chainId) { @@ -98,13 +132,16 @@ const defaultPollingIntervals = (chainId: ChainId) => { } }; -export const chainsSwapPollingInterval: Record = backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = defaultPollingIntervals(parseInt(backendNetwork.id, 10)); - return acc; - }, - {} as Record -); +export const getChainsSwapPollingInterval = (): Record => { + const backendNetworks = getBackendNetworks(); + return backendNetworks.networks.reduce( + (acc, backendNetwork: BackendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = defaultPollingIntervals(parseInt(backendNetwork.id, 10)); + return acc; + }, + {} as Record + ); +}; const defaultSimplehashNetworks = (chainId: ChainId) => { switch (chainId) { @@ -139,15 +176,19 @@ const defaultSimplehashNetworks = (chainId: ChainId) => { } }; -export const chainsSimplehashNetwork: Record = backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = defaultSimplehashNetworks(parseInt(backendNetwork.id, 10)); - return acc; - }, - {} as Record -); +export const getChainsSimplehashNetwork = (): Record => { + const backendNetworks = getBackendNetworks(); + return backendNetworks.networks.reduce( + (acc, backendNetwork: BackendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = defaultSimplehashNetworks(parseInt(backendNetwork.id, 10)); + return acc; + }, + {} as Record + ); +}; const filterChainIdsByService = (servicePath: (services: BackendNetworkServices) => boolean): number[] => { + const backendNetworks = getBackendNetworks(); return backendNetworks.networks .filter((network: BackendNetwork) => { const services = network?.enabledServices; @@ -201,15 +242,16 @@ export const oldDefaultRPC: { [key in ChainId]?: string } = { [ChainId.degen]: process.env.DEGEN_MAINNET_RPC, }; -const chainsGasUnits = backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = backendNetwork.gasUnits; - return acc; - }, - {} as Record -); +export const getChainGasUnits = (chainId?: number): BackendNetwork['gasUnits'] => { + const backendNetworks = getBackendNetworks(); + const chainsGasUnits = backendNetworks.networks.reduce( + (acc, backendNetwork: BackendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = backendNetwork.gasUnits; + return acc; + }, + {} as Record + ); -export const getChainGasUnits = (chainId?: number) => { return (chainId ? chainsGasUnits[chainId] : undefined) || chainsGasUnits[ChainId.mainnet]; }; @@ -218,8 +260,8 @@ export const getChainDefaultRpc = (chainId: ChainId) => { case ChainId.mainnet: return useConnectedToHardhatStore.getState().connectedToHardhat ? 'http://127.0.0.1:8545' - : defaultChains[ChainId.mainnet].rpcUrls.default.http[0]; + : getDefaultChains()[ChainId.mainnet].rpcUrls.default.http[0]; default: - return defaultChains[chainId].rpcUrls.default.http[0]; + return getDefaultChains()[chainId].rpcUrls.default.http[0]; } }; diff --git a/src/components/DappBrowser/control-panel/ControlPanel.tsx b/src/components/DappBrowser/control-panel/ControlPanel.tsx index a7867ee6f68..07f52d92f7b 100644 --- a/src/components/DappBrowser/control-panel/ControlPanel.tsx +++ b/src/components/DappBrowser/control-panel/ControlPanel.tsx @@ -62,7 +62,7 @@ import { swapsStore } from '@/state/swaps/swapsStore'; import { userAssetsStore } from '@/state/assets/userAssets'; import { greaterThan } from '@/helpers/utilities'; import { ChainId } from '@/chains/types'; -import { chainsLabel, defaultChains } from '@/chains'; +import { getChainsLabel, getDefaultChains } from '@/chains'; const PAGES = { HOME: 'home', @@ -183,12 +183,12 @@ export const ControlPanel = () => { const { testnetsEnabled } = store.getState().settings; const allNetworkItems = useMemo(() => { - return Object.values(defaultChains) + return Object.values(getDefaultChains()) .filter(({ testnet }) => testnetsEnabled || !testnet) .map(chain => { return { IconComponent: , - label: chainsLabel[chain.id], + label: getChainsLabel()[chain.id], secondaryLabel: i18n.t( isConnected && chain.id === currentChainId ? i18n.l.dapp_browser.control_panel.connected diff --git a/src/components/DappBrowser/handleProviderRequest.ts b/src/components/DappBrowser/handleProviderRequest.ts index c8466c853a4..0bf86a5bae2 100644 --- a/src/components/DappBrowser/handleProviderRequest.ts +++ b/src/components/DappBrowser/handleProviderRequest.ts @@ -12,7 +12,7 @@ import { getDappMetadata } from '@/resources/metadata/dapp'; import { useAppSessionsStore } from '@/state/appSessions'; import { BigNumber } from '@ethersproject/bignumber'; import { ChainId } from '@/chains/types'; -import { chainsNativeAsset, defaultChains, SUPPORTED_CHAIN_IDS } from '@/chains'; +import { getChainsNativeAsset, getDefaultChains, getSupportedChainIds } from '@/chains'; export type ProviderRequestPayload = RequestArguments & { id: number; @@ -162,7 +162,7 @@ const messengerProviderRequestFn = async (messenger: Messenger, request: Provide const isSupportedChainId = (chainId: number | string) => { const numericChainId = BigNumber.from(chainId).toNumber(); - return !!SUPPORTED_CHAIN_IDS.find(chainId => chainId === numericChainId); + return !!getSupportedChainIds().find(chainId => chainId === numericChainId); }; const getActiveSession = ({ host }: { host: string }): ActiveSession => { const hostSessions = useAppSessionsStore.getState().getActiveSession({ host }); @@ -265,7 +265,7 @@ export const handleProviderRequestApp = ({ messenger, data, meta }: { messenger: callbackOptions?: CallbackOptions; }): { chainAlreadyAdded: boolean } => { const { chainId } = proposedChain; - if (defaultChains[Number(chainId)]) { + if (getDefaultChains()[Number(chainId)]) { // TODO - Open add / switch ethereum chain return { chainAlreadyAdded: true }; } else { @@ -320,7 +320,7 @@ export const handleProviderRequestApp = ({ messenger, data, meta }: { messenger: callbackOptions?: CallbackOptions; }) => { const { chainId } = proposedChain; - const supportedChainId = SUPPORTED_CHAIN_IDS.includes(Number(chainId)); + const supportedChainId = getSupportedChainIds().includes(Number(chainId)); if (supportedChainId) { const host = getDappHost(callbackOptions?.sender.url) || ''; const activeSession = getActiveSession({ host }); @@ -343,7 +343,7 @@ export const handleProviderRequestApp = ({ messenger, data, meta }: { messenger: onSwitchEthereumChainSupported, getProvider, getActiveSession, - getChainNativeCurrency: chainId => chainsNativeAsset[chainId], + getChainNativeCurrency: chainId => getChainsNativeAsset()[chainId], }); // @ts-ignore diff --git a/src/components/L2Disclaimer.js b/src/components/L2Disclaimer.js index 3e44506a096..a9b5b385194 100644 --- a/src/components/L2Disclaimer.js +++ b/src/components/L2Disclaimer.js @@ -10,7 +10,7 @@ import { darkModeThemeColors } from '@/styles/colors'; import * as lang from '@/languages'; import { isL2Chain } from '@/handlers/web3'; import { EthCoinIcon } from './coin-icon/EthCoinIcon'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; const L2Disclaimer = ({ chainId, @@ -57,7 +57,7 @@ const L2Disclaimer = ({ ? customText : lang.t(lang.l.expanded_state.asset.l2_disclaimer, { symbol, - network: chainsName[chainId], + network: getChainsName()[chainId], })} diff --git a/src/components/Transactions/TransactionDetailsCard.tsx b/src/components/Transactions/TransactionDetailsCard.tsx index 96d0af6092b..17d9f89688a 100644 --- a/src/components/Transactions/TransactionDetailsCard.tsx +++ b/src/components/Transactions/TransactionDetailsCard.tsx @@ -20,7 +20,7 @@ import { CARD_BORDER_WIDTH, EXPANDED_CARD_TOP_INSET, } from '@/components/Transactions/constants'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; interface TransactionDetailsCardProps { chainId: ChainId; @@ -93,7 +93,7 @@ export const TransactionDetailsCard = ({ - {} + {} {!!(meta?.to?.address || toAddress || showTransferToRow) && ( {i18n.t(i18n.l.walletconnect.simulation.simulation_card.messages.need_more_native, { symbol: walletBalance?.symbol, - network: chainsName[chainId], + network: getChainsName()[chainId], })} ) : ( diff --git a/src/components/cards/NFTOffersCard/Offer.tsx b/src/components/cards/NFTOffersCard/Offer.tsx index c9c0afd6f64..cc8113de7af 100644 --- a/src/components/cards/NFTOffersCard/Offer.tsx +++ b/src/components/cards/NFTOffersCard/Offer.tsx @@ -23,7 +23,7 @@ import { useExternalToken } from '@/resources/assets/externalAssetsQuery'; import { useAccountSettings } from '@/hooks'; import { Network } from '@/chains/types'; import { AddressOrEth } from '@/__swaps__/types/assets'; -import { chainsIdByName } from '@/chains'; +import { getChainsIdByName } from '@/chains'; const TWO_HOURS_MS = 2 * 60 * 60 * 1000; export const CELL_HORIZONTAL_PADDING = 7; @@ -68,7 +68,7 @@ export const Offer = ({ offer }: { offer: NftOffer }) => { const { colorMode } = useColorMode(); const theme = useTheme(); const { nativeCurrency } = useAccountSettings(); - const offerChainId = chainsIdByName[offer.network as Network]; + const offerChainId = getChainsIdByName()[offer.network as Network]; const { data: externalAsset } = useExternalToken({ address: offer.paymentToken.address as AddressOrEth, chainId: offerChainId, diff --git a/src/components/context-menu-buttons/ChainContextMenu.tsx b/src/components/context-menu-buttons/ChainContextMenu.tsx index 894a39642cb..4971f34f238 100644 --- a/src/components/context-menu-buttons/ChainContextMenu.tsx +++ b/src/components/context-menu-buttons/ChainContextMenu.tsx @@ -6,7 +6,7 @@ import * as i18n from '@/languages'; import { useUserAssetsStore } from '@/state/assets/userAssets'; import { showActionSheetWithOptions } from '@/utils'; import { ChainId } from '@/chains/types'; -import { chainsLabel, chainsName } from '@/chains'; +import { getChainsLabel, getChainsName } from '@/chains'; interface DefaultButtonOptions { iconColor?: TextProps['color']; @@ -58,10 +58,10 @@ export const ChainContextMenu = ({ const chainItems = balanceSortedChains.map(chainId => { return { actionKey: `${chainId}`, - actionTitle: chainsLabel[chainId], + actionTitle: getChainsLabel()[chainId], icon: { iconType: 'ASSET', - iconValue: `${chainsName[chainId]}Badge${chainId === ChainId.mainnet ? '' : 'NoShadow'}`, + iconValue: `${getChainsName()[chainId]}Badge${chainId === ChainId.mainnet ? '' : 'NoShadow'}`, }, }; }); @@ -111,7 +111,7 @@ export const ChainContextMenu = ({ const displayName = useMemo(() => { if (!selectedChainId) return allNetworksText; - const name = chainsLabel[selectedChainId]; + const name = getChainsLabel()[selectedChainId]; return name.endsWith(' Chain') ? name.slice(0, -6) : name; }, [allNetworksText, selectedChainId]); diff --git a/src/components/discover/DiscoverSearchInput.js b/src/components/discover/DiscoverSearchInput.js index 7d82759befe..038db1c34b6 100644 --- a/src/components/discover/DiscoverSearchInput.js +++ b/src/components/discover/DiscoverSearchInput.js @@ -13,7 +13,7 @@ import styled from '@/styled-thing'; import { margin, padding } from '@/styles'; import { deviceUtils } from '@/utils'; import DiscoverSheetContext from '@/screens/discover/DiscoverScreenContext'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; export const ExchangeSearchHeight = 40; const ExchangeSearchWidth = deviceUtils.dimensions.width - 30; @@ -132,7 +132,7 @@ const ExchangeSearch = ( const placeholder = useMemo(() => { if (!currentChainId) return placeholderText; return lang.t('button.exchange_search_placeholder_network', { - network: chainsName[currentChainId], + network: getChainsName()[currentChainId], }); }, [currentChainId, placeholderText]); diff --git a/src/components/exchange/ConfirmExchangeButton.js b/src/components/exchange/ConfirmExchangeButton.js index 2d1c786d13e..ee577b65a4c 100644 --- a/src/components/exchange/ConfirmExchangeButton.js +++ b/src/components/exchange/ConfirmExchangeButton.js @@ -14,7 +14,7 @@ import Routes from '@/navigation/routesNames'; import { lightModeThemeColors } from '@/styles'; import { useTheme } from '@/theme'; import handleSwapErrorCodes from '@/utils/exchangeErrorCodes'; -import { chainsNativeAsset } from '@/chains'; +import { getChainsNativeAsset } from '@/chains'; const NOOP = () => null; @@ -95,7 +95,7 @@ export default function ConfirmExchangeButton({ label = lang.t('button.confirm_exchange.insufficient_funds'); } else if (isSufficientGas != null && !isSufficientGas) { label = lang.t('button.confirm_exchange.insufficient_token', { - tokenName: chainsNativeAsset[chainId].symbol, + tokenName: getChainsNativeAsset()[chainId].symbol, }); } else if (!isValidGas && isGasReady) { label = lang.t('button.confirm_exchange.invalid_fee'); diff --git a/src/components/exchange/CurrencySelectModalHeader.tsx b/src/components/exchange/CurrencySelectModalHeader.tsx index 204946d9c4e..fd51bd8871e 100644 --- a/src/components/exchange/CurrencySelectModalHeader.tsx +++ b/src/components/exchange/CurrencySelectModalHeader.tsx @@ -8,7 +8,7 @@ import { useNavigation } from '@/navigation'; import Routes from '@/navigation/routesNames'; import RainbowCoinIcon from '../coin-icon/RainbowCoinIcon'; import { useTheme } from '@/theme'; -import { chainsIdByName } from '@/chains'; +import { getChainsIdByName } from '@/chains'; export const CurrencySelectModalHeaderHeight = 59; @@ -58,7 +58,7 @@ export default function CurrencySelectModalHeader({ defaultChains[chainId]) + .map(chainId => getDefaultChains()[chainId]) .map(chain => ({ actionKey: chain.id, - actionTitle: chainsLabel[chain.id], + actionTitle: getChainsLabel()[chain.id], icon: { iconType: 'ASSET', iconValue: `${isL2Chain({ chainId: chain.id }) ? `${chain.name}BadgeNoShadow` : 'ethereumBadge'}`, }, })); -const androidNetworkMenuItems = supportedSwapChainIds.map(chainId => defaultChains[chainId].id); +const androidNetworkMenuItems = supportedSwapChainIds.map(chainId => getDefaultChains()[chainId].id); const NetworkSwitcherv1 = ({ colors, @@ -93,7 +93,7 @@ const NetworkSwitcherv1 = ({ weight={prominent ? 'heavy' : 'bold'} > {lang.t('expanded_state.swap.network_switcher', { - network: chainsName[currentChainId], + network: getChainsName()[currentChainId], })} diff --git a/src/components/exchange/NetworkSwitcherv2.tsx b/src/components/exchange/NetworkSwitcherv2.tsx index a293f31be76..7e9bc0985b9 100644 --- a/src/components/exchange/NetworkSwitcherv2.tsx +++ b/src/components/exchange/NetworkSwitcherv2.tsx @@ -8,7 +8,7 @@ import { position } from '@rainbow-me/styles'; import { useTheme } from '@/theme'; import { EthCoinIcon } from '../coin-icon/EthCoinIcon'; import { ChainId } from '@/chains/types'; -import { chainsLabel, defaultChains, supportedSwapChainIds } from '@/chains'; +import { getChainsLabel, getDefaultChains, supportedSwapChainIds } from '@/chains'; const NetworkSwitcherv2 = ({ currentChainId, @@ -22,11 +22,11 @@ const NetworkSwitcherv2 = ({ const { colors } = useTheme(); const scrollViewRef = useRef(null); const networkMenuItems = useMemo(() => { - return Object.values(defaultChains) + return Object.values(getDefaultChains()) .filter(chain => supportedSwapChainIds.includes(chain.id)) .map(chain => ({ chainId: chain.id, - title: chainsLabel[chain.id], + title: getChainsLabel()[chain.id], })); }, []); diff --git a/src/components/exchange/exchangeAssetRowContextMenuProps.ts b/src/components/exchange/exchangeAssetRowContextMenuProps.ts index 63c776cebff..ec6cec49a79 100644 --- a/src/components/exchange/exchangeAssetRowContextMenuProps.ts +++ b/src/components/exchange/exchangeAssetRowContextMenuProps.ts @@ -4,7 +4,7 @@ import { NativeSyntheticEvent } from 'react-native'; import { setClipboard } from '../../hooks/useClipboard'; import { abbreviations, ethereumUtils, haptics, showActionSheetWithOptions } from '@/utils'; import { ChainId } from '@/chains/types'; -import { chainsIdByName } from '@/chains'; +import { getChainsIdByName } from '@/chains'; const buildBlockExplorerAction = (chainId: ChainId) => { const blockExplorerText = lang.t('exchange.coin_row.view_on', { @@ -44,7 +44,7 @@ export default function contextMenuProps(item: any, onCopySwapDetailsText: (addr }; const onPressAndroid = () => { - const blockExplorerText = `View on ${startCase(ethereumUtils.getBlockExplorer({ chainId: chainsIdByName[item?.network] }))}`; + const blockExplorerText = `View on ${startCase(ethereumUtils.getBlockExplorer({ chainId: getChainsIdByName()[item?.network] }))}`; const androidContractActions = [lang.t('wallet.action.copy_contract_address'), blockExplorerText, lang.t('button.cancel')]; showActionSheetWithOptions( @@ -59,13 +59,13 @@ export default function contextMenuProps(item: any, onCopySwapDetailsText: (addr handleCopyContractAddress(item?.address); } if (idx === 1) { - ethereumUtils.openTokenEtherscanURL({ address: item?.address, chainId: chainsIdByName[item?.network] }); + ethereumUtils.openTokenEtherscanURL({ address: item?.address, chainId: getChainsIdByName()[item?.network] }); } } ); }; - const blockExplorerAction = buildBlockExplorerAction(chainsIdByName[item?.network]); + const blockExplorerAction = buildBlockExplorerAction(getChainsIdByName()[item?.network]); const menuConfig = { menuItems: [ blockExplorerAction, @@ -81,7 +81,7 @@ export default function contextMenuProps(item: any, onCopySwapDetailsText: (addr if (actionKey === CoinRowActionsEnum.copyAddress) { handleCopyContractAddress(item?.address); } else if (actionKey === CoinRowActionsEnum.blockExplorer) { - ethereumUtils.openTokenEtherscanURL({ address: item?.address, chainId: chainsIdByName[item?.network] }); + ethereumUtils.openTokenEtherscanURL({ address: item?.address, chainId: getChainsIdByName()[item?.network] }); } }; return { diff --git a/src/components/expanded-state/AvailableNetworks.js b/src/components/expanded-state/AvailableNetworks.js index 29ac98354ca..aebc7fc213d 100644 --- a/src/components/expanded-state/AvailableNetworks.js +++ b/src/components/expanded-state/AvailableNetworks.js @@ -14,7 +14,7 @@ import Divider from '@/components/Divider'; import { Text } from '../text'; import { EthCoinIcon } from '../coin-icon/EthCoinIcon'; import { ChainId } from '@/chains/types'; -import { defaultChains } from '@/chains'; +import { getDefaultChains } from '@/chains'; const AvailableNetworksv1 = ({ asset, networks, hideDivider, marginBottom = 24, marginHorizontal = 19, prominent }) => { const { colors } = useTheme(); @@ -87,7 +87,7 @@ const AvailableNetworksv1 = ({ asset, networks, hideDivider, marginBottom = 24, availableNetworks: availableChainIds?.length, }) : lang.t('expanded_state.asset.available_network', { - availableNetwork: defaultChains[availableChainIds[0]]?.name, + availableNetwork: getDefaultChains()[availableChainIds[0]]?.name, })} diff --git a/src/components/expanded-state/AvailableNetworksv2.tsx b/src/components/expanded-state/AvailableNetworksv2.tsx index 9a53a2c605f..7a330cf260f 100644 --- a/src/components/expanded-state/AvailableNetworksv2.tsx +++ b/src/components/expanded-state/AvailableNetworksv2.tsx @@ -25,7 +25,7 @@ import { swapsStore } from '@/state/swaps/swapsStore'; import { InteractionManager } from 'react-native'; import { ChainId } from '@/chains/types'; import { getUniqueId } from '@/utils/ethereumUtils'; -import { chainsLabel, chainsName, defaultChains, supportedSwapChainIds } from '@/chains'; +import { getChainsLabel, getChainsName, getDefaultChains, supportedSwapChainIds } from '@/chains'; import { isL2Chain } from '@/handlers/web3'; const NOOP = () => null; @@ -95,7 +95,7 @@ const AvailableNetworksv2 = ({ address: newAsset.address as AddressOrEth, type: newAsset.type as AssetType, chainId: asset.chainId, - chainName: chainsName[asset.chainId], + chainName: getChainsName()[asset.chainId], isNativeAsset: false, native: {}, }, @@ -103,7 +103,7 @@ const AvailableNetworksv2 = ({ ...newAsset, uniqueId, chainId: asset.chainId, - chainName: chainsName[asset.chainId], + chainName: getChainsName()[asset.chainId], address: newAsset.address as AddressOrEth, highLiquidity: newAsset.highLiquidity ?? false, isRainbowCurated: newAsset.isRainbowCurated ?? false, @@ -134,7 +134,7 @@ const AvailableNetworksv2 = ({ } newAsset.uniqueId = getUniqueId(asset.address, chainId); - newAsset.type = chainsName[chainId]; + newAsset.type = getChainsName()[chainId]; navigate(Routes.EXCHANGE_MODAL, { params: { @@ -168,10 +168,10 @@ const AvailableNetworksv2 = ({ const networkMenuItems = supportedSwapChainIds .filter(chainId => chainId !== ChainId.mainnet) - .map(chainId => defaultChains[chainId]) + .map(chainId => getDefaultChains()[chainId]) .map(chain => ({ actionKey: chain.id, - actionTitle: chainsLabel[chain.id], + actionTitle: getChainsLabel()[chain.id], icon: { iconType: 'ASSET', iconValue: `${isL2Chain({ chainId: chain.id }) ? `${chain.name}BadgeNoShadow` : 'ethereumBadge'}`, @@ -236,7 +236,7 @@ const AvailableNetworksv2 = ({ availableNetworks: availableChainIds?.length, }) : lang.t('expanded_state.asset.available_networkv2', { - availableNetwork: chainsName[availableChainIds[0]], + availableNetwork: getChainsName()[availableChainIds[0]], })} diff --git a/src/components/expanded-state/SwapDetailsState.js b/src/components/expanded-state/SwapDetailsState.js index 19af013c189..cd05ed8d30c 100644 --- a/src/components/expanded-state/SwapDetailsState.js +++ b/src/components/expanded-state/SwapDetailsState.js @@ -15,10 +15,10 @@ import { useHeight, usePrevious, usePriceImpactDetails, useSwapCurrencies } from import { useNavigation } from '@/navigation'; import styled from '@/styled-thing'; import { padding, position } from '@/styles'; -import { abbreviations, ethereumUtils } from '@/utils'; +import { abbreviations } from '@/utils'; import { getCrosschainSwapServiceTime } from '@/handlers/swap'; import { SwapPriceImpactType } from '@/hooks/usePriceImpactDetails'; -import { chainsIdByName } from '@/chains'; +import { getChainsIdByName } from '@/chains'; const AnimatedContainer = styled(Animated.View)({ ...position.sizeAsObject('100%'), @@ -72,7 +72,7 @@ export default function SwapDetailsState({ confirmButtonProps, restoreFocusOnSwa const prevIsFocused = usePrevious(isFocused); const { params: { longFormHeight, currentNetwork, flashbotTransaction, isRefuelTx, onClose } = {} } = useRoute(); const { inputCurrency, outputCurrency } = useSwapCurrencies(); - const chainId = chainsIdByName[currentNetwork]; + const chainId = getChainsIdByName()[currentNetwork]; const { derivedValues: { inputAmount, outputAmount }, diff --git a/src/components/expanded-state/asset/ChartExpandedState.js b/src/components/expanded-state/asset/ChartExpandedState.js index d54bce38627..07d8ad3ddc1 100644 --- a/src/components/expanded-state/asset/ChartExpandedState.js +++ b/src/components/expanded-state/asset/ChartExpandedState.js @@ -36,7 +36,7 @@ import { Box } from '@/design-system'; import { useExternalToken } from '@/resources/assets/externalAssetsQuery'; import { bigNumberFormat } from '@/helpers/bigNumberFormat'; import { greaterThanOrEqualTo } from '@/helpers/utilities'; -import { chainsName, supportedSwapChainIds } from '@/chains'; +import { getChainsName, supportedSwapChainIds } from '@/chains'; import { ChainId } from '@/chains/types'; const defaultCarouselHeight = 60; @@ -166,7 +166,7 @@ export default function ChartExpandedState({ asset }) { chainId: asset.chainId, network: asset.network, address: asset.address, - mainnetAddress: asset?.networks?.[chainsName[ChainId.mainnet]]?.address, + mainnetAddress: asset?.networks?.[getChainsName()[ChainId.mainnet]]?.address, } : asset; }, [asset, genericAsset, hasBalance]); diff --git a/src/components/expanded-state/swap-details/SwapDetailsExchangeRow.js b/src/components/expanded-state/swap-details/SwapDetailsExchangeRow.js index 7e0cb82c02c..1f4ab05de44 100644 --- a/src/components/expanded-state/swap-details/SwapDetailsExchangeRow.js +++ b/src/components/expanded-state/swap-details/SwapDetailsExchangeRow.js @@ -10,10 +10,10 @@ import { usePrevious, useStepper } from '@/hooks'; import { ImgixImage } from '@/components/images'; import { getExchangeIconUrl, magicMemo } from '@/utils'; import { SocketBridges } from '@/references/swap/bridges'; -import { defaultChains } from '@/chains'; +import { getDefaultChains } from '@/chains'; const parseExchangeName = name => { - const networks = Object.values(defaultChains).map(network => network.name.toLowerCase()); + const networks = Object.values(getDefaultChains()).map(network => network.name.toLowerCase()); const removeNetworks = name => networks.some(network => name.toLowerCase().includes(network)) ? name.slice(name.indexOf('_') + 1, name.length) : name; diff --git a/src/components/expanded-state/swap-details/SwapDetailsRewardRow.tsx b/src/components/expanded-state/swap-details/SwapDetailsRewardRow.tsx index 017565f83bc..461f4c2c1c8 100644 --- a/src/components/expanded-state/swap-details/SwapDetailsRewardRow.tsx +++ b/src/components/expanded-state/swap-details/SwapDetailsRewardRow.tsx @@ -9,14 +9,14 @@ import { ChainBadge } from '@/components/coin-icon'; import { useTheme } from '@/theme'; import * as i18n from '@/languages'; import { ChainId } from '@/chains/types'; -import { chainsNativeAsset } from '@/chains'; +import { getChainsNativeAsset } from '@/chains'; export function SwapDetailsRewardRow({ reward }: { reward: Reward }) { const { navigate } = useNavigation(); const { isDarkMode } = useTheme(); const roundedAmount = Math.round(reward.amount * 1000) / 1000; - const nativeAsset = chainsNativeAsset[ChainId.optimism]; + const nativeAsset = getChainsNativeAsset()[ChainId.optimism]; const accentColor = isDarkMode ? nativeAsset.colors.primary : nativeAsset.colors.fallback || nativeAsset.colors.primary; return ( diff --git a/src/components/gas/GasSpeedButton.tsx b/src/components/gas/GasSpeedButton.tsx index 2b8669ef9c9..76adc8c0f58 100644 --- a/src/components/gas/GasSpeedButton.tsx +++ b/src/components/gas/GasSpeedButton.tsx @@ -27,7 +27,7 @@ import { IS_ANDROID } from '@/env'; import { ContextMenu } from '../context-menu'; import { EthCoinIcon } from '../coin-icon/EthCoinIcon'; import { ChainId } from '@/chains/types'; -import { chainsGasSpeeds } from '@/chains'; +import { getChainsGasSpeeds } from '@/chains'; import { ThemeContextProps, useTheme } from '@/theme'; import { OnPressMenuItemEventObject } from 'react-native-ios-context-menu'; import { ParsedAddressAsset } from '@/entities'; @@ -388,7 +388,7 @@ const GasSpeedButton = ({ const speedOptions = useMemo(() => { if (speeds) return speeds; - return chainsGasSpeeds[chainId]; + return getChainsGasSpeeds()[chainId]; }, [chainId, speeds]); const menuConfig = useMemo(() => { diff --git a/src/components/positions/PositionsCard.tsx b/src/components/positions/PositionsCard.tsx index 6a49be54cf8..c056f075476 100644 --- a/src/components/positions/PositionsCard.tsx +++ b/src/components/positions/PositionsCard.tsx @@ -18,7 +18,7 @@ import RainbowCoinIcon from '../coin-icon/RainbowCoinIcon'; import { useAccountSettings } from '@/hooks'; import { useExternalToken } from '@/resources/assets/externalAssetsQuery'; import { AddressOrEth } from '@/__swaps__/types/assets'; -import { chainsIdByName } from '@/chains'; +import { getChainsIdByName } from '@/chains'; type PositionCardProps = { position: RainbowPosition; @@ -33,7 +33,7 @@ type CoinStackToken = { function CoinIconForStack({ token }: { token: CoinStackToken }) { const theme = useTheme(); const { nativeCurrency } = useAccountSettings(); - const chainId = chainsIdByName[token.network]; + const chainId = getChainsIdByName()[token.network]; const { data: externalAsset } = useExternalToken({ address: token.address as AddressOrEth, chainId, currency: nativeCurrency }); return ( diff --git a/src/components/remote-promo-sheet/check-fns/hasSwapTxn.ts b/src/components/remote-promo-sheet/check-fns/hasSwapTxn.ts index 738e33cdf58..3a4de5277a6 100644 --- a/src/components/remote-promo-sheet/check-fns/hasSwapTxn.ts +++ b/src/components/remote-promo-sheet/check-fns/hasSwapTxn.ts @@ -1,5 +1,5 @@ import type { EthereumAddress, RainbowTransaction } from '@/entities'; -import { SUPPORTED_MAINNET_CHAIN_IDS } from '@/chains'; +import { getSupportedMainnetChainIds } from '@/chains'; import { queryClient } from '@/react-query/queryClient'; import store from '@/redux/store'; import { consolidatedTransactionsQueryKey } from '@/resources/transactions/consolidatedTransactions'; @@ -16,7 +16,7 @@ export const hasSwapTxn = async (): Promise => { const paginatedTransactionsKey = consolidatedTransactionsQueryKey({ address: accountAddress, currency: nativeCurrency, - chainIds: SUPPORTED_MAINNET_CHAIN_IDS, + chainIds: getSupportedMainnetChainIds(), }); const queryData = queryClient.getQueryData(paginatedTransactionsKey); const pages = queryData?.pages || []; diff --git a/src/components/sheet/sheet-action-buttons/SwapActionButton.tsx b/src/components/sheet/sheet-action-buttons/SwapActionButton.tsx index ac86628dcea..9ee773238c9 100644 --- a/src/components/sheet/sheet-action-buttons/SwapActionButton.tsx +++ b/src/components/sheet/sheet-action-buttons/SwapActionButton.tsx @@ -16,7 +16,7 @@ import { swapsStore } from '@/state/swaps/swapsStore'; import { InteractionManager } from 'react-native'; import { AddressOrEth, AssetType, ParsedSearchAsset } from '@/__swaps__/types/assets'; import exchangeModalTypes from '@/helpers/exchangeModalTypes'; -import { chainsIdByName, chainsName } from '@/chains'; +import { getChainsIdByName, getChainsName } from '@/chains'; type SwapActionButtonProps = { asset: RainbowToken; @@ -51,7 +51,7 @@ function SwapActionButton({ asset, color: givenColor, inputType, label, fromDisc return; } - const chainId = chainsIdByName[asset.network]; + const chainId = getChainsIdByName()[asset.network]; const uniqueId = `${asset.address}_${chainId}`; const userAsset = userAssetsStore.getState().userAssets.get(uniqueId); @@ -62,7 +62,7 @@ function SwapActionButton({ asset, color: givenColor, inputType, label, fromDisc address: asset.address as AddressOrEth, type: asset.type as AssetType, chainId, - chainName: chainsName[chainId], + chainName: getChainsName()[chainId], isNativeAsset: false, native: {}, }, @@ -70,7 +70,7 @@ function SwapActionButton({ asset, color: givenColor, inputType, label, fromDisc ...asset, uniqueId, chainId, - chainName: chainsName[chainId], + chainName: getChainsName()[chainId], address: asset.address as AddressOrEth, highLiquidity: asset.highLiquidity ?? false, isRainbowCurated: asset.isRainbowCurated ?? false, @@ -96,7 +96,7 @@ function SwapActionButton({ asset, color: givenColor, inputType, label, fromDisc ...nativeAssetForChain, uniqueId: `${nativeAssetForChain.address}_${chainId}`, chainId, - chainName: chainsName[chainId], + chainName: getChainsName()[chainId], address: nativeAssetForChain.address as AddressOrEth, type: nativeAssetForChain.type as AssetType, mainnetAddress: nativeAssetForChain.mainnet_address as AddressOrEth, diff --git a/src/components/toasts/TestnetToast.js b/src/components/toasts/TestnetToast.js index b31eb9befea..e266f408733 100644 --- a/src/components/toasts/TestnetToast.js +++ b/src/components/toasts/TestnetToast.js @@ -5,13 +5,13 @@ import Toast from './Toast'; import { useInternetStatus } from '@/hooks'; import { ChainId } from '@/chains/types'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; -import { chainsName, chainsNativeAsset } from '@/chains'; +import { getChainsName, getChainsNativeAsset } from '@/chains'; const TestnetToast = ({ chainId }) => { const { connectedToHardhat } = useConnectedToHardhatStore(); const isConnected = useInternetStatus(); - const nativeAsset = chainsNativeAsset[chainId]; - const name = chainsName[chainId]; + const nativeAsset = getChainsNativeAsset()[chainId]; + const name = getChainsName()[chainId]; const color = isDarkMode ? nativeAsset.colors.primary : nativeAsset.colors.fallback || nativeAsset.colors.primary; const [visible, setVisible] = useState(chainId !== ChainId.mainnet); const [networkName, setNetworkName] = useState(name); diff --git a/src/components/walletconnect-list/WalletConnectListItem.js b/src/components/walletconnect-list/WalletConnectListItem.js index 5d1055524c8..cee3f5cb237 100644 --- a/src/components/walletconnect-list/WalletConnectListItem.js +++ b/src/components/walletconnect-list/WalletConnectListItem.js @@ -24,7 +24,7 @@ import styled from '@/styled-thing'; import { padding } from '@/styles'; import { showActionSheetWithOptions } from '@/utils'; import { ChainId } from '@/chains/types'; -import { chainsIdByName, chainsLabel, chainsNativeAsset } from '@/chains'; +import { getChainsIdByName, getChainsLabel, getChainsNativeAsset } from '@/chains'; const ContainerPadding = 15; const VendorLogoIconSize = 50; @@ -70,11 +70,11 @@ export default function WalletConnectListItem({ account, chainId, dappIcon, dapp }, [wallets, walletNames, account]); const connectionNetworkInfo = useMemo(() => { - const nativeAsset = chainsNativeAsset[chainId]; + const nativeAsset = getChainsNativeAsset()[chainId]; return { id: chainId, color: isDarkMode ? nativeAsset.colors.primary : nativeAsset.colors.fallback || nativeAsset.colors.primary, - name: chainsLabel[chainId], + name: getChainsLabel()[chainId], }; }, [chainId, isDarkMode]); @@ -133,7 +133,7 @@ export default function WalletConnectListItem({ account, chainId, dappIcon, dapp handlePressChangeWallet(); } else if (actionKey.indexOf(NETWORK_MENU_ACTION_KEY_FILTER) !== -1) { const networkValue = actionKey.replace(NETWORK_MENU_ACTION_KEY_FILTER, ''); - walletConnectUpdateSessionConnectorByDappUrl(dappUrl, account, chainsIdByName[networkValue]); + walletConnectUpdateSessionConnectorByDappUrl(dappUrl, account, getChainsIdByName()[networkValue]); } }, [account, dappName, dappUrl, handlePressChangeWallet, walletConnectDisconnectAllByDappUrl, walletConnectUpdateSessionConnectorByDappUrl] diff --git a/src/components/walletconnect-list/WalletConnectV2ListItem.tsx b/src/components/walletconnect-list/WalletConnectV2ListItem.tsx index 56a9d22b4cf..4b4d2cc6474 100644 --- a/src/components/walletconnect-list/WalletConnectV2ListItem.tsx +++ b/src/components/walletconnect-list/WalletConnectV2ListItem.tsx @@ -25,7 +25,7 @@ import { Box, Inline } from '@/design-system'; import ChainBadge from '@/components/coin-icon/ChainBadge'; import { EthCoinIcon } from '../coin-icon/EthCoinIcon'; import { ChainId } from '@/chains/types'; -import { SUPPORTED_CHAIN_IDS } from '@/chains'; +import { getSupportedChainIds } from '@/chains'; const CONTAINER_PADDING = 15; const VENDOR_LOGO_ICON_SIZE = 50; @@ -78,7 +78,7 @@ export function WalletConnectV2ListItem({ session, reload }: { session: SessionT const chains = useMemo(() => namespaces?.eip155?.chains || [], [namespaces]); const chainIds = useMemo( () => - (chains?.map(chain => parseInt(chain.split(':')[1]))?.filter(chainId => SUPPORTED_CHAIN_IDS.includes(chainId)) ?? []) as ChainId[], + (chains?.map(chain => parseInt(chain.split(':')[1]))?.filter(chainId => getSupportedChainIds().includes(chainId)) ?? []) as ChainId[], [chains] ); diff --git a/src/featuresToUnlock/tokenGatedUtils.ts b/src/featuresToUnlock/tokenGatedUtils.ts index 014f178732a..1f9dfb4517b 100644 --- a/src/featuresToUnlock/tokenGatedUtils.ts +++ b/src/featuresToUnlock/tokenGatedUtils.ts @@ -3,7 +3,7 @@ import { EthereumAddress } from '@/entities'; import { getProvider } from '@/handlers/web3'; import { tokenGateCheckerAbi } from '@/references'; import { Network } from '@/chains/types'; -import { chainsIdByName } from '@/chains'; +import { getChainsIdByName } from '@/chains'; export type TokenGateCheckerNetwork = | Network.arbitrum @@ -29,7 +29,7 @@ export const checkIfWalletsOwnNft = async ( network: TokenGateCheckerNetwork, walletsToCheck: EthereumAddress[] ) => { - const p = await getProvider({ chainId: chainsIdByName[network] }); + const p = getProvider({ chainId: getChainsIdByName()[network] }); const contractInstance = new Contract(TOKEN_GATE_CHECKER_ADDRESS[network], tokenGateCheckerAbi, p); diff --git a/src/handlers/assets.ts b/src/handlers/assets.ts index 1fb241b4e6f..e53c7439c1f 100644 --- a/src/handlers/assets.ts +++ b/src/handlers/assets.ts @@ -3,12 +3,12 @@ import { Contract } from '@ethersproject/contracts'; import { erc20ABI } from '@/references'; import { convertAmountToBalanceDisplay, convertRawAmountToDecimalFormat } from '@/helpers/utilities'; import { ChainId } from '@/chains/types'; -import { chainsNativeAsset } from '@/chains'; +import { getChainsNativeAsset } from '@/chains'; import { isLowerCaseMatch } from '@/utils'; import { AddressOrEth } from '@/__swaps__/types/assets'; export function isNativeAsset(address: AddressOrEth | string, chainId: ChainId) { - return isLowerCaseMatch(chainsNativeAsset[chainId].address, address); + return isLowerCaseMatch(getChainsNativeAsset()[chainId].address, address); } export async function getOnchainAssetBalance({ address, decimals, symbol }: any, userAddress: any, chainId: ChainId, provider: any) { diff --git a/src/handlers/gasFees.ts b/src/handlers/gasFees.ts index 8a63ce38bf6..b8fa1d64be5 100644 --- a/src/handlers/gasFees.ts +++ b/src/handlers/gasFees.ts @@ -1,4 +1,4 @@ -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; import { RainbowFetchClient } from '../rainbow-fetch'; import { ChainId } from '@/chains/types'; @@ -11,4 +11,5 @@ const rainbowMeteorologyApi = new RainbowFetchClient({ timeout: 30000, // 30 secs }); -export const rainbowMeteorologyGetData = (chainId: ChainId) => rainbowMeteorologyApi.get(`/meteorology/v1/gas/${chainsName[chainId]}`, {}); +export const rainbowMeteorologyGetData = (chainId: ChainId) => + rainbowMeteorologyApi.get(`/meteorology/v1/gas/${getChainsName()[chainId]}`, {}); diff --git a/src/handlers/tokenSearch.ts b/src/handlers/tokenSearch.ts index be7293fa56b..a83c2261284 100644 --- a/src/handlers/tokenSearch.ts +++ b/src/handlers/tokenSearch.ts @@ -5,7 +5,7 @@ import { TokenSearchThreshold, TokenSearchTokenListId, TokenSearchUniswapAssetKe import { logger, RainbowError } from '@/logger'; import { EthereumAddress } from '@rainbow-me/swaps'; import { RainbowToken, TokenSearchToken } from '@/entities/tokens'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; type TokenSearchApiResponse = { data: TokenSearchToken[]; @@ -94,7 +94,7 @@ export const tokenSearch = async (searchParams: { return tokenSearch.data.data.map(token => { const networkKeys = Object.keys(token.networks); const chainId = Number(networkKeys[0]); - const network = chainsName[chainId]; + const network = getChainsName()[chainId]; return { ...token, chainId, diff --git a/src/handlers/web3.ts b/src/handlers/web3.ts index 8955ee41ddb..1efa4beca34 100644 --- a/src/handlers/web3.ts +++ b/src/handlers/web3.ts @@ -35,7 +35,7 @@ import { ethereumUtils } from '@/utils'; import { logger, RainbowError } from '@/logger'; import { IS_IOS, RPC_PROXY_API_KEY, RPC_PROXY_BASE_URL } from '@/env'; import { ChainId } from '@/chains/types'; -import { defaultChains } from '@/chains'; +import { getDefaultChains } from '@/chains'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; export enum TokenStandard { @@ -116,7 +116,7 @@ export const web3SetHttpProvider = async (chainId: ChainId): Promise { - return defaultChains[chainId].id !== ChainId.mainnet && !defaultChains[chainId].testnet; + return getDefaultChains()[chainId]?.id !== ChainId.mainnet && !getDefaultChains()[chainId]?.testnet; }; /** @@ -125,7 +125,7 @@ export const isL2Chain = ({ chainId = ChainId.mainnet }: { chainId?: ChainId }): * @return Whether or not the network is a testnet. */ export const isTestnetChain = ({ chainId = ChainId.mainnet }: { chainId?: ChainId }): boolean => { - return !!defaultChains[chainId].testnet; + return !!getDefaultChains()[chainId]?.testnet; }; // shoudl figure out better way to include this in networks @@ -152,7 +152,7 @@ export const getProvider = ({ chainId = ChainId.mainnet }: { chainId?: number }) const cachedProvider = chainsProviders.get(chainId); - const providerUrl = defaultChains[chainId]?.rpcUrls?.default?.http?.[0]; + const providerUrl = getDefaultChains()[chainId]?.rpcUrls?.default?.http?.[0]; if (cachedProvider && cachedProvider?.connection.url === providerUrl) { return cachedProvider; diff --git a/src/helpers/walletConnectNetworks.ts b/src/helpers/walletConnectNetworks.ts index 69fb67ee2c1..aab56343243 100644 --- a/src/helpers/walletConnectNetworks.ts +++ b/src/helpers/walletConnectNetworks.ts @@ -2,13 +2,13 @@ import store from '@/redux/store'; import { showActionSheetWithOptions } from '@/utils'; import * as i18n from '@/languages'; import { ChainId } from '@/chains/types'; -import { chainsLabel, defaultChains } from '@/chains'; +import { getChainsLabel, getDefaultChains } from '@/chains'; import { isL2Chain } from '@/handlers/web3'; import { MenuActionConfig } from 'react-native-ios-context-menu'; const androidNetworkActions = () => { const { testnetsEnabled } = store.getState().settings; - return Object.values(defaultChains) + return Object.values(getDefaultChains()) .filter(chain => testnetsEnabled || !chain.testnet) .map(chain => chain.id); }; @@ -18,11 +18,11 @@ export const NETWORK_MENU_ACTION_KEY_FILTER = 'switch-to-network-'; export const networksMenuItems: () => MenuActionConfig[] = () => { const { testnetsEnabled } = store.getState().settings; - return Object.values(defaultChains) + return Object.values(getDefaultChains()) .filter(chain => testnetsEnabled || !chain.testnet) .map(chain => ({ actionKey: `${NETWORK_MENU_ACTION_KEY_FILTER}${chain.id}`, - actionTitle: chainsLabel[chain.id], + actionTitle: getChainsLabel()[chain.id], icon: { iconType: 'ASSET', iconValue: `${isL2Chain({ chainId: chain.id }) ? `${chain.name}BadgeNoShadow` : 'ethereumBadge'}`, @@ -79,7 +79,7 @@ export const androidShowNetworksActionSheet = (callback: any) => { (idx: number) => { if (idx !== undefined) { const networkActions = androidNetworkActions(); - const chain = defaultChains[networkActions[idx]] || defaultChains[ChainId.mainnet]; + const chain = getDefaultChains()[networkActions[idx]] || getDefaultChains()[ChainId.mainnet]; callback({ chainId: chain.id }); } } diff --git a/src/hooks/useAccountTransactions.ts b/src/hooks/useAccountTransactions.ts index e1c47bf5de8..bf8d778acce 100644 --- a/src/hooks/useAccountTransactions.ts +++ b/src/hooks/useAccountTransactions.ts @@ -10,7 +10,7 @@ import { RainbowTransaction } from '@/entities'; import { pendingTransactionsStore, usePendingTransactionsStore } from '@/state/pendingTransactions'; import { nonceStore } from '@/state/nonces'; import { ChainId } from '@/chains/types'; -import { SUPPORTED_CHAIN_IDS, SUPPORTED_MAINNET_CHAIN_IDS } from '@/chains'; +import { getSupportedChainIds, getSupportedMainnetChainIds } from '@/chains'; export const NOE_PAGE = 30; @@ -43,7 +43,7 @@ export default function useAccountTransactions() { } return latestTxMap; }, - new Map(SUPPORTED_CHAIN_IDS.map(chainId => [chainId, null as RainbowTransaction | null])) + new Map(getSupportedChainIds().map(chainId => [chainId, null as RainbowTransaction | null])) ); watchForPendingTransactionsReportedByRainbowBackend({ currentAddress: accountAddress, @@ -61,7 +61,7 @@ export default function useAccountTransactions() { const { setNonce } = nonceStore.getState(); const { setPendingTransactions, pendingTransactions: storePendingTransactions } = pendingTransactionsStore.getState(); const pendingTransactions = storePendingTransactions[currentAddress] || []; - for (const chainId of SUPPORTED_MAINNET_CHAIN_IDS) { + for (const chainId of getSupportedMainnetChainIds()) { const latestTxConfirmedByBackend = latestTransactions.get(chainId); if (latestTxConfirmedByBackend) { const latestNonceConfirmedByBackend = latestTxConfirmedByBackend.nonce || 0; diff --git a/src/hooks/useCalculateGasLimit.ts b/src/hooks/useCalculateGasLimit.ts index 20ca1d3c825..b1a0fb0e954 100644 --- a/src/hooks/useCalculateGasLimit.ts +++ b/src/hooks/useCalculateGasLimit.ts @@ -10,7 +10,7 @@ import { GasFeeParamsBySpeed } from '@/entities'; import { StaticJsonRpcProvider } from '@ethersproject/providers'; import { useGas } from '@/hooks'; import { ChainId } from '@/chains/types'; -import { needsL1SecurityFeeChains } from '@/chains'; +import { getNeedsL1SecurityFeeChains } from '@/chains'; type CalculateGasLimitProps = { isMessageRequest: boolean; @@ -52,7 +52,7 @@ export const useCalculateGasLimit = ({ } finally { logger.debug('WC: Setting gas limit to', { gas: convertHexToString(gas) }, logger.DebugContext.walletconnect); - const needsL1SecurityFee = needsL1SecurityFeeChains.includes(chainId); + const needsL1SecurityFee = getNeedsL1SecurityFeeChains().includes(chainId); if (needsL1SecurityFee) { const l1GasFeeOptimism = await ethereumUtils.calculateL1FeeOptimism(txPayload, provider || web3Provider); updateTxFee(gas, null, l1GasFeeOptimism); diff --git a/src/hooks/useSearchCurrencyList.ts b/src/hooks/useSearchCurrencyList.ts index 027dd4cd7aa..6e32beb31d7 100644 --- a/src/hooks/useSearchCurrencyList.ts +++ b/src/hooks/useSearchCurrencyList.ts @@ -19,7 +19,7 @@ import { IS_TEST } from '@/env'; import { useFavorites } from '@/resources/favorites'; import { getUniqueId } from '@/utils/ethereumUtils'; import { ChainId } from '@/chains/types'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; type swapCurrencyListType = | 'verifiedAssets' @@ -200,7 +200,7 @@ const useSearchCurrencyList = (searchQuery: string, searchChainId = ChainId.main }, }, symbol, - network: chainsName[chainId], + network: getChainsName()[chainId], uniqueId, } as RainbowToken, ]; diff --git a/src/hooks/useSwapCurrencyList.ts b/src/hooks/useSwapCurrencyList.ts index eb08733578d..107cf8bc1e6 100644 --- a/src/hooks/useSwapCurrencyList.ts +++ b/src/hooks/useSwapCurrencyList.ts @@ -19,7 +19,7 @@ import { useFavorites } from '@/resources/favorites'; import { getUniqueId } from '@/utils/ethereumUtils'; import { logger } from '@/logger'; import { ChainId, Network } from '@/chains/types'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; type swapCurrencyListType = | 'verifiedAssets' @@ -205,7 +205,7 @@ const useSwapCurrencyList = (searchQuery: string, searchChainId = ChainId.mainne }, }, symbol, - network: chainsName[chainId], + network: getChainsName()[chainId], uniqueId, } as RainbowToken, ]; diff --git a/src/hooks/useSwapDerivedOutputs.ts b/src/hooks/useSwapDerivedOutputs.ts index 338ffd40c9c..d98649081fb 100644 --- a/src/hooks/useSwapDerivedOutputs.ts +++ b/src/hooks/useSwapDerivedOutputs.ts @@ -34,7 +34,7 @@ import { ethereumUtils } from '@/utils'; import { useDispatch, useSelector } from 'react-redux'; import { SwappableAsset } from '../entities/tokens'; import useAccountSettings from './useAccountSettings'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; const SWAP_POLLING_INTERVAL = 5000; @@ -464,7 +464,7 @@ export default function useSwapDerivedOutputs(type: string) { inputTokenName: inputCurrency?.name || '', inputTokenSymbol: inputCurrency?.symbol || '', liquiditySources: (data.tradeDetails?.protocols as any[]) || [], - network: chainsName[inputCurrency?.chainId], + network: getChainsName()[inputCurrency?.chainId], outputTokenAddress: outputCurrency?.address || '', outputTokenName: outputCurrency?.name || '', outputTokenSymbol: outputCurrency?.symbol || '', diff --git a/src/hooks/useWatchPendingTxs.ts b/src/hooks/useWatchPendingTxs.ts index 9d5c6fc825c..5f6827d0bff 100644 --- a/src/hooks/useWatchPendingTxs.ts +++ b/src/hooks/useWatchPendingTxs.ts @@ -17,7 +17,7 @@ import { getNftSortForAddress } from './useNFTsSortBy'; import { ChainId } from '@/chains/types'; import { staleBalancesStore } from '@/state/staleBalances'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; -import { SUPPORTED_MAINNET_CHAIN_IDS } from '@/chains'; +import { getSupportedMainnetChainIds } from '@/chains'; export const useWatchPendingTransactions = ({ address }: { address: string }) => { const { storePendingTransactions, setPendingTransactions } = usePendingTransactionsStore(state => ({ @@ -210,7 +210,7 @@ export const useWatchPendingTransactions = ({ address }: { address: string }) => queryKey: consolidatedTransactionsQueryKey({ address, currency: nativeCurrency, - chainIds: SUPPORTED_MAINNET_CHAIN_IDS, + chainIds: getSupportedMainnetChainIds(), }), }); @@ -220,7 +220,7 @@ export const useWatchPendingTransactions = ({ address }: { address: string }) => queryKey: consolidatedTransactionsQueryKey({ address, currency: nativeCurrency, - chainIds: SUPPORTED_MAINNET_CHAIN_IDS, + chainIds: getSupportedMainnetChainIds(), }), }); }, 2000); diff --git a/src/navigation/config.tsx b/src/navigation/config.tsx index fbe583c44b8..0e81ff55198 100644 --- a/src/navigation/config.tsx +++ b/src/navigation/config.tsx @@ -29,7 +29,7 @@ import { IS_ANDROID } from '@/env'; import { SignTransactionSheetRouteProp } from '@/screens/SignTransactionSheet'; import { RequestSource } from '@/utils/requestNavigationHandlers'; import { ChainId } from '@/chains/types'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; export const sharedCoolModalTopOffset = safeAreaInsetValues.top; @@ -491,7 +491,7 @@ export const ensAdditionalRecordsSheetConfig: PartialNavigatorConfigOptions = { }; export const explainSheetConfig: PartialNavigatorConfigOptions = { - options: ({ route: { params = { network: chainsName[ChainId.mainnet] } } }) => { + options: ({ route: { params = { network: getChainsName()[ChainId.mainnet] } } }) => { // @ts-ignore const explainerConfig = explainers(params.network)[params?.type]; return buildCoolModalConfig({ diff --git a/src/raps/actions/claimBridge.ts b/src/raps/actions/claimBridge.ts index e410d7c1565..876d2c12e70 100644 --- a/src/raps/actions/claimBridge.ts +++ b/src/raps/actions/claimBridge.ts @@ -14,12 +14,12 @@ import { REFERRER_CLAIM } from '@/references'; import { addNewTransaction } from '@/state/pendingTransactions'; import ethereumUtils from '@/utils/ethereumUtils'; import { AddressZero } from '@ethersproject/constants'; -import { CrosschainQuote, QuoteError, SwapType, getClaimBridgeQuote } from '@rainbow-me/swaps'; +import { CrosschainQuote, QuoteError, getClaimBridgeQuote } from '@rainbow-me/swaps'; import { Address } from 'viem'; import { ActionProps } from '../references'; import { executeCrosschainSwap } from './crosschainSwap'; import { ChainId } from '@/chains/types'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; // This action is used to bridge the claimed funds to another chain export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps<'claimBridge'>) { @@ -160,7 +160,7 @@ export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps const typedAssetToBuy: ParsedAddressAsset = { ...parameters.assetToBuy, - network: chainsName[parameters.assetToBuy.chainId], + network: getChainsName()[parameters.assetToBuy.chainId], chainId: parameters.assetToBuy.chainId, colors: undefined, networks: undefined, @@ -168,7 +168,7 @@ export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps }; const typedAssetToSell = { ...parameters.assetToSell, - network: chainsName[parameters.assetToSell.chainId], + network: getChainsName()[parameters.assetToSell.chainId], chainId: parameters.assetToSell.chainId, colors: undefined, networks: undefined, @@ -196,7 +196,7 @@ export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps from: bridgeQuote.from, to: bridgeQuote.to as Address, hash: swap.hash as TxHash, - network: chainsName[parameters.chainId], + network: getChainsName()[parameters.chainId], nonce: swap.nonce, status: TransactionStatus.pending, type: 'bridge', diff --git a/src/raps/actions/crosschainSwap.ts b/src/raps/actions/crosschainSwap.ts index 04ba753930a..2ae2724b216 100644 --- a/src/raps/actions/crosschainSwap.ts +++ b/src/raps/actions/crosschainSwap.ts @@ -24,7 +24,7 @@ import { AddysNetworkDetails, ParsedAsset } from '@/resources/assets/types'; import { ExtendedAnimatedAssetWithColors } from '@/__swaps__/types/assets'; import { Screens, TimeToSignOperation, performanceTracking } from '@/state/performance/performance'; import { swapsStore } from '@/state/swaps/swapsStore'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; const getCrosschainSwapDefaultGasLimit = (quote: CrosschainQuote) => quote?.routes?.[0]?.userTxs?.[0]?.gasFees?.gasLimit; @@ -183,7 +183,7 @@ export const crosschainSwap = async ({ const assetToBuy = { ...parameters.assetToBuy, - network: chainsName[parameters.assetToBuy.chainId], + network: getChainsName()[parameters.assetToBuy.chainId], networks: parameters.assetToBuy.networks as Record, colors: parameters.assetToBuy.colors as TokenColors, price: nativePriceForAssetToBuy, @@ -191,7 +191,7 @@ export const crosschainSwap = async ({ const assetToSell = { ...parameters.assetToSell, - network: chainsName[parameters.assetToSell.chainId], + network: getChainsName()[parameters.assetToSell.chainId], networks: parameters.assetToSell.networks as Record, colors: parameters.assetToSell.colors as TokenColors, price: nativePriceForAssetToSell, @@ -224,7 +224,7 @@ export const crosschainSwap = async ({ ], gasLimit, hash: swap.hash as TxHash, - network: chainsName[parameters.chainId], + network: getChainsName()[parameters.chainId], nonce: swap.nonce, status: TransactionStatus.pending, type: 'swap', diff --git a/src/raps/actions/swap.ts b/src/raps/actions/swap.ts index d04d5cd254f..2c260ca36fd 100644 --- a/src/raps/actions/swap.ts +++ b/src/raps/actions/swap.ts @@ -43,7 +43,7 @@ import { AddysNetworkDetails, ParsedAsset } from '@/resources/assets/types'; import { ExtendedAnimatedAssetWithColors } from '@/__swaps__/types/assets'; import { Screens, TimeToSignOperation, performanceTracking } from '@/state/performance/performance'; import { swapsStore } from '@/state/swaps/swapsStore'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; const WRAP_GAS_PADDING = 1.002; @@ -314,7 +314,7 @@ export const swap = async ({ const assetToBuy = { ...parameters.assetToBuy, - network: chainsName[parameters.assetToBuy.chainId], + network: getChainsName()[parameters.assetToBuy.chainId], networks: parameters.assetToBuy.networks as Record, colors: parameters.assetToBuy.colors as TokenColors, price: nativePriceForAssetToBuy, @@ -322,7 +322,7 @@ export const swap = async ({ const assetToSell = { ...parameters.assetToSell, - network: chainsName[parameters.assetToSell.chainId], + network: getChainsName()[parameters.assetToSell.chainId], networks: parameters.assetToSell.networks as Record, colors: parameters.assetToSell.colors as TokenColors, price: nativePriceForAssetToSell, @@ -355,7 +355,7 @@ export const swap = async ({ ], gasLimit, hash: swap.hash as TxHash, - network: chainsName[parameters.chainId], + network: getChainsName()[parameters.chainId], nonce: swap.nonce, status: TransactionStatus.pending, type: 'swap', diff --git a/src/raps/actions/unlock.ts b/src/raps/actions/unlock.ts index af0bce33217..ad47b9c79d2 100644 --- a/src/raps/actions/unlock.ts +++ b/src/raps/actions/unlock.ts @@ -20,7 +20,7 @@ import { overrideWithFastSpeedIfNeeded } from './../utils'; import { toHex } from '@/__swaps__/utils/hex'; import { TokenColors } from '@/graphql/__generated__/metadata'; import { ParsedAsset } from '@/resources/assets/types'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; export const getAssetRawAllowance = async ({ owner, @@ -270,7 +270,7 @@ export const unlock = async ({ const transaction = { asset: { ...assetToUnlock, - network: chainsName[assetToUnlock.chainId], + network: getChainsName()[assetToUnlock.chainId], colors: assetToUnlock.colors as TokenColors, } as ParsedAsset, data: approval.data, @@ -279,7 +279,7 @@ export const unlock = async ({ from: parameters.fromAddress, to: assetAddress, hash: approval.hash as TxHash, - network: chainsName[chainId], + network: getChainsName()[chainId], chainId: approval.chainId, nonce: approval.nonce, status: TransactionStatus.pending, diff --git a/src/rapsV2/actions/claimTransactionClaimableAction.ts b/src/rapsV2/actions/claimTransactionClaimableAction.ts index 7874b9e295b..bcbc7d25522 100644 --- a/src/rapsV2/actions/claimTransactionClaimableAction.ts +++ b/src/rapsV2/actions/claimTransactionClaimableAction.ts @@ -4,7 +4,7 @@ import { getProvider } from '@/handlers/web3'; import { RainbowError } from '@/logger'; import { addNewTransaction } from '@/state/pendingTransactions'; import { NewTransaction, TransactionStatus } from '@/entities'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; export async function claimTransactionClaimable({ parameters, wallet }: ActionProps<'claimTransactionClaimableAction'>) { const { claimTx, asset } = parameters; @@ -23,7 +23,7 @@ export async function claimTransactionClaimable({ parameters, wallet }: ActionPr to: result.result.to ?? null, chainId: result.result.chainId, hash: result.result.hash, - network: chainsName[result.result.chainId], + network: getChainsName()[result.result.chainId], status: TransactionStatus.pending, type: 'claim', nonce: result.result.nonce, diff --git a/src/redux/gas.ts b/src/redux/gas.ts index c5f8cd2fd1a..ba62c877681 100644 --- a/src/redux/gas.ts +++ b/src/redux/gas.ts @@ -38,7 +38,7 @@ import { ethUnits } from '@/references'; import { ethereumUtils, gasUtils } from '@/utils'; import { ChainId } from '@/chains/types'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; -import { chainsSwapPollingInterval, meteorologySupportedChainIds, needsL1SecurityFeeChains } from '@/chains'; +import { getChainsSwapPollingInterval, meteorologySupportedChainIds, getNeedsL1SecurityFeeChains } from '@/chains'; import { MeteorologyLegacyResponse, MeteorologyResponse } from '@/entities/gas'; import { addBuffer } from '@/helpers/utilities'; @@ -375,7 +375,7 @@ export const gasPricesStartPolling = } else { try { // OP chains have an additional fee we need to load - if (needsL1SecurityFeeChains.includes(chainId)) { + if (getNeedsL1SecurityFeeChains().includes(chainId)) { dataIsReady = l1GasFeeOptimism !== null; } const meteorologyGasParams = await getMeteorologyGasParams(chainId); @@ -511,7 +511,7 @@ export const gasPricesStartPolling = } }; - const pollingInterval = chainsSwapPollingInterval[chainId]; + const pollingInterval = getChainsSwapPollingInterval()[chainId]; watchGasPrices(chainId, pollingInterval); }; @@ -547,7 +547,7 @@ export const gasUpdateTxFee = const { defaultGasLimit, gasLimit, gasFeeParamsBySpeed, selectedGasFee, chainId, currentBlockParams } = getState().gas; const { nativeCurrency } = getState().settings; - if (isEmpty(gasFeeParamsBySpeed) || (needsL1SecurityFeeChains.includes(chainId) && l1GasFeeOptimism === null)) { + if (isEmpty(gasFeeParamsBySpeed) || (getNeedsL1SecurityFeeChains().includes(chainId) && l1GasFeeOptimism === null)) { // if fee prices not ready, we need to store the gas limit for future calculations // the rest is as the initial state value if (updatedGasLimit) { diff --git a/src/redux/walletconnect.ts b/src/redux/walletconnect.ts index cf18a5b301a..2616d7e5462 100644 --- a/src/redux/walletconnect.ts +++ b/src/redux/walletconnect.ts @@ -33,7 +33,7 @@ import { Verify } from '@walletconnect/types'; import { RequestSource, handleWalletConnectRequest } from '@/utils/requestNavigationHandlers'; import { ChainId } from '@/chains/types'; import { Address } from 'viem'; -import { SUPPORTED_CHAIN_IDS } from '@/chains'; +import { getSupportedChainIds } from '@/chains'; // -- Variables --------------------------------------- // let showRedirectSheetThreshold = 300; @@ -477,7 +477,7 @@ const listenOnNewMessages = // @ts-expect-error "_chainId" is private. const currentChainId = Number(walletConnector._chainId); const numericChainId = Number(convertHexToString(chainId)); - if (SUPPORTED_CHAIN_IDS.includes(numericChainId)) { + if (getSupportedChainIds().includes(numericChainId)) { dispatch(walletConnectSetPendingRedirect()); Navigation.handleAction(Routes.WALLET_CONNECT_APPROVAL_SHEET, { callback: async (approved: boolean) => { diff --git a/src/resources/addys/claimables/query.ts b/src/resources/addys/claimables/query.ts index 311da649a50..b13d2d548af 100644 --- a/src/resources/addys/claimables/query.ts +++ b/src/resources/addys/claimables/query.ts @@ -9,7 +9,7 @@ import { parseClaimables } from './utils'; import { useRemoteConfig } from '@/model/remoteConfig'; import { CLAIMABLES, useExperimentalFlag } from '@/config'; import { IS_TEST } from '@/env'; -import { SUPPORTED_CHAIN_IDS } from '@/chains'; +import { getSupportedChainIds } from '@/chains'; export const ADDYS_BASE_URL = 'https://addys.p.rainbow.me/v3'; @@ -41,7 +41,7 @@ type ClaimablesQueryKey = ReturnType; async function claimablesQueryFunction({ queryKey: [{ address, currency }] }: QueryFunctionArgs) { try { - const url = `/${SUPPORTED_CHAIN_IDS.join(',')}/${address}/claimables`; + const url = `/${getSupportedChainIds().join(',')}/${address}/claimables`; const { data } = await addysHttp.get(url, { params: { currency: currency.toLowerCase(), diff --git a/src/resources/addys/claimables/utils.ts b/src/resources/addys/claimables/utils.ts index 5b047644c97..d60b2ac966f 100644 --- a/src/resources/addys/claimables/utils.ts +++ b/src/resources/addys/claimables/utils.ts @@ -3,7 +3,7 @@ import { AddysClaimable, Claimable } from './types'; import { convertRawAmountToBalance, convertRawAmountToNativeDisplay, greaterThan } from '@/helpers/utilities'; import { parseAsset } from '@/resources/assets/assets'; import { Network } from '@/chains/types'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; export const parseClaimables = (claimables: AddysClaimable[], currency: NativeCurrencyKey): Claimable[] => { return claimables @@ -20,7 +20,7 @@ export const parseClaimables = (claimables: AddysClaimable[], currency: NativeCu address: claimable.asset.asset_code, asset: { ...claimable.asset, - network: chainsName[claimable.network] as Network, + network: getChainsName()[claimable.network] as Network, transferable: claimable.asset.transferable ?? false, }, }), diff --git a/src/resources/assets/UserAssetsQuery.ts b/src/resources/assets/UserAssetsQuery.ts index c584448a355..9c549400cdf 100644 --- a/src/resources/assets/UserAssetsQuery.ts +++ b/src/resources/assets/UserAssetsQuery.ts @@ -11,7 +11,7 @@ import { fetchHardhatBalances } from './hardhatAssets'; import { AddysAccountAssetsMeta, AddysAccountAssetsResponse, RainbowAddressAssets } from './types'; import { Network } from '@/chains/types'; import { staleBalancesStore } from '@/state/staleBalances'; -import { SUPPORTED_MAINNET_CHAIN_IDS } from '@/chains'; +import { getSupportedMainnetChainIds } from '@/chains'; // /////////////////////////////////////////////// // Query Types @@ -80,7 +80,7 @@ async function userAssetsQueryFunction({ const { erroredChainIds, results } = await fetchAndParseUserAssetsForChainIds({ address, currency, - chainIds: SUPPORTED_MAINNET_CHAIN_IDS, + chainIds: getSupportedMainnetChainIds(), staleBalanceParam, }); let parsedSuccessResults = results; diff --git a/src/resources/assets/assets.ts b/src/resources/assets/assets.ts index b6c6b761cf7..03ddc3c411d 100644 --- a/src/resources/assets/assets.ts +++ b/src/resources/assets/assets.ts @@ -13,7 +13,7 @@ import { RainbowPositions } from '@/resources/defi/types'; import { AddysAddressAsset, AddysAsset, ParsedAsset, RainbowAddressAssets } from './types'; import { getUniqueId } from '@/utils/ethereumUtils'; import { ChainId } from '@/chains/types'; -import { chainsIdByName } from '@/chains'; +import { getChainsIdByName } from '@/chains'; const storage = new MMKV(); @@ -40,7 +40,7 @@ export const filterPositionsData = ( export function parseAsset({ address, asset }: { address: string; asset: AddysAsset }): ParsedAsset { const network = asset?.network; - const chainId = chainsIdByName[network]; + const chainId = getChainsIdByName()[network]; const mainnetAddress = asset?.networks?.[ChainId.mainnet]?.address; const uniqueId = getUniqueId(address, chainId); diff --git a/src/resources/assets/hardhatAssets.ts b/src/resources/assets/hardhatAssets.ts index 8945031038c..e2cd84969e2 100644 --- a/src/resources/assets/hardhatAssets.ts +++ b/src/resources/assets/hardhatAssets.ts @@ -9,7 +9,7 @@ import { AddressOrEth, UniqueId, ZerionAsset } from '@/__swaps__/types/assets'; import { AddressZero } from '@ethersproject/constants'; import chainAssetsByChainId from '@/references/testnet-assets-by-chain'; import { ChainId, ChainName, Network } from '@/chains/types'; -import { SUPPORTED_CHAIN_IDS } from '@/chains'; +import { getSupportedChainIds } from '@/chains'; const MAINNET_BALANCE_CHECKER = '0x4dcf4562268dd384fe814c00fad239f06c2a0c2b'; @@ -125,6 +125,6 @@ export const fetchHardhatBalancesByChainId = async ( return { assets: updatedAssets, - chainIdsInResponse: SUPPORTED_CHAIN_IDS, + chainIdsInResponse: getSupportedChainIds(), }; }; diff --git a/src/resources/assets/useUserAsset.ts b/src/resources/assets/useUserAsset.ts index e6033701e58..e5260de9cdd 100644 --- a/src/resources/assets/useUserAsset.ts +++ b/src/resources/assets/useUserAsset.ts @@ -4,7 +4,7 @@ import { useUserAssets } from '@/resources/assets/UserAssetsQuery'; import { selectUserAssetWithUniqueId } from '@/resources/assets/assetSelectors'; import { getUniqueId } from '@/utils/ethereumUtils'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; -import { chainsNativeAsset } from '@/chains'; +import { getChainsNativeAsset } from '@/chains'; export function useUserAsset(uniqueId: string) { const { accountAddress, nativeCurrency } = useAccountSettings(); @@ -23,7 +23,7 @@ export function useUserAsset(uniqueId: string) { } export function useUserNativeNetworkAsset(chainId: ChainId) { - const nativeCurrency = chainsNativeAsset[chainId]; + const nativeCurrency = getChainsNativeAsset()[chainId]; const { address } = nativeCurrency; const uniqueId = getUniqueId(address, chainId); return useUserAsset(uniqueId); diff --git a/src/resources/defi/PositionsQuery.ts b/src/resources/defi/PositionsQuery.ts index 0bd90cffb14..5dfa50f4c7c 100644 --- a/src/resources/defi/PositionsQuery.ts +++ b/src/resources/defi/PositionsQuery.ts @@ -7,12 +7,12 @@ import { rainbowFetch } from '@/rainbow-fetch'; import { ADDYS_API_KEY } from 'react-native-dotenv'; import { AddysPositionsResponse, PositionsArgs } from './types'; import { parsePositions } from './utils'; -import { SUPPORTED_CHAIN_IDS } from '@/chains'; +import { getSupportedChainIds } from '@/chains'; import { DEFI_POSITIONS, useExperimentalFlag } from '@/config'; import { IS_TEST } from '@/env'; export const buildPositionsUrl = (address: string) => { - const networkString = SUPPORTED_CHAIN_IDS.join(','); + const networkString = getSupportedChainIds().join(','); return `https://addys.p.rainbow.me/v3/${networkString}/${address}/positions`; }; diff --git a/src/resources/defi/utils.ts b/src/resources/defi/utils.ts index 3adc0a45c2e..b58cb848481 100644 --- a/src/resources/defi/utils.ts +++ b/src/resources/defi/utils.ts @@ -14,7 +14,7 @@ import { import { add, convertAmountToNativeDisplay, convertRawAmountToNativeDisplay, subtract } from '@/helpers/utilities'; import { maybeSignUri } from '@/handlers/imgix'; import { ethereumUtils } from '@/utils'; -import { chainsIdByName } from '@/chains'; +import { getChainsIdByName } from '@/chains'; export const parsePosition = (position: Position, currency: NativeCurrencyKey): RainbowPosition => { let totalDeposits = '0'; @@ -135,7 +135,7 @@ export const parsePositions = (data: AddysPositionsResponse, currency: NativeCur parsedPositions.forEach(({ deposits }) => { deposits.forEach(({ asset }) => { - const uniqueId = ethereumUtils.getUniqueId(asset.asset_code.toLowerCase(), chainsIdByName[asset.network]); + const uniqueId = ethereumUtils.getUniqueId(asset.asset_code.toLowerCase(), getChainsIdByName()[asset.network]); positionTokens.push(uniqueId); }); }); diff --git a/src/resources/favorites.ts b/src/resources/favorites.ts index 82413ed4ac7..90e36bb4036 100644 --- a/src/resources/favorites.ts +++ b/src/resources/favorites.ts @@ -8,7 +8,7 @@ import { promiseUtils } from '@/utils'; import { useQuery } from '@tanstack/react-query'; import { omit } from 'lodash'; import { externalTokenQueryKey, fetchExternalToken } from './assets/externalAssetsQuery'; -import { chainsIdByName, chainsName } from '@/chains'; +import { getChainsIdByName, getChainsName } from '@/chains'; import { analyticsV2 } from '@/analytics'; export const favoritesQueryKey = createQueryKey('favorites', {}, { persisterVersion: 4 }); @@ -23,7 +23,7 @@ const getUniqueId = (address: AddressOrEth, chainId: ChainId) => getStandardized async function fetchMetadata(addresses: string[], chainId = ChainId.mainnet) { const favoritesMetadata: Record = {}; const newFavoritesMeta: Record = {}; - const network = chainsName[chainId]; + const network = getChainsName()[chainId]; // Map addresses to an array of promises returned by fetchExternalToken const fetchPromises: Promise[] = addresses.map(async address => { @@ -96,7 +96,7 @@ export async function refreshFavorites() { const updatedMetadataByNetwork = await Promise.all( Object.entries(favoritesByNetwork).map(async ([network, networkFavorites]) => - fetchMetadata(networkFavorites, chainsIdByName[network as Network]) + fetchMetadata(networkFavorites, getChainsIdByName()[network as Network]) ) ); diff --git a/src/resources/nfts/simplehash/index.ts b/src/resources/nfts/simplehash/index.ts index 83ffac0574b..c5ffd198a0a 100644 --- a/src/resources/nfts/simplehash/index.ts +++ b/src/resources/nfts/simplehash/index.ts @@ -4,7 +4,7 @@ import { SimpleHashListing, SimpleHashNFT, SimpleHashMarketplaceId } from '@/res import { UniqueAsset } from '@/entities'; import { RainbowError, logger } from '@/logger'; import { ChainId } from '@/chains/types'; -import { chainsSimplehashNetwork } from '@/chains'; +import { getChainsSimplehashNetwork } from '@/chains'; export const START_CURSOR = 'start'; @@ -19,7 +19,7 @@ export async function fetchSimpleHashNFT( tokenId: string, chainId: Omit = ChainId.mainnet ): Promise { - const simplehashNetwork = chainsSimplehashNetwork[chainId as ChainId]; + const simplehashNetwork = getChainsSimplehashNetwork()[chainId as ChainId]; if (!simplehashNetwork) { logger.warn(`[simplehash]: no SimpleHash for chainId: ${chainId}`); @@ -44,7 +44,7 @@ export async function fetchSimpleHashNFTListing( // array of all eth listings on OpenSea for this token let listings: SimpleHashListing[] = []; let cursor = START_CURSOR; - const simplehashNetwork = chainsSimplehashNetwork[chainId as ChainId]; + const simplehashNetwork = getChainsSimplehashNetwork()[chainId as ChainId]; if (!simplehashNetwork) { logger.warn(`[simplehash]: no SimpleHash for chainId: ${chainId}`); @@ -83,7 +83,7 @@ export async function fetchSimpleHashNFTListing( * @param nft */ export async function refreshNFTContractMetadata(nft: UniqueAsset) { - const simplehashNetwork = chainsSimplehashNetwork[nft.isPoap ? ChainId.gnosis : nft.chainId]; + const simplehashNetwork = getChainsSimplehashNetwork()[nft.isPoap ? ChainId.gnosis : nft.chainId]; if (!simplehashNetwork) { logger.warn(`[simplehash]: no SimpleHash for chainId: ${nft.chainId}`); @@ -135,7 +135,7 @@ export async function refreshNFTContractMetadata(nft: UniqueAsset) { * @param nft */ export async function reportNFT(nft: UniqueAsset) { - const simplehashNetwork = chainsSimplehashNetwork[nft.isPoap ? ChainId.gnosis : nft.chainId]; + const simplehashNetwork = getChainsSimplehashNetwork()[nft.isPoap ? ChainId.gnosis : nft.chainId]; if (!simplehashNetwork) { logger.warn(`[simplehash]: no SimpleHash for chainId: ${nft.chainId}`); diff --git a/src/resources/nfts/simplehash/utils.ts b/src/resources/nfts/simplehash/utils.ts index ab3c0fc3f56..2eabe2a5423 100644 --- a/src/resources/nfts/simplehash/utils.ts +++ b/src/resources/nfts/simplehash/utils.ts @@ -21,7 +21,7 @@ import { TokenStandard } from '@/handlers/web3'; import { handleNFTImages } from '@/utils/handleNFTImages'; import { SimpleHashNft } from '@/graphql/__generated__/arc'; import { Network } from '@/chains/types'; -import { chainsIdByName } from '@/chains'; +import { getChainsIdByName } from '@/chains'; const ENS_COLLECTION_NAME = 'ENS'; const SVG_MIME_TYPE = 'image/svg+xml'; @@ -79,7 +79,7 @@ export function simpleHashNFTToUniqueAsset(nft: SimpleHashNft, address: string): slug: marketplace?.marketplace_collection_id ?? '', twitter_username: collection.twitter_username, }, - chainId: chainsIdByName[nft.chain], + chainId: getChainsIdByName()[nft.chain], description: nft.description, external_link: nft.external_url, familyImage: collection.image_url, diff --git a/src/resources/transactions/consolidatedTransactions.ts b/src/resources/transactions/consolidatedTransactions.ts index 616af75da8e..aea6382082e 100644 --- a/src/resources/transactions/consolidatedTransactions.ts +++ b/src/resources/transactions/consolidatedTransactions.ts @@ -5,7 +5,7 @@ import { RainbowError, logger } from '@/logger'; import { rainbowFetch } from '@/rainbow-fetch'; import { ADDYS_API_KEY } from 'react-native-dotenv'; import { parseTransaction } from '@/parsers/transactions'; -import { chainsIdByName, SUPPORTED_MAINNET_CHAIN_IDS } from '@/chains'; +import { getChainsIdByName, getSupportedMainnetChainIds } from '@/chains'; const CONSOLIDATED_TRANSACTIONS_INTERVAL = 30000; const CONSOLIDATED_TRANSACTIONS_TIMEOUT = 20000; @@ -106,7 +106,9 @@ async function parseConsolidatedTransactions( ): Promise { const data = message?.payload?.transactions || []; - const parsedTransactionPromises = data.map((tx: TransactionApiResponse) => parseTransaction(tx, currency, chainsIdByName[tx.network])); + const parsedTransactionPromises = data.map((tx: TransactionApiResponse) => + parseTransaction(tx, currency, getChainsIdByName()[tx.network]) + ); // Filter out undefined values immediately const parsedConsolidatedTransactions = (await Promise.all(parsedTransactionPromises)).flat(); // Filter out any remaining undefined values @@ -125,7 +127,7 @@ export function useConsolidatedTransactions( consolidatedTransactionsQueryKey({ address, currency, - chainIds: SUPPORTED_MAINNET_CHAIN_IDS, + chainIds: getSupportedMainnetChainIds(), }), consolidatedTransactionsQueryFunction, { diff --git a/src/resources/transactions/transaction.ts b/src/resources/transactions/transaction.ts index da7cde08be7..4ac0c1b7f8b 100644 --- a/src/resources/transactions/transaction.ts +++ b/src/resources/transactions/transaction.ts @@ -8,7 +8,7 @@ import { ADDYS_API_KEY } from 'react-native-dotenv'; import { parseTransaction } from '@/parsers/transactions'; import { RainbowError, logger } from '@/logger'; import { ChainId } from '@/chains/types'; -import { SUPPORTED_MAINNET_CHAIN_IDS } from '@/chains'; +import { getSupportedMainnetChainIds } from '@/chains'; export type ConsolidatedTransactionsResult = QueryFunctionResult; export type PaginatedTransactions = { pages: ConsolidatedTransactionsResult[] }; @@ -81,7 +81,7 @@ export function useBackendTransaction({ hash, chainId }: BackendTransactionArgs) const paginatedTransactionsKey = consolidatedTransactionsQueryKey({ address: accountAddress, currency: nativeCurrency, - chainIds: SUPPORTED_MAINNET_CHAIN_IDS, + chainIds: getSupportedMainnetChainIds(), }); const params: TransactionArgs = { diff --git a/src/screens/CurrencySelectModal.tsx b/src/screens/CurrencySelectModal.tsx index bca7126d7b0..066856d17e0 100644 --- a/src/screens/CurrencySelectModal.tsx +++ b/src/screens/CurrencySelectModal.tsx @@ -40,7 +40,7 @@ import DiscoverSearchInput from '@/components/discover/DiscoverSearchInput'; import { externalTokenQueryKey, fetchExternalToken } from '@/resources/assets/externalAssetsQuery'; import { queryClient } from '@/react-query/queryClient'; import { ChainId, Network } from '@/chains/types'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; export interface EnrichedExchangeAsset extends SwappableAsset { ens: boolean; @@ -315,7 +315,7 @@ export default function CurrencySelectModal() { (item: any) => { if (type === CurrencySelectionTypes.output && currentChainId && currentChainId !== ChainId.mainnet) { const currentL2WalletAssets = assetsInWallet.filter( - ({ network }) => network && network?.toLowerCase() === chainsName[currentChainId]?.toLowerCase() + ({ network }) => network && network?.toLowerCase() === getChainsName()[currentChainId]?.toLowerCase() ); if (currentL2WalletAssets?.length < 1) { Keyboard.dismiss(); @@ -364,7 +364,7 @@ export default function CurrencySelectModal() { ...newAsset, decimals: item?.networks?.[currentChainId]?.decimals || item.decimals, address: item?.address || item?.networks?.[currentChainId]?.address, - network: chainsName[currentChainId], + network: getChainsName()[currentChainId], ...externalAsset, }; } diff --git a/src/screens/ExchangeModal.tsx b/src/screens/ExchangeModal.tsx index 2f8aa2c28df..c7e6b511d03 100644 --- a/src/screens/ExchangeModal.tsx +++ b/src/screens/ExchangeModal.tsx @@ -74,7 +74,7 @@ import { TokenColors } from '@/graphql/__generated__/metadata'; import { estimateSwapGasLimit } from '@/raps/actions'; import { estimateCrosschainSwapGasLimit } from '@/raps/actions/crosschainSwap'; import { parseGasParamAmounts } from '@/parsers'; -import { chainsName, needsL1SecurityFeeChains, shouldDefaultToFastGasChainIds, supportedFlashbotsChainIds } from '@/chains'; +import { getChainsName, getNeedsL1SecurityFeeChains, shouldDefaultToFastGasChainIds, supportedFlashbotsChainIds } from '@/chains'; export const DEFAULT_SLIPPAGE_BIPS = { [ChainId.mainnet]: 100, @@ -95,7 +95,7 @@ export const getDefaultSlippageFromConfig = (chainId: ChainId) => { const configSlippage = getRemoteConfig().default_slippage_bips as unknown as { [network: string]: number; }; - const network = chainsName[chainId]; + const network = getChainsName()[chainId]; const slippage = configSlippage?.[network] ?? DEFAULT_SLIPPAGE_BIPS[chainId] ?? 100; return slippage; }; @@ -293,7 +293,7 @@ export function ExchangeModal({ fromDiscover, ignoreInitialTypeCheck, testID, ty }); if (gasLimit) { - if (needsL1SecurityFeeChains.includes(currentChainId)) { + if (getNeedsL1SecurityFeeChains().includes(currentChainId)) { if (tradeDetails) { const l1GasFeeOptimism = await ethereumUtils.calculateL1FeeOptimism( // eslint-disable-next-line @typescript-eslint/ban-ts-comment @@ -432,7 +432,7 @@ export function ExchangeModal({ fromDiscover, ignoreInitialTypeCheck, testID, ty const transformedAssetToSell = { ...inputCurrency, - chainName: chainsName[inputCurrency.chainId], + chainName: getChainsName()[inputCurrency.chainId], address: inputCurrency.address as AddressOrEth, chainId: inputCurrency.chainId, colors: inputCurrency.colors as TokenColors, @@ -440,7 +440,7 @@ export function ExchangeModal({ fromDiscover, ignoreInitialTypeCheck, testID, ty const transformedAssetToBuy = { ...outputCurrency, - chainName: chainsName[outputCurrency.chainId], + chainName: getChainsName()[outputCurrency.chainId], address: outputCurrency.address as AddressOrEth, chainId: outputCurrency.chainId, colors: outputCurrency.colors as TokenColors, @@ -500,7 +500,7 @@ export function ExchangeModal({ fromDiscover, ignoreInitialTypeCheck, testID, ty legacyGasPrice: (selectedGasFee?.gasFeeParams as unknown as LegacyGasFeeParams)?.gasPrice?.amount || '', liquiditySources: JSON.stringify(tradeDetails?.protocols || []), maxNetworkFee: (selectedGasFee?.gasFee as GasFee)?.maxFee?.value?.amount || '', - network: chainsName[currentChainId], + network: getChainsName()[currentChainId], networkFee: selectedGasFee?.gasFee?.estimatedFee?.value?.amount || '', outputTokenAddress: outputCurrency?.address || '', outputTokenName: outputCurrency?.name || '', @@ -581,7 +581,7 @@ export function ExchangeModal({ fromDiscover, ignoreInitialTypeCheck, testID, ty legacyGasPrice: (selectedGasFee?.gasFeeParams as unknown as LegacyGasFeeParams)?.gasPrice?.amount || '', liquiditySources: JSON.stringify(tradeDetails?.protocols || []), maxNetworkFee: (selectedGasFee?.gasFee as GasFee)?.maxFee?.value?.amount || '', - network: chainsName[currentChainId], + network: getChainsName()[currentChainId], networkFee: selectedGasFee?.gasFee?.estimatedFee?.value?.amount || '', outputTokenAddress: outputCurrency?.address || '', outputTokenName: outputCurrency?.name || '', @@ -712,7 +712,7 @@ export function ExchangeModal({ fromDiscover, ignoreInitialTypeCheck, testID, ty setParams({ focused: false }); navigate(Routes.SWAP_DETAILS_SHEET, { confirmButtonProps, - currentNetwork: chainsName[currentChainId], + currentNetwork: getChainsName()[currentChainId], flashbotTransaction: flashbots, isRefuelTx, restoreFocusOnSwapModal: () => { diff --git a/src/screens/ExplainSheet.js b/src/screens/ExplainSheet.js index e4184cfa82c..27797d6aaf6 100644 --- a/src/screens/ExplainSheet.js +++ b/src/screens/ExplainSheet.js @@ -24,7 +24,7 @@ import * as i18n from '@/languages'; import { EthCoinIcon } from '@/components/coin-icon/EthCoinIcon'; import RainbowCoinIcon from '@/components/coin-icon/RainbowCoinIcon'; import { ChainId } from '@/chains/types'; -import { chainsLabel } from '@/chains'; +import { getChainsLabel } from '@/chains'; const { GAS_TRENDS } = gasUtils; export const ExplainSheetHeight = android ? 454 : 434; @@ -79,7 +79,7 @@ const FLOOR_PRICE_EXPLAINER = lang.t('explain.floor_price.text'); const gasExplainer = network => lang.t('explain.gas.text', { networkName: network }); const availableNetworksExplainer = (tokenSymbol, chainIds) => { - const readableNetworks = chainIds?.map(chainId => chainsLabel[chainId])?.join(', '); + const readableNetworks = chainIds?.map(chainId => getChainsLabel()[chainId])?.join(', '); return lang.t('explain.available_networks.text', { tokenSymbol: tokenSymbol, @@ -211,7 +211,7 @@ export const explainers = (params, theme) => { title: params?.inputToken ? lang.t(`explain.output_disabled.${params?.isCrosschainSwap ? 'title_crosschain' : 'title'}`, { inputToken: params?.inputToken, - fromNetwork: chainsLabel[fromChainId], + fromNetwork: getChainsLabel()[fromChainId], }) : lang.t('explain.output_disabled.title_empty'), @@ -219,11 +219,11 @@ export const explainers = (params, theme) => { ? lang.t(`explain.output_disabled.${params?.isBridgeSwap ? 'text_bridge' : 'text_crosschain'}`, { inputToken: params?.inputToken, outputToken: params?.outputToken, - fromNetwork: chainsLabel[fromChainId], - toNetwork: chainsLabel[toChainId], + fromNetwork: getChainsLabel()[fromChainId], + toNetwork: getChainsLabel()[toChainId], }) : lang.t('explain.output_disabled.text', { - fromNetwork: chainsLabel[fromChainId], + fromNetwork: getChainsLabel()[fromChainId], inputToken: params?.inputToken, outputToken: params?.outputToken, }), @@ -251,9 +251,9 @@ export const explainers = (params, theme) => { /> ), extraHeight: 2, - text: gasExplainer(chainsLabel[chainId]), + text: gasExplainer(getChainsLabel()[chainId]), title: lang.t('explain.gas.title', { - networkName: chainsLabel[chainId], + networkName: getChainsLabel()[chainId], }), }, ens_primary_name: { @@ -534,14 +534,14 @@ export const explainers = (params, theme) => { }, swapResetInputs: { button: { - label: `Continue with ${chainsLabel[chainId]}`, + label: `Continue with ${getChainsLabel()[chainId]}`, bgColor: colors?.networkColors[chainId] && colors?.alpha(colors?.networkColors[chainId], 0.06), textColor: colors?.networkColors?.[chainId], }, emoji: '🔐', extraHeight: -90, text: SWAP_RESET_EXPLAINER, - title: `Switching to ${chainsLabel[chainId]}`, + title: `Switching to ${getChainsLabel()[chainId]}`, logo: chainId !== ChainId.mainnet ? ( diff --git a/src/screens/MintsSheet/card/Card.tsx b/src/screens/MintsSheet/card/Card.tsx index c0317d7fc0f..0377bbe287d 100644 --- a/src/screens/MintsSheet/card/Card.tsx +++ b/src/screens/MintsSheet/card/Card.tsx @@ -13,7 +13,7 @@ import ChainBadge from '@/components/coin-icon/ChainBadge'; import { navigateToMintCollection } from '@/resources/reservoir/mints'; import { EthCoinIcon } from '@/components/coin-icon/EthCoinIcon'; import { ChainId } from '@/chains/types'; -import { chainsNativeAsset } from '@/chains'; +import { getChainsNativeAsset } from '@/chains'; export const NUM_NFTS = 3; @@ -28,7 +28,7 @@ export function Card({ collection }: { collection: MintableCollection }) { const separatorTertiary = useForegroundColor('separatorTertiary'); const price = convertRawAmountToRoundedDecimal(collection.mintStatus.price, 18, 6); - const currencySymbol = chainsNativeAsset[collection.chainId].symbol; + const currencySymbol = getChainsNativeAsset()[collection.chainId].symbol; const isFree = !price; // update elapsed time every minute if it's less than an hour diff --git a/src/screens/NFTOffersSheet/OfferRow.tsx b/src/screens/NFTOffersSheet/OfferRow.tsx index 9707e780a89..59a47f0c0f6 100644 --- a/src/screens/NFTOffersSheet/OfferRow.tsx +++ b/src/screens/NFTOffersSheet/OfferRow.tsx @@ -18,7 +18,7 @@ import { Network } from '@/chains/types'; import { useAccountSettings } from '@/hooks'; import RainbowCoinIcon from '@/components/coin-icon/RainbowCoinIcon'; import { AddressOrEth } from '@/__swaps__/types/assets'; -import { chainsIdByName } from '@/chains'; +import { getChainsIdByName } from '@/chains'; const NFT_SIZE = 50; const MARKETPLACE_ORB_SIZE = 18; @@ -99,7 +99,7 @@ export const OfferRow = ({ offer }: { offer: NftOffer }) => { const { colorMode } = useColorMode(); const theme = useTheme(); const bgColor = useBackgroundColor('surfaceSecondaryElevated'); - const chainId = chainsIdByName[offer.network as Network]; + const chainId = getChainsIdByName()[offer.network as Network]; const { data: externalAsset } = useExternalToken({ address: offer.paymentToken.address as AddressOrEth, chainId, diff --git a/src/screens/NFTSingleOfferSheet/index.tsx b/src/screens/NFTSingleOfferSheet/index.tsx index c5370caa023..87889ca93a8 100644 --- a/src/screens/NFTSingleOfferSheet/index.tsx +++ b/src/screens/NFTSingleOfferSheet/index.tsx @@ -52,7 +52,7 @@ import { getNextNonce } from '@/state/nonces'; import { metadataPOSTClient } from '@/graphql'; import { ethUnits } from '@/references'; import { Transaction } from '@/graphql/__generated__/metadataPOST'; -import { chainsIdByName, chainsNativeAsset, defaultChains, getChainDefaultRpc } from '@/chains'; +import { getChainsIdByName, getChainsNativeAsset, getDefaultChains, getChainDefaultRpc } from '@/chains'; const NFT_IMAGE_HEIGHT = 160; const TWO_HOURS_MS = 2 * 60 * 60 * 1000; @@ -94,7 +94,7 @@ export function NFTSingleOfferSheet() { } = useLegacyNFTs({ address: accountAddress }); const { offer } = params as { offer: NftOffer }; - const offerChainId = chainsIdByName[offer.network as Network]; + const offerChainId = getChainsIdByName()[offer.network as Network]; const { data: externalAsset } = useExternalToken({ address: offer.paymentToken.address, chainId: offerChainId, @@ -164,7 +164,7 @@ export function NFTSingleOfferSheet() { const feesPercentage = Math.floor(offer.feesPercentage * 10) / 10; const royaltiesPercentage = Math.floor(offer.royaltiesPercentage * 10) / 10; - const chain = defaultChains[offerChainId]; + const chain = getDefaultChains()[offerChainId]; useEffect(() => { setParams({ longFormHeight: height }); @@ -431,7 +431,7 @@ export function NFTSingleOfferSheet() { if (!isAccepting) { if (insufficientEth) { buttonLabel = lang.t('button.confirm_exchange.insufficient_token', { - tokenName: chainsNativeAsset[offerChainId].symbol, + tokenName: getChainsNativeAsset()[offerChainId].symbol, }); } else { buttonLabel = i18n.t(i18n.l.nft_offers.single_offer_sheet.hold_to_sell); diff --git a/src/screens/SendConfirmationSheet.tsx b/src/screens/SendConfirmationSheet.tsx index 2c63775d21e..26614c97890 100644 --- a/src/screens/SendConfirmationSheet.tsx +++ b/src/screens/SendConfirmationSheet.tsx @@ -62,7 +62,7 @@ import { useConsolidatedTransactions } from '@/resources/transactions/consolidat import RainbowCoinIcon from '@/components/coin-icon/RainbowCoinIcon'; import { performanceTracking, TimeToSignOperation, Screens } from '@/state/performance/performance'; import { ChainId } from '@/chains/types'; -import { chainsLabel } from '@/chains'; +import { getChainsLabel } from '@/chains'; const Container = styled(Centered).attrs({ direction: 'column', @@ -133,7 +133,7 @@ export function getDefaultCheckboxes({ checked: false, id: 'has-wallet-that-supports', label: lang.t('wallet.transaction.checkboxes.has_a_wallet_that_supports', { - networkName: chainsLabel[chainId], + networkName: getChainsLabel()[chainId], }), }, ]; @@ -599,7 +599,7 @@ export const SendConfirmationSheet = () => { onPress={handleL2DisclaimerPress} prominent customText={i18n.t(i18n.l.expanded_state.asset.l2_disclaimer_send, { - network: chainsLabel[asset.chainId], + network: getChainsLabel()[asset.chainId], })} symbol={asset.symbol} /> diff --git a/src/screens/SendSheet.tsx b/src/screens/SendSheet.tsx index 5ad35e5c58c..832e1fbc559 100644 --- a/src/screens/SendSheet.tsx +++ b/src/screens/SendSheet.tsx @@ -65,7 +65,7 @@ import { usePersistentDominantColorFromImage } from '@/hooks/usePersistentDomina import { performanceTracking, Screens, TimeToSignOperation } from '@/state/performance/performance'; import { REGISTRATION_STEPS } from '@/helpers/ens'; import { ChainId } from '@/chains/types'; -import { chainsName, chainsNativeAsset, needsL1SecurityFeeChains } from '@/chains'; +import { getChainsName, getChainsNativeAsset, getNeedsL1SecurityFeeChains } from '@/chains'; import { RootStackParamList } from '@/navigation/types'; import { ThemeContextProps, useTheme } from '@/theme'; import { StaticJsonRpcProvider } from '@ethersproject/providers'; @@ -416,7 +416,7 @@ export default function SendSheet() { }); if (!wallet) return; - const currentChainIdNetwork = chainsName[currentChainId ?? ChainId.mainnet]; + const currentChainIdNetwork = getChainsName()[currentChainId ?? ChainId.mainnet]; const validTransaction = isValidAddress && amountDetails.isSufficientBalance && isSufficientGas && isValidGas; if (!selectedGasFee?.gasFee?.estimatedFee || !validTransaction) { @@ -448,7 +448,7 @@ export default function SendSheet() { ); if (updatedGasLimit && !lessThan(updatedGasLimit, gasLimit)) { - if (needsL1SecurityFeeChains.includes(currentChainId)) { + if (getNeedsL1SecurityFeeChains().includes(currentChainId)) { updateTxFeeForOptimism(updatedGasLimit); } else { updateTxFee(updatedGasLimit, null); @@ -670,14 +670,14 @@ export default function SendSheet() { !selectedGasFee || isEmpty(selectedGasFee?.gasFee) || !toAddress || - (needsL1SecurityFeeChains.includes(currentChainId) && l1GasFeeOptimism === null) + (getNeedsL1SecurityFeeChains().includes(currentChainId) && l1GasFeeOptimism === null) ) { label = lang.t('button.confirm_exchange.loading'); disabled = true; } else if (!isZeroAssetAmount && !isSufficientGas) { disabled = true; label = lang.t('button.confirm_exchange.insufficient_token', { - tokenName: chainsNativeAsset[currentChainId || ChainId.mainnet].symbol, + tokenName: getChainsNativeAsset()[currentChainId || ChainId.mainnet].symbol, }); } else if (!isValidGas) { disabled = true; @@ -855,7 +855,7 @@ export default function SendSheet() { currentChainId ) .then(async gasLimit => { - if (gasLimit && needsL1SecurityFeeChains.includes(currentChainId)) { + if (gasLimit && getNeedsL1SecurityFeeChains().includes(currentChainId)) { updateTxFeeForOptimism(gasLimit); } else { updateTxFee(gasLimit, null); diff --git a/src/screens/SettingsSheet/components/NetworkSection.tsx b/src/screens/SettingsSheet/components/NetworkSection.tsx index df337be22ec..2cdf7630b5c 100644 --- a/src/screens/SettingsSheet/components/NetworkSection.tsx +++ b/src/screens/SettingsSheet/components/NetworkSection.tsx @@ -9,7 +9,7 @@ import { Separator, Stack } from '@/design-system'; import { useAccountSettings, useLoadAccountData } from '@/hooks'; import { settingsUpdateNetwork } from '@/redux/settings'; import { ChainId } from '@/chains/types'; -import { defaultChains } from '@/chains'; +import { getDefaultChains } from '@/chains'; import { isL2Chain } from '@/handlers/web3'; interface NetworkSectionProps { @@ -33,7 +33,7 @@ const NetworkSection = ({ inDevSection }: NetworkSectionProps) => { ); const renderNetworkList = useCallback(() => { - return Object.values(defaultChains) + return Object.values(getDefaultChains()) .filter(({ id }) => !isL2Chain({ chainId: id })) .map(({ name, id, testnet }) => ( { from: displayDetails?.request?.from, gasLimit, hash: sendResult.hash, - network: chainsName[chainId] as Network, + network: getChainsName()[chainId] as Network, nonce: sendResult.nonce, to: displayDetails?.request?.to, value: sendResult.value.toString(), @@ -414,7 +414,7 @@ export const SignTransactionSheet = () => { dappName: transactionDetails.dappName, dappUrl: transactionDetails.dappUrl, isHardwareWallet: accountInfo.isHardwareWallet, - network: chainsName[chainId] as Network, + network: getChainsName()[chainId] as Network, }); if (!sendInsteadOfSign) { @@ -447,7 +447,7 @@ export const SignTransactionSheet = () => { dappUrl: transactionDetails?.dappUrl, formattedDappUrl, rpcMethod: req?.method, - network: chainsName[chainId] as Network, + network: getChainsName()[chainId] as Network, }); // If the user is using a hardware wallet, we don't want to close the sheet on an error if (!accountInfo.isHardwareWallet) { @@ -528,7 +528,7 @@ export const SignTransactionSheet = () => { dappName: transactionDetails?.dappName, dappUrl: transactionDetails?.dappUrl, isHardwareWallet: accountInfo.isHardwareWallet, - network: chainsName[chainId] as Network, + network: getChainsName()[chainId] as Network, }); onSuccessCallback?.(response.result); @@ -716,7 +716,7 @@ export const SignTransactionSheet = () => { {`${walletBalance?.display} ${i18n.t(i18n.l.walletconnect.simulation.profile_section.on_network, { - network: defaultChains[chainId]?.name, + network: getDefaultChains()[chainId]?.name, })}`} diff --git a/src/screens/WalletConnectApprovalSheet.tsx b/src/screens/WalletConnectApprovalSheet.tsx index 09e8f31305c..e47a3d91b53 100644 --- a/src/screens/WalletConnectApprovalSheet.tsx +++ b/src/screens/WalletConnectApprovalSheet.tsx @@ -30,7 +30,7 @@ import { InfoAlert } from '@/components/info-alert/info-alert'; import { EthCoinIcon } from '@/components/coin-icon/EthCoinIcon'; import { findWalletWithAccount } from '@/helpers/findWalletWithAccount'; import { ChainId } from '@/chains/types'; -import { chainsLabel, chainsNativeAsset, defaultChains } from '@/chains'; +import { getChainsLabel, getChainsNativeAsset, getDefaultChains } from '@/chains'; import { ThemeContextProps, useTheme } from '@/theme'; import { noop } from 'lodash'; import { RootStackParamList } from '@/navigation/types'; @@ -132,7 +132,7 @@ const NetworkPill = ({ chainIds }: { chainIds: ChainId[] }) => { - {chainsLabel[availableNetworkChainIds[0]]} + {getChainsLabel()[availableNetworkChainIds[0]]} @@ -229,8 +229,8 @@ export function WalletConnectApprovalSheet() { * v2. */ const approvalNetworkInfo = useMemo(() => { - const chain = defaultChains[approvalChainId || ChainId.mainnet]; - const nativeAsset = chainsNativeAsset[chain.id]; + const chain = getDefaultChains()[approvalChainId || ChainId.mainnet]; + const nativeAsset = getChainsNativeAsset()[chain.id]; return { chainId: chain.id, color: isDarkMode ? nativeAsset.colors.primary : nativeAsset.colors.fallback || nativeAsset.colors.primary, @@ -365,7 +365,7 @@ export function WalletConnectApprovalSheet() { {`${ - type === WalletConnectApprovalSheetType.connect ? approvalNetworkInfo.name : chainsLabel[chainId] + type === WalletConnectApprovalSheetType.connect ? approvalNetworkInfo.name : getChainsLabel()[chainId] } ${type === WalletConnectApprovalSheetType.connect && menuItems.length > 1 ? '􀁰' : ''}`} @@ -406,7 +406,7 @@ export function WalletConnectApprovalSheet() { {type === WalletConnectApprovalSheetType.connect ? lang.t(lang.l.walletconnect.wants_to_connect) : lang.t(lang.l.walletconnect.wants_to_connect_to_network, { - network: chainsLabel[chainId], + network: getChainsLabel()[chainId], })} diff --git a/src/screens/claimables/ClaimingClaimableSharedUI.tsx b/src/screens/claimables/ClaimingClaimableSharedUI.tsx index a788f349939..42eec0efa42 100644 --- a/src/screens/claimables/ClaimingClaimableSharedUI.tsx +++ b/src/screens/claimables/ClaimingClaimableSharedUI.tsx @@ -10,7 +10,7 @@ import { SponsoredClaimable, TransactionClaimable } from '@/resources/addys/clai import RainbowCoinIcon from '@/components/coin-icon/RainbowCoinIcon'; import { useTheme } from '@/theme'; import { FasterImageView } from '@candlefinance/faster-image'; -import { chainsLabel } from '@/chains'; +import { getChainsLabel } from '@/chains'; import { useNavigation } from '@/navigation'; import { TextColor } from '@/design-system/color/palettes'; import Animated, { useAnimatedStyle, useSharedValue, withTiming } from 'react-native-reanimated'; @@ -262,7 +262,7 @@ export const ClaimingClaimableSharedUI = ({ {i18n.t(i18n.l.claimables.panel.amount_to_claim_on_network, { amount: nativeCurrencyGasFeeDisplay, - network: chainsLabel[claimable.chainId], + network: getChainsLabel()[claimable.chainId], })} diff --git a/src/screens/claimables/ClaimingTransactionClaimable.tsx b/src/screens/claimables/ClaimingTransactionClaimable.tsx index 04106fbd7f4..4738e7d51e7 100644 --- a/src/screens/claimables/ClaimingTransactionClaimable.tsx +++ b/src/screens/claimables/ClaimingTransactionClaimable.tsx @@ -5,7 +5,7 @@ import { Claimable, TransactionClaimable } from '@/resources/addys/claimables/ty import { estimateGasWithPadding, getProvider } from '@/handlers/web3'; import { parseGasParamsForTransaction } from '@/parsers'; import { getNextNonce } from '@/state/nonces'; -import { needsL1SecurityFeeChains } from '@/chains'; +import { getNeedsL1SecurityFeeChains } from '@/chains'; import { logger, RainbowError } from '@/logger'; import { ClaimingClaimableSharedUI, ClaimStatus } from './ClaimingClaimableSharedUI'; import { TransactionRequest } from '@ethersproject/providers'; @@ -108,7 +108,7 @@ export const ClaimingTransactionClaimable = ({ claimable }: { claimable: Transac return; } - if (needsL1SecurityFeeChains.includes(claimable.chainId)) { + if (getNeedsL1SecurityFeeChains().includes(claimable.chainId)) { const l1SecurityFee = await ethereumUtils.calculateL1FeeOptimism( { to: claimable.action.to, diff --git a/src/screens/discover/components/DiscoverSearch.js b/src/screens/discover/components/DiscoverSearch.js index 3f596cabf86..a3172798530 100644 --- a/src/screens/discover/components/DiscoverSearch.js +++ b/src/screens/discover/components/DiscoverSearch.js @@ -23,7 +23,7 @@ import { getPoapAndOpenSheetWithQRHash, getPoapAndOpenSheetWithSecretWord } from import { navigateToMintCollection } from '@/resources/reservoir/mints'; import { TAB_BAR_HEIGHT } from '@/navigation/SwipeNavigator'; import { ChainId, Network } from '@/chains/types'; -import { chainsIdByName } from '@/chains'; +import { getChainsIdByName } from '@/chains'; export const SearchContainer = styled(Row)({ height: '100%', @@ -134,7 +134,7 @@ export default function DiscoverSearch() { network === Network.optimism; } const contractAddress = query.split('/')[1]; - navigateToMintCollection(contractAddress, chainsIdByName[network]); + navigateToMintCollection(contractAddress, getChainsIdByName()[network]); } }; checkAndHandleMint(searchQuery); diff --git a/src/screens/mints/MintSheet.tsx b/src/screens/mints/MintSheet.tsx index 09c628a8865..cc8903404e5 100644 --- a/src/screens/mints/MintSheet.tsx +++ b/src/screens/mints/MintSheet.tsx @@ -56,7 +56,7 @@ import { getNextNonce } from '@/state/nonces'; import { metadataPOSTClient } from '@/graphql'; import { Transaction } from '@/graphql/__generated__/metadataPOST'; import { ChainId } from '@/chains/types'; -import { chainsName, defaultChains, getChainDefaultRpc } from '@/chains'; +import { getChainsName, getDefaultChains, getChainDefaultRpc } from '@/chains'; const NFT_IMAGE_HEIGHT = 250; // inset * 2 -> 28 *2 @@ -249,7 +249,7 @@ const MintSheet = () => { const estimateMintGas = async () => { const signer = createWalletClient({ account: accountAddress, - chain: defaultChains[chainId], + chain: getDefaultChains()[chainId], transport: http(getChainDefaultRpc(chainId)), }); try { @@ -355,7 +355,7 @@ const MintSheet = () => { const privateKey = await loadPrivateKey(accountAddress, false); // @ts-ignore const account = privateKeyToAccount(privateKey); - const chain = defaultChains[chainId]; + const chain = getDefaultChains()[chainId]; const signer = createWalletClient({ account, chain, @@ -389,7 +389,7 @@ const MintSheet = () => { type: 'nft', icon_url: imageUrl, address: mintCollection.id || '', - network: chainsName[chainId], + network: getChainsName()[chainId], name: mintCollection.name || '', decimals: 18, symbol: 'NFT', @@ -399,7 +399,7 @@ const MintSheet = () => { const paymentAsset = { type: 'nft', address: ETH_ADDRESS, - network: chainsName[chainId], + network: getChainsName()[chainId], name: mintCollection.publicMintInfo?.price?.currency?.name || 'Ethereum', decimals: mintCollection.publicMintInfo?.price?.currency?.decimals || 18, symbol: ETH_SYMBOL, @@ -412,7 +412,7 @@ const MintSheet = () => { to: item.data?.to, from: item.data?.from, hash: item.txHashes[0].txHash, - network: chainsName[chainId], + network: getChainsName()[chainId], nonce, changes: [ { @@ -704,7 +704,7 @@ const MintSheet = () => { )} - {`${defaultChains[chainId].name}`} + {`${getDefaultChains()[chainId].name}`} diff --git a/src/screens/points/claim-flow/ClaimRewardsPanel.tsx b/src/screens/points/claim-flow/ClaimRewardsPanel.tsx index d39b3619b3c..67d16a48d77 100644 --- a/src/screens/points/claim-flow/ClaimRewardsPanel.tsx +++ b/src/screens/points/claim-flow/ClaimRewardsPanel.tsx @@ -34,7 +34,7 @@ import { useMeteorologySuggestions } from '@/__swaps__/utils/meteorology'; import { AnimatedSpinner } from '@/components/animations/AnimatedSpinner'; import { RainbowError, logger } from '@/logger'; import { RewardsActionButton } from '../components/RewardsActionButton'; -import { chainsLabel, chainsName } from '@/chains'; +import { getChainsLabel, getChainsName } from '@/chains'; type ClaimStatus = 'idle' | 'claiming' | 'success' | PointsErrorType | 'error' | 'bridge-error'; type ClaimNetwork = '10' | '8453' | '7777777'; @@ -93,7 +93,7 @@ export const ClaimRewardsPanel = () => { const NETWORK_LIST_ITEMS = CLAIM_NETWORKS.map(chainId => { return { IconComponent: , - label: chainsLabel[chainId], + label: getChainsLabel()[chainId], uniqueId: chainId.toString(), selected: false, }; @@ -213,7 +213,7 @@ const ClaimingRewards = ({ const opEth_ = await ethereumUtils.getNativeAssetForNetwork({ chainId: ChainId.optimism }); const opEth = { ...opEth_, - chainName: chainsName[ChainId.optimism], + chainName: getChainsName()[ChainId.optimism], }; // Fetch the native asset from the destination chain @@ -229,7 +229,7 @@ const ClaimingRewards = ({ // Add missing properties to match types const destinationEth = { ...destinationEth_, - chainName: chainsName[chainId as ChainId], + chainName: getChainsName()[chainId as ChainId], }; const selectedGas = { @@ -340,15 +340,15 @@ const ClaimingRewards = ({ switch (claimStatus) { case 'idle': return i18n.t(i18n.l.points.points.claim_on_network, { - network: chainId ? chainsLabel[chainId] : '', + network: chainId ? getChainsLabel()[chainId] : '', }); case 'claiming': return i18n.t(i18n.l.points.points.claiming_on_network, { - network: chainId ? chainsLabel[chainId] : '', + network: chainId ? getChainsLabel()[chainId] : '', }); case 'success': return i18n.t(i18n.l.points.points.claimed_on_network, { - network: chainId ? chainsLabel[chainId] : '', + network: chainId ? getChainsLabel()[chainId] : '', }); case 'bridge-error': return i18n.t(i18n.l.points.points.bridge_error); @@ -494,7 +494,7 @@ const ClaimingRewards = ({ {i18n.t(i18n.l.points.points.bridge_error_explainer, { - network: chainId ? chainsLabel[chainId] : '', + network: chainId ? getChainsLabel()[chainId] : '', })} diff --git a/src/screens/positions/SubPositionListItem.tsx b/src/screens/positions/SubPositionListItem.tsx index d4708f43517..aa3cc16e8cb 100644 --- a/src/screens/positions/SubPositionListItem.tsx +++ b/src/screens/positions/SubPositionListItem.tsx @@ -10,7 +10,7 @@ import { NativeDisplay, PositionAsset } from '@/resources/defi/types'; import { useExternalToken } from '@/resources/assets/externalAssetsQuery'; import { useAccountSettings } from '@/hooks'; import RainbowCoinIcon from '@/components/coin-icon/RainbowCoinIcon'; -import { chainsIdByName } from '@/chains'; +import { getChainsIdByName } from '@/chains'; type Props = { asset: PositionAsset; @@ -23,7 +23,7 @@ type Props = { export const SubPositionListItem: React.FC = ({ asset, apy, quantity, native, positionColor }) => { const theme = useTheme(); const { nativeCurrency } = useAccountSettings(); - const chainId = chainsIdByName[asset.network]; + const chainId = getChainsIdByName()[asset.network]; const { data: externalAsset } = useExternalToken({ address: asset.asset_code, chainId, currency: nativeCurrency }); const priceChangeColor = (asset.price?.relative_change_24h || 0) < 0 ? theme.colors.blueGreyDark60 : theme.colors.green; diff --git a/src/state/assets/userAssets.ts b/src/state/assets/userAssets.ts index 1ac63f8e1de..e4e41f5d870 100644 --- a/src/state/assets/userAssets.ts +++ b/src/state/assets/userAssets.ts @@ -8,7 +8,7 @@ import { useStore } from 'zustand'; import { useCallback } from 'react'; import { swapsStore } from '@/state/swaps/swapsStore'; import { ChainId } from '@/chains/types'; -import { SUPPORTED_CHAIN_IDS } from '@/chains'; +import { getSupportedChainIds } from '@/chains'; import { useSelector } from 'react-redux'; const SEARCH_CACHE_MAX_ENTRIES = 50; @@ -20,7 +20,7 @@ const getDefaultCacheKeys = (): Set => { const queryKeysToPreserve = new Set(); queryKeysToPreserve.add('all'); - for (const chainId of SUPPORTED_CHAIN_IDS) { + for (const chainId of getSupportedChainIds()) { queryKeysToPreserve.add(`${chainId}`); } return queryKeysToPreserve; @@ -281,7 +281,7 @@ export const createUserAssetsStore = (address: Address | string) => }); // Ensure all supported chains are in the map with a fallback value of 0 - SUPPORTED_CHAIN_IDS.forEach(chainId => { + getSupportedChainIds().forEach(chainId => { if (!unsortedChainBalances.has(chainId)) { unsortedChainBalances.set(chainId, 0); idsByChain.set(chainId, []); diff --git a/src/state/nonces/index.ts b/src/state/nonces/index.ts index fa0ae319441..cc011f369e5 100644 --- a/src/state/nonces/index.ts +++ b/src/state/nonces/index.ts @@ -2,7 +2,7 @@ import create from 'zustand'; import { createStore } from '../internal/createStore'; import { Network, ChainId } from '@/chains/types'; import { getProvider } from '@/handlers/web3'; -import { chainsIdByName } from '@/chains'; +import { getChainsIdByName } from '@/chains'; type NonceData = { currentNonce?: number; @@ -82,7 +82,7 @@ export const nonceStore = createStore>( if (!newNonces[address]) { newNonces[address] = {} as Record; } - newNonces[address][chainsIdByName[network as Network]] = nonceData; + newNonces[address][getChainsIdByName()[network as Network]] = nonceData; } } return { diff --git a/src/utils/ethereumUtils.ts b/src/utils/ethereumUtils.ts index 89549ce63f2..e33a7641121 100644 --- a/src/utils/ethereumUtils.ts +++ b/src/utils/ethereumUtils.ts @@ -50,11 +50,11 @@ import { } from '@/resources/assets/externalAssetsQuery'; import { ChainId, Network } from '@/chains/types'; import { AddressOrEth } from '@/__swaps__/types/assets'; -import { chainsIdByName, chainsName, chainsNativeAsset, defaultChains, getChainGasUnits } from '@/chains'; +import { getChainsIdByName, getChainsName, getChainsNativeAsset, getDefaultChains, getChainGasUnits } from '@/chains'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; const getNetworkNativeAsset = ({ chainId }: { chainId: ChainId }) => { - const nativeAssetAddress = chainsNativeAsset[chainId].address; + const nativeAssetAddress = getChainsNativeAsset()[chainId].address; const nativeAssetUniqueId = getUniqueId(nativeAssetAddress, chainId); return getAccountAsset(nativeAssetUniqueId); }; @@ -73,7 +73,7 @@ export const getNativeAssetForNetwork = async ({ // If the asset is on a different wallet, or not available in this wallet if (differentWallet || !nativeAsset) { - const chainNativeAsset = chainsNativeAsset[chainId]; + const chainNativeAsset = getChainsNativeAsset()[chainId]; const mainnetAddress = chainNativeAsset?.address || ETH_ADDRESS; const nativeAssetAddress = chainNativeAsset.address as AddressOrEth; @@ -88,7 +88,7 @@ export const getNativeAssetForNetwork = async ({ // @ts-ignore nativeAsset = { ...externalAsset, - network: chainsName[chainId], + network: getChainsName()[chainId], uniqueId: getUniqueId(chainNativeAsset.address, chainId), address: chainNativeAsset.address, decimals: chainNativeAsset.decimals, @@ -176,7 +176,7 @@ const getAssetPrice = (address: EthereumAddress = ETH_ADDRESS): number => { export const useNativeAsset = ({ chainId }: { chainId: ChainId }) => { const { nativeCurrency } = store.getState().settings; - const address = (chainsNativeAsset[chainId]?.address || ETH_ADDRESS) as AddressOrEth; + const address = (getChainsNativeAsset()[chainId]?.address || ETH_ADDRESS) as AddressOrEth; const { data: nativeAsset } = useExternalToken({ address, @@ -278,8 +278,8 @@ const getDataString = (func: string, arrVals: string[]) => { */ function getEtherscanHostForNetwork({ chainId }: { chainId: ChainId }): string { const base_host = 'etherscan.io'; - const blockExplorer = defaultChains[chainId]?.blockExplorers?.default?.url; - const network = chainsName[chainId]; + const blockExplorer = getDefaultChains()[chainId]?.blockExplorers?.default?.url; + const network = getChainsName()[chainId]; if (network && isTestnetChain({ chainId })) { return `${network}.${base_host}`; @@ -354,29 +354,29 @@ export const getFirstTransactionTimestamp = async (address: EthereumAddress): Pr }; function getBlockExplorer({ chainId }: { chainId: ChainId }) { - return defaultChains[chainId]?.blockExplorers?.default.name || 'etherscan'; + return getDefaultChains()[chainId]?.blockExplorers?.default.name || 'etherscan'; } function openAddressInBlockExplorer({ address, chainId }: { address: EthereumAddress; chainId: ChainId }) { - const explorer = defaultChains[chainId]?.blockExplorers?.default?.url; + const explorer = getDefaultChains()[chainId]?.blockExplorers?.default?.url; Linking.openURL(`${explorer}/address/${address}`); } function openTokenEtherscanURL({ address, chainId }: { address: EthereumAddress; chainId: ChainId }) { if (!isString(address)) return; - const explorer = defaultChains[chainId]?.blockExplorers?.default?.url; + const explorer = getDefaultChains()[chainId]?.blockExplorers?.default?.url; Linking.openURL(`${explorer}/token/${address}`); } function openNftInBlockExplorer({ contractAddress, tokenId, chainId }: { contractAddress: string; tokenId: string; chainId: ChainId }) { - const explorer = defaultChains[chainId]?.blockExplorers?.default?.url; + const explorer = getDefaultChains()[chainId]?.blockExplorers?.default?.url; Linking.openURL(`${explorer}/token/${contractAddress}?a=${tokenId}`); } function openTransactionInBlockExplorer({ hash, chainId }: { hash: string; chainId: ChainId }) { const normalizedHash = hash.replace(/-.*/g, ''); if (!isString(hash)) return; - const explorer = defaultChains[chainId]?.blockExplorers?.default?.url; + const explorer = getDefaultChains()[chainId]?.blockExplorers?.default?.url; Linking.openURL(`${explorer}/tx/${normalizedHash}`); } @@ -392,14 +392,14 @@ async function parseEthereumUrl(data: string) { const functionName = ethUrl.function_name; let asset = null; const chainId = (ethUrl.chain_id as ChainId) || ChainId.mainnet; - const network = chainsName[chainId]; + const network = getChainsName()[chainId]; let address: any = null; let nativeAmount: any = null; const { nativeCurrency } = store.getState().settings; if (!functionName) { // Send native asset - const chainId = chainsIdByName[network]; + const chainId = getChainsIdByName()[network]; asset = getNetworkNativeAsset({ chainId }); // @ts-ignore @@ -455,7 +455,7 @@ export const getAddressAndChainIdFromUniqueId = (uniqueId: string): { address: A // If the unique ID contains '_', the last part is the network and the rest is the address const network = parts[1] as Network; // Assuming the last part is a valid Network enum value const address = parts[0] as AddressOrEth; - const chainId = chainsIdByName[network]; + const chainId = getChainsIdByName()[network]; return { address, chainId }; }; diff --git a/src/utils/getUrlForTrustIconFallback.ts b/src/utils/getUrlForTrustIconFallback.ts index c9757d3080d..e2768840d2d 100644 --- a/src/utils/getUrlForTrustIconFallback.ts +++ b/src/utils/getUrlForTrustIconFallback.ts @@ -1,6 +1,6 @@ import { ChainId } from '@/chains/types'; import { EthereumAddress } from '@/entities'; -import { chainsName } from '@/chains'; +import { getChainsName } from '@/chains'; export default function getUrlForTrustIconFallback(address: EthereumAddress, chainId: ChainId): string | null { if (!address) return null; @@ -13,7 +13,7 @@ export default function getUrlForTrustIconFallback(address: EthereumAddress, cha networkPath = 'smartchain'; break; default: - networkPath = chainsName[chainId]; + networkPath = getChainsName()[chainId]; } return `https://rainbowme-res.cloudinary.com/image/upload/assets/${networkPath}/${address}.png`; } diff --git a/src/utils/requestNavigationHandlers.ts b/src/utils/requestNavigationHandlers.ts index fe7abb2dd6a..c48d68ef87a 100644 --- a/src/utils/requestNavigationHandlers.ts +++ b/src/utils/requestNavigationHandlers.ts @@ -35,7 +35,7 @@ import { toUtf8String } from '@ethersproject/strings'; import { BigNumber } from '@ethersproject/bignumber'; import { Address } from 'viem'; import { ChainId } from '@/chains/types'; -import { chainsName, SUPPORTED_MAINNET_CHAIN_IDS } from '@/chains'; +import { getChainsName, getSupportedMainnetChainIds } from '@/chains'; import { MobileWalletProtocolUserErrors } from '@/components/MobileWalletProtocolListener'; import { hideWalletConnectToast } from '@/components/toasts/WalletConnectToast'; @@ -123,7 +123,7 @@ export const handleMobileWalletProtocolRequest = async ({ const routeParams: WalletconnectApprovalSheetRouteParams = { receivedTimestamp, meta: { - chainIds: SUPPORTED_MAINNET_CHAIN_IDS, + chainIds: getSupportedMainnetChainIds(), dappName: dappMetadata?.appName || dappMetadata?.appUrl || action.appName || action.appIconUrl || action.appId || '', dappUrl: dappMetadata?.appUrl || action.appId || '', imageUrl: maybeSignUri(dappMetadata?.iconUrl || action.appIconUrl), @@ -169,7 +169,7 @@ export const handleMobileWalletProtocolRequest = async ({ } if (action.method === 'wallet_switchEthereumChain') { - const isSupportedChain = SUPPORTED_MAINNET_CHAIN_IDS.includes(BigNumber.from(action.params.chainId).toNumber()); + const isSupportedChain = getSupportedMainnetChainIds().includes(BigNumber.from(action.params.chainId).toNumber()); if (!isSupportedChain) { await rejectAction(action, { message: 'Unsupported chain', @@ -301,7 +301,7 @@ export const handleDappBrowserConnectionPrompt = ( const routeParams: WalletconnectApprovalSheetRouteParams = { receivedTimestamp, meta: { - chainIds: SUPPORTED_MAINNET_CHAIN_IDS, + chainIds: getSupportedMainnetChainIds(), dappName: dappData?.dappName || dappData.dappUrl, dappUrl: dappData.dappUrl, imageUrl: maybeSignUri(dappData.imageUrl), @@ -404,7 +404,7 @@ export const handleWalletConnectRequest = async (request: WalletconnectRequestDa // @ts-expect-error Property '_chainId' is private and only accessible within class 'Connector'.ts(2341) const chainId = request?.walletConnectV2RequestValues?.chainId || walletConnector?._chainId; - const network = chainsName[chainId]; + const network = getChainsName()[chainId]; // @ts-expect-error Property '_accounts' is private and only accessible within class 'Connector'.ts(2341) const address = request?.walletConnectV2RequestValues?.address || walletConnector?._accounts?.[0]; diff --git a/src/walletConnect/index.tsx b/src/walletConnect/index.tsx index 5fd857f8ab6..a6f58994df2 100644 --- a/src/walletConnect/index.tsx +++ b/src/walletConnect/index.tsx @@ -44,7 +44,7 @@ import { handleWalletConnectRequest } from '@/utils/requestNavigationHandlers'; import { PerformanceMetrics } from '@/performance/tracking/types/PerformanceMetrics'; import { PerformanceTracking } from '@/performance/tracking'; import { ChainId } from '@/chains/types'; -import { SUPPORTED_CHAIN_IDS } from '@/chains'; +import { getSupportedChainIds } from '@/chains'; import { hideWalletConnectToast } from '@/components/toasts/WalletConnectToast'; const SUPPORTED_SESSION_EVENTS = ['chainChanged', 'accountsChanged']; @@ -447,7 +447,7 @@ export async function onSessionProposal(proposal: WalletKitTypes.SessionProposal // we already checked for eip155 namespace above const chainIds = chains?.map(chain => parseInt(chain.split('eip155:')[1])); - const supportedChainIds = chainIds.filter(chainId => SUPPORTED_CHAIN_IDS.includes(chainId)); + const supportedChainIds = chainIds.filter(chainId => getSupportedChainIds().includes(chainId)); const peerMeta = proposer.metadata; const metadata = await fetchDappMetadata({ url: peerMeta.url, status: true }); @@ -488,7 +488,7 @@ export async function onSessionProposal(proposal: WalletKitTypes.SessionProposal const supportedEvents = requiredNamespaces?.eip155?.events || SUPPORTED_SESSION_EVENTS; /** @see https://chainagnostic.org/CAIPs/caip-2 */ - const caip2ChainIds = SUPPORTED_CHAIN_IDS.map(id => `eip155:${id}`); + const caip2ChainIds = getSupportedChainIds().map(id => `eip155:${id}`); const namespaces = getApprovedNamespaces({ proposal: proposal.params, supportedNamespaces: { From e446a5f0df49bf1657e69429da9354b0063ffb83 Mon Sep 17 00:00:00 2001 From: Matthew Wall Date: Mon, 21 Oct 2024 16:35:13 -0400 Subject: [PATCH 02/11] backend networks store --- src/chains/index.ts | 52 +++++++-------- src/components/BackendNetworks.tsx | 7 +- src/resources/metadata/backendNetworks.ts | 8 +-- src/state/backendNetworks/backendNetworks.ts | 68 ++++++++++++++++++++ 4 files changed, 104 insertions(+), 31 deletions(-) create mode 100644 src/state/backendNetworks/backendNetworks.ts diff --git a/src/chains/index.ts b/src/chains/index.ts index 69ffd94341d..59abdb2d260 100644 --- a/src/chains/index.ts +++ b/src/chains/index.ts @@ -1,28 +1,34 @@ import { Chain } from 'viem/chains'; -import { queryClient } from '@/react-query'; -import { backendNetworksQueryKey, BackendNetworksResponse } from '@/resources/metadata/backendNetworks'; +import { BackendNetworksResponse } from '@/resources/metadata/backendNetworks'; import { ChainId, BackendNetwork, BackendNetworkServices, chainHardhat, chainHardhatOptimism } from './types'; import { transformBackendNetworksToChains } from './utils/backendNetworks'; import { gasUtils } from '@/utils'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; import { IS_TEST } from '@/env'; import buildTimeNetworks from '@/references/networks.json'; +import { backendNetworksStore } from '@/state/backendNetworks/backendNetworks'; + +const backendNetworks = backendNetworksStore.getState().backendNetworks; const getBackendNetworks = (): BackendNetworksResponse => { - return queryClient.getQueryData(backendNetworksQueryKey()) ?? buildTimeNetworks; + 'worklet'; + return backendNetworks.value ?? buildTimeNetworks; }; const getBackendChains = (): Chain[] => { + 'worklet'; const backendNetworks = getBackendNetworks(); return transformBackendNetworksToChains(backendNetworks.networks); }; export const getSupportedChains = (): Chain[] => { + 'worklet'; const backendChains = getBackendChains(); return IS_TEST ? [...backendChains, chainHardhat, chainHardhatOptimism] : backendChains; }; export const getDefaultChains = (): Record => { + 'worklet'; const supportedChains = getSupportedChains(); return supportedChains.reduce( (acc, chain) => { @@ -34,18 +40,22 @@ export const getDefaultChains = (): Record => { }; export const getSupportedChainIds = (): ChainId[] => { + 'worklet'; return getSupportedChains().map(chain => chain.id); }; export const getSupportedMainnetChains = (): Chain[] => { + 'worklet'; return getSupportedChains().filter(chain => !chain.testnet); }; export const getSupportedMainnetChainIds = (): ChainId[] => { + 'worklet'; return getSupportedMainnetChains().map(chain => chain.id); }; export const getNeedsL1SecurityFeeChains = (): ChainId[] => { + 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks .filter((backendNetwork: BackendNetwork) => backendNetwork.opStack) @@ -53,6 +63,7 @@ export const getNeedsL1SecurityFeeChains = (): ChainId[] => { }; export const getChainsNativeAsset = (): Record => { + 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -64,6 +75,7 @@ export const getChainsNativeAsset = (): Record => { + 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -75,6 +87,7 @@ export const getChainsLabel = (): Record => { }; export const getChainsName = (): Record => { + 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -86,6 +99,7 @@ export const getChainsName = (): Record => { }; export const getChainsIdByName = (): Record => { + 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -97,6 +111,7 @@ export const getChainsIdByName = (): Record => { }; const defaultGasSpeeds = (chainId: ChainId) => { + 'worklet'; switch (chainId) { case ChainId.bsc: case ChainId.goerli: @@ -110,6 +125,7 @@ const defaultGasSpeeds = (chainId: ChainId) => { }; export const getChainsGasSpeeds = (): Record => { + 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -121,6 +137,7 @@ export const getChainsGasSpeeds = (): Record => { }; const defaultPollingIntervals = (chainId: ChainId) => { + 'worklet'; switch (chainId) { case ChainId.polygon: return 2_000; @@ -133,6 +150,7 @@ const defaultPollingIntervals = (chainId: ChainId) => { }; export const getChainsSwapPollingInterval = (): Record => { + 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -144,6 +162,7 @@ export const getChainsSwapPollingInterval = (): Record => { }; const defaultSimplehashNetworks = (chainId: ChainId) => { + 'worklet'; switch (chainId) { case ChainId.apechain: return 'apechain'; @@ -177,6 +196,7 @@ const defaultSimplehashNetworks = (chainId: ChainId) => { }; export const getChainsSimplehashNetwork = (): Record => { + 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -188,6 +208,7 @@ export const getChainsSimplehashNetwork = (): Record => { }; const filterChainIdsByService = (servicePath: (services: BackendNetworkServices) => boolean): number[] => { + 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks .filter((network: BackendNetwork) => { @@ -219,30 +240,8 @@ export const supportedFlashbotsChainIds = [ChainId.mainnet]; export const shouldDefaultToFastGasChainIds = [ChainId.mainnet, ChainId.polygon, ChainId.goerli]; -export const oldDefaultRPC: { [key in ChainId]?: string } = { - [ChainId.mainnet]: process.env.ETH_MAINNET_RPC, - [ChainId.optimism]: process.env.OPTIMISM_MAINNET_RPC, - [ChainId.arbitrum]: process.env.ARBITRUM_MAINNET_RPC, - [ChainId.polygon]: process.env.POLYGON_MAINNET_RPC, - [ChainId.base]: process.env.BASE_MAINNET_RPC, - [ChainId.zora]: process.env.ZORA_MAINNET_RPC, - [ChainId.bsc]: process.env.BSC_MAINNET_RPC, - [ChainId.sepolia]: process.env.ETH_SEPOLIA_RPC, - [ChainId.holesky]: process.env.ETH_HOLESKY_RPC, - [ChainId.optimismSepolia]: process.env.OPTIMISM_SEPOLIA_RPC, - [ChainId.bscTestnet]: process.env.BSC_TESTNET_RPC, - [ChainId.arbitrumSepolia]: process.env.ARBITRUM_SEPOLIA_RPC, - [ChainId.baseSepolia]: process.env.BASE_SEPOLIA_RPC, - [ChainId.zoraSepolia]: process.env.ZORA_SEPOLIA_RPC, - [ChainId.avalanche]: process.env.AVALANCHE_MAINNET_RPC, - [ChainId.avalancheFuji]: process.env.AVALANCHE_FUJI_RPC, - [ChainId.blast]: process.env.BLAST_MAINNET_RPC, - [ChainId.blastSepolia]: process.env.BLAST_SEPOLIA_RPC, - [ChainId.polygonAmoy]: process.env.POLYGON_AMOY_RPC, - [ChainId.degen]: process.env.DEGEN_MAINNET_RPC, -}; - export const getChainGasUnits = (chainId?: number): BackendNetwork['gasUnits'] => { + 'worklet'; const backendNetworks = getBackendNetworks(); const chainsGasUnits = backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -256,6 +255,7 @@ export const getChainGasUnits = (chainId?: number): BackendNetwork['gasUnits'] = }; export const getChainDefaultRpc = (chainId: ChainId) => { + 'worklet'; switch (chainId) { case ChainId.mainnet: return useConnectedToHardhatStore.getState().connectedToHardhat diff --git a/src/components/BackendNetworks.tsx b/src/components/BackendNetworks.tsx index 9ff6747ddd2..415d05b1796 100644 --- a/src/components/BackendNetworks.tsx +++ b/src/components/BackendNetworks.tsx @@ -1,7 +1,12 @@ import { useBackendNetworks } from '@/resources/metadata/backendNetworks'; +import { backendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const BackendNetworks = () => { - useBackendNetworks(); + useBackendNetworks({ + onSuccess(data) { + backendNetworksStore.getState().setBackendNetworks(data); + }, + }); return null; }; diff --git a/src/resources/metadata/backendNetworks.ts b/src/resources/metadata/backendNetworks.ts index 71a1f75b695..860c3019dff 100644 --- a/src/resources/metadata/backendNetworks.ts +++ b/src/resources/metadata/backendNetworks.ts @@ -50,13 +50,13 @@ export async function backendNetworksQueryFunction({ // /////////////////////////////////////////////// // Query Hook -export function useBackendNetworks( - config: QueryConfigWithSelect = {} +export function useBackendNetworks( + config: QueryConfigWithSelect = {} ) { return useQuery(backendNetworksQueryKey(), backendNetworksQueryFunction, { ...config, - cacheTime: 1000 * 60 * 60 * 24, // 24 hours - staleTime: 1000 * 60 * 15, // 15 minutes + refetchInterval: 60_000, + staleTime: process.env.IS_TESTING === 'true' ? 0 : 1000, }); } diff --git a/src/state/backendNetworks/backendNetworks.ts b/src/state/backendNetworks/backendNetworks.ts new file mode 100644 index 00000000000..af757dc6665 --- /dev/null +++ b/src/state/backendNetworks/backendNetworks.ts @@ -0,0 +1,68 @@ +import { BackendNetworksResponse } from '@/resources/metadata/backendNetworks'; +import { createRainbowStore } from '@/state/internal/createRainbowStore'; +import { makeMutable, SharedValue } from 'react-native-reanimated'; +import { logger, RainbowError } from '@/logger'; +import buildTimeNetworks from '@/references/networks.json'; + +export interface BackendNetworksState { + backendNetworks: SharedValue; + setBackendNetworks: (backendNetworks: BackendNetworksResponse) => void; +} + +type StateWithTransforms = Omit, 'backendNetworks'> & { + backendNetworks: BackendNetworksResponse; +}; + +function serializer(state: Partial, version?: number) { + try { + const transformedStateToPersist: StateWithTransforms = { + ...state, + backendNetworks: state.backendNetworks ? state.backendNetworks.value : buildTimeNetworks, + }; + + return JSON.stringify({ + state: transformedStateToPersist, + version, + }); + } catch (error) { + logger.error(new RainbowError(`[backendNetworksStore]: Failed to serialize state for backend networks storage`), { + error, + }); + throw error; + } +} + +function deserializer(serializedState: string) { + let parsedState: { state: StateWithTransforms; version: number }; + try { + parsedState = JSON.parse(serializedState); + } catch (error) { + logger.error(new RainbowError(`[backendNetworksStore]: Failed to parse serialized state from backend networks storage`), { + error, + }); + throw error; + } + + const { state, version } = parsedState; + + return { + state: { + ...state, + backendNetworks: makeMutable(state.backendNetworks), + }, + version, + }; +} + +export const backendNetworksStore = createRainbowStore( + set => ({ + backendNetworks: makeMutable(buildTimeNetworks), + setBackendNetworks: (backendNetworks: BackendNetworksResponse) => set({ backendNetworks: makeMutable(backendNetworks) }), + }), + { + storageKey: 'backendNetworks', + version: 1, + serializer, + deserializer, + } +); From 08c8dd8f701c6140ce9694c4fbd7d43a811a9e9f Mon Sep 17 00:00:00 2001 From: Matthew Wall Date: Mon, 21 Oct 2024 21:06:04 -0400 Subject: [PATCH 03/11] wrote a couple worklet functions to get swaps working --- .../screens/Swap/components/ReviewPanel.tsx | 8 +- .../components/TokenList/ChainSelection.tsx | 8 +- .../Swap/hooks/useSwapInputsController.ts | 11 ++- .../screens/Swap/providers/swap-provider.tsx | 7 +- src/__swaps__/utils/swaps.ts | 12 ++- src/chains/index.ts | 52 ++++++------ src/components/BackendNetworks.tsx | 4 +- src/state/backendNetworks/backendNetworks.ts | 81 +++++-------------- 8 files changed, 84 insertions(+), 99 deletions(-) diff --git a/src/__swaps__/screens/Swap/components/ReviewPanel.tsx b/src/__swaps__/screens/Swap/components/ReviewPanel.tsx index 44a8c2d3622..2b9360844f3 100644 --- a/src/__swaps__/screens/Swap/components/ReviewPanel.tsx +++ b/src/__swaps__/screens/Swap/components/ReviewPanel.tsx @@ -48,8 +48,9 @@ import { NavigationSteps, useSwapContext } from '../providers/swap-provider'; import { AnimatedSwitch } from './AnimatedSwitch'; import { EstimatedSwapGasFee, EstimatedSwapGasFeeSlot } from './EstimatedSwapGasFee'; import { UnmountOnAnimatedReaction } from './UnmountOnAnimatedReaction'; -import { getChainsLabel } from '@/chains'; +import { getChainsLabelWorklet } from '@/chains'; import { ChainId } from '@/chains/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const UNKNOWN_LABEL = i18n.t(i18n.l.swap.unknown); const REVIEW_LABEL = i18n.t(i18n.l.expanded_state.swap_details.review); @@ -318,6 +319,7 @@ export const SlippageRow = () => { export function ReviewPanel() { const { navigate } = useNavigation(); const { isDarkMode } = useColorMode(); + const backendNetworks = useBackendNetworksStore(state => state.backendNetworksSharedValue); const { configProgress, lastTypedInput, internalSelectedInputAsset, internalSelectedOutputAsset, quote } = useSwapContext(); const labelTertiary = useForegroundColor('labelTertiary'); @@ -325,7 +327,9 @@ export function ReviewPanel() { const unknown = i18n.t(i18n.l.swap.unknown); - const chainName = useDerivedValue(() => getChainsLabel()[internalSelectedInputAsset.value?.chainId ?? ChainId.mainnet]); + const chainName = useDerivedValue( + () => getChainsLabelWorklet(backendNetworks)[internalSelectedInputAsset.value?.chainId ?? ChainId.mainnet] + ); const minReceivedOrMaxSoldLabel = useDerivedValue(() => { const isInputBasedTrade = lastTypedInput.value === 'inputAmount' || lastTypedInput.value === 'inputNativeValue'; diff --git a/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx b/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx index 26c171c59cf..7b0d9d6fbb6 100644 --- a/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx +++ b/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx @@ -18,7 +18,8 @@ import { userAssetsStore, useUserAssetsStore } from '@/state/assets/userAssets'; import { swapsStore } from '@/state/swaps/swapsStore'; import { showActionSheetWithOptions } from '@/utils'; import { OnPressMenuItemEventObject } from 'react-native-ios-context-menu'; -import { getChainsLabel, getChainsName } from '@/chains'; +import { getChainsLabel, getChainsLabelWorklet, getChainsName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; type ChainSelectionProps = { allText?: string; @@ -29,6 +30,7 @@ export const ChainSelection = memo(function ChainSelection({ allText, output }: const { isDarkMode } = useColorMode(); const { accentColor: accountColor } = useAccountAccentColor(); const { selectedOutputChainId, setSelectedOutputChainId } = useSwapContext(); + const backendNetworks = useBackendNetworksStore(state => state.backendNetworksSharedValue); // chains sorted by balance on output, chains without balance hidden on input const { balanceSortedChainList, filter } = useUserAssetsStore(state => ({ @@ -48,10 +50,10 @@ export const ChainSelection = memo(function ChainSelection({ allText, output }: const chainName = useDerivedValue(() => { return output - ? getChainsLabel()[selectedOutputChainId.value] + ? getChainsLabelWorklet(backendNetworks)[selectedOutputChainId.value] : inputListFilter.value === 'all' ? allText - : getChainsLabel()[inputListFilter.value as ChainId]; + : getChainsLabelWorklet(backendNetworks)[inputListFilter.value as ChainId]; }); const handleSelectChain = useCallback( diff --git a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts index 877ef1eb5b1..1e43105fba3 100644 --- a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts +++ b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts @@ -47,6 +47,7 @@ import { SharedValue, runOnJS, runOnUI, useAnimatedReaction, useDerivedValue, us import { useDebouncedCallback } from 'use-debounce'; import { NavigationSteps } from './useSwapNavigation'; import { deepEqualWorklet } from '@/worklets/comparisons'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const REMOTE_CONFIG = getRemoteConfig(); @@ -77,6 +78,8 @@ export function useSwapInputsController({ sliderXPosition: SharedValue; slippage: SharedValue; }) { + const backendNetworks = useBackendNetworksStore(state => state.backendNetworksSharedValue); + const percentageToSwap = useDerivedValue(() => { return Math.round(clamp((sliderXPosition.value - SCRUBBER_WIDTH / SLIDER_WIDTH) / SLIDER_WIDTH, 0, 1) * 100) / 100; }); @@ -665,11 +668,15 @@ export function useSwapInputsController({ if (!didInputAssetChange && !didOutputAssetChange) return; if (current.assetToSellNetwork !== previous?.assetToSellNetwork) { - const previousDefaultSlippage = getDefaultSlippageWorklet(previous?.assetToSellNetwork || ChainId.mainnet, REMOTE_CONFIG); + const previousDefaultSlippage = getDefaultSlippageWorklet( + previous?.assetToSellNetwork || ChainId.mainnet, + REMOTE_CONFIG, + backendNetworks + ); // If the user has not overridden the default slippage, update it if (slippage.value === previousDefaultSlippage) { - const newSlippage = getDefaultSlippageWorklet(current.assetToSellNetwork || ChainId.mainnet, REMOTE_CONFIG); + const newSlippage = getDefaultSlippageWorklet(current.assetToSellNetwork || ChainId.mainnet, REMOTE_CONFIG, backendNetworks); slippage.value = newSlippage; runOnJS(setSlippage)(newSlippage); } diff --git a/src/__swaps__/screens/Swap/providers/swap-provider.tsx b/src/__swaps__/screens/Swap/providers/swap-provider.tsx index 41190c5c650..9fe1fbf0c13 100644 --- a/src/__swaps__/screens/Swap/providers/swap-provider.tsx +++ b/src/__swaps__/screens/Swap/providers/swap-provider.tsx @@ -57,6 +57,7 @@ import { performanceTracking, Screens, TimeToSignOperation } from '@/state/perfo import { getRemoteConfig } from '@/model/remoteConfig'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; import { getChainsNativeAsset, supportedFlashbotsChainIds } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const swapping = i18n.t(i18n.l.swap.actions.swapping); const holdToSwap = i18n.t(i18n.l.swap.actions.hold_to_swap); @@ -135,6 +136,8 @@ interface SwapProviderProps { export const SwapProvider = ({ children }: SwapProviderProps) => { const { nativeCurrency } = useAccountSettings(); + const backendNetworks = useBackendNetworksStore(state => state.backendNetworksSharedValue); + const isFetching = useSharedValue(false); const isQuoteStale = useSharedValue(0); // TODO: Convert this to a boolean const isSwapping = useSharedValue(false); @@ -164,7 +167,9 @@ export const SwapProvider = ({ children }: SwapProviderProps) => { ); const configProgress = useSharedValue(NavigationSteps.INPUT_ELEMENT_FOCUSED); - const slippage = useSharedValue(getDefaultSlippageWorklet(initialSelectedInputAsset?.chainId || ChainId.mainnet, getRemoteConfig())); + const slippage = useSharedValue( + getDefaultSlippageWorklet(initialSelectedInputAsset?.chainId || ChainId.mainnet, getRemoteConfig(), backendNetworks) + ); const hasEnoughFundsForGas = useSharedValue(undefined); diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index ad4b4e0c439..520a7b7c052 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -38,7 +38,8 @@ import { AddressOrEth, ExtendedAnimatedAssetWithColors, ParsedSearchAsset } from import { inputKeys } from '../types/swap'; import { valueBasedDecimalFormatter } from './decimalFormatter'; import { convertAmountToRawAmount } from './numbers'; -import { getChainsName } from '@/chains'; +import { getChainsName, getChainsNameWorklet } from '@/chains'; +import { BackendNetworksResponse } from '@/resources/metadata/backendNetworks'; // /---- 🎨 Color functions 🎨 ----/ // // @@ -367,11 +368,16 @@ export const getDefaultSlippage = (chainId: ChainId, config: RainbowConfig) => { ); }; -export const getDefaultSlippageWorklet = (chainId: ChainId, config: RainbowConfig) => { +export const getDefaultSlippageWorklet = ( + chainId: ChainId, + config: RainbowConfig, + backendNetworks: SharedValue +) => { 'worklet'; return slippageInBipsToStringWorklet( - (config.default_slippage_bips as unknown as { [key: string]: number })[getChainsName()[chainId]] || DEFAULT_SLIPPAGE_BIPS[chainId] + (config.default_slippage_bips as unknown as { [key: string]: number })[getChainsNameWorklet(backendNetworks)[chainId]] || + DEFAULT_SLIPPAGE_BIPS[chainId] ); }; diff --git a/src/chains/index.ts b/src/chains/index.ts index 59abdb2d260..7ff8e5b9e2b 100644 --- a/src/chains/index.ts +++ b/src/chains/index.ts @@ -6,29 +6,24 @@ import { gasUtils } from '@/utils'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; import { IS_TEST } from '@/env'; import buildTimeNetworks from '@/references/networks.json'; -import { backendNetworksStore } from '@/state/backendNetworks/backendNetworks'; - -const backendNetworks = backendNetworksStore.getState().backendNetworks; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; +import { SharedValue } from 'react-native-reanimated'; const getBackendNetworks = (): BackendNetworksResponse => { - 'worklet'; - return backendNetworks.value ?? buildTimeNetworks; + return useBackendNetworksStore.getState().backendNetworks ?? buildTimeNetworks; }; const getBackendChains = (): Chain[] => { - 'worklet'; const backendNetworks = getBackendNetworks(); return transformBackendNetworksToChains(backendNetworks.networks); }; export const getSupportedChains = (): Chain[] => { - 'worklet'; const backendChains = getBackendChains(); return IS_TEST ? [...backendChains, chainHardhat, chainHardhatOptimism] : backendChains; }; export const getDefaultChains = (): Record => { - 'worklet'; const supportedChains = getSupportedChains(); return supportedChains.reduce( (acc, chain) => { @@ -40,22 +35,18 @@ export const getDefaultChains = (): Record => { }; export const getSupportedChainIds = (): ChainId[] => { - 'worklet'; return getSupportedChains().map(chain => chain.id); }; export const getSupportedMainnetChains = (): Chain[] => { - 'worklet'; return getSupportedChains().filter(chain => !chain.testnet); }; export const getSupportedMainnetChainIds = (): ChainId[] => { - 'worklet'; return getSupportedMainnetChains().map(chain => chain.id); }; export const getNeedsL1SecurityFeeChains = (): ChainId[] => { - 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks .filter((backendNetwork: BackendNetwork) => backendNetwork.opStack) @@ -63,7 +54,6 @@ export const getNeedsL1SecurityFeeChains = (): ChainId[] => { }; export const getChainsNativeAsset = (): Record => { - 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -75,7 +65,6 @@ export const getChainsNativeAsset = (): Record => { - 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -87,7 +76,6 @@ export const getChainsLabel = (): Record => { }; export const getChainsName = (): Record => { - 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -99,7 +87,6 @@ export const getChainsName = (): Record => { }; export const getChainsIdByName = (): Record => { - 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -111,7 +98,6 @@ export const getChainsIdByName = (): Record => { }; const defaultGasSpeeds = (chainId: ChainId) => { - 'worklet'; switch (chainId) { case ChainId.bsc: case ChainId.goerli: @@ -125,7 +111,6 @@ const defaultGasSpeeds = (chainId: ChainId) => { }; export const getChainsGasSpeeds = (): Record => { - 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -137,7 +122,6 @@ export const getChainsGasSpeeds = (): Record => { }; const defaultPollingIntervals = (chainId: ChainId) => { - 'worklet'; switch (chainId) { case ChainId.polygon: return 2_000; @@ -150,7 +134,6 @@ const defaultPollingIntervals = (chainId: ChainId) => { }; export const getChainsSwapPollingInterval = (): Record => { - 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -162,7 +145,6 @@ export const getChainsSwapPollingInterval = (): Record => { }; const defaultSimplehashNetworks = (chainId: ChainId) => { - 'worklet'; switch (chainId) { case ChainId.apechain: return 'apechain'; @@ -196,7 +178,6 @@ const defaultSimplehashNetworks = (chainId: ChainId) => { }; export const getChainsSimplehashNetwork = (): Record => { - 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -208,7 +189,6 @@ export const getChainsSimplehashNetwork = (): Record => { }; const filterChainIdsByService = (servicePath: (services: BackendNetworkServices) => boolean): number[] => { - 'worklet'; const backendNetworks = getBackendNetworks(); return backendNetworks.networks .filter((network: BackendNetwork) => { @@ -241,7 +221,6 @@ export const supportedFlashbotsChainIds = [ChainId.mainnet]; export const shouldDefaultToFastGasChainIds = [ChainId.mainnet, ChainId.polygon, ChainId.goerli]; export const getChainGasUnits = (chainId?: number): BackendNetwork['gasUnits'] => { - 'worklet'; const backendNetworks = getBackendNetworks(); const chainsGasUnits = backendNetworks.networks.reduce( (acc, backendNetwork: BackendNetwork) => { @@ -255,7 +234,6 @@ export const getChainGasUnits = (chainId?: number): BackendNetwork['gasUnits'] = }; export const getChainDefaultRpc = (chainId: ChainId) => { - 'worklet'; switch (chainId) { case ChainId.mainnet: return useConnectedToHardhatStore.getState().connectedToHardhat @@ -265,3 +243,27 @@ export const getChainDefaultRpc = (chainId: ChainId) => { return getDefaultChains()[chainId].rpcUrls.default.http[0]; } }; + +// --- worklet functions --- + +export const getChainsLabelWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return backendNetworks.value.networks.reduce( + (acc, backendNetwork: BackendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = backendNetwork.label; + return acc; + }, + {} as Record + ); +}; + +export const getChainsNameWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return backendNetworks.value.networks.reduce( + (acc, backendNetwork: BackendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = backendNetwork.name; + return acc; + }, + {} as Record + ); +}; diff --git a/src/components/BackendNetworks.tsx b/src/components/BackendNetworks.tsx index 415d05b1796..ba1d9e6337f 100644 --- a/src/components/BackendNetworks.tsx +++ b/src/components/BackendNetworks.tsx @@ -1,10 +1,10 @@ import { useBackendNetworks } from '@/resources/metadata/backendNetworks'; -import { backendNetworksStore } from '@/state/backendNetworks/backendNetworks'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const BackendNetworks = () => { useBackendNetworks({ onSuccess(data) { - backendNetworksStore.getState().setBackendNetworks(data); + useBackendNetworksStore.getState().setBackendNetworks(data); }, }); diff --git a/src/state/backendNetworks/backendNetworks.ts b/src/state/backendNetworks/backendNetworks.ts index af757dc6665..110d25766b1 100644 --- a/src/state/backendNetworks/backendNetworks.ts +++ b/src/state/backendNetworks/backendNetworks.ts @@ -1,68 +1,27 @@ -import { BackendNetworksResponse } from '@/resources/metadata/backendNetworks'; -import { createRainbowStore } from '@/state/internal/createRainbowStore'; import { makeMutable, SharedValue } from 'react-native-reanimated'; -import { logger, RainbowError } from '@/logger'; +import { queryClient } from '@/react-query'; import buildTimeNetworks from '@/references/networks.json'; +import { backendNetworksQueryKey, BackendNetworksResponse } from '@/resources/metadata/backendNetworks'; +import { createRainbowStore } from '@/state/internal/createRainbowStore'; -export interface BackendNetworksState { - backendNetworks: SharedValue; - setBackendNetworks: (backendNetworks: BackendNetworksResponse) => void; -} +const INITIAL_BACKEND_NETWORKS = queryClient.getQueryData(backendNetworksQueryKey()) ?? buildTimeNetworks; -type StateWithTransforms = Omit, 'backendNetworks'> & { +export interface BackendNetworksState { backendNetworks: BackendNetworksResponse; -}; - -function serializer(state: Partial, version?: number) { - try { - const transformedStateToPersist: StateWithTransforms = { - ...state, - backendNetworks: state.backendNetworks ? state.backendNetworks.value : buildTimeNetworks, - }; - - return JSON.stringify({ - state: transformedStateToPersist, - version, - }); - } catch (error) { - logger.error(new RainbowError(`[backendNetworksStore]: Failed to serialize state for backend networks storage`), { - error, - }); - throw error; - } -} - -function deserializer(serializedState: string) { - let parsedState: { state: StateWithTransforms; version: number }; - try { - parsedState = JSON.parse(serializedState); - } catch (error) { - logger.error(new RainbowError(`[backendNetworksStore]: Failed to parse serialized state from backend networks storage`), { - error, - }); - throw error; - } - - const { state, version } = parsedState; - - return { - state: { - ...state, - backendNetworks: makeMutable(state.backendNetworks), - }, - version, - }; + backendNetworksSharedValue: SharedValue; + setBackendNetworks: (backendNetworks: BackendNetworksResponse) => void; } -export const backendNetworksStore = createRainbowStore( - set => ({ - backendNetworks: makeMutable(buildTimeNetworks), - setBackendNetworks: (backendNetworks: BackendNetworksResponse) => set({ backendNetworks: makeMutable(backendNetworks) }), - }), - { - storageKey: 'backendNetworks', - version: 1, - serializer, - deserializer, - } -); +export const useBackendNetworksStore = createRainbowStore(set => ({ + backendNetworks: INITIAL_BACKEND_NETWORKS, + backendNetworksSharedValue: makeMutable(INITIAL_BACKEND_NETWORKS), + + setBackendNetworks: backendNetworks => + set(state => { + state.backendNetworksSharedValue.value = backendNetworks; + return { + ...state, + backendNetworks: backendNetworks, + }; + }), +})); From 64bd9697a7b503be760441bb0ba54f99cb5fb3d8 Mon Sep 17 00:00:00 2001 From: Matthew Wall Date: Mon, 21 Oct 2024 21:17:27 -0400 Subject: [PATCH 04/11] fix other calls --- .../screens/Swap/components/TokenList/ChainSelection.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx b/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx index 7b0d9d6fbb6..8d0f300e819 100644 --- a/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx +++ b/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx @@ -18,7 +18,7 @@ import { userAssetsStore, useUserAssetsStore } from '@/state/assets/userAssets'; import { swapsStore } from '@/state/swaps/swapsStore'; import { showActionSheetWithOptions } from '@/utils'; import { OnPressMenuItemEventObject } from 'react-native-ios-context-menu'; -import { getChainsLabel, getChainsLabelWorklet, getChainsName } from '@/chains'; +import { getChainsLabelWorklet, getChainsNameWorklet } from '@/chains'; import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; type ChainSelectionProps = { @@ -80,11 +80,11 @@ export const ChainSelection = memo(function ChainSelection({ allText, output }: const supportedChains = balanceSortedChainList.map(chainId => { return { actionKey: `${chainId}`, - actionTitle: getChainsLabel()[chainId], + actionTitle: getChainsLabelWorklet(backendNetworks)[chainId], icon: { iconType: 'ASSET', // NOTE: chainsName[chainId] for mainnet is 'mainnet' and we need it to be 'ethereum' - iconValue: chainId === ChainId.mainnet ? 'ethereumBadge' : `${getChainsName()[chainId]}BadgeNoShadow`, + iconValue: chainId === ChainId.mainnet ? 'ethereumBadge' : `${getChainsNameWorklet(backendNetworks)[chainId]}BadgeNoShadow`, }, }; }); From ba791314a7e36892bf151fbbd9289cee455ed163 Mon Sep 17 00:00:00 2001 From: Matthew Wall Date: Wed, 23 Oct 2024 11:39:47 -0400 Subject: [PATCH 05/11] Update package.json --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 69e2e100897..b9e525e39f8 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,7 @@ "install-pods-fast": "cd ios && bundle exec pod install && cd ..", "install-pods-fast-jsc": "cd ios && bundle exec env USE_HERMES=NO pod install && cd ..", "install-pods-no-flipper": "cd ios && bundle exec env SKIP_FLIPPER=true pod install --repo-update && cd ..", - "ios": "react-native run-ios --simulator='iPhone 15 Pro'", + "ios": "react-native run-ios --simulator='iPhone 16 Pro'", "format": "prettier --write .", "format:check": "prettier --check .", "lint": "yarn format:check && yarn lint:ts && yarn lint:js", From 0cc068a2dcf8e0d849358c726b8b33ebdedb38e3 Mon Sep 17 00:00:00 2001 From: Matthew Wall Date: Wed, 23 Oct 2024 11:39:59 -0400 Subject: [PATCH 06/11] Update ios/Podfile.lock --- ios/Podfile.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ios/Podfile.lock b/ios/Podfile.lock index af7eb5f5407..10d554bc320 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -2525,7 +2525,7 @@ SPEC CHECKSUMS: TOCropViewController: 80b8985ad794298fb69d3341de183f33d1853654 ToolTipMenu: 8ac61aded0fbc4acfe7e84a7d0c9479d15a9a382 VisionCamera: 2af28201c3de77245f8c58b7a5274d5979df70df - Yoga: 04f1db30bb810187397fa4c37dd1868a27af229c + Yoga: 88480008ccacea6301ff7bf58726e27a72931c8d PODFILE CHECKSUM: 98c3fc206d7041ac7388693bb0753109d1884b57 From 2dbbbbcd38aa7ff193e75f4551aec6dd1bb80cfd Mon Sep 17 00:00:00 2001 From: Matthew Wall Date: Thu, 24 Oct 2024 14:05:51 -0400 Subject: [PATCH 07/11] move all functions into backendNetworksStore and replace calls --- src/__swaps__/screens/Swap/Swap.tsx | 2 +- .../components/AnimatedChainImage.android.tsx | 2 +- .../components/AnimatedChainImage.ios.tsx | 2 +- .../screens/Swap/components/CoinRow.tsx | 9 +- .../screens/Swap/components/FlipButton.tsx | 2 +- .../screens/Swap/components/GasButton.tsx | 2 +- .../screens/Swap/components/GasPanel.tsx | 2 +- .../screens/Swap/components/ReviewPanel.tsx | 5 +- .../screens/Swap/components/SwapCoinIcon.tsx | 2 +- .../Swap/components/SwapOutputAsset.tsx | 2 +- .../components/TokenList/ChainSelection.tsx | 13 +- .../components/TokenList/TokenToBuyList.tsx | 2 +- src/__swaps__/screens/Swap/dummyValues.ts | 2 +- .../Swap/hooks/useAnimatedSwapStyles.ts | 2 +- .../screens/Swap/hooks/useCustomGas.ts | 2 +- .../screens/Swap/hooks/useEstimatedGasFee.ts | 4 +- .../Swap/hooks/useNativeAssetForChain.ts | 2 +- .../Swap/hooks/useSearchCurrencyLists.ts | 2 +- .../screens/Swap/hooks/useSelectedGas.ts | 2 +- .../Swap/hooks/useSwapEstimatedGasLimit.ts | 2 +- .../Swap/hooks/useSwapInputsController.ts | 16 +- .../Swap/hooks/useSwapOutputQuotesDisabled.ts | 12 +- .../SyncSwapStateAndSharedValues.tsx | 2 +- .../screens/Swap/providers/swap-provider.tsx | 21 +- .../Swap/resources/_selectors/assets.ts | 2 +- .../screens/Swap/resources/assets/assets.ts | 2 +- .../Swap/resources/assets/userAssets.ts | 6 +- .../resources/assets/userAssetsByChain.ts | 2 +- .../Swap/resources/search/discovery.ts | 2 +- .../screens/Swap/resources/search/search.ts | 2 +- .../screens/Swap/resources/search/utils.ts | 2 +- src/__swaps__/types/assets.ts | 2 +- src/__swaps__/types/refraction.ts | 2 +- src/__swaps__/types/search.ts | 2 +- src/__swaps__/utils/address.ts | 2 +- src/__swaps__/utils/assets.ts | 18 +- src/__swaps__/utils/chains.ts | 6 +- src/__swaps__/utils/gasUtils.ts | 2 +- src/__swaps__/utils/meteorology.ts | 2 +- src/__swaps__/utils/swaps.ts | 45 +- src/__swaps__/utils/userChains.ts | 27 +- src/analytics/event.ts | 2 +- src/appIcons/appIcons.ts | 2 +- src/chains/index.ts | 273 -------- .../control-panel/ControlPanel.tsx | 8 +- .../DappBrowser/handleProviderRequest.ts | 15 +- .../Transactions/TransactionDetailsCard.tsx | 12 +- .../Transactions/TransactionDetailsRow.tsx | 2 +- .../TransactionSimulatedEventRow.tsx | 6 +- .../TransactionSimulationCard.tsx | 6 +- .../FastComponents/FastBalanceCoinRow.tsx | 2 +- .../FastComponents/FastCoinBadge.tsx | 2 +- .../FastCurrencySelectionRow.tsx | 2 +- .../ProfileActionButtonsRow.tsx | 2 +- src/components/cards/EthCard.tsx | 2 +- src/components/cards/NFTOffersCard/Offer.tsx | 6 +- src/components/cards/OpRewardsCard.tsx | 2 +- src/components/change-wallet/WalletList.tsx | 2 +- src/components/coin-icon/ChainImage.tsx | 2 +- src/components/coin-icon/EthCoinIcon.tsx | 2 +- src/components/coin-icon/RainbowCoinIcon.tsx | 2 +- src/components/coin-icon/TwoCoinsIcon.tsx | 2 +- .../coin-row/FastTransactionCoinRow.tsx | 2 +- .../context-menu-buttons/ChainContextMenu.tsx | 10 +- .../ens-profile/ActionButtons/MoreButton.tsx | 2 +- .../exchange/CurrencySelectModalHeader.tsx | 4 +- src/components/exchange/ExchangeAssetList.tsx | 1 - src/components/exchange/ExchangeField.tsx | 2 +- .../exchange/ExchangeInputField.tsx | 2 +- .../exchange/ExchangeOutputField.tsx | 2 +- src/components/exchange/ExchangeTokenRow.tsx | 2 +- src/components/exchange/NetworkSwitcherv2.tsx | 10 +- .../exchangeAssetRowContextMenuProps.ts | 18 +- .../expanded-state/AvailableNetworksv2.tsx | 24 +- .../UniqueTokenExpandedState.tsx | 2 +- .../swap-details/SwapDetailsRewardRow.tsx | 6 +- .../swap-settings/MaxToleranceInput.tsx | 2 +- .../UniqueTokenExpandedStateHeader.tsx | 2 +- src/components/gas/GasSpeedButton.tsx | 6 +- src/components/positions/PositionsCard.tsx | 6 +- .../check-fns/hasSwapTxn.ts | 4 +- .../sheet-action-buttons/SwapActionButton.tsx | 11 +- .../WalletConnectV2ListItem.tsx | 8 +- src/entities/tokens.ts | 2 +- src/entities/transactions/transaction.ts | 2 +- src/entities/uniqueAssets.ts | 2 +- src/featuresToUnlock/tokenGatedUtils.ts | 6 +- src/handlers/assets.ts | 6 +- src/handlers/ens.ts | 2 +- src/handlers/gasFees.ts | 6 +- src/handlers/localstorage/globalSettings.ts | 2 +- src/handlers/localstorage/removeWallet.ts | 2 +- src/handlers/swap.ts | 2 +- src/handlers/tokenSearch.ts | 4 +- src/handlers/web3.ts | 11 +- src/helpers/SharedValuesContext.tsx | 8 + src/helpers/ens.ts | 2 +- src/helpers/gas.ts | 2 +- src/helpers/networkInfo.ts | 2 +- src/helpers/signingWallet.ts | 2 +- src/helpers/validators.ts | 2 +- src/helpers/walletConnectNetworks.ts | 13 +- src/hooks/charts/useChartInfo.ts | 2 +- src/hooks/useAccountTransactions.ts | 13 +- src/hooks/useAdditionalAssetData.ts | 2 +- src/hooks/useAsset.ts | 2 +- src/hooks/useCalculateGasLimit.ts | 6 +- src/hooks/useENSRegistrationActionHandler.ts | 2 +- src/hooks/useENSRegistrationCosts.ts | 2 +- src/hooks/useENSRegistrationStepHandler.tsx | 2 +- src/hooks/useENSSearch.ts | 2 +- src/hooks/useGas.ts | 2 +- src/hooks/useHasEnoughBalance.ts | 2 +- src/hooks/useImportingWallet.ts | 2 +- src/hooks/useNonceForDisplay.ts | 2 +- src/hooks/usePriceImpactDetails.ts | 2 +- src/hooks/useSearchCurrencyList.ts | 6 +- src/hooks/useSwapCurrencyList.ts | 6 +- src/hooks/useSwapDerivedOutputs.ts | 5 +- src/hooks/useSwapRefuel.ts | 2 +- src/hooks/useSwappableUserAssets.ts | 36 +- src/hooks/useTransactionSetup.ts | 2 +- src/hooks/useWatchPendingTxs.ts | 10 +- .../migratePinnedAndHiddenTokenUniqueIds.ts | 2 +- src/model/remoteConfig.ts | 16 +- src/model/wallet.ts | 3 +- src/navigation/config.tsx | 6 +- src/parsers/transactions.ts | 2 +- src/raps/actions/claimBridge.ts | 12 +- src/raps/actions/crosschainSwap.ts | 12 +- src/raps/actions/ens.ts | 2 +- src/raps/actions/swap.ts | 12 +- src/raps/actions/unlock.ts | 10 +- src/raps/references.ts | 2 +- src/raps/unlockAndSwap.ts | 2 +- src/raps/utils.ts | 2 +- .../claimTransactionClaimableAction.ts | 4 +- src/redux/ensRegistration.ts | 2 +- src/redux/gas.ts | 15 +- src/redux/requests.ts | 2 +- src/redux/settings.ts | 2 +- src/redux/showcaseTokens.ts | 2 +- src/redux/walletconnect.ts | 6 +- src/references/gasUnits.ts | 2 +- src/references/index.ts | 2 +- src/references/rainbow-token-list/index.ts | 2 +- src/references/testnet-assets-by-chain.ts | 2 +- src/resources/addys/claimables/query.ts | 4 +- src/resources/addys/claimables/types.ts | 2 +- src/resources/addys/claimables/utils.ts | 6 +- src/resources/addys/types.ts | 2 +- src/resources/assets/UserAssetsQuery.ts | 6 +- src/resources/assets/assets.ts | 6 +- src/resources/assets/externalAssetsQuery.ts | 2 +- src/resources/assets/hardhatAssets.ts | 6 +- src/resources/assets/types.ts | 2 +- src/resources/assets/useUserAsset.ts | 6 +- src/resources/defi/PositionsQuery.ts | 4 +- src/resources/defi/types.ts | 2 +- src/resources/defi/utils.ts | 6 +- src/resources/ens/ensAddressQuery.ts | 2 +- src/resources/favorites.ts | 10 +- src/resources/metadata/backendNetworks.ts | 2 +- src/resources/nfts/index.ts | 2 +- src/resources/nfts/simplehash/index.ts | 12 +- src/resources/nfts/simplehash/types.ts | 2 +- src/resources/nfts/simplehash/utils.ts | 8 +- src/resources/nfts/types.ts | 2 +- src/resources/nfts/utils.ts | 2 +- src/resources/reservoir/client.ts | 2 +- src/resources/reservoir/mints.ts | 2 +- src/resources/reservoir/utils.ts | 2 +- .../transactions/consolidatedTransactions.ts | 10 +- src/resources/transactions/transaction.ts | 6 +- .../transactions/transactionSimulation.ts | 2 +- .../AddCash/components/ProviderCard.tsx | 2 +- src/screens/AddCash/utils.ts | 2 +- src/screens/CurrencySelectModal.tsx | 12 +- src/screens/ENSConfirmRegisterSheet.tsx | 3 +- src/screens/ExchangeModal.tsx | 34 +- src/screens/MintsSheet/card/Card.tsx | 6 +- src/screens/NFTOffersSheet/OfferRow.tsx | 6 +- src/screens/NFTSingleOfferSheet/index.tsx | 16 +- src/screens/SendConfirmationSheet.tsx | 8 +- src/screens/SendSheet.tsx | 14 +- .../components/CurrencySection.tsx | 2 +- .../components/NetworkSection.tsx | 6 +- src/screens/SignTransactionSheet.tsx | 15 +- src/screens/SpeedUpAndCancelSheet.tsx | 6 +- src/screens/WalletConnectApprovalSheet.tsx | 16 +- .../claimables/ClaimingClaimableSharedUI.tsx | 4 +- .../ClaimingTransactionClaimable.tsx | 4 +- src/screens/mints/MintSheet.tsx | 22 +- .../points/claim-flow/ClaimRewardsPanel.tsx | 20 +- .../points/components/LeaderboardRow.tsx | 2 +- src/screens/points/content/PointsContent.tsx | 2 +- .../points/contexts/PointsProfileContext.tsx | 2 +- src/screens/positions/SubPositionListItem.tsx | 4 +- .../TransactionDetailsValueAndFeeSection.tsx | 2 +- .../components/TransactionMasthead.tsx | 2 +- src/state/appSessions/index.test.ts | 2 +- src/state/appSessions/index.ts | 2 +- src/state/assets/userAssets.ts | 21 +- src/state/backendNetworks/backendNetworks.ts | 598 +++++++++++++++++- .../backendNetworks}/types.ts | 0 .../backendNetworks/utils.ts} | 2 +- src/state/nonces/index.ts | 7 +- src/state/pendingTransactions/index.ts | 2 +- src/state/staleBalances/index.test.ts | 2 +- src/state/swaps/swapsStore.ts | 2 +- src/state/sync/UserAssetsSync.tsx | 2 +- src/storage/index.ts | 2 +- src/styles/colors.ts | 2 +- src/utils/ethereumUtils.ts | 34 +- src/utils/getUrlForTrustIconFallback.ts | 6 +- src/utils/requestNavigationHandlers.ts | 15 +- src/walletConnect/index.tsx | 11 +- 217 files changed, 1250 insertions(+), 824 deletions(-) delete mode 100644 src/chains/index.ts rename src/{chains => state/backendNetworks}/types.ts (100%) rename src/{chains/utils/backendNetworks.ts => state/backendNetworks/utils.ts} (96%) diff --git a/src/__swaps__/screens/Swap/Swap.tsx b/src/__swaps__/screens/Swap/Swap.tsx index b6fd788cc39..c295f8290eb 100644 --- a/src/__swaps__/screens/Swap/Swap.tsx +++ b/src/__swaps__/screens/Swap/Swap.tsx @@ -18,7 +18,7 @@ import { SwapInputAsset } from '@/__swaps__/screens/Swap/components/SwapInputAss import { SwapNavbar } from '@/__swaps__/screens/Swap/components/SwapNavbar'; import { SwapOutputAsset } from '@/__swaps__/screens/Swap/components/SwapOutputAsset'; import { SwapSheetGestureBlocker } from '@/__swaps__/screens/Swap/components/SwapSheetGestureBlocker'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { SwapAssetType } from '@/__swaps__/types/swap'; import { parseSearchAsset } from '@/__swaps__/utils/assets'; import { AbsolutePortalRoot } from '@/components/AbsolutePortal'; diff --git a/src/__swaps__/screens/Swap/components/AnimatedChainImage.android.tsx b/src/__swaps__/screens/Swap/components/AnimatedChainImage.android.tsx index 49d30869f71..19f39bac85c 100644 --- a/src/__swaps__/screens/Swap/components/AnimatedChainImage.android.tsx +++ b/src/__swaps__/screens/Swap/components/AnimatedChainImage.android.tsx @@ -14,7 +14,7 @@ const OptimismBadge = require('@/assets/badges/optimism.png'); const PolygonBadge = require('@/assets/badges/polygon.png'); const ZoraBadge = require('@/assets/badges/zora.png'); -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { globalColors } from '@/design-system'; import { PIXEL_RATIO } from '@/utils/deviceUtils'; import { useSwapsStore } from '@/state/swaps/swapsStore'; diff --git a/src/__swaps__/screens/Swap/components/AnimatedChainImage.ios.tsx b/src/__swaps__/screens/Swap/components/AnimatedChainImage.ios.tsx index cad0369a89a..56eea037e15 100644 --- a/src/__swaps__/screens/Swap/components/AnimatedChainImage.ios.tsx +++ b/src/__swaps__/screens/Swap/components/AnimatedChainImage.ios.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { Image, StyleSheet, View } from 'react-native'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { useAnimatedProps, useDerivedValue } from 'react-native-reanimated'; import { AnimatedFasterImage } from '@/components/AnimatedComponents/AnimatedFasterImage'; import { DEFAULT_FASTER_IMAGE_CONFIG } from '@/components/images/ImgixImage'; diff --git a/src/__swaps__/screens/Swap/components/CoinRow.tsx b/src/__swaps__/screens/Swap/components/CoinRow.tsx index f1020deaf40..a02a3ba283b 100644 --- a/src/__swaps__/screens/Swap/components/CoinRow.tsx +++ b/src/__swaps__/screens/Swap/components/CoinRow.tsx @@ -1,7 +1,7 @@ import { BalancePill } from '@/__swaps__/screens/Swap/components/BalancePill'; import { CoinRowButton } from '@/__swaps__/screens/Swap/components/CoinRowButton'; -import { AddressOrEth, ParsedSearchAsset } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { AddressOrEth, ParsedSearchAsset, UniqueId } from '@/__swaps__/types/assets'; +import { ChainId } from '@/state/backendNetworks/types'; import { SearchAsset } from '@/__swaps__/types/search'; import { ButtonPressAnimation } from '@/components/animations'; import { ContextMenuButton } from '@/components/context-menu'; @@ -17,7 +17,7 @@ import React, { useCallback, useMemo } from 'react'; import { GestureResponderEvent } from 'react-native'; import { OnPressMenuItemEventObject } from 'react-native-ios-context-menu'; import { SwapCoinIcon } from './SwapCoinIcon'; -import { getSupportedChainIds } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const COIN_ROW_WITH_PADDING_HEIGHT = 56; @@ -51,7 +51,7 @@ interface InputCoinRowProps { nativePriceChange?: string; onPress: (asset: ParsedSearchAsset | null) => void; output?: false | undefined; - uniqueId: string; + uniqueId: UniqueId; testID?: string; } @@ -185,6 +185,7 @@ export function CoinRow({ isFavorite, onPress, output, uniqueId, testID, ...asse } const InfoButton = ({ address, chainId }: { address: string; chainId: ChainId }) => { + const getSupportedChainIds = useBackendNetworksStore(state => state.getSupportedChainIds); const supportedChain = getSupportedChainIds().includes(chainId); const handleCopy = useCallback(() => { diff --git a/src/__swaps__/screens/Swap/components/FlipButton.tsx b/src/__swaps__/screens/Swap/components/FlipButton.tsx index 2e400d2717d..8298b6aacc7 100644 --- a/src/__swaps__/screens/Swap/components/FlipButton.tsx +++ b/src/__swaps__/screens/Swap/components/FlipButton.tsx @@ -14,7 +14,7 @@ import { TIMING_CONFIGS } from '@/components/animations/animationConfigs'; import { SwapAssetType } from '@/__swaps__/types/swap'; import { GestureHandlerButton } from './GestureHandlerButton'; import { useSwapsStore } from '@/state/swaps/swapsStore'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; export const FlipButton = () => { const { isDarkMode } = useColorMode(); diff --git a/src/__swaps__/screens/Swap/components/GasButton.tsx b/src/__swaps__/screens/Swap/components/GasButton.tsx index 384e3e2f232..70ab401d621 100644 --- a/src/__swaps__/screens/Swap/components/GasButton.tsx +++ b/src/__swaps__/screens/Swap/components/GasButton.tsx @@ -22,7 +22,7 @@ import { NavigationSteps, useSwapContext } from '../providers/swap-provider'; import { EstimatedSwapGasFee, EstimatedSwapGasFeeSlot } from './EstimatedSwapGasFee'; import { GestureHandlerButton } from './GestureHandlerButton'; import { UnmountOnAnimatedReaction } from './UnmountOnAnimatedReaction'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const { SWAP_GAS_ICONS } = gasUtils; const GAS_BUTTON_HIT_SLOP = 16; diff --git a/src/__swaps__/screens/Swap/components/GasPanel.tsx b/src/__swaps__/screens/Swap/components/GasPanel.tsx index 8c0c46c55a2..4691d7d6b07 100644 --- a/src/__swaps__/screens/Swap/components/GasPanel.tsx +++ b/src/__swaps__/screens/Swap/components/GasPanel.tsx @@ -4,7 +4,7 @@ import Animated, { runOnJS, useAnimatedReaction, useAnimatedStyle, withDelay, wi import { MIN_FLASHBOTS_PRIORITY_FEE, THICK_BORDER_WIDTH } from '@/__swaps__/screens/Swap/constants'; import { NavigationSteps, useSwapContext } from '@/__swaps__/screens/Swap/providers/swap-provider'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { GasSpeed } from '@/__swaps__/types/gas'; import { gweiToWei, weiToGwei } from '@/__swaps__/utils/ethereum'; import { diff --git a/src/__swaps__/screens/Swap/components/ReviewPanel.tsx b/src/__swaps__/screens/Swap/components/ReviewPanel.tsx index 2b9360844f3..b4c3d9ecf90 100644 --- a/src/__swaps__/screens/Swap/components/ReviewPanel.tsx +++ b/src/__swaps__/screens/Swap/components/ReviewPanel.tsx @@ -48,9 +48,8 @@ import { NavigationSteps, useSwapContext } from '../providers/swap-provider'; import { AnimatedSwitch } from './AnimatedSwitch'; import { EstimatedSwapGasFee, EstimatedSwapGasFeeSlot } from './EstimatedSwapGasFee'; import { UnmountOnAnimatedReaction } from './UnmountOnAnimatedReaction'; -import { getChainsLabelWorklet } from '@/chains'; -import { ChainId } from '@/chains/types'; -import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; +import { getChainsLabelWorklet, useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; +import { ChainId } from '@/state/backendNetworks/types'; const UNKNOWN_LABEL = i18n.t(i18n.l.swap.unknown); const REVIEW_LABEL = i18n.t(i18n.l.expanded_state.swap_details.review); diff --git a/src/__swaps__/screens/Swap/components/SwapCoinIcon.tsx b/src/__swaps__/screens/Swap/components/SwapCoinIcon.tsx index d65c2af7408..bb5069c5092 100644 --- a/src/__swaps__/screens/Swap/components/SwapCoinIcon.tsx +++ b/src/__swaps__/screens/Swap/components/SwapCoinIcon.tsx @@ -10,7 +10,7 @@ import { FallbackIcon as CoinIconTextFallback, isETH } from '@/utils'; import { FastFallbackCoinIconImage } from '@/components/asset-list/RecyclerAssetList2/FastComponents/FastFallbackCoinIconImage'; import Animated from 'react-native-reanimated'; import FastImage, { Source } from 'react-native-fast-image'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; // TODO: Delete this and replace with RainbowCoinIcon // ⚠️ When replacing this component with RainbowCoinIcon, make sure diff --git a/src/__swaps__/screens/Swap/components/SwapOutputAsset.tsx b/src/__swaps__/screens/Swap/components/SwapOutputAsset.tsx index e3a5557ead5..591addf78fd 100644 --- a/src/__swaps__/screens/Swap/components/SwapOutputAsset.tsx +++ b/src/__swaps__/screens/Swap/components/SwapOutputAsset.tsx @@ -17,7 +17,7 @@ import { TokenList } from '@/__swaps__/screens/Swap/components/TokenList/TokenLi import { BASE_INPUT_WIDTH, INPUT_INNER_WIDTH, INPUT_PADDING, THICK_BORDER_WIDTH } from '@/__swaps__/screens/Swap/constants'; import { IS_ANDROID, IS_IOS } from '@/env'; import { useSwapContext } from '@/__swaps__/screens/Swap/providers/swap-provider'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import * as i18n from '@/languages'; import { useNavigation } from '@/navigation'; import Routes from '@/navigation/routesNames'; diff --git a/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx b/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx index 8d0f300e819..6e803ae4904 100644 --- a/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx +++ b/src/__swaps__/screens/Swap/components/TokenList/ChainSelection.tsx @@ -6,7 +6,7 @@ import { Text as RNText, StyleSheet } from 'react-native'; import Animated, { useDerivedValue, useSharedValue } from 'react-native-reanimated'; import { useSwapContext } from '@/__swaps__/screens/Swap/providers/swap-provider'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { opacity } from '@/__swaps__/utils/swaps'; import { analyticsV2 } from '@/analytics'; import { ChainImage } from '@/components/coin-icon/ChainImage'; @@ -18,8 +18,7 @@ import { userAssetsStore, useUserAssetsStore } from '@/state/assets/userAssets'; import { swapsStore } from '@/state/swaps/swapsStore'; import { showActionSheetWithOptions } from '@/utils'; import { OnPressMenuItemEventObject } from 'react-native-ios-context-menu'; -import { getChainsLabelWorklet, getChainsNameWorklet } from '@/chains'; -import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; +import { getChainsLabelWorklet, getChainsNameWorklet, useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; type ChainSelectionProps = { allText?: string; @@ -49,11 +48,13 @@ export const ChainSelection = memo(function ChainSelection({ allText, output }: }, [accountColor, isDarkMode]); const chainName = useDerivedValue(() => { + const chainLabels = getChainsLabelWorklet(backendNetworks); + return output - ? getChainsLabelWorklet(backendNetworks)[selectedOutputChainId.value] + ? chainLabels[selectedOutputChainId.value] : inputListFilter.value === 'all' ? allText - : getChainsLabelWorklet(backendNetworks)[inputListFilter.value as ChainId]; + : chainLabels[inputListFilter.value as ChainId]; }); const handleSelectChain = useCallback( @@ -103,7 +104,7 @@ export const ChainSelection = memo(function ChainSelection({ allText, output }: return { menuItems: supportedChains, }; - }, [balanceSortedChainList, output]); + }, [backendNetworks, balanceSortedChainList, output]); const onShowActionSheet = useCallback(() => { const chainTitles = menuConfig.menuItems.map(chain => chain.actionTitle); diff --git a/src/__swaps__/screens/Swap/components/TokenList/TokenToBuyList.tsx b/src/__swaps__/screens/Swap/components/TokenList/TokenToBuyList.tsx index 1e59b8aae87..749800f3339 100644 --- a/src/__swaps__/screens/Swap/components/TokenList/TokenToBuyList.tsx +++ b/src/__swaps__/screens/Swap/components/TokenList/TokenToBuyList.tsx @@ -3,7 +3,7 @@ import { COIN_ROW_WITH_PADDING_HEIGHT, CoinRow } from '@/__swaps__/screens/Swap/ import { ListEmpty } from '@/__swaps__/screens/Swap/components/TokenList/ListEmpty'; import { AssetToBuySectionId, useSearchCurrencyLists } from '@/__swaps__/screens/Swap/hooks/useSearchCurrencyLists'; import { useSwapContext } from '@/__swaps__/screens/Swap/providers/swap-provider'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { SearchAsset } from '@/__swaps__/types/search'; import { SwapAssetType } from '@/__swaps__/types/swap'; import { parseSearchAsset } from '@/__swaps__/utils/assets'; diff --git a/src/__swaps__/screens/Swap/dummyValues.ts b/src/__swaps__/screens/Swap/dummyValues.ts index ab4bb9be3c8..d20740cfee6 100644 --- a/src/__swaps__/screens/Swap/dummyValues.ts +++ b/src/__swaps__/screens/Swap/dummyValues.ts @@ -1,4 +1,4 @@ -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; // /---- 🗑️ TODO: Delete these dummy values 🗑️ ----/ // // diff --git a/src/__swaps__/screens/Swap/hooks/useAnimatedSwapStyles.ts b/src/__swaps__/screens/Swap/hooks/useAnimatedSwapStyles.ts index 244dd9f993e..19313195039 100644 --- a/src/__swaps__/screens/Swap/hooks/useAnimatedSwapStyles.ts +++ b/src/__swaps__/screens/Swap/hooks/useAnimatedSwapStyles.ts @@ -23,7 +23,7 @@ import { safeAreaInsetValues } from '@/utils'; import { getSoftMenuBarHeight } from 'react-native-extra-dimensions-android'; import { DerivedValue, SharedValue, interpolate, useAnimatedStyle, useDerivedValue, withSpring, withTiming } from 'react-native-reanimated'; import { NavigationSteps } from './useSwapNavigation'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { SPRING_CONFIGS, TIMING_CONFIGS } from '@/components/animations/animationConfigs'; const INSET_BOTTOM = IS_ANDROID ? getSoftMenuBarHeight() - 24 : safeAreaInsetValues.bottom + 16; diff --git a/src/__swaps__/screens/Swap/hooks/useCustomGas.ts b/src/__swaps__/screens/Swap/hooks/useCustomGas.ts index 74559a1e1e3..00c0f0bbe22 100644 --- a/src/__swaps__/screens/Swap/hooks/useCustomGas.ts +++ b/src/__swaps__/screens/Swap/hooks/useCustomGas.ts @@ -1,4 +1,4 @@ -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { createRainbowStore } from '@/state/internal/createRainbowStore'; export type EIP1159GasSettings = { diff --git a/src/__swaps__/screens/Swap/hooks/useEstimatedGasFee.ts b/src/__swaps__/screens/Swap/hooks/useEstimatedGasFee.ts index 9d47932ba9b..2adc5c8fd89 100644 --- a/src/__swaps__/screens/Swap/hooks/useEstimatedGasFee.ts +++ b/src/__swaps__/screens/Swap/hooks/useEstimatedGasFee.ts @@ -1,6 +1,6 @@ -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { weiToGwei } from '@/__swaps__/utils/ethereum'; -import { add, convertAmountToNativeDisplayWorklet, formatNumber, multiply } from '@/__swaps__/utils/numbers'; +import { convertAmountToNativeDisplayWorklet, formatNumber, multiply } from '@/__swaps__/utils/numbers'; import { useNativeAsset } from '@/utils/ethereumUtils'; import { useMemo } from 'react'; import { formatUnits } from 'viem'; diff --git a/src/__swaps__/screens/Swap/hooks/useNativeAssetForChain.ts b/src/__swaps__/screens/Swap/hooks/useNativeAssetForChain.ts index ffd07d2654c..66a61acc05f 100644 --- a/src/__swaps__/screens/Swap/hooks/useNativeAssetForChain.ts +++ b/src/__swaps__/screens/Swap/hooks/useNativeAssetForChain.ts @@ -1,7 +1,7 @@ import { useCallback } from 'react'; import { ExtendedAnimatedAssetWithColors } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { SharedValue, runOnJS, useAnimatedReaction, useDerivedValue, useSharedValue } from 'react-native-reanimated'; import { ParsedAddressAsset } from '@/entities'; diff --git a/src/__swaps__/screens/Swap/hooks/useSearchCurrencyLists.ts b/src/__swaps__/screens/Swap/hooks/useSearchCurrencyLists.ts index bf88f7abf6f..d85dd24011d 100644 --- a/src/__swaps__/screens/Swap/hooks/useSearchCurrencyLists.ts +++ b/src/__swaps__/screens/Swap/hooks/useSearchCurrencyLists.ts @@ -1,6 +1,6 @@ import { TokenSearchResult, useTokenSearch } from '@/__swaps__/screens/Swap/resources/search/search'; import { AddressOrEth } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { SearchAsset, TokenSearchAssetKey, TokenSearchThreshold } from '@/__swaps__/types/search'; import { addHexPrefix } from '@/__swaps__/utils/hex'; import { isLowerCaseMatch } from '@/__swaps__/utils/strings'; diff --git a/src/__swaps__/screens/Swap/hooks/useSelectedGas.ts b/src/__swaps__/screens/Swap/hooks/useSelectedGas.ts index 4fa9145a0b7..2323417d28b 100644 --- a/src/__swaps__/screens/Swap/hooks/useSelectedGas.ts +++ b/src/__swaps__/screens/Swap/hooks/useSelectedGas.ts @@ -1,4 +1,4 @@ -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { GasSpeed } from '@/__swaps__/types/gas'; import { getCachedGasSuggestions, useMeteorologySuggestions } from '@/__swaps__/utils/meteorology'; import { createRainbowStore } from '@/state/internal/createRainbowStore'; diff --git a/src/__swaps__/screens/Swap/hooks/useSwapEstimatedGasLimit.ts b/src/__swaps__/screens/Swap/hooks/useSwapEstimatedGasLimit.ts index bc9b301a87b..467da9b9e8f 100644 --- a/src/__swaps__/screens/Swap/hooks/useSwapEstimatedGasLimit.ts +++ b/src/__swaps__/screens/Swap/hooks/useSwapEstimatedGasLimit.ts @@ -2,7 +2,7 @@ import { CrosschainQuote, Quote, QuoteError, SwapType } from '@rainbow-me/swaps' import { useQuery } from '@tanstack/react-query'; import { ParsedSearchAsset } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { estimateUnlockAndCrosschainSwap } from '@/raps/unlockAndCrosschainSwap'; import { estimateUnlockAndSwap } from '@/raps/unlockAndSwap'; import { QueryConfigWithSelect, QueryFunctionArgs, QueryFunctionResult, createQueryKey } from '@/react-query'; diff --git a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts index 1e43105fba3..e9e7fca5e67 100644 --- a/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts +++ b/src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts @@ -8,7 +8,7 @@ import { } from '@/__swaps__/safe-math/SafeMath'; import { SCRUBBER_WIDTH, SLIDER_WIDTH, snappySpringConfig } from '@/__swaps__/screens/Swap/constants'; import { ExtendedAnimatedAssetWithColors } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { RequestNewQuoteParams, inputKeys, inputMethods, inputValuesType } from '@/__swaps__/types/swap'; import { valueBasedDecimalFormatter } from '@/__swaps__/utils/decimalFormatter'; import { getInputValuesForSliderPositionWorklet, updateInputValuesAfterFlip } from '@/__swaps__/utils/flipAssets'; @@ -78,8 +78,6 @@ export function useSwapInputsController({ sliderXPosition: SharedValue; slippage: SharedValue; }) { - const backendNetworks = useBackendNetworksStore(state => state.backendNetworksSharedValue); - const percentageToSwap = useDerivedValue(() => { return Math.round(clamp((sliderXPosition.value - SCRUBBER_WIDTH / SLIDER_WIDTH) / SLIDER_WIDTH, 0, 1) * 100) / 100; }); @@ -659,7 +657,7 @@ export function useSwapInputsController({ () => ({ assetToBuyId: internalSelectedOutputAsset.value?.uniqueId, assetToSellId: internalSelectedInputAsset.value?.uniqueId, - assetToSellNetwork: internalSelectedInputAsset.value?.chainId, + assetToSellChainId: internalSelectedInputAsset.value?.chainId, }), (current, previous) => { const didInputAssetChange = current.assetToSellId !== previous?.assetToSellId; @@ -667,16 +665,12 @@ export function useSwapInputsController({ if (!didInputAssetChange && !didOutputAssetChange) return; - if (current.assetToSellNetwork !== previous?.assetToSellNetwork) { - const previousDefaultSlippage = getDefaultSlippageWorklet( - previous?.assetToSellNetwork || ChainId.mainnet, - REMOTE_CONFIG, - backendNetworks - ); + if (current.assetToSellChainId !== previous?.assetToSellChainId) { + const previousDefaultSlippage = getDefaultSlippageWorklet(previous?.assetToSellChainId || ChainId.mainnet, REMOTE_CONFIG); // If the user has not overridden the default slippage, update it if (slippage.value === previousDefaultSlippage) { - const newSlippage = getDefaultSlippageWorklet(current.assetToSellNetwork || ChainId.mainnet, REMOTE_CONFIG, backendNetworks); + const newSlippage = getDefaultSlippageWorklet(current.assetToSellChainId || ChainId.mainnet, REMOTE_CONFIG); slippage.value = newSlippage; runOnJS(setSlippage)(newSlippage); } diff --git a/src/__swaps__/screens/Swap/hooks/useSwapOutputQuotesDisabled.ts b/src/__swaps__/screens/Swap/hooks/useSwapOutputQuotesDisabled.ts index 63649915485..cf3259ab0eb 100644 --- a/src/__swaps__/screens/Swap/hooks/useSwapOutputQuotesDisabled.ts +++ b/src/__swaps__/screens/Swap/hooks/useSwapOutputQuotesDisabled.ts @@ -1,6 +1,10 @@ import { SharedValue, useDerivedValue } from 'react-native-reanimated'; import { ExtendedAnimatedAssetWithColors } from '@/__swaps__/types/assets'; -import { supportedSwapExactOutputChainIds, supportedBridgeExactOutputChainIds } from '@/chains'; +import { + useBackendNetworksStore, + getSwapExactOutputSupportedChainIdsWorklet, + getBridgeExactOutputSupportedChainIdsWorklet, +} from '@/state/backendNetworks/backendNetworks'; export const useSwapOutputQuotesDisabled = ({ inputAsset, @@ -9,13 +13,15 @@ export const useSwapOutputQuotesDisabled = ({ inputAsset: SharedValue; outputAsset: SharedValue; }): SharedValue => { + const backendNetworks = useBackendNetworksStore(state => state.backendNetworksSharedValue); + const outputQuotesAreDisabled = useDerivedValue(() => { if (!inputAsset.value || !outputAsset.value) return false; if (inputAsset.value.chainId === outputAsset.value.chainId) { - return !supportedSwapExactOutputChainIds.includes(inputAsset.value.chainId); + return !getSwapExactOutputSupportedChainIdsWorklet(backendNetworks).includes(inputAsset.value.chainId); } else { - return !supportedBridgeExactOutputChainIds.includes(inputAsset.value.chainId); + return !getBridgeExactOutputSupportedChainIdsWorklet(backendNetworks).includes(inputAsset.value.chainId); } }); diff --git a/src/__swaps__/screens/Swap/providers/SyncSwapStateAndSharedValues.tsx b/src/__swaps__/screens/Swap/providers/SyncSwapStateAndSharedValues.tsx index 99e1dfc56b8..353745931c8 100644 --- a/src/__swaps__/screens/Swap/providers/SyncSwapStateAndSharedValues.tsx +++ b/src/__swaps__/screens/Swap/providers/SyncSwapStateAndSharedValues.tsx @@ -13,7 +13,7 @@ import { toScaledIntegerWorklet, } from '@/__swaps__/safe-math/SafeMath'; import { ExtendedAnimatedAssetWithColors } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { ParsedAddressAsset } from '@/entities'; import { useUserNativeNetworkAsset } from '@/resources/assets/useUserAsset'; import { CrosschainQuote, Quote, QuoteError } from '@rainbow-me/swaps'; diff --git a/src/__swaps__/screens/Swap/providers/swap-provider.tsx b/src/__swaps__/screens/Swap/providers/swap-provider.tsx index b2e058c8d45..261af64bc75 100644 --- a/src/__swaps__/screens/Swap/providers/swap-provider.tsx +++ b/src/__swaps__/screens/Swap/providers/swap-provider.tsx @@ -24,7 +24,7 @@ import { useSwapTextStyles } from '@/__swaps__/screens/Swap/hooks/useSwapTextSty import { SwapWarningType, useSwapWarning } from '@/__swaps__/screens/Swap/hooks/useSwapWarning'; import { userAssetsQueryKey as swapsUserAssetsQueryKey } from '@/__swaps__/screens/Swap/resources/assets/userAssets'; import { AddressOrEth, ExtendedAnimatedAssetWithColors, ParsedSearchAsset } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { inputKeys, SwapAssetType } from '@/__swaps__/types/swap'; import { getDefaultSlippageWorklet, parseAssetAndExtend } from '@/__swaps__/utils/swaps'; import { analyticsV2 } from '@/analytics'; @@ -56,8 +56,11 @@ import { SyncGasStateToSharedValues, SyncQuoteSharedValuesToState } from './Sync import { performanceTracking, Screens, TimeToSignOperation } from '@/state/performance/performance'; import { getRemoteConfig } from '@/model/remoteConfig'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; -import { getChainsNativeAsset, supportedFlashbotsChainIds } from '@/chains'; -import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; +import { + useBackendNetworksStore, + getFlashbotsSupportedChainIdsWorklet, + getChainsNativeAssetWorklet, +} from '@/state/backendNetworks/backendNetworks'; const swapping = i18n.t(i18n.l.swap.actions.swapping); const holdToSwap = i18n.t(i18n.l.swap.actions.hold_to_swap); @@ -137,6 +140,7 @@ export const SwapProvider = ({ children }: SwapProviderProps) => { const { nativeCurrency } = useAccountSettings(); const backendNetworks = useBackendNetworksStore(state => state.backendNetworksSharedValue); + const getFlashbotsSupportedChainIds = useBackendNetworksStore(state => state.getFlashbotsSupportedChainIds); const isFetching = useSharedValue(false); const isQuoteStale = useSharedValue(0); // TODO: Convert this to a boolean @@ -167,9 +171,7 @@ export const SwapProvider = ({ children }: SwapProviderProps) => { ); const configProgress = useSharedValue(NavigationSteps.INPUT_ELEMENT_FOCUSED); - const slippage = useSharedValue( - getDefaultSlippageWorklet(initialSelectedInputAsset?.chainId || ChainId.mainnet, getRemoteConfig(), backendNetworks) - ); + const slippage = useSharedValue(getDefaultSlippageWorklet(initialSelectedInputAsset?.chainId || ChainId.mainnet, getRemoteConfig())); const hasEnoughFundsForGas = useSharedValue(undefined); @@ -205,7 +207,7 @@ export const SwapProvider = ({ children }: SwapProviderProps) => { NotificationManager?.postNotification('rapInProgress'); const provider = - parameters.flashbots && supportedFlashbotsChainIds.includes(parameters.chainId) + parameters.flashbots && getFlashbotsSupportedChainIds().includes(parameters.chainId) ? await getFlashbotsProvider() : getProvider({ chainId: parameters.chainId }); const connectedToHardhat = useConnectedToHardhatStore.getState().connectedToHardhat; @@ -407,7 +409,8 @@ export const SwapProvider = ({ children }: SwapProviderProps) => { const type = inputAsset.chainId !== outputAsset.chainId ? 'crosschainSwap' : 'swap'; const quoteData = q as QuoteTypeMap[typeof type]; - const flashbots = (SwapSettings.flashbots.value && !!supportedFlashbotsChainIds.includes(inputAsset.chainId)) ?? false; + const flashbots = + (SwapSettings.flashbots.value && !!getFlashbotsSupportedChainIdsWorklet(backendNetworks).includes(inputAsset.chainId)) ?? false; const isNativeWrapOrUnwrap = quoteData.swapType === SwapType.wrap || quoteData.swapType === SwapType.unwrap; @@ -760,7 +763,7 @@ export const SwapProvider = ({ children }: SwapProviderProps) => { } if (hasEnoughFundsForGas.value === false) { - const nativeCurrency = getChainsNativeAsset()[sellAsset?.chainId || ChainId.mainnet]; + const nativeCurrency = getChainsNativeAssetWorklet(backendNetworks)[sellAsset?.chainId || ChainId.mainnet]; return { label: `${insufficient} ${nativeCurrency.symbol}`, disabled: true, diff --git a/src/__swaps__/screens/Swap/resources/_selectors/assets.ts b/src/__swaps__/screens/Swap/resources/_selectors/assets.ts index 4c3e8d8dbbf..4c764ecdfbd 100644 --- a/src/__swaps__/screens/Swap/resources/_selectors/assets.ts +++ b/src/__swaps__/screens/Swap/resources/_selectors/assets.ts @@ -1,5 +1,5 @@ import { ParsedAssetsDict, ParsedAssetsDictByChain, ParsedUserAsset, UniqueId } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { deriveAddressAndChainWithUniqueId } from '@/__swaps__/utils/address'; import { add } from '@/__swaps__/utils/numbers'; diff --git a/src/__swaps__/screens/Swap/resources/assets/assets.ts b/src/__swaps__/screens/Swap/resources/assets/assets.ts index d9e01be8db7..1177df0402d 100644 --- a/src/__swaps__/screens/Swap/resources/assets/assets.ts +++ b/src/__swaps__/screens/Swap/resources/assets/assets.ts @@ -4,7 +4,7 @@ import { requestMetadata } from '@/graphql'; import { QueryConfigWithSelect, QueryFunctionArgs, QueryFunctionResult, createQueryKey, queryClient } from '@/react-query'; import { SupportedCurrencyKey } from '@/references'; import { AddressOrEth, AssetMetadata, ParsedAsset, UniqueId } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { chunkArray, createAssetQuery, parseAssetMetadata } from '@/__swaps__/utils/assets'; import { RainbowError, logger } from '@/logger'; export const ASSETS_TIMEOUT_DURATION = 10000; diff --git a/src/__swaps__/screens/Swap/resources/assets/userAssets.ts b/src/__swaps__/screens/Swap/resources/assets/userAssets.ts index 1a85ffcdf21..e2523ceb985 100644 --- a/src/__swaps__/screens/Swap/resources/assets/userAssets.ts +++ b/src/__swaps__/screens/Swap/resources/assets/userAssets.ts @@ -8,14 +8,14 @@ import { RainbowError, logger } from '@/logger'; import { RainbowFetchClient } from '@/rainbow-fetch'; import { SupportedCurrencyKey } from '@/references'; import { ParsedAssetsDictByChain, ZerionAsset } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { AddressAssetsReceivedMessage } from '@/__swaps__/types/refraction'; import { parseUserAsset } from '@/__swaps__/utils/assets'; import { greaterThan } from '@/__swaps__/utils/numbers'; import { fetchUserAssetsByChain } from './userAssetsByChain'; import { fetchHardhatBalancesByChainId } from '@/resources/assets/hardhatAssets'; -import { getSupportedChainIds } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; const addysHttp = new RainbowFetchClient({ @@ -113,7 +113,7 @@ async function userAssetsQueryFunction({ const cachedUserAssets = (cache.find(userAssetsQueryKey({ address, currency, testnetMode }))?.state?.data || {}) as ParsedAssetsDictByChain; try { - const url = `/${getSupportedChainIds().join(',')}/${address}/assets`; + const url = `/${useBackendNetworksStore.getState().getSupportedChainIds().join(',')}/${address}/assets`; const res = await addysHttp.get(url, { params: { currency: currency.toLowerCase(), diff --git a/src/__swaps__/screens/Swap/resources/assets/userAssetsByChain.ts b/src/__swaps__/screens/Swap/resources/assets/userAssetsByChain.ts index 7c73e8a5a09..9fb15647109 100644 --- a/src/__swaps__/screens/Swap/resources/assets/userAssetsByChain.ts +++ b/src/__swaps__/screens/Swap/resources/assets/userAssetsByChain.ts @@ -4,7 +4,7 @@ import { Address } from 'viem'; import { QueryConfigWithSelect, QueryFunctionArgs, QueryFunctionResult, createQueryKey, queryClient } from '@/react-query'; import { SupportedCurrencyKey } from '@/references'; import { ParsedAssetsDictByChain, ParsedUserAsset } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { AddressAssetsReceivedMessage } from '@/__swaps__/types/refraction'; import { RainbowError, logger } from '@/logger'; diff --git a/src/__swaps__/screens/Swap/resources/search/discovery.ts b/src/__swaps__/screens/Swap/resources/search/discovery.ts index 5c8565facfd..ebb15d0f59b 100644 --- a/src/__swaps__/screens/Swap/resources/search/discovery.ts +++ b/src/__swaps__/screens/Swap/resources/search/discovery.ts @@ -1,4 +1,4 @@ -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { SearchAsset } from '@/__swaps__/types/search'; import { RainbowError, logger } from '@/logger'; import { RainbowFetchClient } from '@/rainbow-fetch'; diff --git a/src/__swaps__/screens/Swap/resources/search/search.ts b/src/__swaps__/screens/Swap/resources/search/search.ts index 2cfe70ebda0..0c9b94ba58f 100644 --- a/src/__swaps__/screens/Swap/resources/search/search.ts +++ b/src/__swaps__/screens/Swap/resources/search/search.ts @@ -1,5 +1,5 @@ /* eslint-disable no-nested-ternary */ -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { SearchAsset, TokenSearchAssetKey, TokenSearchListId, TokenSearchThreshold } from '@/__swaps__/types/search'; import { RainbowError, logger } from '@/logger'; import { RainbowFetchClient } from '@/rainbow-fetch'; diff --git a/src/__swaps__/screens/Swap/resources/search/utils.ts b/src/__swaps__/screens/Swap/resources/search/utils.ts index 0e4ee669429..5691c7b4f42 100644 --- a/src/__swaps__/screens/Swap/resources/search/utils.ts +++ b/src/__swaps__/screens/Swap/resources/search/utils.ts @@ -1,4 +1,4 @@ -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { SearchAsset } from '@/__swaps__/types/search'; import { ARBITRUM_ETH_ADDRESS, diff --git a/src/__swaps__/types/assets.ts b/src/__swaps__/types/assets.ts index f6bd292a44d..c6f7bcd84a5 100644 --- a/src/__swaps__/types/assets.ts +++ b/src/__swaps__/types/assets.ts @@ -1,7 +1,7 @@ import type { Address } from 'viem'; import { ETH_ADDRESS } from '@/references'; -import { ChainId, ChainName } from '@/chains/types'; +import { ChainId, ChainName } from '@/state/backendNetworks/types'; import { SearchAsset } from '@/__swaps__/types/search'; import { ResponseByTheme } from '../utils/swaps'; diff --git a/src/__swaps__/types/refraction.ts b/src/__swaps__/types/refraction.ts index 802b8fc0f33..674027f9324 100644 --- a/src/__swaps__/types/refraction.ts +++ b/src/__swaps__/types/refraction.ts @@ -1,5 +1,5 @@ import { ZerionAsset } from '@/__swaps__/types/assets'; -import { ChainId, ChainName } from '@/chains/types'; +import { ChainId, ChainName } from '@/state/backendNetworks/types'; import { PaginatedTransactionsApiResponse } from '@/entities'; /** diff --git a/src/__swaps__/types/search.ts b/src/__swaps__/types/search.ts index e108655d0d0..c11d1a6f920 100644 --- a/src/__swaps__/types/search.ts +++ b/src/__swaps__/types/search.ts @@ -1,7 +1,7 @@ import { Address } from 'viem'; import { AddressOrEth, AssetType, ParsedAsset, UniqueId } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { AssetToBuySectionId } from '../screens/Swap/hooks/useSearchCurrencyLists'; export type TokenSearchAssetKey = keyof ParsedAsset; diff --git a/src/__swaps__/utils/address.ts b/src/__swaps__/utils/address.ts index 1573c130a76..a3b3e40c978 100644 --- a/src/__swaps__/utils/address.ts +++ b/src/__swaps__/utils/address.ts @@ -1,7 +1,7 @@ import { Address } from 'viem'; import { AddressOrEth, UniqueId } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; export function truncateAddress(address?: AddressOrEth) { if (!address) return ''; diff --git a/src/__swaps__/utils/assets.ts b/src/__swaps__/utils/assets.ts index ccf787969bc..c87c5f62995 100644 --- a/src/__swaps__/utils/assets.ts +++ b/src/__swaps__/utils/assets.ts @@ -12,7 +12,7 @@ import { ZerionAsset, ZerionAssetPrice, } from '@/__swaps__/types/assets'; -import { ChainId, ChainName } from '@/chains/types'; +import { ChainId, ChainName } from '@/state/backendNetworks/types'; import * as i18n from '@/languages'; import { SearchAsset } from '@/__swaps__/types/search'; @@ -26,7 +26,7 @@ import { convertRawAmountToDecimalFormat, } from '@/__swaps__/utils/numbers'; import { isLowerCaseMatch, isLowerCaseMatchWorklet } from '@/__swaps__/utils/strings'; -import { getChainsIdByName, getChainsName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const isSameAsset = (a1: Pick, a2: Pick) => +a1.chainId === +a2.chainId && isLowerCaseMatch(a1.address, a2.address); @@ -80,7 +80,10 @@ const getUniqueIdForAsset = ({ asset }: { asset: ZerionAsset | AssetApiResponse const address = asset.asset_code; const chainName = asset.network ?? ChainName.mainnet; const networks = 'networks' in asset ? asset.networks || {} : {}; - const chainId = ('chain_id' in asset && asset.chain_id) || getChainsIdByName()[chainName] || Number(Object.keys(networks)[0]); + const chainId = + ('chain_id' in asset && asset.chain_id) || + useBackendNetworksStore.getState().getChainsIdByName()[chainName] || + Number(Object.keys(networks)[0]); // ZerionAsset should be removed when we move fully away from websckets/refraction api const mainnetAddress = isZerionAsset(asset) @@ -94,7 +97,10 @@ export function parseAsset({ asset, currency }: { asset: ZerionAsset | AssetApiR const address = asset.asset_code; const chainName = asset.network ?? ChainName.mainnet; const networks = 'networks' in asset ? asset.networks || {} : {}; - const chainId = ('chain_id' in asset && asset.chain_id) || getChainsIdByName()[chainName] || Number(Object.keys(networks)[0]); + const chainId = + ('chain_id' in asset && asset.chain_id) || + useBackendNetworksStore.getState().getChainsIdByName()[chainName] || + Number(Object.keys(networks)[0]); // ZerionAsset should be removed when we move fully away from websckets/refraction api const mainnetAddress = isZerionAsset(asset) @@ -172,7 +178,7 @@ export function parseAssetMetadata({ const parsedAsset = { address, chainId, - chainName: getChainsName()[chainId], + chainName: useBackendNetworksStore.getState().getChainsName()[chainId], colors: asset?.colors, decimals: asset?.decimals, icon_url: asset?.iconUrl, @@ -290,7 +296,7 @@ export const parseSearchAsset = ({ isNativeAsset: isNativeAsset(searchAsset.address, searchAsset.chainId), address: searchAsset.address, chainId: searchAsset.chainId, - chainName: getChainsName()[searchAsset.chainId], + chainName: useBackendNetworksStore.getState().getChainsName()[searchAsset.chainId], native: { balance: userAsset?.native.balance || { amount: '0', diff --git a/src/__swaps__/utils/chains.ts b/src/__swaps__/utils/chains.ts index 0d25aecc938..688e85a0743 100644 --- a/src/__swaps__/utils/chains.ts +++ b/src/__swaps__/utils/chains.ts @@ -1,8 +1,8 @@ import { celo, fantom, harmonyOne, moonbeam } from 'viem/chains'; import { AddressOrEth } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { isLowerCaseMatch } from '@/__swaps__/utils/strings'; -import { getChainsNativeAsset } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; // @ts-expect-error Property '[ChainId.hardhat]' is missing export const customChainIdsToAssetNames: Record = { @@ -44,7 +44,7 @@ export const customChainIdsToAssetNames: Record = { }; export function isNativeAsset(address: AddressOrEth, chainId: ChainId) { - return isLowerCaseMatch(getChainsNativeAsset()[chainId].address, address); + return isLowerCaseMatch(useBackendNetworksStore.getState().getChainsNativeAsset()[chainId].address, address); } export const chainIdToUse = (connectedToHardhat: boolean, connectedToHardhatOp: boolean, activeSessionChainId: number) => { diff --git a/src/__swaps__/utils/gasUtils.ts b/src/__swaps__/utils/gasUtils.ts index 2052ca02b18..6c8f12e5715 100644 --- a/src/__swaps__/utils/gasUtils.ts +++ b/src/__swaps__/utils/gasUtils.ts @@ -11,7 +11,7 @@ import * as i18n from '@/languages'; import { OVM_GAS_PRICE_ORACLE, gasUnits, supportedNativeCurrencies, optimismGasOracleAbi, SupportedCurrencyKey } from '@/references'; import { ParsedAsset } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { BlocksToConfirmation, GasFeeLegacyParams, GasFeeParam, GasFeeParams, GasSpeed } from '@/__swaps__/types/gas'; import { gweiToWei, weiToGwei } from '@/__swaps__/utils/ethereum'; diff --git a/src/__swaps__/utils/meteorology.ts b/src/__swaps__/utils/meteorology.ts index b7f80508866..4e9d52afb6c 100644 --- a/src/__swaps__/utils/meteorology.ts +++ b/src/__swaps__/utils/meteorology.ts @@ -1,6 +1,6 @@ import { useQuery } from '@tanstack/react-query'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { rainbowMeteorologyGetData } from '@/handlers/gasFees'; import { abs, lessThan, subtract } from '@/helpers/utilities'; import { gweiToWei } from '@/parsers'; diff --git a/src/__swaps__/utils/swaps.ts b/src/__swaps__/utils/swaps.ts index 520a7b7c052..c3b6d936fa0 100644 --- a/src/__swaps__/utils/swaps.ts +++ b/src/__swaps__/utils/swaps.ts @@ -9,12 +9,11 @@ import { SLIDER_WIDTH, STABLECOIN_MINIMUM_SIGNIFICANT_DECIMALS, } from '@/__swaps__/screens/Swap/constants'; -import { ChainId } from '@/chains/types'; import { globalColors } from '@/design-system'; import { ForegroundColor, palettes } from '@/design-system/color/palettes'; import { TokenColors } from '@/graphql/__generated__/metadata'; import * as i18n from '@/languages'; -import { RainbowConfig } from '@/model/remoteConfig'; +import { DEFAULT_CONFIG, RainbowConfig } from '@/model/remoteConfig'; import store from '@/redux/store'; import { supportedNativeCurrencies } from '@/references'; import { userAssetsStore } from '@/state/assets/userAssets'; @@ -38,8 +37,7 @@ import { AddressOrEth, ExtendedAnimatedAssetWithColors, ParsedSearchAsset } from import { inputKeys } from '../types/swap'; import { valueBasedDecimalFormatter } from './decimalFormatter'; import { convertAmountToRawAmount } from './numbers'; -import { getChainsName, getChainsNameWorklet } from '@/chains'; -import { BackendNetworksResponse } from '@/resources/metadata/backendNetworks'; +import { ChainId } from '@/state/backendNetworks/types'; // /---- 🎨 Color functions 🎨 ----/ // // @@ -340,20 +338,6 @@ export const opacityWorklet = (color: string, opacity: number) => { // // /---- END worklet utils ----/ // -export const DEFAULT_SLIPPAGE_BIPS = { - [ChainId.apechain]: 200, - [ChainId.arbitrum]: 200, - [ChainId.avalanche]: 200, - [ChainId.base]: 200, - [ChainId.blast]: 200, - [ChainId.bsc]: 200, - [ChainId.degen]: 200, - [ChainId.mainnet]: 100, - [ChainId.optimism]: 200, - [ChainId.polygon]: 200, - [ChainId.zora]: 200, -}; - export const slippageInBipsToString = (slippageInBips: number) => (slippageInBips / 100).toFixed(1); export const slippageInBipsToStringWorklet = (slippageInBips: number) => { @@ -362,23 +346,24 @@ export const slippageInBipsToStringWorklet = (slippageInBips: number) => { }; export const getDefaultSlippage = (chainId: ChainId, config: RainbowConfig) => { - return slippageInBipsToString( - // NOTE: JSON.parse doesn't type the result as a Record - (config.default_slippage_bips as unknown as Record)[getChainsName()[chainId]] || DEFAULT_SLIPPAGE_BIPS[chainId] + const amount = +( + (config.default_slippage_bips_chainId as unknown as { [key: number]: number })[chainId] || + DEFAULT_CONFIG.default_slippage_bips_chainId[chainId] || + 200 ); + + return slippageInBipsToString(amount); }; -export const getDefaultSlippageWorklet = ( - chainId: ChainId, - config: RainbowConfig, - backendNetworks: SharedValue -) => { +export const getDefaultSlippageWorklet = (chainId: ChainId, config: RainbowConfig) => { 'worklet'; - - return slippageInBipsToStringWorklet( - (config.default_slippage_bips as unknown as { [key: string]: number })[getChainsNameWorklet(backendNetworks)[chainId]] || - DEFAULT_SLIPPAGE_BIPS[chainId] + const amount = +( + (config.default_slippage_bips_chainId as unknown as { [key: number]: number })[chainId] || + DEFAULT_CONFIG.default_slippage_bips_chainId[chainId] || + 200 ); + + return slippageInBipsToStringWorklet(amount); }; export type Colors = { diff --git a/src/__swaps__/utils/userChains.ts b/src/__swaps__/utils/userChains.ts index bb8c8922f9e..5330863e70e 100644 --- a/src/__swaps__/utils/userChains.ts +++ b/src/__swaps__/utils/userChains.ts @@ -21,8 +21,8 @@ import { sepolia, } from 'viem/chains'; -import { ChainId } from '@/chains/types'; -import { getChainsLabel } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const chainIdMap: Record< ChainId.mainnet | ChainId.optimism | ChainId.polygon | ChainId.base | ChainId.bsc | ChainId.zora | ChainId.avalanche, @@ -42,14 +42,21 @@ export const chainLabelMap: Record< ChainId.mainnet | ChainId.optimism | ChainId.polygon | ChainId.base | ChainId.bsc | ChainId.zora | ChainId.avalanche, string[] > = { - [ChainId.mainnet]: [getChainsLabel()[goerli.id], getChainsLabel()[sepolia.id], getChainsLabel()[holesky.id]], - [ChainId.optimism]: [getChainsLabel()[optimismSepolia.id]], - [ChainId.arbitrum]: [getChainsLabel()[arbitrumGoerli.id], getChainsLabel()[arbitrumSepolia.id]], - [ChainId.polygon]: [getChainsLabel()[polygonMumbai.id]], - [ChainId.base]: [getChainsLabel()[baseSepolia.id]], - [ChainId.bsc]: [getChainsLabel()[bscTestnet.id]], - [ChainId.zora]: [getChainsLabel()[zoraSepolia.id]], - [ChainId.avalanche]: [getChainsLabel()[avalancheFuji.id]], + [ChainId.mainnet]: [ + useBackendNetworksStore.getState().getChainsLabel()[goerli.id], + useBackendNetworksStore.getState().getChainsLabel()[sepolia.id], + useBackendNetworksStore.getState().getChainsLabel()[holesky.id], + ], + [ChainId.optimism]: [useBackendNetworksStore.getState().getChainsLabel()[optimismSepolia.id]], + [ChainId.arbitrum]: [ + useBackendNetworksStore.getState().getChainsLabel()[arbitrumGoerli.id], + useBackendNetworksStore.getState().getChainsLabel()[arbitrumSepolia.id], + ], + [ChainId.polygon]: [useBackendNetworksStore.getState().getChainsLabel()[polygonMumbai.id]], + [ChainId.base]: [useBackendNetworksStore.getState().getChainsLabel()[baseSepolia.id]], + [ChainId.bsc]: [useBackendNetworksStore.getState().getChainsLabel()[bscTestnet.id]], + [ChainId.zora]: [useBackendNetworksStore.getState().getChainsLabel()[zoraSepolia.id]], + [ChainId.avalanche]: [useBackendNetworksStore.getState().getChainsLabel()[avalancheFuji.id]], }; export const sortNetworks = (order: ChainId[], chains: Chain[]) => { diff --git a/src/analytics/event.ts b/src/analytics/event.ts index 12b53862765..973f01ba89a 100644 --- a/src/analytics/event.ts +++ b/src/analytics/event.ts @@ -1,5 +1,5 @@ import { AddressOrEth, ExtendedAnimatedAssetWithColors, ParsedSearchAsset } from '@/__swaps__/types/assets'; -import { ChainId, Network } from '@/chains/types'; +import { ChainId, Network } from '@/state/backendNetworks/types'; import { SwapAssetType } from '@/__swaps__/types/swap'; import { UnlockableAppIconKey } from '@/appIcons/appIcons'; import { CardType } from '@/components/cards/GenericCard'; diff --git a/src/appIcons/appIcons.ts b/src/appIcons/appIcons.ts index a4429006d58..97ae364095a 100644 --- a/src/appIcons/appIcons.ts +++ b/src/appIcons/appIcons.ts @@ -14,7 +14,7 @@ import AppIconPoolboy from '@/assets/appIconPoolboy.png'; import AppIconAdworld from '@/assets/appIconAdworld.png'; import AppIconFarcaster from '@/assets/appIconFarcaster.png'; import { TokenGateCheckerNetwork } from '@/featuresToUnlock/tokenGatedUtils'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; // optimism app icon unlocking NFTs const OPTIMISTIC_EXPLORER_NFT_ADDRESS: EthereumAddress = '0x81b30ff521D1fEB67EDE32db726D95714eb00637'; diff --git a/src/chains/index.ts b/src/chains/index.ts deleted file mode 100644 index 621b820f9cd..00000000000 --- a/src/chains/index.ts +++ /dev/null @@ -1,273 +0,0 @@ -import { Chain } from 'viem/chains'; -import { BackendNetworksResponse } from '@/resources/metadata/backendNetworks'; -import { ChainId, BackendNetwork, BackendNetworkServices, chainHardhat, chainHardhatOptimism } from './types'; -import { transformBackendNetworksToChains } from './utils/backendNetworks'; -import { gasUtils } from '@/utils'; -import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; -import { IS_TEST } from '@/env'; -import buildTimeNetworks from '@/references/networks.json'; -import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; -import { SharedValue } from 'react-native-reanimated'; - -const getBackendNetworks = (): BackendNetworksResponse => { - return useBackendNetworksStore.getState().backendNetworks ?? buildTimeNetworks; -}; - -const getBackendChains = (): Chain[] => { - const backendNetworks = getBackendNetworks(); - return transformBackendNetworksToChains(backendNetworks.networks); -}; - -export const getSupportedChains = (): Chain[] => { - const backendChains = getBackendChains(); - return IS_TEST ? [...backendChains, chainHardhat, chainHardhatOptimism] : backendChains; -}; - -export const getDefaultChains = (): Record => { - const supportedChains = getSupportedChains(); - return supportedChains.reduce( - (acc, chain) => { - acc[chain.id] = chain; - return acc; - }, - {} as Record - ); -}; - -export const getSupportedChainIds = (): ChainId[] => { - return getSupportedChains().map(chain => chain.id); -}; - -export const getSupportedMainnetChains = (): Chain[] => { - return getSupportedChains().filter(chain => !chain.testnet); -}; - -export const getSupportedMainnetChainIds = (): ChainId[] => { - return getSupportedMainnetChains().map(chain => chain.id); -}; - -export const getNeedsL1SecurityFeeChains = (): ChainId[] => { - const backendNetworks = getBackendNetworks(); - return backendNetworks.networks - .filter((backendNetwork: BackendNetwork) => backendNetwork.opStack) - .map((backendNetwork: BackendNetwork) => parseInt(backendNetwork.id, 10)); -}; - -export const getChainsNativeAsset = (): Record => { - const backendNetworks = getBackendNetworks(); - return backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = backendNetwork.nativeAsset; - return acc; - }, - {} as Record - ); -}; - -export const getChainsLabel = (): Record => { - const backendNetworks = getBackendNetworks(); - return backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = backendNetwork.label; - return acc; - }, - {} as Record - ); -}; - -export const getChainsName = (): Record => { - const backendNetworks = getBackendNetworks(); - return backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = backendNetwork.name; - return acc; - }, - {} as Record - ); -}; - -export const getChainsIdByName = (): Record => { - const backendNetworks = getBackendNetworks(); - return backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[backendNetwork.name] = parseInt(backendNetwork.id, 10); - return acc; - }, - {} as Record - ); -}; - -const defaultGasSpeeds = (chainId: ChainId) => { - switch (chainId) { - case ChainId.bsc: - case ChainId.goerli: - case ChainId.polygon: - return [gasUtils.NORMAL, gasUtils.FAST, gasUtils.URGENT]; - case ChainId.gnosis: - return [gasUtils.NORMAL]; - default: - return [gasUtils.NORMAL, gasUtils.FAST, gasUtils.URGENT, gasUtils.CUSTOM]; - } -}; - -export const getChainsGasSpeeds = (): Record => { - const backendNetworks = getBackendNetworks(); - return backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = defaultGasSpeeds(parseInt(backendNetwork.id, 10)); - return acc; - }, - {} as Record - ); -}; - -const defaultPollingIntervals = (chainId: ChainId) => { - switch (chainId) { - case ChainId.polygon: - return 2_000; - case ChainId.arbitrum: - case ChainId.bsc: - return 3_000; - default: - return 5_000; - } -}; - -export const getChainsSwapPollingInterval = (): Record => { - const backendNetworks = getBackendNetworks(); - return backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = defaultPollingIntervals(parseInt(backendNetwork.id, 10)); - return acc; - }, - {} as Record - ); -}; - -const defaultSimplehashNetworks = (chainId: ChainId) => { - switch (chainId) { - case ChainId.apechain: - return 'apechain'; - case ChainId.arbitrum: - return 'arbitrum'; - case ChainId.avalanche: - return 'avalanche'; - case ChainId.base: - return 'base'; - case ChainId.blast: - return 'blast'; - case ChainId.bsc: - return 'bsc'; - case ChainId.degen: - return 'degen'; - case ChainId.gnosis: - return 'gnosis'; - case ChainId.goerli: - return 'ethereum-goerli'; - case ChainId.mainnet: - return 'ethereum'; - case ChainId.optimism: - return 'optimism'; - case ChainId.polygon: - return 'polygon'; - case ChainId.zora: - return 'zora'; - default: - return ''; - } -}; - -export const getChainsSimplehashNetwork = (): Record => { - const backendNetworks = getBackendNetworks(); - return backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = defaultSimplehashNetworks(parseInt(backendNetwork.id, 10)); - return acc; - }, - {} as Record - ); -}; - -const filterChainIdsByService = (servicePath: (services: BackendNetworkServices) => boolean): number[] => { - const backendNetworks = getBackendNetworks(); - return backendNetworks.networks - .filter((network: BackendNetwork) => { - const services = network?.enabledServices; - return services && servicePath(services); - }) - .map((network: BackendNetwork) => parseInt(network.id, 10)); -}; - -export const meteorologySupportedChainIds = filterChainIdsByService(services => services.meteorology.enabled); - -export const supportedSwapChainIds = filterChainIdsByService(services => services.swap.enabled); - -export const supportedSwapExactOutputChainIds = filterChainIdsByService(services => services.swap.swapExactOutput); - -export const supportedBridgeExactOutputChainIds = filterChainIdsByService(services => services.swap.bridgeExactOutput); - -export const supportedNotificationsChainIds = filterChainIdsByService(services => services.notifications.enabled); - -export const supportedApprovalsChainIds = filterChainIdsByService(services => services.addys.approvals); - -export const supportedTransactionsChainIds = filterChainIdsByService(services => services.addys.transactions); - -export const supportedAssetsChainIds = filterChainIdsByService(services => services.addys.assets); - -export const supportedPositionsChainIds = filterChainIdsByService(services => services.addys.positions); - -export const supportedTokenSearchChainIds = filterChainIdsByService(services => services.tokenSearch.enabled); - -export const supportedNftChainIds = filterChainIdsByService(services => services.nftProxy.enabled); - -export const supportedFlashbotsChainIds = [ChainId.mainnet]; - -export const shouldDefaultToFastGasChainIds = [ChainId.mainnet, ChainId.polygon, ChainId.goerli]; - -export const getChainGasUnits = (chainId?: number): BackendNetwork['gasUnits'] => { - const backendNetworks = getBackendNetworks(); - const chainsGasUnits = backendNetworks.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = backendNetwork.gasUnits; - return acc; - }, - {} as Record - ); - - return (chainId ? chainsGasUnits[chainId] : undefined) || chainsGasUnits[ChainId.mainnet]; -}; - -export const getChainDefaultRpc = (chainId: ChainId) => { - switch (chainId) { - case ChainId.mainnet: - return useConnectedToHardhatStore.getState().connectedToHardhat - ? 'http://127.0.0.1:8545' - : getDefaultChains()[ChainId.mainnet].rpcUrls.default.http[0]; - default: - return getDefaultChains()[chainId].rpcUrls.default.http[0]; - } -}; - -// --- worklet functions --- - -export const getChainsLabelWorklet = (backendNetworks: SharedValue) => { - 'worklet'; - return backendNetworks.value.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = backendNetwork.label; - return acc; - }, - {} as Record - ); -}; - -export const getChainsNameWorklet = (backendNetworks: SharedValue) => { - 'worklet'; - return backendNetworks.value.networks.reduce( - (acc, backendNetwork: BackendNetwork) => { - acc[parseInt(backendNetwork.id, 10)] = backendNetwork.name; - return acc; - }, - {} as Record - ); -}; diff --git a/src/components/DappBrowser/control-panel/ControlPanel.tsx b/src/components/DappBrowser/control-panel/ControlPanel.tsx index 07f52d92f7b..cd3c587b259 100644 --- a/src/components/DappBrowser/control-panel/ControlPanel.tsx +++ b/src/components/DappBrowser/control-panel/ControlPanel.tsx @@ -61,8 +61,8 @@ import { SWAPS_V2, useExperimentalFlag } from '@/config'; import { swapsStore } from '@/state/swaps/swapsStore'; import { userAssetsStore } from '@/state/assets/userAssets'; import { greaterThan } from '@/helpers/utilities'; -import { ChainId } from '@/chains/types'; -import { getChainsLabel, getDefaultChains } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const PAGES = { HOME: 'home', @@ -183,12 +183,12 @@ export const ControlPanel = () => { const { testnetsEnabled } = store.getState().settings; const allNetworkItems = useMemo(() => { - return Object.values(getDefaultChains()) + return Object.values(useBackendNetworksStore.getState().getDefaultChains()) .filter(({ testnet }) => testnetsEnabled || !testnet) .map(chain => { return { IconComponent: , - label: getChainsLabel()[chain.id], + label: useBackendNetworksStore.getState().getChainsLabel()[chain.id], secondaryLabel: i18n.t( isConnected && chain.id === currentChainId ? i18n.l.dapp_browser.control_panel.connected diff --git a/src/components/DappBrowser/handleProviderRequest.ts b/src/components/DappBrowser/handleProviderRequest.ts index 0bf86a5bae2..c56b9e5cd17 100644 --- a/src/components/DappBrowser/handleProviderRequest.ts +++ b/src/components/DappBrowser/handleProviderRequest.ts @@ -11,8 +11,8 @@ import { Tab } from '@rainbow-me/provider/dist/references/messengers'; import { getDappMetadata } from '@/resources/metadata/dapp'; import { useAppSessionsStore } from '@/state/appSessions'; import { BigNumber } from '@ethersproject/bignumber'; -import { ChainId } from '@/chains/types'; -import { getChainsNativeAsset, getDefaultChains, getSupportedChainIds } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export type ProviderRequestPayload = RequestArguments & { id: number; @@ -162,7 +162,10 @@ const messengerProviderRequestFn = async (messenger: Messenger, request: Provide const isSupportedChainId = (chainId: number | string) => { const numericChainId = BigNumber.from(chainId).toNumber(); - return !!getSupportedChainIds().find(chainId => chainId === numericChainId); + return !!useBackendNetworksStore + .getState() + .getSupportedChainIds() + .find(chainId => chainId === numericChainId); }; const getActiveSession = ({ host }: { host: string }): ActiveSession => { const hostSessions = useAppSessionsStore.getState().getActiveSession({ host }); @@ -265,7 +268,7 @@ export const handleProviderRequestApp = ({ messenger, data, meta }: { messenger: callbackOptions?: CallbackOptions; }): { chainAlreadyAdded: boolean } => { const { chainId } = proposedChain; - if (getDefaultChains()[Number(chainId)]) { + if (useBackendNetworksStore.getState().getDefaultChains()[Number(chainId)]) { // TODO - Open add / switch ethereum chain return { chainAlreadyAdded: true }; } else { @@ -320,7 +323,7 @@ export const handleProviderRequestApp = ({ messenger, data, meta }: { messenger: callbackOptions?: CallbackOptions; }) => { const { chainId } = proposedChain; - const supportedChainId = getSupportedChainIds().includes(Number(chainId)); + const supportedChainId = useBackendNetworksStore.getState().getSupportedChainIds().includes(Number(chainId)); if (supportedChainId) { const host = getDappHost(callbackOptions?.sender.url) || ''; const activeSession = getActiveSession({ host }); @@ -343,7 +346,7 @@ export const handleProviderRequestApp = ({ messenger, data, meta }: { messenger: onSwitchEthereumChainSupported, getProvider, getActiveSession, - getChainNativeCurrency: chainId => getChainsNativeAsset()[chainId], + getChainNativeCurrency: chainId => useBackendNetworksStore.getState().getChainsNativeAsset()[chainId], }); // @ts-ignore diff --git a/src/components/Transactions/TransactionDetailsCard.tsx b/src/components/Transactions/TransactionDetailsCard.tsx index 17d9f89688a..8e90144e879 100644 --- a/src/components/Transactions/TransactionDetailsCard.tsx +++ b/src/components/Transactions/TransactionDetailsCard.tsx @@ -7,7 +7,7 @@ import { TextColor } from '@/design-system/color/palettes'; import { abbreviations, ethereumUtils } from '@/utils'; import { TransactionSimulationMeta } from '@/graphql/__generated__/metadataPOST'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { TransactionDetailsRow } from '@/components/Transactions/TransactionDetailsRow'; import { FadedScrollCard } from '@/components/FadedScrollCard'; @@ -20,7 +20,7 @@ import { CARD_BORDER_WIDTH, EXPANDED_CARD_TOP_INSET, } from '@/components/Transactions/constants'; -import { getChainsName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; interface TransactionDetailsCardProps { chainId: ChainId; @@ -93,7 +93,13 @@ export const TransactionDetailsCard = ({ - {} + { + + } {!!(meta?.to?.address || toAddress || showTransferToRow) && ( {i18n.t(i18n.l.walletconnect.simulation.simulation_card.messages.need_more_native, { symbol: walletBalance?.symbol, - network: getChainsName()[chainId], + network: useBackendNetworksStore.getState().getChainsName()[chainId], })} ) : ( diff --git a/src/components/asset-list/RecyclerAssetList2/FastComponents/FastBalanceCoinRow.tsx b/src/components/asset-list/RecyclerAssetList2/FastComponents/FastBalanceCoinRow.tsx index e597de4bf30..e9dd9154fed 100644 --- a/src/components/asset-list/RecyclerAssetList2/FastComponents/FastBalanceCoinRow.tsx +++ b/src/components/asset-list/RecyclerAssetList2/FastComponents/FastBalanceCoinRow.tsx @@ -12,7 +12,7 @@ import Routes from '@/navigation/routesNames'; import { borders, colors, padding, shadow } from '@/styles'; import RainbowCoinIcon from '@/components/coin-icon/RainbowCoinIcon'; import { NativeCurrencyKey } from '@/entities'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; interface CoinCheckButtonProps { isHidden: boolean; diff --git a/src/components/asset-list/RecyclerAssetList2/FastComponents/FastCoinBadge.tsx b/src/components/asset-list/RecyclerAssetList2/FastComponents/FastCoinBadge.tsx index 5eba92ba6fa..dd948ecd527 100644 --- a/src/components/asset-list/RecyclerAssetList2/FastComponents/FastCoinBadge.tsx +++ b/src/components/asset-list/RecyclerAssetList2/FastComponents/FastCoinBadge.tsx @@ -20,7 +20,7 @@ import DegenBadge from '@/assets/badges/degenBadge.png'; import DegenBadgeDark from '@/assets/badges/degenBadgeDark.png'; import ApechainBadge from '@/assets/badges/apechainBadge.png'; import ApechainBadgeDark from '@/assets/badges/apechainBadgeDark.png'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; interface FastChainBadgeProps { chainId: ChainId; diff --git a/src/components/asset-list/RecyclerAssetList2/FastComponents/FastCurrencySelectionRow.tsx b/src/components/asset-list/RecyclerAssetList2/FastComponents/FastCurrencySelectionRow.tsx index d9c41c51347..d122b9a622e 100644 --- a/src/components/asset-list/RecyclerAssetList2/FastComponents/FastCurrencySelectionRow.tsx +++ b/src/components/asset-list/RecyclerAssetList2/FastComponents/FastCurrencySelectionRow.tsx @@ -13,7 +13,7 @@ import { colors, fonts, fontWithWidth, getFontSize } from '@/styles'; import { deviceUtils } from '@/utils'; import RainbowCoinIcon from '@/components/coin-icon/RainbowCoinIcon'; import { useExternalToken } from '@/resources/assets/externalAssetsQuery'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const SafeRadialGradient = (IS_TESTING === 'true' ? View : RadialGradient) as typeof RadialGradient; diff --git a/src/components/asset-list/RecyclerAssetList2/profile-header/ProfileActionButtonsRow.tsx b/src/components/asset-list/RecyclerAssetList2/profile-header/ProfileActionButtonsRow.tsx index b5200222c2e..adc5a5b905c 100644 --- a/src/components/asset-list/RecyclerAssetList2/profile-header/ProfileActionButtonsRow.tsx +++ b/src/components/asset-list/RecyclerAssetList2/profile-header/ProfileActionButtonsRow.tsx @@ -20,7 +20,7 @@ import { useAccountAccentColor } from '@/hooks/useAccountAccentColor'; import { addressCopiedToastAtom } from '@/recoil/addressCopiedToastAtom'; import { swapsStore } from '@/state/swaps/swapsStore'; import { userAssetsStore } from '@/state/assets/userAssets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; export const ProfileActionButtonsRowHeight = 80; diff --git a/src/components/cards/EthCard.tsx b/src/components/cards/EthCard.tsx index 17719704d4e..b4504d62421 100644 --- a/src/components/cards/EthCard.tsx +++ b/src/components/cards/EthCard.tsx @@ -22,7 +22,7 @@ import * as i18n from '@/languages'; import { ButtonPressAnimationTouchEvent } from '@/components/animations/ButtonPressAnimation/types'; import { useExternalToken } from '@/resources/assets/externalAssetsQuery'; import assetTypes from '@/entities/assetTypes'; -import { Network, ChainId } from '@/chains/types'; +import { Network, ChainId } from '@/state/backendNetworks/types'; import { getUniqueId } from '@/utils/ethereumUtils'; import { EthCoinIcon } from '../coin-icon/EthCoinIcon'; diff --git a/src/components/cards/NFTOffersCard/Offer.tsx b/src/components/cards/NFTOffersCard/Offer.tsx index cc8113de7af..85452eab6c6 100644 --- a/src/components/cards/NFTOffersCard/Offer.tsx +++ b/src/components/cards/NFTOffersCard/Offer.tsx @@ -21,9 +21,9 @@ import Svg, { Path } from 'react-native-svg'; import RainbowCoinIcon from '@/components/coin-icon/RainbowCoinIcon'; import { useExternalToken } from '@/resources/assets/externalAssetsQuery'; import { useAccountSettings } from '@/hooks'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; import { AddressOrEth } from '@/__swaps__/types/assets'; -import { getChainsIdByName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const TWO_HOURS_MS = 2 * 60 * 60 * 1000; export const CELL_HORIZONTAL_PADDING = 7; @@ -68,7 +68,7 @@ export const Offer = ({ offer }: { offer: NftOffer }) => { const { colorMode } = useColorMode(); const theme = useTheme(); const { nativeCurrency } = useAccountSettings(); - const offerChainId = getChainsIdByName()[offer.network as Network]; + const offerChainId = useBackendNetworksStore.getState().getChainsIdByName()[offer.network as Network]; const { data: externalAsset } = useExternalToken({ address: offer.paymentToken.address as AddressOrEth, chainId: offerChainId, diff --git a/src/components/cards/OpRewardsCard.tsx b/src/components/cards/OpRewardsCard.tsx index 9c6c1ca601b..3c1251010b3 100644 --- a/src/components/cards/OpRewardsCard.tsx +++ b/src/components/cards/OpRewardsCard.tsx @@ -8,7 +8,7 @@ import * as i18n from '@/languages'; import { useNavigation } from '@/navigation'; import Routes from '@/navigation/routesNames'; import { colors } from '@/styles'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const GRADIENT: Gradient = { colors: ['#520907', '#B22824'], diff --git a/src/components/change-wallet/WalletList.tsx b/src/components/change-wallet/WalletList.tsx index 5d08e917f60..8f35108db8d 100644 --- a/src/components/change-wallet/WalletList.tsx +++ b/src/components/change-wallet/WalletList.tsx @@ -18,7 +18,7 @@ import { position } from '@/styles'; import { EditWalletContextMenuActions } from '@/screens/ChangeWalletSheet'; import { HARDWARE_WALLETS, useExperimentalFlag } from '@/config'; import { Inset, Stack } from '@/design-system'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; const listTopPadding = 7.5; const rowHeight = 59; diff --git a/src/components/coin-icon/ChainImage.tsx b/src/components/coin-icon/ChainImage.tsx index 4db59d9c61f..0be5f993fa5 100644 --- a/src/components/coin-icon/ChainImage.tsx +++ b/src/components/coin-icon/ChainImage.tsx @@ -1,5 +1,5 @@ import React, { useMemo } from 'react'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import ArbitrumBadge from '@/assets/badges/arbitrum.png'; import BaseBadge from '@/assets/badges/base.png'; diff --git a/src/components/coin-icon/EthCoinIcon.tsx b/src/components/coin-icon/EthCoinIcon.tsx index a1b23be263f..3d9aa81a1c4 100644 --- a/src/components/coin-icon/EthCoinIcon.tsx +++ b/src/components/coin-icon/EthCoinIcon.tsx @@ -3,7 +3,7 @@ import { useTheme } from '@/theme'; import { useNativeAsset } from '@/utils/ethereumUtils'; import RainbowCoinIcon from './RainbowCoinIcon'; import { ETH_SYMBOL } from '@/references'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; type EthCoinIconProps = { size?: number; diff --git a/src/components/coin-icon/RainbowCoinIcon.tsx b/src/components/coin-icon/RainbowCoinIcon.tsx index f47cfb57a07..118c9445f42 100644 --- a/src/components/coin-icon/RainbowCoinIcon.tsx +++ b/src/components/coin-icon/RainbowCoinIcon.tsx @@ -7,7 +7,7 @@ import { FallbackIcon as CoinIconTextFallback } from '@/utils'; import { FastFallbackCoinIconImage } from '../asset-list/RecyclerAssetList2/FastComponents/FastFallbackCoinIconImage'; import { FastChainBadge } from '../asset-list/RecyclerAssetList2/FastComponents/FastCoinBadge'; import { TokenColors } from '@/graphql/__generated__/metadata'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const fallbackTextStyles = { fontFamily: fonts.family.SFProRounded, diff --git a/src/components/coin-icon/TwoCoinsIcon.tsx b/src/components/coin-icon/TwoCoinsIcon.tsx index e84d15062cc..d70e91b6d75 100644 --- a/src/components/coin-icon/TwoCoinsIcon.tsx +++ b/src/components/coin-icon/TwoCoinsIcon.tsx @@ -4,7 +4,7 @@ import { ParsedAddressAsset } from '@/entities'; import { useTheme } from '@/theme'; import ChainBadge from './ChainBadge'; import RainbowCoinIcon from './RainbowCoinIcon'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; export function TwoCoinsIcon({ size = 45, diff --git a/src/components/coin-row/FastTransactionCoinRow.tsx b/src/components/coin-row/FastTransactionCoinRow.tsx index fdc2b5b8866..f0fa251c68f 100644 --- a/src/components/coin-row/FastTransactionCoinRow.tsx +++ b/src/components/coin-row/FastTransactionCoinRow.tsx @@ -10,7 +10,7 @@ import Routes from '@rainbow-me/routes'; import { ImgixImage } from '../images'; import { CardSize } from '../unique-token/CardSize'; import { ChainBadge } from '../coin-icon'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { address } from '@/utils/abbreviations'; import { convertAmountAndPriceToNativeDisplay, diff --git a/src/components/context-menu-buttons/ChainContextMenu.tsx b/src/components/context-menu-buttons/ChainContextMenu.tsx index 4971f34f238..eb3184bb1dd 100644 --- a/src/components/context-menu-buttons/ChainContextMenu.tsx +++ b/src/components/context-menu-buttons/ChainContextMenu.tsx @@ -5,8 +5,8 @@ import { Bleed, Box, Inline, Text, TextProps } from '@/design-system'; import * as i18n from '@/languages'; import { useUserAssetsStore } from '@/state/assets/userAssets'; import { showActionSheetWithOptions } from '@/utils'; -import { ChainId } from '@/chains/types'; -import { getChainsLabel, getChainsName } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; interface DefaultButtonOptions { iconColor?: TextProps['color']; @@ -58,10 +58,10 @@ export const ChainContextMenu = ({ const chainItems = balanceSortedChains.map(chainId => { return { actionKey: `${chainId}`, - actionTitle: getChainsLabel()[chainId], + actionTitle: useBackendNetworksStore.getState().getChainsLabel()[chainId], icon: { iconType: 'ASSET', - iconValue: `${getChainsName()[chainId]}Badge${chainId === ChainId.mainnet ? '' : 'NoShadow'}`, + iconValue: `${useBackendNetworksStore.getState().getChainsName()[chainId]}Badge${chainId === ChainId.mainnet ? '' : 'NoShadow'}`, }, }; }); @@ -111,7 +111,7 @@ export const ChainContextMenu = ({ const displayName = useMemo(() => { if (!selectedChainId) return allNetworksText; - const name = getChainsLabel()[selectedChainId]; + const name = useBackendNetworksStore.getState().getChainsLabel()[selectedChainId]; return name.endsWith(' Chain') ? name.slice(0, -6) : name; }, [allNetworksText, selectedChainId]); diff --git a/src/components/ens-profile/ActionButtons/MoreButton.tsx b/src/components/ens-profile/ActionButtons/MoreButton.tsx index 1e662c71302..e33486d93a3 100644 --- a/src/components/ens-profile/ActionButtons/MoreButton.tsx +++ b/src/components/ens-profile/ActionButtons/MoreButton.tsx @@ -11,7 +11,7 @@ import { RAINBOW_PROFILES_BASE_URL } from '@/references'; import Routes from '@/navigation/routesNames'; import { ethereumUtils } from '@/utils'; import { formatAddressForDisplay } from '@/utils/abbreviations'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const ACTIONS = { ADD_CONTACT: 'add-contact', diff --git a/src/components/exchange/CurrencySelectModalHeader.tsx b/src/components/exchange/CurrencySelectModalHeader.tsx index fd51bd8871e..0cf43b17ed6 100644 --- a/src/components/exchange/CurrencySelectModalHeader.tsx +++ b/src/components/exchange/CurrencySelectModalHeader.tsx @@ -8,7 +8,7 @@ import { useNavigation } from '@/navigation'; import Routes from '@/navigation/routesNames'; import RainbowCoinIcon from '../coin-icon/RainbowCoinIcon'; import { useTheme } from '@/theme'; -import { getChainsIdByName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const CurrencySelectModalHeaderHeight = 59; @@ -58,7 +58,7 @@ export default function CurrencySelectModalHeader({ (null); const networkMenuItems = useMemo(() => { - return Object.values(getDefaultChains()) - .filter(chain => supportedSwapChainIds.includes(chain.id)) + return Object.values(useBackendNetworksStore.getState().getDefaultChains()) + .filter(chain => useBackendNetworksStore.getState().getSupportedChainIds().includes(chain.id)) .map(chain => ({ chainId: chain.id, - title: getChainsLabel()[chain.id], + title: useBackendNetworksStore.getState().getChainsLabel()[chain.id], })); }, []); diff --git a/src/components/exchange/exchangeAssetRowContextMenuProps.ts b/src/components/exchange/exchangeAssetRowContextMenuProps.ts index ec6cec49a79..f2c96d0b227 100644 --- a/src/components/exchange/exchangeAssetRowContextMenuProps.ts +++ b/src/components/exchange/exchangeAssetRowContextMenuProps.ts @@ -3,8 +3,8 @@ import { startCase } from 'lodash'; import { NativeSyntheticEvent } from 'react-native'; import { setClipboard } from '../../hooks/useClipboard'; import { abbreviations, ethereumUtils, haptics, showActionSheetWithOptions } from '@/utils'; -import { ChainId } from '@/chains/types'; -import { getChainsIdByName } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const buildBlockExplorerAction = (chainId: ChainId) => { const blockExplorerText = lang.t('exchange.coin_row.view_on', { @@ -44,7 +44,7 @@ export default function contextMenuProps(item: any, onCopySwapDetailsText: (addr }; const onPressAndroid = () => { - const blockExplorerText = `View on ${startCase(ethereumUtils.getBlockExplorer({ chainId: getChainsIdByName()[item?.network] }))}`; + const blockExplorerText = `View on ${startCase(ethereumUtils.getBlockExplorer({ chainId: useBackendNetworksStore.getState().getChainsIdByName()[item?.network] }))}`; const androidContractActions = [lang.t('wallet.action.copy_contract_address'), blockExplorerText, lang.t('button.cancel')]; showActionSheetWithOptions( @@ -59,13 +59,16 @@ export default function contextMenuProps(item: any, onCopySwapDetailsText: (addr handleCopyContractAddress(item?.address); } if (idx === 1) { - ethereumUtils.openTokenEtherscanURL({ address: item?.address, chainId: getChainsIdByName()[item?.network] }); + ethereumUtils.openTokenEtherscanURL({ + address: item?.address, + chainId: useBackendNetworksStore.getState().getChainsIdByName()[item?.network], + }); } } ); }; - const blockExplorerAction = buildBlockExplorerAction(getChainsIdByName()[item?.network]); + const blockExplorerAction = buildBlockExplorerAction(useBackendNetworksStore.getState().getChainsIdByName()[item?.network]); const menuConfig = { menuItems: [ blockExplorerAction, @@ -81,7 +84,10 @@ export default function contextMenuProps(item: any, onCopySwapDetailsText: (addr if (actionKey === CoinRowActionsEnum.copyAddress) { handleCopyContractAddress(item?.address); } else if (actionKey === CoinRowActionsEnum.blockExplorer) { - ethereumUtils.openTokenEtherscanURL({ address: item?.address, chainId: getChainsIdByName()[item?.network] }); + ethereumUtils.openTokenEtherscanURL({ + address: item?.address, + chainId: useBackendNetworksStore.getState().getChainsIdByName()[item?.network], + }); } }; return { diff --git a/src/components/expanded-state/AvailableNetworksv2.tsx b/src/components/expanded-state/AvailableNetworksv2.tsx index 77dee4876ce..e5d67cf1099 100644 --- a/src/components/expanded-state/AvailableNetworksv2.tsx +++ b/src/components/expanded-state/AvailableNetworksv2.tsx @@ -23,9 +23,9 @@ import { parseSearchAsset } from '@/__swaps__/utils/assets'; import { AddressOrEth, AssetType } from '@/__swaps__/types/assets'; import { swapsStore } from '@/state/swaps/swapsStore'; import { InteractionManager } from 'react-native'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { getUniqueId } from '@/utils/ethereumUtils'; -import { getChainsLabel, getChainsName, getDefaultChains, supportedSwapChainIds } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const NOOP = () => null; @@ -80,6 +80,8 @@ const AvailableNetworksv2 = ({ const uniqueId = `${newAsset.address}_${asset.chainId}`; const userAsset = userAssetsStore.getState().userAssets.get(uniqueId); + const chainName = useBackendNetworksStore.getState().getChainsName()[asset.chainId]; + const parsedAsset = parseSearchAsset({ assetWithPrice: { ...newAsset, @@ -87,7 +89,7 @@ const AvailableNetworksv2 = ({ address: newAsset.address as AddressOrEth, type: newAsset.type as AssetType, chainId: asset.chainId, - chainName: getChainsName()[asset.chainId], + chainName, isNativeAsset: false, native: {}, }, @@ -95,7 +97,7 @@ const AvailableNetworksv2 = ({ ...newAsset, uniqueId, chainId: asset.chainId, - chainName: getChainsName()[asset.chainId], + chainName, address: newAsset.address as AddressOrEth, highLiquidity: newAsset.highLiquidity ?? false, isRainbowCurated: newAsset.isRainbowCurated ?? false, @@ -126,7 +128,7 @@ const AvailableNetworksv2 = ({ } newAsset.uniqueId = getUniqueId(asset.address, chainId); - newAsset.type = getChainsName()[chainId]; + newAsset.type = useBackendNetworksStore.getState().getChainsName()[chainId]; navigate(Routes.EXCHANGE_MODAL, { params: { @@ -165,15 +167,17 @@ const AvailableNetworksv2 = ({ convertAssetAndNavigate(availableChainIds[0]); }, [availableChainIds, convertAssetAndNavigate]); - const networkMenuItems = supportedSwapChainIds + const networkMenuItems = useBackendNetworksStore + .getState() + .getSupportedChainIds() .filter(chainId => chainId !== ChainId.mainnet) - .map(chainId => getDefaultChains()[chainId]) + .map(chainId => useBackendNetworksStore.getState().getDefaultChains()[chainId]) .map(chain => ({ actionKey: `${chain.id}`, - actionTitle: getChainsLabel()[chain.id], + actionTitle: useBackendNetworksStore.getState().getChainsLabel()[chain.id], icon: { iconType: 'ASSET', - iconValue: `${getChainsName()[chain.id]}Badge${chain.id === ChainId.mainnet ? '' : 'NoShadow'}`, + iconValue: `${useBackendNetworksStore.getState().getChainsName()[chain.id]}Badge${chain.id === ChainId.mainnet ? '' : 'NoShadow'}`, }, })); @@ -235,7 +239,7 @@ const AvailableNetworksv2 = ({ availableNetworks: availableChainIds?.length, }) : lang.t('expanded_state.asset.available_networkv2', { - availableNetwork: getChainsName()[availableChainIds[0]], + availableNetwork: useBackendNetworksStore.getState().getChainsName()[availableChainIds[0]], })} diff --git a/src/components/expanded-state/UniqueTokenExpandedState.tsx b/src/components/expanded-state/UniqueTokenExpandedState.tsx index 255706e32c8..105c3f0e680 100644 --- a/src/components/expanded-state/UniqueTokenExpandedState.tsx +++ b/src/components/expanded-state/UniqueTokenExpandedState.tsx @@ -65,7 +65,7 @@ import { buildRainbowUrl } from '@/utils/buildRainbowUrl'; import isHttpUrl from '@/helpers/isHttpUrl'; import { useNFTOffers } from '@/resources/reservoir/nftOffersQuery'; import { convertAmountToNativeDisplay } from '@/helpers/utilities'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const BackgroundBlur = styled(BlurView).attrs({ blurAmount: 100, diff --git a/src/components/expanded-state/swap-details/SwapDetailsRewardRow.tsx b/src/components/expanded-state/swap-details/SwapDetailsRewardRow.tsx index 461f4c2c1c8..bd09a88a6e9 100644 --- a/src/components/expanded-state/swap-details/SwapDetailsRewardRow.tsx +++ b/src/components/expanded-state/swap-details/SwapDetailsRewardRow.tsx @@ -8,15 +8,15 @@ import Routes from '@/navigation/routesNames'; import { ChainBadge } from '@/components/coin-icon'; import { useTheme } from '@/theme'; import * as i18n from '@/languages'; -import { ChainId } from '@/chains/types'; -import { getChainsNativeAsset } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export function SwapDetailsRewardRow({ reward }: { reward: Reward }) { const { navigate } = useNavigation(); const { isDarkMode } = useTheme(); const roundedAmount = Math.round(reward.amount * 1000) / 1000; - const nativeAsset = getChainsNativeAsset()[ChainId.optimism]; + const nativeAsset = useBackendNetworksStore.getState().getChainsNativeAsset()[ChainId.optimism]; const accentColor = isDarkMode ? nativeAsset.colors.primary : nativeAsset.colors.fallback || nativeAsset.colors.primary; return ( diff --git a/src/components/expanded-state/swap-settings/MaxToleranceInput.tsx b/src/components/expanded-state/swap-settings/MaxToleranceInput.tsx index e803f523096..d96eb26f373 100644 --- a/src/components/expanded-state/swap-settings/MaxToleranceInput.tsx +++ b/src/components/expanded-state/swap-settings/MaxToleranceInput.tsx @@ -11,7 +11,7 @@ import { useMagicAutofocus, useSwapSettings } from '@/hooks'; import { useNavigation } from '@/navigation'; import Routes from '@/navigation/routesNames'; import { colors } from '@/styles'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const convertBipsToPercent = (bips: number) => (bips / 100).toString(); const convertPercentToBips = (percent: number) => (percent * 100).toString(); diff --git a/src/components/expanded-state/unique-token/UniqueTokenExpandedStateHeader.tsx b/src/components/expanded-state/unique-token/UniqueTokenExpandedStateHeader.tsx index 990158f132b..7e5126d1b84 100644 --- a/src/components/expanded-state/unique-token/UniqueTokenExpandedStateHeader.tsx +++ b/src/components/expanded-state/unique-token/UniqueTokenExpandedStateHeader.tsx @@ -21,7 +21,7 @@ import isSVGImage from '@/utils/isSVG'; import { refreshNFTContractMetadata, reportNFT } from '@/resources/nfts/simplehash'; import { ContextCircleButton } from '@/components/context-menu'; import { IS_ANDROID, IS_IOS } from '@/env'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const AssetActionsEnum = { copyTokenID: 'copyTokenID', diff --git a/src/components/gas/GasSpeedButton.tsx b/src/components/gas/GasSpeedButton.tsx index dffeaae4ef7..39ca7d145dd 100644 --- a/src/components/gas/GasSpeedButton.tsx +++ b/src/components/gas/GasSpeedButton.tsx @@ -26,8 +26,8 @@ import { ethereumUtils, gasUtils } from '@/utils'; import { IS_ANDROID } from '@/env'; import { ContextMenu } from '../context-menu'; import { EthCoinIcon } from '../coin-icon/EthCoinIcon'; -import { ChainId } from '@/chains/types'; -import { getChainsGasSpeeds } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { ThemeContextProps, useTheme } from '@/theme'; import { ParsedAddressAsset } from '@/entities'; import { GasSpeed } from '@/__swaps__/types/gas'; @@ -390,7 +390,7 @@ const GasSpeedButton = ({ const speedOptions = useMemo(() => { if (speeds) return speeds; - return getChainsGasSpeeds()[chainId]; + return useBackendNetworksStore.getState().getChainsGasSpeeds()[chainId]; }, [chainId, speeds]); const menuConfig = useMemo(() => { diff --git a/src/components/positions/PositionsCard.tsx b/src/components/positions/PositionsCard.tsx index c056f075476..94a80ed60f4 100644 --- a/src/components/positions/PositionsCard.tsx +++ b/src/components/positions/PositionsCard.tsx @@ -13,12 +13,12 @@ import { event } from '@/analytics/event'; import { IS_ANDROID } from '@/env'; import { capitalize, uniqBy } from 'lodash'; import { RainbowDeposit, RainbowPosition } from '@/resources/defi/types'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; import RainbowCoinIcon from '../coin-icon/RainbowCoinIcon'; import { useAccountSettings } from '@/hooks'; import { useExternalToken } from '@/resources/assets/externalAssetsQuery'; import { AddressOrEth } from '@/__swaps__/types/assets'; -import { getChainsIdByName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; type PositionCardProps = { position: RainbowPosition; @@ -33,7 +33,7 @@ type CoinStackToken = { function CoinIconForStack({ token }: { token: CoinStackToken }) { const theme = useTheme(); const { nativeCurrency } = useAccountSettings(); - const chainId = getChainsIdByName()[token.network]; + const chainId = useBackendNetworksStore.getState().getChainsIdByName()[token.network]; const { data: externalAsset } = useExternalToken({ address: token.address as AddressOrEth, chainId, currency: nativeCurrency }); return ( diff --git a/src/components/remote-promo-sheet/check-fns/hasSwapTxn.ts b/src/components/remote-promo-sheet/check-fns/hasSwapTxn.ts index 3a4de5277a6..17c4d22b04d 100644 --- a/src/components/remote-promo-sheet/check-fns/hasSwapTxn.ts +++ b/src/components/remote-promo-sheet/check-fns/hasSwapTxn.ts @@ -1,5 +1,5 @@ import type { EthereumAddress, RainbowTransaction } from '@/entities'; -import { getSupportedMainnetChainIds } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { queryClient } from '@/react-query/queryClient'; import store from '@/redux/store'; import { consolidatedTransactionsQueryKey } from '@/resources/transactions/consolidatedTransactions'; @@ -16,7 +16,7 @@ export const hasSwapTxn = async (): Promise => { const paginatedTransactionsKey = consolidatedTransactionsQueryKey({ address: accountAddress, currency: nativeCurrency, - chainIds: getSupportedMainnetChainIds(), + chainIds: useBackendNetworksStore.getState().getSupportedMainnetChainIds(), }); const queryData = queryClient.getQueryData(paginatedTransactionsKey); const pages = queryData?.pages || []; diff --git a/src/components/sheet/sheet-action-buttons/SwapActionButton.tsx b/src/components/sheet/sheet-action-buttons/SwapActionButton.tsx index 9ee773238c9..1a1d4918161 100644 --- a/src/components/sheet/sheet-action-buttons/SwapActionButton.tsx +++ b/src/components/sheet/sheet-action-buttons/SwapActionButton.tsx @@ -16,7 +16,7 @@ import { swapsStore } from '@/state/swaps/swapsStore'; import { InteractionManager } from 'react-native'; import { AddressOrEth, AssetType, ParsedSearchAsset } from '@/__swaps__/types/assets'; import exchangeModalTypes from '@/helpers/exchangeModalTypes'; -import { getChainsIdByName, getChainsName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; type SwapActionButtonProps = { asset: RainbowToken; @@ -51,7 +51,8 @@ function SwapActionButton({ asset, color: givenColor, inputType, label, fromDisc return; } - const chainId = getChainsIdByName()[asset.network]; + const chainId = useBackendNetworksStore.getState().getChainsIdByName()[asset.network]; + const chainName = useBackendNetworksStore.getState().getChainsName()[chainId]; const uniqueId = `${asset.address}_${chainId}`; const userAsset = userAssetsStore.getState().userAssets.get(uniqueId); @@ -62,7 +63,7 @@ function SwapActionButton({ asset, color: givenColor, inputType, label, fromDisc address: asset.address as AddressOrEth, type: asset.type as AssetType, chainId, - chainName: getChainsName()[chainId], + chainName, isNativeAsset: false, native: {}, }, @@ -70,7 +71,7 @@ function SwapActionButton({ asset, color: givenColor, inputType, label, fromDisc ...asset, uniqueId, chainId, - chainName: getChainsName()[chainId], + chainName, address: asset.address as AddressOrEth, highLiquidity: asset.highLiquidity ?? false, isRainbowCurated: asset.isRainbowCurated ?? false, @@ -96,7 +97,7 @@ function SwapActionButton({ asset, color: givenColor, inputType, label, fromDisc ...nativeAssetForChain, uniqueId: `${nativeAssetForChain.address}_${chainId}`, chainId, - chainName: getChainsName()[chainId], + chainName, address: nativeAssetForChain.address as AddressOrEth, type: nativeAssetForChain.type as AssetType, mainnetAddress: nativeAssetForChain.mainnet_address as AddressOrEth, diff --git a/src/components/walletconnect-list/WalletConnectV2ListItem.tsx b/src/components/walletconnect-list/WalletConnectV2ListItem.tsx index 4b4d2cc6474..ee1fdf35660 100644 --- a/src/components/walletconnect-list/WalletConnectV2ListItem.tsx +++ b/src/components/walletconnect-list/WalletConnectV2ListItem.tsx @@ -24,8 +24,8 @@ import { changeAccount, disconnectSession } from '@/walletConnect'; import { Box, Inline } from '@/design-system'; import ChainBadge from '@/components/coin-icon/ChainBadge'; import { EthCoinIcon } from '../coin-icon/EthCoinIcon'; -import { ChainId } from '@/chains/types'; -import { getSupportedChainIds } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const CONTAINER_PADDING = 15; const VENDOR_LOGO_ICON_SIZE = 50; @@ -78,7 +78,9 @@ export function WalletConnectV2ListItem({ session, reload }: { session: SessionT const chains = useMemo(() => namespaces?.eip155?.chains || [], [namespaces]); const chainIds = useMemo( () => - (chains?.map(chain => parseInt(chain.split(':')[1]))?.filter(chainId => getSupportedChainIds().includes(chainId)) ?? []) as ChainId[], + chains + ?.map(chain => parseInt(chain.split(':')[1])) + ?.filter(chainId => useBackendNetworksStore.getState().getSupportedChainIds().includes(chainId)) ?? [], [chains] ); diff --git a/src/entities/tokens.ts b/src/entities/tokens.ts index c8f2eddc099..bd67a05eaeb 100644 --- a/src/entities/tokens.ts +++ b/src/entities/tokens.ts @@ -1,6 +1,6 @@ import { EthereumAddress } from '.'; import { Chain } from '@wagmi/chains'; -import { Network, ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { TokenColors } from '@/graphql/__generated__/metadata'; export interface ZerionAssetPrice { diff --git a/src/entities/transactions/transaction.ts b/src/entities/transactions/transaction.ts index 00d2bb26e10..fe4d6cab39c 100644 --- a/src/entities/transactions/transaction.ts +++ b/src/entities/transactions/transaction.ts @@ -7,7 +7,7 @@ import { SwapType } from '@rainbow-me/swaps'; import { SwapMetadata } from '@/raps/references'; import { UniqueAsset } from '../uniqueAssets'; import { ParsedAsset, AddysAsset } from '@/resources/assets/types'; -import { ChainId, Network } from '@/chains/types'; +import { ChainId, Network } from '@/state/backendNetworks/types'; import { TransactionResponse } from '@ethersproject/providers'; import { BytesLike } from '@ethersproject/bytes'; diff --git a/src/entities/uniqueAssets.ts b/src/entities/uniqueAssets.ts index 78f9f5ad4b7..9876d2e971a 100644 --- a/src/entities/uniqueAssets.ts +++ b/src/entities/uniqueAssets.ts @@ -1,4 +1,4 @@ -import { Network, ChainId } from '@/chains/types'; +import { ChainId, Network } from '@/state/backendNetworks/types'; import { AssetContract, AssetType } from '.'; interface UniqueAssetLastSale { diff --git a/src/featuresToUnlock/tokenGatedUtils.ts b/src/featuresToUnlock/tokenGatedUtils.ts index 1f9dfb4517b..2b4b532ff8b 100644 --- a/src/featuresToUnlock/tokenGatedUtils.ts +++ b/src/featuresToUnlock/tokenGatedUtils.ts @@ -2,8 +2,8 @@ import { Contract } from '@ethersproject/contracts'; import { EthereumAddress } from '@/entities'; import { getProvider } from '@/handlers/web3'; import { tokenGateCheckerAbi } from '@/references'; -import { Network } from '@/chains/types'; -import { getChainsIdByName } from '@/chains'; +import { Network } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export type TokenGateCheckerNetwork = | Network.arbitrum @@ -29,7 +29,7 @@ export const checkIfWalletsOwnNft = async ( network: TokenGateCheckerNetwork, walletsToCheck: EthereumAddress[] ) => { - const p = getProvider({ chainId: getChainsIdByName()[network] }); + const p = getProvider({ chainId: useBackendNetworksStore.getState().getChainsIdByName()[network] }); const contractInstance = new Contract(TOKEN_GATE_CHECKER_ADDRESS[network], tokenGateCheckerAbi, p); diff --git a/src/handlers/assets.ts b/src/handlers/assets.ts index e53c7439c1f..64c7cf65f6f 100644 --- a/src/handlers/assets.ts +++ b/src/handlers/assets.ts @@ -2,13 +2,13 @@ import { Contract } from '@ethersproject/contracts'; import { erc20ABI } from '@/references'; import { convertAmountToBalanceDisplay, convertRawAmountToDecimalFormat } from '@/helpers/utilities'; -import { ChainId } from '@/chains/types'; -import { getChainsNativeAsset } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { isLowerCaseMatch } from '@/utils'; import { AddressOrEth } from '@/__swaps__/types/assets'; export function isNativeAsset(address: AddressOrEth | string, chainId: ChainId) { - return isLowerCaseMatch(getChainsNativeAsset()[chainId].address, address); + return isLowerCaseMatch(useBackendNetworksStore.getState().getChainsNativeAsset()[chainId].address, address); } export async function getOnchainAssetBalance({ address, decimals, symbol }: any, userAddress: any, chainId: ChainId, provider: any) { diff --git a/src/handlers/ens.ts b/src/handlers/ens.ts index 0686f977e57..fcb14c14fb5 100644 --- a/src/handlers/ens.ts +++ b/src/handlers/ens.ts @@ -24,7 +24,7 @@ import { prefetchENSAddress } from '@/resources/ens/ensAddressQuery'; import { MimeType, handleNFTImages } from '@/utils/handleNFTImages'; import store from '@/redux/store'; import { logger, RainbowError } from '@/logger'; -import { ChainId, Network } from '@/chains/types'; +import { ChainId, Network } from '@/state/backendNetworks/types'; const DUMMY_RECORDS = { description: 'description', diff --git a/src/handlers/gasFees.ts b/src/handlers/gasFees.ts index b8fa1d64be5..9b63ae789b1 100644 --- a/src/handlers/gasFees.ts +++ b/src/handlers/gasFees.ts @@ -1,6 +1,6 @@ -import { getChainsName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { RainbowFetchClient } from '../rainbow-fetch'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const rainbowMeteorologyApi = new RainbowFetchClient({ baseURL: 'https://metadata.p.rainbow.me', @@ -12,4 +12,4 @@ const rainbowMeteorologyApi = new RainbowFetchClient({ }); export const rainbowMeteorologyGetData = (chainId: ChainId) => - rainbowMeteorologyApi.get(`/meteorology/v1/gas/${getChainsName()[chainId]}`, {}); + rainbowMeteorologyApi.get(`/meteorology/v1/gas/${useBackendNetworksStore.getState().getChainsName()[chainId]}`, {}); diff --git a/src/handlers/localstorage/globalSettings.ts b/src/handlers/localstorage/globalSettings.ts index 2338baccdf0..5a64f1c605d 100644 --- a/src/handlers/localstorage/globalSettings.ts +++ b/src/handlers/localstorage/globalSettings.ts @@ -1,4 +1,4 @@ -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { getGlobal, saveGlobal } from './common'; import { NativeCurrencyKeys } from '@/entities'; import { Language } from '@/languages'; diff --git a/src/handlers/localstorage/removeWallet.ts b/src/handlers/localstorage/removeWallet.ts index 3933e6a22bd..206e6b11fac 100644 --- a/src/handlers/localstorage/removeWallet.ts +++ b/src/handlers/localstorage/removeWallet.ts @@ -5,7 +5,7 @@ import { getKey } from './common'; import { walletConnectAccountLocalKeys } from './walletconnectRequests'; import { logger, RainbowError } from '@/logger'; import { removeNotificationSettingsForWallet } from '@/notifications/settings'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; export const removeWalletData = async (accountAddress: any) => { logger.debug('[localstorage/removeWallet]: removing wallet data', { accountAddress }); diff --git a/src/handlers/swap.ts b/src/handlers/swap.ts index 9332fa73eb0..7627d8ca67d 100644 --- a/src/handlers/swap.ts +++ b/src/handlers/swap.ts @@ -21,7 +21,7 @@ import { add, convertRawAmountToDecimalFormat, divide, lessThan, multiply, subtr import { erc20ABI, ethUnits } from '@/references'; import { ethereumUtils } from '@/utils'; import { logger, RainbowError } from '@/logger'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; export enum Field { INPUT = 'INPUT', diff --git a/src/handlers/tokenSearch.ts b/src/handlers/tokenSearch.ts index a83c2261284..43dc0073e46 100644 --- a/src/handlers/tokenSearch.ts +++ b/src/handlers/tokenSearch.ts @@ -5,7 +5,7 @@ import { TokenSearchThreshold, TokenSearchTokenListId, TokenSearchUniswapAssetKe import { logger, RainbowError } from '@/logger'; import { EthereumAddress } from '@rainbow-me/swaps'; import { RainbowToken, TokenSearchToken } from '@/entities/tokens'; -import { getChainsName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; type TokenSearchApiResponse = { data: TokenSearchToken[]; @@ -94,7 +94,7 @@ export const tokenSearch = async (searchParams: { return tokenSearch.data.data.map(token => { const networkKeys = Object.keys(token.networks); const chainId = Number(networkKeys[0]); - const network = getChainsName()[chainId]; + const network = useBackendNetworksStore.getState().getChainsName()[chainId]; return { ...token, chainId, diff --git a/src/handlers/web3.ts b/src/handlers/web3.ts index b2979c4057a..22bcd636f9b 100644 --- a/src/handlers/web3.ts +++ b/src/handlers/web3.ts @@ -34,8 +34,8 @@ import { import { ethereumUtils } from '@/utils'; import { logger, RainbowError } from '@/logger'; import { IS_IOS, RPC_PROXY_API_KEY, RPC_PROXY_BASE_URL } from '@/env'; -import { ChainId } from '@/chains/types'; -import { getDefaultChains } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; export enum TokenStandard { @@ -101,7 +101,8 @@ export type NewTransactionNonNullable = { * @return Whether or not the network is a L2 network. */ export const isL2Chain = ({ chainId = ChainId.mainnet }: { chainId?: ChainId }): boolean => { - return getDefaultChains()[chainId]?.id !== ChainId.mainnet && !getDefaultChains()[chainId]?.testnet; + const defaultChains = useBackendNetworksStore.getState().getDefaultChains(); + return defaultChains[chainId]?.id !== ChainId.mainnet && !defaultChains[chainId]?.testnet; }; /** @@ -110,7 +111,7 @@ export const isL2Chain = ({ chainId = ChainId.mainnet }: { chainId?: ChainId }): * @return Whether or not the network is a testnet. */ export const isTestnetChain = ({ chainId = ChainId.mainnet }: { chainId?: ChainId }): boolean => { - return !!getDefaultChains()[chainId]?.testnet; + return !!useBackendNetworksStore.getState().getDefaultChains()[chainId]?.testnet; }; // shoudl figure out better way to include this in networks @@ -137,7 +138,7 @@ export const getProvider = ({ chainId = ChainId.mainnet }: { chainId?: number }) const cachedProvider = chainsProviders.get(chainId); - const providerUrl = getDefaultChains()[chainId]?.rpcUrls?.default?.http?.[0]; + const providerUrl = useBackendNetworksStore.getState().getDefaultChains()[chainId]?.rpcUrls?.default?.http?.[0]; if (cachedProvider && cachedProvider?.connection.url === providerUrl) { return cachedProvider; diff --git a/src/helpers/SharedValuesContext.tsx b/src/helpers/SharedValuesContext.tsx index d7d2035c8db..08dee0b4544 100644 --- a/src/helpers/SharedValuesContext.tsx +++ b/src/helpers/SharedValuesContext.tsx @@ -22,3 +22,11 @@ export function SharedValuesProvider({ children }: PropsWithChildren) { ); return {children}; } + +export const useSharedValuesContext = () => { + const context = React.useContext(Context); + if (context === undefined) { + throw new Error('useSharedValuesContext must be used within a SharedValuesProvider'); + } + return context; +}; diff --git a/src/helpers/ens.ts b/src/helpers/ens.ts index d00fbd56622..a4bc0a3fb27 100644 --- a/src/helpers/ens.ts +++ b/src/helpers/ens.ts @@ -25,7 +25,7 @@ import { import { colors } from '@/styles'; import { labelhash } from '@/utils'; import { encodeContenthash, isValidContenthash } from '@/utils/contenthash'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; export const ENS_SECONDS_WAIT = 60; export const ENS_SECONDS_PADDING = 5; diff --git a/src/helpers/gas.ts b/src/helpers/gas.ts index e9d3f17939b..08c8756ed28 100644 --- a/src/helpers/gas.ts +++ b/src/helpers/gas.ts @@ -1,6 +1,6 @@ import { memoFn } from '../utils/memoFn'; import { gasUtils } from '@/utils'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { isL2Chain } from '@/handlers/web3'; const { GasTrends } = gasUtils; diff --git a/src/helpers/networkInfo.ts b/src/helpers/networkInfo.ts index cd8f6bcc139..4668c35288b 100644 --- a/src/helpers/networkInfo.ts +++ b/src/helpers/networkInfo.ts @@ -1,4 +1,4 @@ -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; // TODO: networkInfo is DEPRECATED after the new network support changes const networkInfo = { diff --git a/src/helpers/signingWallet.ts b/src/helpers/signingWallet.ts index 769bb1cadf0..10532dd3e95 100644 --- a/src/helpers/signingWallet.ts +++ b/src/helpers/signingWallet.ts @@ -3,7 +3,7 @@ import { generateMnemonic } from 'bip39'; import { default as LibWallet } from 'ethereumjs-wallet'; import { RAINBOW_MASTER_KEY } from 'react-native-dotenv'; import { loadString, publicAccessControlOptions, saveString } from '../model/keychain'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { loadWallet } from '../model/wallet'; import { signingWalletAddress, signingWallet as signingWalletKeychain } from '../utils/keychainConstants'; import { EthereumAddress } from '@/entities'; diff --git a/src/helpers/validators.ts b/src/helpers/validators.ts index c2c5fce0942..e2ceccd5c0a 100644 --- a/src/helpers/validators.ts +++ b/src/helpers/validators.ts @@ -2,7 +2,7 @@ import { isValidAddress } from 'ethereumjs-util'; import { memoFn } from '../utils/memoFn'; import { getProvider, isHexStringIgnorePrefix, isValidMnemonic, resolveUnstoppableDomain } from '@/handlers/web3'; import { sanitizeSeedPhrase } from '@/utils/formatters'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; // Currently supported Top Level Domains from Unstoppable Domains const supportedUnstoppableDomains = ['888', 'bitcoin', 'blockchain', 'coin', 'crypto', 'dao', 'nft', 'wallet', 'x', 'zil']; diff --git a/src/helpers/walletConnectNetworks.ts b/src/helpers/walletConnectNetworks.ts index aab56343243..662191d0eb4 100644 --- a/src/helpers/walletConnectNetworks.ts +++ b/src/helpers/walletConnectNetworks.ts @@ -1,14 +1,14 @@ import store from '@/redux/store'; import { showActionSheetWithOptions } from '@/utils'; import * as i18n from '@/languages'; -import { ChainId } from '@/chains/types'; -import { getChainsLabel, getDefaultChains } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { isL2Chain } from '@/handlers/web3'; import { MenuActionConfig } from 'react-native-ios-context-menu'; const androidNetworkActions = () => { const { testnetsEnabled } = store.getState().settings; - return Object.values(getDefaultChains()) + return Object.values(useBackendNetworksStore.getState().getDefaultChains()) .filter(chain => testnetsEnabled || !chain.testnet) .map(chain => chain.id); }; @@ -18,11 +18,11 @@ export const NETWORK_MENU_ACTION_KEY_FILTER = 'switch-to-network-'; export const networksMenuItems: () => MenuActionConfig[] = () => { const { testnetsEnabled } = store.getState().settings; - return Object.values(getDefaultChains()) + return Object.values(useBackendNetworksStore.getState().getDefaultChains()) .filter(chain => testnetsEnabled || !chain.testnet) .map(chain => ({ actionKey: `${NETWORK_MENU_ACTION_KEY_FILTER}${chain.id}`, - actionTitle: getChainsLabel()[chain.id], + actionTitle: useBackendNetworksStore.getState().getChainsLabel()[chain.id], icon: { iconType: 'ASSET', iconValue: `${isL2Chain({ chainId: chain.id }) ? `${chain.name}BadgeNoShadow` : 'ethereumBadge'}`, @@ -78,8 +78,9 @@ export const androidShowNetworksActionSheet = (callback: any) => { }, (idx: number) => { if (idx !== undefined) { + const defaultChains = useBackendNetworksStore.getState().getDefaultChains(); const networkActions = androidNetworkActions(); - const chain = getDefaultChains()[networkActions[idx]] || getDefaultChains()[ChainId.mainnet]; + const chain = defaultChains[networkActions[idx]] || defaultChains[ChainId.mainnet]; callback({ chainId: chain.id }); } } diff --git a/src/hooks/charts/useChartInfo.ts b/src/hooks/charts/useChartInfo.ts index dd1c6f91ad3..09159ab38a5 100644 --- a/src/hooks/charts/useChartInfo.ts +++ b/src/hooks/charts/useChartInfo.ts @@ -5,7 +5,7 @@ import { metadataClient } from '@/graphql'; import { useQuery } from '@tanstack/react-query'; import { createQueryKey } from '@/react-query'; import { SupportedCurrencyKey } from '@/references'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const chartTimes = ['hour', 'day', 'week', 'month', 'year'] as const; type ChartTime = (typeof chartTimes)[number]; diff --git a/src/hooks/useAccountTransactions.ts b/src/hooks/useAccountTransactions.ts index bf8d778acce..31908ddb4ae 100644 --- a/src/hooks/useAccountTransactions.ts +++ b/src/hooks/useAccountTransactions.ts @@ -9,8 +9,8 @@ import { useConsolidatedTransactions } from '@/resources/transactions/consolidat import { RainbowTransaction } from '@/entities'; import { pendingTransactionsStore, usePendingTransactionsStore } from '@/state/pendingTransactions'; import { nonceStore } from '@/state/nonces'; -import { ChainId } from '@/chains/types'; -import { getSupportedChainIds, getSupportedMainnetChainIds } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const NOE_PAGE = 30; @@ -43,7 +43,12 @@ export default function useAccountTransactions() { } return latestTxMap; }, - new Map(getSupportedChainIds().map(chainId => [chainId, null as RainbowTransaction | null])) + new Map( + useBackendNetworksStore + .getState() + .getSupportedChainIds() + .map(chainId => [chainId, null as RainbowTransaction | null]) + ) ); watchForPendingTransactionsReportedByRainbowBackend({ currentAddress: accountAddress, @@ -61,7 +66,7 @@ export default function useAccountTransactions() { const { setNonce } = nonceStore.getState(); const { setPendingTransactions, pendingTransactions: storePendingTransactions } = pendingTransactionsStore.getState(); const pendingTransactions = storePendingTransactions[currentAddress] || []; - for (const chainId of getSupportedMainnetChainIds()) { + for (const chainId of useBackendNetworksStore.getState().getSupportedMainnetChainIds()) { const latestTxConfirmedByBackend = latestTransactions.get(chainId); if (latestTxConfirmedByBackend) { const latestNonceConfirmedByBackend = latestTxConfirmedByBackend.nonce || 0; diff --git a/src/hooks/useAdditionalAssetData.ts b/src/hooks/useAdditionalAssetData.ts index 0a89867ccf8..271d75819df 100644 --- a/src/hooks/useAdditionalAssetData.ts +++ b/src/hooks/useAdditionalAssetData.ts @@ -2,7 +2,7 @@ import { useQuery } from '@tanstack/react-query'; import { NativeCurrencyKey } from '@/entities'; import { metadataClient } from '@/graphql'; import { Token } from '@/graphql/__generated__/metadata'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; // Types type TokenMetadata = Pick< diff --git a/src/hooks/useAsset.ts b/src/hooks/useAsset.ts index cea27883fff..663c50858a5 100644 --- a/src/hooks/useAsset.ts +++ b/src/hooks/useAsset.ts @@ -4,7 +4,7 @@ import { getUniqueId } from '@/utils/ethereumUtils'; import { useExternalToken } from '@/resources/assets/externalAssetsQuery'; import { useSelector } from 'react-redux'; import { AppState } from '@/redux/store'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { Address } from 'viem'; // To fetch an asset from account assets, diff --git a/src/hooks/useCalculateGasLimit.ts b/src/hooks/useCalculateGasLimit.ts index 96df6156ebe..703d073a268 100644 --- a/src/hooks/useCalculateGasLimit.ts +++ b/src/hooks/useCalculateGasLimit.ts @@ -9,8 +9,8 @@ import { InteractionManager } from 'react-native'; import { GasFeeParamsBySpeed } from '@/entities'; import { StaticJsonRpcProvider } from '@ethersproject/providers'; import { useGas } from '@/hooks'; -import { ChainId } from '@/chains/types'; -import { getNeedsL1SecurityFeeChains } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; type CalculateGasLimitProps = { isMessageRequest: boolean; @@ -52,7 +52,7 @@ export const useCalculateGasLimit = ({ } finally { logger.debug('WC: Setting gas limit to', { gas: convertHexToString(gas) }, logger.DebugContext.walletconnect); - const needsL1SecurityFee = getNeedsL1SecurityFeeChains().includes(chainId); + const needsL1SecurityFee = useBackendNetworksStore.getState().getNeedsL1SecurityFeeChains().includes(chainId); if (needsL1SecurityFee) { const l1GasFeeOptimism = await ethereumUtils.calculateL1FeeOptimism(txPayload, provider); updateTxFee(gas, null, l1GasFeeOptimism); diff --git a/src/hooks/useENSRegistrationActionHandler.ts b/src/hooks/useENSRegistrationActionHandler.ts index 95337c4d4b9..a61bf71ee92 100644 --- a/src/hooks/useENSRegistrationActionHandler.ts +++ b/src/hooks/useENSRegistrationActionHandler.ts @@ -25,7 +25,7 @@ import store from '@/redux/store'; import { performanceTracking, Screens, TimeToSignOperation } from '@/state/performance/performance'; import { noop } from 'lodash'; import { logger, RainbowError } from '@/logger'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { IS_IOS } from '@/env'; // Generic type for action functions diff --git a/src/hooks/useENSRegistrationCosts.ts b/src/hooks/useENSRegistrationCosts.ts index 95ce537981e..a2653f3c86d 100644 --- a/src/hooks/useENSRegistrationCosts.ts +++ b/src/hooks/useENSRegistrationCosts.ts @@ -27,7 +27,7 @@ import { import { add, addBuffer, addDisplay, fromWei, greaterThanOrEqualTo, multiply } from '@/helpers/utilities'; import { ethUnits, timeUnits } from '@/references'; import { ethereumUtils, gasUtils } from '@/utils'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; enum QUERY_KEYS { GET_COMMIT_GAS_LIMIT = 'GET_COMMIT_GAS_LIMIT', diff --git a/src/hooks/useENSRegistrationStepHandler.tsx b/src/hooks/useENSRegistrationStepHandler.tsx index 24b9ceea113..d99183c9bec 100644 --- a/src/hooks/useENSRegistrationStepHandler.tsx +++ b/src/hooks/useENSRegistrationStepHandler.tsx @@ -14,7 +14,7 @@ import { REGISTRATION_STEPS, } from '@/helpers/ens'; import { updateTransactionRegistrationParameters } from '@/redux/ensRegistration'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; const checkRegisterBlockTimestamp = async ({ diff --git a/src/hooks/useENSSearch.ts b/src/hooks/useENSSearch.ts index 5e9d207375d..6fc3e3451f7 100644 --- a/src/hooks/useENSSearch.ts +++ b/src/hooks/useENSSearch.ts @@ -6,7 +6,7 @@ import { fetchRegistrationDate } from '@/handlers/ens'; import { ENS_DOMAIN, formatRentPrice, getAvailable, getENSRegistrarControllerContract, getNameExpires, getRentPrice } from '@/helpers/ens'; import { timeUnits } from '@/references'; import { ethereumUtils, validateENS } from '@/utils'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const formatTime = (timestamp: string, abbreviated = true) => { const style = abbreviated ? 'MMM d, y' : 'MMMM d, y'; diff --git a/src/hooks/useGas.ts b/src/hooks/useGas.ts index 3933239f905..ac556bf1f44 100644 --- a/src/hooks/useGas.ts +++ b/src/hooks/useGas.ts @@ -26,7 +26,7 @@ import { ethereumUtils } from '@/utils'; import { useExternalToken } from '@/resources/assets/externalAssetsQuery'; import { BNB_MAINNET_ADDRESS, ETH_ADDRESS, MATIC_MAINNET_ADDRESS } from '@/references'; import useAccountSettings from './useAccountSettings'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const checkSufficientGas = (txFee: LegacyGasFee | GasFee, chainId: ChainId, nativeAsset?: ParsedAddressAsset) => { const isLegacyGasNetwork = !(txFee as GasFee)?.maxFee; diff --git a/src/hooks/useHasEnoughBalance.ts b/src/hooks/useHasEnoughBalance.ts index f9179628c22..491a9c2c70e 100644 --- a/src/hooks/useHasEnoughBalance.ts +++ b/src/hooks/useHasEnoughBalance.ts @@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'; import { fromWei, greaterThanOrEqualTo } from '@/helpers/utilities'; import BigNumber from 'bignumber.js'; import { SelectedGasFee } from '@/entities'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; type WalletBalance = { amount: string | number; diff --git a/src/hooks/useImportingWallet.ts b/src/hooks/useImportingWallet.ts index e78fa43a2e8..d0f92e12a3a 100644 --- a/src/hooks/useImportingWallet.ts +++ b/src/hooks/useImportingWallet.ts @@ -31,7 +31,7 @@ import { handleReviewPromptAction } from '@/utils/reviewAlert'; import { ReviewPromptAction } from '@/storage/schema'; import { checkWalletsForBackupStatus } from '@/screens/SettingsSheet/utils'; import walletBackupTypes from '@/helpers/walletBackupTypes'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; export default function useImportingWallet({ showImportModal = true } = {}) { const { accountAddress } = useAccountSettings(); diff --git a/src/hooks/useNonceForDisplay.ts b/src/hooks/useNonceForDisplay.ts index 8308bc460e9..98376442019 100644 --- a/src/hooks/useNonceForDisplay.ts +++ b/src/hooks/useNonceForDisplay.ts @@ -1,6 +1,6 @@ import { useEffect, useState } from 'react'; import { getNextNonce } from '@/state/nonces'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { logger, RainbowError } from '@/logger'; type UseNonceParams = { diff --git a/src/hooks/usePriceImpactDetails.ts b/src/hooks/usePriceImpactDetails.ts index 85a68a0238e..d95f331b052 100644 --- a/src/hooks/usePriceImpactDetails.ts +++ b/src/hooks/usePriceImpactDetails.ts @@ -14,7 +14,7 @@ import { import { CrosschainQuote, Quote, SwapType } from '@rainbow-me/swaps'; import { useNativeAsset } from '@/utils/ethereumUtils'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; export enum SwapPriceImpactType { none = 'none', diff --git a/src/hooks/useSearchCurrencyList.ts b/src/hooks/useSearchCurrencyList.ts index 6e32beb31d7..b5f11644149 100644 --- a/src/hooks/useSearchCurrencyList.ts +++ b/src/hooks/useSearchCurrencyList.ts @@ -18,8 +18,8 @@ import { CROSSCHAIN_SWAPS, useExperimentalFlag } from '@/config'; import { IS_TEST } from '@/env'; import { useFavorites } from '@/resources/favorites'; import { getUniqueId } from '@/utils/ethereumUtils'; -import { ChainId } from '@/chains/types'; -import { getChainsName } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; type swapCurrencyListType = | 'verifiedAssets' @@ -200,7 +200,7 @@ const useSearchCurrencyList = (searchQuery: string, searchChainId = ChainId.main }, }, symbol, - network: getChainsName()[chainId], + network: useBackendNetworksStore.getState().getChainsName()[chainId], uniqueId, } as RainbowToken, ]; diff --git a/src/hooks/useSwapCurrencyList.ts b/src/hooks/useSwapCurrencyList.ts index 107cf8bc1e6..31d625a39ee 100644 --- a/src/hooks/useSwapCurrencyList.ts +++ b/src/hooks/useSwapCurrencyList.ts @@ -18,8 +18,8 @@ import { IS_TEST } from '@/env'; import { useFavorites } from '@/resources/favorites'; import { getUniqueId } from '@/utils/ethereumUtils'; import { logger } from '@/logger'; -import { ChainId, Network } from '@/chains/types'; -import { getChainsName } from '@/chains'; +import { ChainId, Network } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; type swapCurrencyListType = | 'verifiedAssets' @@ -205,7 +205,7 @@ const useSwapCurrencyList = (searchQuery: string, searchChainId = ChainId.mainne }, }, symbol, - network: getChainsName()[chainId], + network: useBackendNetworksStore.getState().getChainsName()[chainId], uniqueId, } as RainbowToken, ]; diff --git a/src/hooks/useSwapDerivedOutputs.ts b/src/hooks/useSwapDerivedOutputs.ts index d98649081fb..71cb52d85a1 100644 --- a/src/hooks/useSwapDerivedOutputs.ts +++ b/src/hooks/useSwapDerivedOutputs.ts @@ -7,7 +7,6 @@ import { QuoteError, QuoteParams, Source, - SwapType, } from '@rainbow-me/swaps'; import { useQuery } from '@tanstack/react-query'; import { useCallback, useMemo, useState } from 'react'; @@ -34,7 +33,7 @@ import { ethereumUtils } from '@/utils'; import { useDispatch, useSelector } from 'react-redux'; import { SwappableAsset } from '../entities/tokens'; import useAccountSettings from './useAccountSettings'; -import { getChainsName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const SWAP_POLLING_INTERVAL = 5000; @@ -464,7 +463,7 @@ export default function useSwapDerivedOutputs(type: string) { inputTokenName: inputCurrency?.name || '', inputTokenSymbol: inputCurrency?.symbol || '', liquiditySources: (data.tradeDetails?.protocols as any[]) || [], - network: getChainsName()[inputCurrency?.chainId], + network: useBackendNetworksStore.getState().getChainsName()[inputCurrency?.chainId], outputTokenAddress: outputCurrency?.address || '', outputTokenName: outputCurrency?.name || '', outputTokenSymbol: outputCurrency?.symbol || '', diff --git a/src/hooks/useSwapRefuel.ts b/src/hooks/useSwapRefuel.ts index 05bfc52a667..7b4d1f6acee 100644 --- a/src/hooks/useSwapRefuel.ts +++ b/src/hooks/useSwapRefuel.ts @@ -8,7 +8,7 @@ import { CROSSCHAIN_SWAPS, useExperimentalFlag } from '@/config'; import { useAccountSettings, useGas } from '.'; import { isNativeAsset } from '@/handlers/assets'; import { toWei } from '@/handlers/web3'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; export enum RefuelState { 'Add' = 'Add', diff --git a/src/hooks/useSwappableUserAssets.ts b/src/hooks/useSwappableUserAssets.ts index e1d501fec48..4e59d8b2f14 100644 --- a/src/hooks/useSwappableUserAssets.ts +++ b/src/hooks/useSwappableUserAssets.ts @@ -5,8 +5,8 @@ import { ETH_ADDRESS } from '@/references'; import { useSortedUserAssets } from '@/resources/assets/useSortedUserAssets'; import { EthereumAddress, ETH_ADDRESS as ETH_ADDRESS_AGGREGATORS } from '@rainbow-me/swaps'; import { useCallback, useEffect, useMemo, useRef } from 'react'; -import { ChainId } from '@/chains/types'; -import { supportedSwapChainIds } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; type SwappableAddresses = Record; @@ -17,10 +17,13 @@ export const useSwappableUserAssets = (params: { outputCurrency: SwappableAsset const { hiddenCoinsObj } = useCoinListEditOptions(); const swappableAssetsRef = useRef( - supportedSwapChainIds.reduce((acc, chainId) => { - acc[chainId] = []; - return acc; - }, {} as SwappableAddresses) + useBackendNetworksStore + .getState() + .getSwapSupportedChainIds() + .reduce((acc, chainId) => { + acc[chainId] = []; + return acc; + }, {} as SwappableAddresses) ); const filteredAssetsInWallet = (assetsInWallet || []).filter(asset => { @@ -28,7 +31,7 @@ export const useSwappableUserAssets = (params: { outputCurrency: SwappableAsset if (hiddenCoinsObj[asset.uniqueId]) return true; // filter out networks where swaps are not enabled - if (supportedSwapChainIds.includes(asset.chainId)) return true; + if (useBackendNetworksStore.getState().getSwapSupportedChainIds().includes(asset.chainId)) return true; return false; }); @@ -59,14 +62,17 @@ export const useSwappableUserAssets = (params: { outputCurrency: SwappableAsset const getSwappableAddressesInWallet = useCallback(async () => { const walletFilterRequests: Promise[] = []; - supportedSwapChainIds.forEach(chainId => { - const assetsAddressesOnChain = filteredAssetsInWallet - .filter(asset => (asset?.chainId || ChainId.mainnet) === chainId) - .map(asset => (asset?.address === ETH_ADDRESS ? ETH_ADDRESS_AGGREGATORS : asset?.address)); - if (assetsAddressesOnChain.length) { - walletFilterRequests.push(getSwappableAddressesForChainId(assetsAddressesOnChain, chainId)); - } - }); + useBackendNetworksStore + .getState() + .getSwapSupportedChainIds() + .forEach(chainId => { + const assetsAddressesOnChain = filteredAssetsInWallet + .filter(asset => (asset?.chainId || ChainId.mainnet) === chainId) + .map(asset => (asset?.address === ETH_ADDRESS ? ETH_ADDRESS_AGGREGATORS : asset?.address)); + if (assetsAddressesOnChain.length) { + walletFilterRequests.push(getSwappableAddressesForChainId(assetsAddressesOnChain, chainId)); + } + }); await Promise.all(walletFilterRequests); }, [filteredAssetsInWallet, getSwappableAddressesForChainId]); diff --git a/src/hooks/useTransactionSetup.ts b/src/hooks/useTransactionSetup.ts index 0eb1542e66e..28bdf4d4989 100644 --- a/src/hooks/useTransactionSetup.ts +++ b/src/hooks/useTransactionSetup.ts @@ -6,7 +6,7 @@ import { methodRegistryLookupAndParse } from '@/utils/methodRegistry'; import { analytics } from '@/analytics'; import { event } from '@/analytics/event'; import { RequestSource } from '@/utils/requestNavigationHandlers'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; type TransactionSetupParams = { chainId: ChainId; diff --git a/src/hooks/useWatchPendingTxs.ts b/src/hooks/useWatchPendingTxs.ts index 5e800e0b78d..72284234036 100644 --- a/src/hooks/useWatchPendingTxs.ts +++ b/src/hooks/useWatchPendingTxs.ts @@ -9,14 +9,14 @@ import { getProvider } from '@/handlers/web3'; import { consolidatedTransactionsQueryKey } from '@/resources/transactions/consolidatedTransactions'; import { queryClient } from '@/react-query/queryClient'; import { getTransactionFlashbotStatus } from '@/handlers/transactions'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { invalidateAddressNftsQueries } from '@/resources/nfts'; import { useNonceStore } from '@/state/nonces'; import { usePendingTransactionsStore } from '@/state/pendingTransactions'; import { Address } from 'viem'; import { staleBalancesStore } from '@/state/staleBalances'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; -import { getSupportedMainnetChainIds } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const useWatchPendingTransactions = ({ address }: { address: string }) => { const { storePendingTransactions, setPendingTransactions } = usePendingTransactionsStore(state => ({ @@ -205,11 +205,13 @@ export const useWatchPendingTransactions = ({ address }: { address: string }) => queryKey: userAssetsQueryKey({ address, currency: nativeCurrency, connectedToHardhat }), }); + const supportedMainnetChainIds = useBackendNetworksStore.getState().getSupportedMainnetChainIds(); + await queryClient.refetchQueries({ queryKey: consolidatedTransactionsQueryKey({ address, currency: nativeCurrency, - chainIds: getSupportedMainnetChainIds(), + chainIds: supportedMainnetChainIds, }), }); @@ -219,7 +221,7 @@ export const useWatchPendingTransactions = ({ address }: { address: string }) => queryKey: consolidatedTransactionsQueryKey({ address, currency: nativeCurrency, - chainIds: getSupportedMainnetChainIds(), + chainIds: supportedMainnetChainIds, }), }); }, 2000); diff --git a/src/migrations/migrations/migratePinnedAndHiddenTokenUniqueIds.ts b/src/migrations/migrations/migratePinnedAndHiddenTokenUniqueIds.ts index abff230dbbb..20f8fe20986 100644 --- a/src/migrations/migrations/migratePinnedAndHiddenTokenUniqueIds.ts +++ b/src/migrations/migrations/migratePinnedAndHiddenTokenUniqueIds.ts @@ -1,7 +1,7 @@ import { BooleanMap } from '@/hooks/useCoinListEditOptions'; import { Migration, MigrationName } from '@/migrations/types'; import { loadAddress } from '@/model/wallet'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; import { MMKV } from 'react-native-mmkv'; const mmkv = new MMKV(); diff --git a/src/model/remoteConfig.ts b/src/model/remoteConfig.ts index e8828c4db75..1273f79575c 100644 --- a/src/model/remoteConfig.ts +++ b/src/model/remoteConfig.ts @@ -31,6 +31,7 @@ export interface RainbowConfig extends Record data_endpoint: string; data_origin: string; default_slippage_bips: string; + default_slippage_bips_chainId: string; ethereum_goerli_rpc: string; ethereum_mainnet_rpc: string; f2c_enabled: boolean; @@ -112,6 +113,19 @@ export const DEFAULT_CONFIG: RainbowConfig = { polygon: 200, zora: 200, }), + default_slippage_bips_chainId: JSON.stringify({ + '33139': 200, + '42161': 200, + '43114': 200, + '8453': 200, + '81457': 200, + '56': 200, + '666666666': 200, + '1': 100, + '10': 200, + '137': 200, + '7777777': 200, + }), ethereum_goerli_rpc: __DEV__ ? ETHEREUM_GOERLI_RPC_DEV : ETHEREUM_GOERLI_RPC, ethereum_mainnet_rpc: __DEV__ ? ETHEREUM_MAINNET_RPC_DEV : ETHEREUM_MAINNET_RPC, f2c_enabled: true, @@ -188,7 +202,7 @@ export async function fetchRemoteConfig(): Promise { const parameters = remoteConfig().getAll(); Object.entries(parameters).forEach($ => { const [key, entry] = $; - if (key === 'default_slippage_bips') { + if (key === 'default_slippage_bips' || key === 'default_slippage_bips_chainId') { config[key] = JSON.parse(entry.asString()); } else if ( key === 'flashbots_enabled' || diff --git a/src/model/wallet.ts b/src/model/wallet.ts index bb4ed3e6df0..da67e97fdbd 100644 --- a/src/model/wallet.ts +++ b/src/model/wallet.ts @@ -50,8 +50,7 @@ import { setHardwareTXError } from '@/navigation/HardwareWalletTxNavigator'; import { Signer } from '@ethersproject/abstract-signer'; import { sanitizeTypedData } from '@/utils/signingUtils'; import { ExecuteFnParamsWithoutFn, performanceTracking, Screen } from '@/state/performance/performance'; -import { Network } from '@/chains/types'; -import { WalletBalanceResult } from '@/hooks/useWalletBalances'; +import { Network } from '@/state/backendNetworks/types'; export type EthereumPrivateKey = string; type EthereumMnemonic = string; diff --git a/src/navigation/config.tsx b/src/navigation/config.tsx index 0e81ff55198..eb046bc1953 100644 --- a/src/navigation/config.tsx +++ b/src/navigation/config.tsx @@ -28,8 +28,8 @@ import { Box } from '@/design-system'; import { IS_ANDROID } from '@/env'; import { SignTransactionSheetRouteProp } from '@/screens/SignTransactionSheet'; import { RequestSource } from '@/utils/requestNavigationHandlers'; -import { ChainId } from '@/chains/types'; -import { getChainsName } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const sharedCoolModalTopOffset = safeAreaInsetValues.top; @@ -491,7 +491,7 @@ export const ensAdditionalRecordsSheetConfig: PartialNavigatorConfigOptions = { }; export const explainSheetConfig: PartialNavigatorConfigOptions = { - options: ({ route: { params = { network: getChainsName()[ChainId.mainnet] } } }) => { + options: ({ route: { params = { network: useBackendNetworksStore.getState().getChainsName()[ChainId.mainnet] } } }) => { // @ts-ignore const explainerConfig = explainers(params.network)[params?.type]; return buildCoolModalConfig({ diff --git a/src/parsers/transactions.ts b/src/parsers/transactions.ts index e3aecd17c7f..1757b295093 100644 --- a/src/parsers/transactions.ts +++ b/src/parsers/transactions.ts @@ -21,7 +21,7 @@ import { NewTransaction, RainbowTransactionFee } from '@/entities/transactions/t import { parseAddressAsset, parseAsset } from '@/resources/assets/assets'; import { ParsedAsset } from '@/resources/assets/types'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const TransactionOutTypes = [ 'burn', diff --git a/src/raps/actions/claimBridge.ts b/src/raps/actions/claimBridge.ts index 876d2c12e70..181d3288be1 100644 --- a/src/raps/actions/claimBridge.ts +++ b/src/raps/actions/claimBridge.ts @@ -18,8 +18,8 @@ import { CrosschainQuote, QuoteError, getClaimBridgeQuote } from '@rainbow-me/sw import { Address } from 'viem'; import { ActionProps } from '../references'; import { executeCrosschainSwap } from './crosschainSwap'; -import { ChainId } from '@/chains/types'; -import { getChainsName } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; // This action is used to bridge the claimed funds to another chain export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps<'claimBridge'>) { @@ -158,9 +158,11 @@ export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps throw new Error('[CLAIM-BRIDGE]: executeCrosschainSwap returned undefined'); } + const chainsName = useBackendNetworksStore.getState().getChainsName(); + const typedAssetToBuy: ParsedAddressAsset = { ...parameters.assetToBuy, - network: getChainsName()[parameters.assetToBuy.chainId], + network: chainsName[parameters.assetToBuy.chainId], chainId: parameters.assetToBuy.chainId, colors: undefined, networks: undefined, @@ -168,7 +170,7 @@ export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps }; const typedAssetToSell = { ...parameters.assetToSell, - network: getChainsName()[parameters.assetToSell.chainId], + network: chainsName[parameters.assetToSell.chainId], chainId: parameters.assetToSell.chainId, colors: undefined, networks: undefined, @@ -196,7 +198,7 @@ export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps from: bridgeQuote.from, to: bridgeQuote.to as Address, hash: swap.hash as TxHash, - network: getChainsName()[parameters.chainId], + network: chainsName[parameters.chainId], nonce: swap.nonce, status: TransactionStatus.pending, type: 'bridge', diff --git a/src/raps/actions/crosschainSwap.ts b/src/raps/actions/crosschainSwap.ts index b67b78432f1..3b02020658a 100644 --- a/src/raps/actions/crosschainSwap.ts +++ b/src/raps/actions/crosschainSwap.ts @@ -4,7 +4,7 @@ import { Address } from 'viem'; import { estimateGasWithPadding, getProvider } from '@/handlers/web3'; import { REFERRER, gasUnits, ReferrerType } from '@/references'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { NewTransaction, TransactionDirection, TransactionStatus, TxHash } from '@/entities'; import { addNewTransaction } from '@/state/pendingTransactions'; import { RainbowError, logger } from '@/logger'; @@ -24,7 +24,7 @@ import { AddysNetworkDetails, ParsedAsset } from '@/resources/assets/types'; import { ExtendedAnimatedAssetWithColors } from '@/__swaps__/types/assets'; import { Screens, TimeToSignOperation, performanceTracking } from '@/state/performance/performance'; import { swapsStore } from '@/state/swaps/swapsStore'; -import { getChainsName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const getCrosschainSwapDefaultGasLimit = (quote: CrosschainQuote) => quote?.routes?.[0]?.userTxs?.[0]?.gasFees?.gasLimit; @@ -180,9 +180,11 @@ export const crosschainSwap = async ({ } : parameters.assetToSell.price; + const chainsName = useBackendNetworksStore.getState().getChainsName(); + const assetToBuy = { ...parameters.assetToBuy, - network: getChainsName()[parameters.assetToBuy.chainId], + network: chainsName[parameters.assetToBuy.chainId], networks: parameters.assetToBuy.networks as Record, colors: parameters.assetToBuy.colors as TokenColors, price: nativePriceForAssetToBuy, @@ -190,7 +192,7 @@ export const crosschainSwap = async ({ const assetToSell = { ...parameters.assetToSell, - network: getChainsName()[parameters.assetToSell.chainId], + network: chainsName[parameters.assetToSell.chainId], networks: parameters.assetToSell.networks as Record, colors: parameters.assetToSell.colors as TokenColors, price: nativePriceForAssetToSell, @@ -223,7 +225,7 @@ export const crosschainSwap = async ({ ], gasLimit, hash: swap.hash as TxHash, - network: getChainsName()[parameters.chainId], + network: chainsName[parameters.chainId], nonce: swap.nonce, status: TransactionStatus.pending, type: 'swap', diff --git a/src/raps/actions/ens.ts b/src/raps/actions/ens.ts index d0466d77149..e4e315c98a4 100644 --- a/src/raps/actions/ens.ts +++ b/src/raps/actions/ens.ts @@ -12,7 +12,7 @@ import store from '@/redux/store'; import { logger, RainbowError } from '@/logger'; import { parseGasParamAmounts } from '@/parsers'; import { addNewTransaction } from '@/state/pendingTransactions'; -import { ChainId, Network } from '@/chains/types'; +import { ChainId, Network } from '@/state/backendNetworks/types'; import { createRegisterENSRap, createRenewENSRap, diff --git a/src/raps/actions/swap.ts b/src/raps/actions/swap.ts index ad7e63414d1..afb5263ebc2 100644 --- a/src/raps/actions/swap.ts +++ b/src/raps/actions/swap.ts @@ -16,7 +16,7 @@ import { estimateGasWithPadding, getProvider } from '@/handlers/web3'; import { Address } from 'viem'; import { metadataPOSTClient } from '@/graphql'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { NewTransaction, TxHash, TransactionStatus, TransactionDirection } from '@/entities'; import { add } from '@/helpers/utilities'; import { addNewTransaction } from '@/state/pendingTransactions'; @@ -42,7 +42,7 @@ import { AddysNetworkDetails, ParsedAsset } from '@/resources/assets/types'; import { ExtendedAnimatedAssetWithColors } from '@/__swaps__/types/assets'; import { Screens, TimeToSignOperation, performanceTracking } from '@/state/performance/performance'; import { swapsStore } from '@/state/swaps/swapsStore'; -import { getChainsName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const WRAP_GAS_PADDING = 1.002; @@ -306,9 +306,11 @@ export const swap = async ({ } : parameters.assetToSell.price; + const chainsName = useBackendNetworksStore.getState().getChainsName(); + const assetToBuy = { ...parameters.assetToBuy, - network: getChainsName()[parameters.assetToBuy.chainId], + network: chainsName[parameters.assetToBuy.chainId], networks: parameters.assetToBuy.networks as Record, colors: parameters.assetToBuy.colors as TokenColors, price: nativePriceForAssetToBuy, @@ -316,7 +318,7 @@ export const swap = async ({ const assetToSell = { ...parameters.assetToSell, - network: getChainsName()[parameters.assetToSell.chainId], + network: chainsName[parameters.assetToSell.chainId], networks: parameters.assetToSell.networks as Record, colors: parameters.assetToSell.colors as TokenColors, price: nativePriceForAssetToSell, @@ -349,7 +351,7 @@ export const swap = async ({ ], gasLimit, hash: swap.hash as TxHash, - network: getChainsName()[parameters.chainId], + network: chainsName[parameters.chainId], nonce: swap.nonce, status: TransactionStatus.pending, type: 'swap', diff --git a/src/raps/actions/unlock.ts b/src/raps/actions/unlock.ts index ad47b9c79d2..2cfb5a58866 100644 --- a/src/raps/actions/unlock.ts +++ b/src/raps/actions/unlock.ts @@ -5,7 +5,7 @@ import { parseUnits } from '@ethersproject/units'; import { getProvider } from '@/handlers/web3'; import { Address, erc20Abi, erc721Abi } from 'viem'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { TransactionGasParams, TransactionLegacyGasParams } from '@/__swaps__/types/gas'; import { NewTransaction, TransactionStatus, TxHash } from '@/entities'; import { addNewTransaction } from '@/state/pendingTransactions'; @@ -20,7 +20,7 @@ import { overrideWithFastSpeedIfNeeded } from './../utils'; import { toHex } from '@/__swaps__/utils/hex'; import { TokenColors } from '@/graphql/__generated__/metadata'; import { ParsedAsset } from '@/resources/assets/types'; -import { getChainsName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const getAssetRawAllowance = async ({ owner, @@ -267,10 +267,12 @@ export const unlock = async ({ if (!approval) throw new RainbowError('[raps/unlock]: error executeApprove'); + const chainsName = useBackendNetworksStore.getState().getChainsName(); + const transaction = { asset: { ...assetToUnlock, - network: getChainsName()[assetToUnlock.chainId], + network: chainsName[assetToUnlock.chainId], colors: assetToUnlock.colors as TokenColors, } as ParsedAsset, data: approval.data, @@ -279,7 +281,7 @@ export const unlock = async ({ from: parameters.fromAddress, to: assetAddress, hash: approval.hash as TxHash, - network: getChainsName()[chainId], + network: chainsName[chainId], chainId: approval.chainId, nonce: approval.nonce, status: TransactionStatus.pending, diff --git a/src/raps/references.ts b/src/raps/references.ts index 259b8fe330c..c2bc3160caa 100644 --- a/src/raps/references.ts +++ b/src/raps/references.ts @@ -4,7 +4,7 @@ import { Address } from 'viem'; import { ParsedAsset } from '@/__swaps__/types/assets'; import { GasFeeParamsBySpeed, LegacyGasFeeParamsBySpeed, LegacyTransactionGasParamAmounts, TransactionGasParamAmounts } from '@/entities'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; export enum SwapModalField { input = 'inputAmount', diff --git a/src/raps/unlockAndSwap.ts b/src/raps/unlockAndSwap.ts index 01d226f2703..9a02670ad81 100644 --- a/src/raps/unlockAndSwap.ts +++ b/src/raps/unlockAndSwap.ts @@ -6,7 +6,7 @@ import { } from '@rainbow-me/swaps'; import { Address } from 'viem'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { isNativeAsset } from '@/handlers/assets'; import { add } from '@/helpers/utilities'; import { isLowerCaseMatch } from '@/utils'; diff --git a/src/raps/utils.ts b/src/raps/utils.ts index 5baebd0a5b9..042c63c25ed 100644 --- a/src/raps/utils.ts +++ b/src/raps/utils.ts @@ -8,7 +8,7 @@ import { Chain, erc20Abi } from 'viem'; import { GasFeeParamsBySpeed, LegacyGasFeeParamsBySpeed, LegacyTransactionGasParamAmounts, TransactionGasParamAmounts } from '@/entities'; import { gasUtils } from '@/utils'; import { add, greaterThan, multiply } from '@/helpers/utilities'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { gasUnits } from '@/references'; import { toHexNoLeadingZeros } from '@/handlers/web3'; diff --git a/src/rapsV2/actions/claimTransactionClaimableAction.ts b/src/rapsV2/actions/claimTransactionClaimableAction.ts index bcbc7d25522..a516182fcdf 100644 --- a/src/rapsV2/actions/claimTransactionClaimableAction.ts +++ b/src/rapsV2/actions/claimTransactionClaimableAction.ts @@ -4,7 +4,7 @@ import { getProvider } from '@/handlers/web3'; import { RainbowError } from '@/logger'; import { addNewTransaction } from '@/state/pendingTransactions'; import { NewTransaction, TransactionStatus } from '@/entities'; -import { getChainsName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export async function claimTransactionClaimable({ parameters, wallet }: ActionProps<'claimTransactionClaimableAction'>) { const { claimTx, asset } = parameters; @@ -23,7 +23,7 @@ export async function claimTransactionClaimable({ parameters, wallet }: ActionPr to: result.result.to ?? null, chainId: result.result.chainId, hash: result.result.hash, - network: getChainsName()[result.result.chainId], + network: useBackendNetworksStore.getState().getChainsName()[result.result.chainId], status: TransactionStatus.pending, type: 'claim', nonce: result.result.nonce, diff --git a/src/redux/ensRegistration.ts b/src/redux/ensRegistration.ts index ea2158ec215..33a5b23c844 100644 --- a/src/redux/ensRegistration.ts +++ b/src/redux/ensRegistration.ts @@ -5,7 +5,7 @@ import { ENSRegistrations, ENSRegistrationState, Records, RegistrationParameters import { getLocalENSRegistrations, saveLocalENSRegistrations } from '@/handlers/localstorage/accountLocal'; import { ENS_RECORDS, REGISTRATION_MODES } from '@/helpers/ens'; import { omitFlatten } from '@/helpers/utilities'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; const ENS_REGISTRATION_SET_CHANGED_RECORDS = 'ensRegistration/ENS_REGISTRATION_SET_CHANGED_RECORDS'; const ENS_REGISTRATION_SET_INITIAL_RECORDS = 'ensRegistration/ENS_REGISTRATION_SET_INITIAL_RECORDS'; diff --git a/src/redux/gas.ts b/src/redux/gas.ts index ef537f150f4..355ffee1ee3 100644 --- a/src/redux/gas.ts +++ b/src/redux/gas.ts @@ -36,9 +36,9 @@ import { } from '@/parsers'; import { ethUnits } from '@/references'; import { ethereumUtils, gasUtils } from '@/utils'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; -import { getChainsSwapPollingInterval, meteorologySupportedChainIds, getNeedsL1SecurityFeeChains } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { MeteorologyLegacyResponse, MeteorologyResponse } from '@/entities/gas'; import { addBuffer } from '@/helpers/utilities'; @@ -341,7 +341,7 @@ export const gasPricesStartPolling = const { nativeCurrency } = getState().settings; let dataIsReady = true; - const meteorologySupportsChainId = meteorologySupportedChainIds.includes(chainId); + const meteorologySupportsChainId = useBackendNetworksStore.getState().getMeteorologySupportedChainIds().includes(chainId); if (!meteorologySupportsChainId) { const adjustedGasFees = await getProviderGasPrices({ chainId }); if (!adjustedGasFees) return; @@ -377,7 +377,7 @@ export const gasPricesStartPolling = } else { try { // OP chains have an additional fee we need to load - if (getNeedsL1SecurityFeeChains().includes(chainId)) { + if (useBackendNetworksStore.getState().getNeedsL1SecurityFeeChains().includes(chainId)) { dataIsReady = l1GasFeeOptimism !== null; } const meteorologyGasParams = await getMeteorologyGasParams(chainId); @@ -513,7 +513,7 @@ export const gasPricesStartPolling = } }; - const pollingInterval = getChainsSwapPollingInterval()[chainId]; + const pollingInterval = useBackendNetworksStore.getState().getChainsPollingInterval()[chainId]; watchGasPrices(chainId, pollingInterval); }; @@ -549,7 +549,10 @@ export const gasUpdateTxFee = const { defaultGasLimit, gasLimit, gasFeeParamsBySpeed, selectedGasFee, chainId, currentBlockParams } = getState().gas; const { nativeCurrency } = getState().settings; - if (isEmpty(gasFeeParamsBySpeed) || (getNeedsL1SecurityFeeChains().includes(chainId) && l1GasFeeOptimism === null)) { + if ( + isEmpty(gasFeeParamsBySpeed) || + (useBackendNetworksStore.getState().getNeedsL1SecurityFeeChains().includes(chainId) && l1GasFeeOptimism === null) + ) { // if fee prices not ready, we need to store the gas limit for future calculations // the rest is as the initial state value if (updatedGasLimit) { diff --git a/src/redux/requests.ts b/src/redux/requests.ts index 5b3bd5d21ad..6c1bab8a61a 100644 --- a/src/redux/requests.ts +++ b/src/redux/requests.ts @@ -6,7 +6,7 @@ import { getLocalRequests, removeLocalRequest, saveLocalRequests } from '@/handl import { omitFlatten } from '@/helpers/utilities'; import { getRequestDisplayDetails } from '@/parsers'; import { logger } from '@/logger'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; // -- Constants --------------------------------------- // diff --git a/src/redux/settings.ts b/src/redux/settings.ts index 30fb517b016..4d8ed57a335 100644 --- a/src/redux/settings.ts +++ b/src/redux/settings.ts @@ -25,7 +25,7 @@ import { import { getProvider } from '@/handlers/web3'; import { AppState } from '@/redux/store'; import { logger, RainbowError } from '@/logger'; -import { Network, ChainId } from '@/chains/types'; +import { Network, ChainId } from '@/state/backendNetworks/types'; // -- Constants ------------------------------------------------------------- // const SETTINGS_UPDATE_SETTINGS_ADDRESS = 'settings/SETTINGS_UPDATE_SETTINGS_ADDRESS'; diff --git a/src/redux/showcaseTokens.ts b/src/redux/showcaseTokens.ts index 062d292c68f..1ca4bf8db8e 100644 --- a/src/redux/showcaseTokens.ts +++ b/src/redux/showcaseTokens.ts @@ -5,7 +5,7 @@ import { getPreference } from '../model/preferences'; import { AppGetState } from './store'; import { getShowcaseTokens, getWebDataEnabled, saveShowcaseTokens, saveWebDataEnabled } from '@/handlers/localstorage/accountLocal'; import WalletTypes from '@/helpers/walletTypes'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; // -- Constants --------------------------------------- // diff --git a/src/redux/walletconnect.ts b/src/redux/walletconnect.ts index 4048975105c..8c4e9f4c3ff 100644 --- a/src/redux/walletconnect.ts +++ b/src/redux/walletconnect.ts @@ -31,9 +31,9 @@ import { logger, RainbowError } from '@/logger'; import { IS_DEV, IS_IOS, IS_TEST } from '@/env'; import { Verify } from '@walletconnect/types'; import { RequestSource, handleWalletConnectRequest } from '@/utils/requestNavigationHandlers'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { Address } from 'viem'; -import { getSupportedChainIds } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; // -- Variables --------------------------------------- // let showRedirectSheetThreshold = 300; @@ -477,7 +477,7 @@ const listenOnNewMessages = // @ts-expect-error "_chainId" is private. const currentChainId = Number(walletConnector._chainId); const numericChainId = Number(convertHexToString(chainId)); - if (getSupportedChainIds().includes(numericChainId)) { + if (useBackendNetworksStore.getState().getSupportedChainIds().includes(numericChainId)) { dispatch(walletConnectSetPendingRedirect()); Navigation.handleAction(Routes.WALLET_CONNECT_APPROVAL_SHEET, { callback: async (approved: boolean) => { diff --git a/src/references/gasUnits.ts b/src/references/gasUnits.ts index 75be1c71e93..a9517837ca8 100644 --- a/src/references/gasUnits.ts +++ b/src/references/gasUnits.ts @@ -1,4 +1,4 @@ -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; export const gasUnits = { basic_approval: '55000', diff --git a/src/references/index.ts b/src/references/index.ts index 121c6f5dd17..93a2c3bc897 100644 --- a/src/references/index.ts +++ b/src/references/index.ts @@ -1,4 +1,4 @@ -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; import { Asset } from '@/entities'; import { AddressZero } from '@ethersproject/constants'; diff --git a/src/references/rainbow-token-list/index.ts b/src/references/rainbow-token-list/index.ts index cdda1dcae0f..b8ad0db4687 100644 --- a/src/references/rainbow-token-list/index.ts +++ b/src/references/rainbow-token-list/index.ts @@ -6,7 +6,7 @@ import RAINBOW_TOKEN_LIST_DATA from './rainbow-token-list.json'; import { RainbowToken } from '@/entities'; import { STORAGE_IDS } from '@/model/mmkv'; import { logger, RainbowError } from '@/logger'; -import { Network, ChainId } from '@/chains/types'; +import { Network, ChainId } from '@/state/backendNetworks/types'; export const rainbowListStorage = new MMKV({ id: STORAGE_IDS.RAINBOW_TOKEN_LIST, diff --git a/src/references/testnet-assets-by-chain.ts b/src/references/testnet-assets-by-chain.ts index 8f0eedac9ba..141a195f022 100644 --- a/src/references/testnet-assets-by-chain.ts +++ b/src/references/testnet-assets-by-chain.ts @@ -1,5 +1,5 @@ import { UniqueId, ZerionAsset } from '@/__swaps__/types/assets'; -import { ChainId, ChainName } from '@/chains/types'; +import { ChainId, ChainName } from '@/state/backendNetworks/types'; type ChainAssets = { [uniqueId: UniqueId]: { diff --git a/src/resources/addys/claimables/query.ts b/src/resources/addys/claimables/query.ts index b13d2d548af..b1e3d14e87e 100644 --- a/src/resources/addys/claimables/query.ts +++ b/src/resources/addys/claimables/query.ts @@ -9,7 +9,7 @@ import { parseClaimables } from './utils'; import { useRemoteConfig } from '@/model/remoteConfig'; import { CLAIMABLES, useExperimentalFlag } from '@/config'; import { IS_TEST } from '@/env'; -import { getSupportedChainIds } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const ADDYS_BASE_URL = 'https://addys.p.rainbow.me/v3'; @@ -41,7 +41,7 @@ type ClaimablesQueryKey = ReturnType; async function claimablesQueryFunction({ queryKey: [{ address, currency }] }: QueryFunctionArgs) { try { - const url = `/${getSupportedChainIds().join(',')}/${address}/claimables`; + const url = `/${useBackendNetworksStore.getState().getSupportedChainIds().join(',')}/${address}/claimables`; const { data } = await addysHttp.get(url, { params: { currency: currency.toLowerCase(), diff --git a/src/resources/addys/claimables/types.ts b/src/resources/addys/claimables/types.ts index 426ed6e4523..2004563c6de 100644 --- a/src/resources/addys/claimables/types.ts +++ b/src/resources/addys/claimables/types.ts @@ -1,6 +1,6 @@ import { Address } from 'viem'; import { AddysAsset, AddysConsolidatedError, AddysResponseStatus } from '../types'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { ParsedAddressAsset } from '@/entities'; interface Colors { diff --git a/src/resources/addys/claimables/utils.ts b/src/resources/addys/claimables/utils.ts index d60b2ac966f..c50b2e0d1fd 100644 --- a/src/resources/addys/claimables/utils.ts +++ b/src/resources/addys/claimables/utils.ts @@ -2,8 +2,8 @@ import { NativeCurrencyKey } from '@/entities'; import { AddysClaimable, Claimable } from './types'; import { convertRawAmountToBalance, convertRawAmountToNativeDisplay, greaterThan } from '@/helpers/utilities'; import { parseAsset } from '@/resources/assets/assets'; -import { Network } from '@/chains/types'; -import { getChainsName } from '@/chains'; +import { Network } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const parseClaimables = (claimables: AddysClaimable[], currency: NativeCurrencyKey): Claimable[] => { return claimables @@ -20,7 +20,7 @@ export const parseClaimables = (claimables: AddysClaimable[], currency: NativeCu address: claimable.asset.asset_code, asset: { ...claimable.asset, - network: getChainsName()[claimable.network] as Network, + network: useBackendNetworksStore.getState().getChainsName()[claimable.network] as Network, transferable: claimable.asset.transferable ?? false, }, }), diff --git a/src/resources/addys/types.ts b/src/resources/addys/types.ts index 6da5c2cc4d7..17d330b9927 100644 --- a/src/resources/addys/types.ts +++ b/src/resources/addys/types.ts @@ -1,4 +1,4 @@ -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { Address } from 'viem'; interface BridgeableNetwork { diff --git a/src/resources/assets/UserAssetsQuery.ts b/src/resources/assets/UserAssetsQuery.ts index 9c549400cdf..597fff57c30 100644 --- a/src/resources/assets/UserAssetsQuery.ts +++ b/src/resources/assets/UserAssetsQuery.ts @@ -9,9 +9,9 @@ import { useQuery } from '@tanstack/react-query'; import { filterPositionsData, parseAddressAsset } from './assets'; import { fetchHardhatBalances } from './hardhatAssets'; import { AddysAccountAssetsMeta, AddysAccountAssetsResponse, RainbowAddressAssets } from './types'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; import { staleBalancesStore } from '@/state/staleBalances'; -import { getSupportedMainnetChainIds } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; // /////////////////////////////////////////////// // Query Types @@ -80,7 +80,7 @@ async function userAssetsQueryFunction({ const { erroredChainIds, results } = await fetchAndParseUserAssetsForChainIds({ address, currency, - chainIds: getSupportedMainnetChainIds(), + chainIds: useBackendNetworksStore.getState().getSupportedMainnetChainIds(), staleBalanceParam, }); let parsedSuccessResults = results; diff --git a/src/resources/assets/assets.ts b/src/resources/assets/assets.ts index 03ddc3c411d..958a9c2dec7 100644 --- a/src/resources/assets/assets.ts +++ b/src/resources/assets/assets.ts @@ -12,8 +12,8 @@ import { positionsQueryKey } from '@/resources/defi/PositionsQuery'; import { RainbowPositions } from '@/resources/defi/types'; import { AddysAddressAsset, AddysAsset, ParsedAsset, RainbowAddressAssets } from './types'; import { getUniqueId } from '@/utils/ethereumUtils'; -import { ChainId } from '@/chains/types'; -import { getChainsIdByName } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const storage = new MMKV(); @@ -40,7 +40,7 @@ export const filterPositionsData = ( export function parseAsset({ address, asset }: { address: string; asset: AddysAsset }): ParsedAsset { const network = asset?.network; - const chainId = getChainsIdByName()[network]; + const chainId = useBackendNetworksStore.getState().getChainsIdByName()[network]; const mainnetAddress = asset?.networks?.[ChainId.mainnet]?.address; const uniqueId = getUniqueId(address, chainId); diff --git a/src/resources/assets/externalAssetsQuery.ts b/src/resources/assets/externalAssetsQuery.ts index 76a5c01f5e4..21a5a683f8e 100644 --- a/src/resources/assets/externalAssetsQuery.ts +++ b/src/resources/assets/externalAssetsQuery.ts @@ -4,7 +4,7 @@ import { createQueryKey, queryClient, QueryConfig, QueryFunctionArgs, QueryFunct import { convertAmountAndPriceToNativeDisplay, convertAmountToPercentageDisplay } from '@/helpers/utilities'; import { NativeCurrencyKey } from '@/entities'; import { Token } from '@/graphql/__generated__/metadata'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { isNativeAsset } from '@/__swaps__/utils/chains'; import { AddressOrEth } from '@/__swaps__/types/assets'; diff --git a/src/resources/assets/hardhatAssets.ts b/src/resources/assets/hardhatAssets.ts index e2cd84969e2..9eede42dedd 100644 --- a/src/resources/assets/hardhatAssets.ts +++ b/src/resources/assets/hardhatAssets.ts @@ -8,8 +8,8 @@ import { logger, RainbowError } from '@/logger'; import { AddressOrEth, UniqueId, ZerionAsset } from '@/__swaps__/types/assets'; import { AddressZero } from '@ethersproject/constants'; import chainAssetsByChainId from '@/references/testnet-assets-by-chain'; -import { ChainId, ChainName, Network } from '@/chains/types'; -import { getSupportedChainIds } from '@/chains'; +import { ChainId, ChainName, Network } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const MAINNET_BALANCE_CHECKER = '0x4dcf4562268dd384fe814c00fad239f06c2a0c2b'; @@ -125,6 +125,6 @@ export const fetchHardhatBalancesByChainId = async ( return { assets: updatedAssets, - chainIdsInResponse: getSupportedChainIds(), + chainIdsInResponse: useBackendNetworksStore.getState().getSupportedChainIds(), }; }; diff --git a/src/resources/assets/types.ts b/src/resources/assets/types.ts index 3a37f1a76b9..ad5c3a62285 100644 --- a/src/resources/assets/types.ts +++ b/src/resources/assets/types.ts @@ -1,6 +1,6 @@ import { NativeCurrencyKey, ParsedAddressAsset } from '@/entities'; import { TokenColors } from '@/graphql/__generated__/metadata'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; export type AddysAccountAssetsResponse = { meta: AddysAccountAssetsMeta; diff --git a/src/resources/assets/useUserAsset.ts b/src/resources/assets/useUserAsset.ts index e5260de9cdd..4ee1dea9de1 100644 --- a/src/resources/assets/useUserAsset.ts +++ b/src/resources/assets/useUserAsset.ts @@ -1,10 +1,10 @@ -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { useAccountSettings } from '@/hooks'; import { useUserAssets } from '@/resources/assets/UserAssetsQuery'; import { selectUserAssetWithUniqueId } from '@/resources/assets/assetSelectors'; import { getUniqueId } from '@/utils/ethereumUtils'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; -import { getChainsNativeAsset } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export function useUserAsset(uniqueId: string) { const { accountAddress, nativeCurrency } = useAccountSettings(); @@ -23,7 +23,7 @@ export function useUserAsset(uniqueId: string) { } export function useUserNativeNetworkAsset(chainId: ChainId) { - const nativeCurrency = getChainsNativeAsset()[chainId]; + const nativeCurrency = useBackendNetworksStore.getState().getChainsNativeAsset()[chainId]; const { address } = nativeCurrency; const uniqueId = getUniqueId(address, chainId); return useUserAsset(uniqueId); diff --git a/src/resources/defi/PositionsQuery.ts b/src/resources/defi/PositionsQuery.ts index 5dfa50f4c7c..0d6650ae176 100644 --- a/src/resources/defi/PositionsQuery.ts +++ b/src/resources/defi/PositionsQuery.ts @@ -7,12 +7,12 @@ import { rainbowFetch } from '@/rainbow-fetch'; import { ADDYS_API_KEY } from 'react-native-dotenv'; import { AddysPositionsResponse, PositionsArgs } from './types'; import { parsePositions } from './utils'; -import { getSupportedChainIds } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { DEFI_POSITIONS, useExperimentalFlag } from '@/config'; import { IS_TEST } from '@/env'; export const buildPositionsUrl = (address: string) => { - const networkString = getSupportedChainIds().join(','); + const networkString = useBackendNetworksStore.getState().getSupportedChainIds().join(','); return `https://addys.p.rainbow.me/v3/${networkString}/${address}/positions`; }; diff --git a/src/resources/defi/types.ts b/src/resources/defi/types.ts index 56c25596204..b190da524c9 100644 --- a/src/resources/defi/types.ts +++ b/src/resources/defi/types.ts @@ -1,5 +1,5 @@ import { NativeCurrencyKey, ZerionAsset } from '@/entities'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; export type AddysPositionsResponse = | { diff --git a/src/resources/defi/utils.ts b/src/resources/defi/utils.ts index 74c070ef894..569d78e115e 100644 --- a/src/resources/defi/utils.ts +++ b/src/resources/defi/utils.ts @@ -14,7 +14,7 @@ import { import { add, convertAmountToNativeDisplay, convertRawAmountToNativeDisplay, subtract } from '@/helpers/utilities'; import { maybeSignUri } from '@/handlers/imgix'; import { ethereumUtils } from '@/utils'; -import { getChainsIdByName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const parsePosition = (position: Position, currency: NativeCurrencyKey): RainbowPosition => { let totalLocked = '0'; @@ -144,9 +144,11 @@ export const parsePositions = (data: AddysPositionsResponse, currency: NativeCur const positionTokens: string[] = []; + const chainsIdByName = useBackendNetworksStore.getState().getChainsIdByName(); + parsedPositions.forEach(({ deposits }) => { deposits.forEach(({ asset }) => { - const uniqueId = ethereumUtils.getUniqueId(asset.asset_code.toLowerCase(), getChainsIdByName()[asset.network]); + const uniqueId = ethereumUtils.getUniqueId(asset.asset_code.toLowerCase(), chainsIdByName[asset.network]); positionTokens.push(uniqueId); }); }); diff --git a/src/resources/ens/ensAddressQuery.ts b/src/resources/ens/ensAddressQuery.ts index 717b2616a2a..a35a7d11a8e 100644 --- a/src/resources/ens/ensAddressQuery.ts +++ b/src/resources/ens/ensAddressQuery.ts @@ -2,7 +2,7 @@ import { useQuery } from '@tanstack/react-query'; import { createQueryKey, queryClient, QueryFunctionArgs } from '@/react-query'; import { getProvider } from '@/handlers/web3'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; // Set a default stale time of 10 seconds so we don't over-fetch // (query will serve cached data & invalidate after 10s). diff --git a/src/resources/favorites.ts b/src/resources/favorites.ts index 90e36bb4036..4902539e087 100644 --- a/src/resources/favorites.ts +++ b/src/resources/favorites.ts @@ -1,5 +1,5 @@ import { AddressOrEth, UniqueId } from '@/__swaps__/types/assets'; -import { ChainId, Network } from '@/chains/types'; +import { ChainId, Network } from '@/state/backendNetworks/types'; import { getStandardizedUniqueIdWorklet } from '@/__swaps__/utils/swaps'; import { NativeCurrencyKeys, RainbowToken } from '@/entities'; import { createQueryKey, queryClient } from '@/react-query'; @@ -8,7 +8,7 @@ import { promiseUtils } from '@/utils'; import { useQuery } from '@tanstack/react-query'; import { omit } from 'lodash'; import { externalTokenQueryKey, fetchExternalToken } from './assets/externalAssetsQuery'; -import { getChainsIdByName, getChainsName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { analyticsV2 } from '@/analytics'; export const favoritesQueryKey = createQueryKey('favorites', {}, { persisterVersion: 4 }); @@ -23,7 +23,7 @@ const getUniqueId = (address: AddressOrEth, chainId: ChainId) => getStandardized async function fetchMetadata(addresses: string[], chainId = ChainId.mainnet) { const favoritesMetadata: Record = {}; const newFavoritesMeta: Record = {}; - const network = getChainsName()[chainId]; + const network = useBackendNetworksStore.getState().getChainsName()[chainId]; // Map addresses to an array of promises returned by fetchExternalToken const fetchPromises: Promise[] = addresses.map(async address => { @@ -94,9 +94,11 @@ export async function refreshFavorites() { {} as Record ); + const chainsIdByName = useBackendNetworksStore.getState().getChainsIdByName(); + const updatedMetadataByNetwork = await Promise.all( Object.entries(favoritesByNetwork).map(async ([network, networkFavorites]) => - fetchMetadata(networkFavorites, getChainsIdByName()[network as Network]) + fetchMetadata(networkFavorites, chainsIdByName[network as Network]) ) ); diff --git a/src/resources/metadata/backendNetworks.ts b/src/resources/metadata/backendNetworks.ts index 860c3019dff..2df83ce39ef 100644 --- a/src/resources/metadata/backendNetworks.ts +++ b/src/resources/metadata/backendNetworks.ts @@ -1,6 +1,6 @@ import { useQuery } from '@tanstack/react-query'; import { QueryConfigWithSelect, QueryFunctionArgs, createQueryKey, queryClient } from '@/react-query'; -import { BackendNetwork } from '@/chains/types'; +import { BackendNetwork } from '@/state/backendNetworks/types'; import { BACKEND_NETWORKS_QUERY } from './sharedQueries'; // /////////////////////////////////////////////// diff --git a/src/resources/nfts/index.ts b/src/resources/nfts/index.ts index d5585f29197..2c448365e97 100644 --- a/src/resources/nfts/index.ts +++ b/src/resources/nfts/index.ts @@ -8,7 +8,7 @@ import { UniqueAsset } from '@/entities'; import { arcClient } from '@/graphql'; import { NftCollectionSortCriterion, SortDirection } from '@/graphql/__generated__/arc'; import { createSelector } from 'reselect'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const NFTS_STALE_TIME = 600000; // 10 minutes const NFTS_CACHE_TIME_EXTERNAL = 3600000; // 1 hour diff --git a/src/resources/nfts/simplehash/index.ts b/src/resources/nfts/simplehash/index.ts index c5ffd198a0a..dfa305925a8 100644 --- a/src/resources/nfts/simplehash/index.ts +++ b/src/resources/nfts/simplehash/index.ts @@ -3,8 +3,8 @@ import { RainbowFetchClient } from '@/rainbow-fetch'; import { SimpleHashListing, SimpleHashNFT, SimpleHashMarketplaceId } from '@/resources/nfts/simplehash/types'; import { UniqueAsset } from '@/entities'; import { RainbowError, logger } from '@/logger'; -import { ChainId } from '@/chains/types'; -import { getChainsSimplehashNetwork } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const START_CURSOR = 'start'; @@ -19,7 +19,7 @@ export async function fetchSimpleHashNFT( tokenId: string, chainId: Omit = ChainId.mainnet ): Promise { - const simplehashNetwork = getChainsSimplehashNetwork()[chainId as ChainId]; + const simplehashNetwork = useBackendNetworksStore.getState().getChainsSimplehashNetwork()[chainId as ChainId]; if (!simplehashNetwork) { logger.warn(`[simplehash]: no SimpleHash for chainId: ${chainId}`); @@ -44,7 +44,7 @@ export async function fetchSimpleHashNFTListing( // array of all eth listings on OpenSea for this token let listings: SimpleHashListing[] = []; let cursor = START_CURSOR; - const simplehashNetwork = getChainsSimplehashNetwork()[chainId as ChainId]; + const simplehashNetwork = useBackendNetworksStore.getState().getChainsSimplehashNetwork()[chainId as ChainId]; if (!simplehashNetwork) { logger.warn(`[simplehash]: no SimpleHash for chainId: ${chainId}`); @@ -83,7 +83,7 @@ export async function fetchSimpleHashNFTListing( * @param nft */ export async function refreshNFTContractMetadata(nft: UniqueAsset) { - const simplehashNetwork = getChainsSimplehashNetwork()[nft.isPoap ? ChainId.gnosis : nft.chainId]; + const simplehashNetwork = useBackendNetworksStore.getState().getChainsSimplehashNetwork()[nft.isPoap ? ChainId.gnosis : nft.chainId]; if (!simplehashNetwork) { logger.warn(`[simplehash]: no SimpleHash for chainId: ${nft.chainId}`); @@ -135,7 +135,7 @@ export async function refreshNFTContractMetadata(nft: UniqueAsset) { * @param nft */ export async function reportNFT(nft: UniqueAsset) { - const simplehashNetwork = getChainsSimplehashNetwork()[nft.isPoap ? ChainId.gnosis : nft.chainId]; + const simplehashNetwork = useBackendNetworksStore.getState().getChainsSimplehashNetwork()[nft.isPoap ? ChainId.gnosis : nft.chainId]; if (!simplehashNetwork) { logger.warn(`[simplehash]: no SimpleHash for chainId: ${nft.chainId}`); diff --git a/src/resources/nfts/simplehash/types.ts b/src/resources/nfts/simplehash/types.ts index 9c769c72e80..1aad59dba5b 100644 --- a/src/resources/nfts/simplehash/types.ts +++ b/src/resources/nfts/simplehash/types.ts @@ -1,4 +1,4 @@ -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; /** * @see https://docs.simplehash.com/reference/sale-model diff --git a/src/resources/nfts/simplehash/utils.ts b/src/resources/nfts/simplehash/utils.ts index 2eabe2a5423..0c62afa97db 100644 --- a/src/resources/nfts/simplehash/utils.ts +++ b/src/resources/nfts/simplehash/utils.ts @@ -20,8 +20,8 @@ import { deviceUtils } from '@/utils'; import { TokenStandard } from '@/handlers/web3'; import { handleNFTImages } from '@/utils/handleNFTImages'; import { SimpleHashNft } from '@/graphql/__generated__/arc'; -import { Network } from '@/chains/types'; -import { getChainsIdByName } from '@/chains'; +import { Network } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const ENS_COLLECTION_NAME = 'ENS'; const SVG_MIME_TYPE = 'image/svg+xml'; @@ -60,6 +60,8 @@ export function simpleHashNFTToUniqueAsset(nft: SimpleHashNft, address: string): const ownerEntry = nft.owners?.find(o => o.owner_address === address); + const chainsIdByName = useBackendNetworksStore.getState().getChainsIdByName(); + return { animation_url: nft?.video_url ?? nft.audio_url ?? nft.model_url ?? nft.extra_metadata?.animation_original_url ?? undefined, asset_contract: { @@ -79,7 +81,7 @@ export function simpleHashNFTToUniqueAsset(nft: SimpleHashNft, address: string): slug: marketplace?.marketplace_collection_id ?? '', twitter_username: collection.twitter_username, }, - chainId: getChainsIdByName()[nft.chain], + chainId: chainsIdByName[nft.chain], description: nft.description, external_link: nft.external_url, familyImage: collection.image_url, diff --git a/src/resources/nfts/types.ts b/src/resources/nfts/types.ts index 88459dce3af..6f77ce7614d 100644 --- a/src/resources/nfts/types.ts +++ b/src/resources/nfts/types.ts @@ -1,5 +1,5 @@ import { Asset, AssetContract, AssetType } from '@/entities'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; import { UniqueTokenType } from '@/utils/uniqueTokens'; export enum NFTMarketplaceId { diff --git a/src/resources/nfts/utils.ts b/src/resources/nfts/utils.ts index 7b558cd849d..a8c806a4906 100644 --- a/src/resources/nfts/utils.ts +++ b/src/resources/nfts/utils.ts @@ -5,7 +5,7 @@ import { RainbowError, logger } from '@/logger'; import { handleSignificantDecimals } from '@/helpers/utilities'; import { IS_PROD } from '@/env'; import { RESERVOIR_API_KEY_DEV, RESERVOIR_API_KEY_PROD } from 'react-native-dotenv'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; const SUPPORTED_NETWORKS = [Network.mainnet, Network.polygon, Network.bsc, Network.arbitrum, Network.optimism, Network.base, Network.zora]; diff --git a/src/resources/reservoir/client.ts b/src/resources/reservoir/client.ts index cb3021e5258..43b74b03c1c 100644 --- a/src/resources/reservoir/client.ts +++ b/src/resources/reservoir/client.ts @@ -1,7 +1,7 @@ import { createClient } from '@reservoir0x/reservoir-sdk'; import { IS_PROD } from '@/env'; import { RESERVOIR_API_KEY_PROD, RESERVOIR_API_KEY_DEV } from 'react-native-dotenv'; -import { ChainId, Network } from '@/chains/types'; +import { ChainId, Network } from '@/state/backendNetworks/types'; const RESERVOIR_API_KEY = IS_PROD ? RESERVOIR_API_KEY_PROD : RESERVOIR_API_KEY_DEV; diff --git a/src/resources/reservoir/mints.ts b/src/resources/reservoir/mints.ts index faa8375558a..763c15cc03a 100644 --- a/src/resources/reservoir/mints.ts +++ b/src/resources/reservoir/mints.ts @@ -6,7 +6,7 @@ import { logger } from '@/logger'; import { WrappedAlert as Alert } from '@/helpers/alert'; import * as lang from '@/languages'; import { BigNumberish } from '@ethersproject/bignumber'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const showAlert = () => { Alert.alert( diff --git a/src/resources/reservoir/utils.ts b/src/resources/reservoir/utils.ts index 69145106e9d..e1991297161 100644 --- a/src/resources/reservoir/utils.ts +++ b/src/resources/reservoir/utils.ts @@ -1,4 +1,4 @@ -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const RAINBOW_FEE_ADDRESS_MAINNET = '0x69d6d375de8c7ade7e44446df97f49e661fdad7d'; const RAINBOW_FEE_ADDRESS_POLYGON = '0xfb9af3db5e19c4165f413f53fe3bbe6226834548'; diff --git a/src/resources/transactions/consolidatedTransactions.ts b/src/resources/transactions/consolidatedTransactions.ts index aea6382082e..a749e2f72d0 100644 --- a/src/resources/transactions/consolidatedTransactions.ts +++ b/src/resources/transactions/consolidatedTransactions.ts @@ -5,7 +5,7 @@ import { RainbowError, logger } from '@/logger'; import { rainbowFetch } from '@/rainbow-fetch'; import { ADDYS_API_KEY } from 'react-native-dotenv'; import { parseTransaction } from '@/parsers/transactions'; -import { getChainsIdByName, getSupportedMainnetChainIds } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const CONSOLIDATED_TRANSACTIONS_INTERVAL = 30000; const CONSOLIDATED_TRANSACTIONS_TIMEOUT = 20000; @@ -106,9 +106,9 @@ async function parseConsolidatedTransactions( ): Promise { const data = message?.payload?.transactions || []; - const parsedTransactionPromises = data.map((tx: TransactionApiResponse) => - parseTransaction(tx, currency, getChainsIdByName()[tx.network]) - ); + const chainsIdByName = useBackendNetworksStore.getState().getChainsIdByName(); + + const parsedTransactionPromises = data.map((tx: TransactionApiResponse) => parseTransaction(tx, currency, chainsIdByName[tx.network])); // Filter out undefined values immediately const parsedConsolidatedTransactions = (await Promise.all(parsedTransactionPromises)).flat(); // Filter out any remaining undefined values @@ -127,7 +127,7 @@ export function useConsolidatedTransactions( consolidatedTransactionsQueryKey({ address, currency, - chainIds: getSupportedMainnetChainIds(), + chainIds: useBackendNetworksStore.getState().getSupportedMainnetChainIds(), }), consolidatedTransactionsQueryFunction, { diff --git a/src/resources/transactions/transaction.ts b/src/resources/transactions/transaction.ts index 147e2630cd2..8280e63975d 100644 --- a/src/resources/transactions/transaction.ts +++ b/src/resources/transactions/transaction.ts @@ -7,8 +7,8 @@ import { rainbowFetch } from '@/rainbow-fetch'; import { ADDYS_API_KEY } from 'react-native-dotenv'; import { parseTransaction } from '@/parsers/transactions'; import { RainbowError, logger } from '@/logger'; -import { ChainId } from '@/chains/types'; -import { getSupportedMainnetChainIds } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export type ConsolidatedTransactionsResult = QueryFunctionResult; export type PaginatedTransactions = { pages: ConsolidatedTransactionsResult[] }; @@ -81,7 +81,7 @@ export function useBackendTransaction({ hash, chainId }: BackendTransactionArgs) const paginatedTransactionsKey = consolidatedTransactionsQueryKey({ address: accountAddress, currency: nativeCurrency, - chainIds: getSupportedMainnetChainIds(), + chainIds: useBackendNetworksStore.getState().getSupportedMainnetChainIds(), }); const params: TransactionArgs = { diff --git a/src/resources/transactions/transactionSimulation.ts b/src/resources/transactions/transactionSimulation.ts index f099aa62e63..4f889682f58 100644 --- a/src/resources/transactions/transactionSimulation.ts +++ b/src/resources/transactions/transactionSimulation.ts @@ -5,7 +5,7 @@ import { metadataPOSTClient } from '@/graphql'; import { TransactionErrorType, TransactionScanResultType, TransactionSimulationResult } from '@/graphql/__generated__/metadataPOST'; import { isNil } from 'lodash'; import { RequestData } from '@/redux/requests'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; type SimulationArgs = { address: string; diff --git a/src/screens/AddCash/components/ProviderCard.tsx b/src/screens/AddCash/components/ProviderCard.tsx index 7ff2e135dae..9cc19003cd2 100644 --- a/src/screens/AddCash/components/ProviderCard.tsx +++ b/src/screens/AddCash/components/ProviderCard.tsx @@ -16,7 +16,7 @@ import { convertAPINetworkToInternalChainIds } from '@/screens/AddCash/utils'; import { ProviderConfig, CalloutType, PaymentMethod } from '@/screens/AddCash/types'; import * as i18n from '@/languages'; import { EthCoinIcon } from '@/components/coin-icon/EthCoinIcon'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; type PaymentMethodConfig = { name: string; diff --git a/src/screens/AddCash/utils.ts b/src/screens/AddCash/utils.ts index 1cc7a37c6f7..4d334137128 100644 --- a/src/screens/AddCash/utils.ts +++ b/src/screens/AddCash/utils.ts @@ -1,4 +1,4 @@ -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { Network as APINetwork } from '@/screens/AddCash/types'; export function convertAPINetworkToInternalChainIds(network: APINetwork): ChainId | undefined { diff --git a/src/screens/CurrencySelectModal.tsx b/src/screens/CurrencySelectModal.tsx index 066856d17e0..c2bb0378f4e 100644 --- a/src/screens/CurrencySelectModal.tsx +++ b/src/screens/CurrencySelectModal.tsx @@ -39,8 +39,8 @@ import { useSortedUserAssets } from '@/resources/assets/useSortedUserAssets'; import DiscoverSearchInput from '@/components/discover/DiscoverSearchInput'; import { externalTokenQueryKey, fetchExternalToken } from '@/resources/assets/externalAssetsQuery'; import { queryClient } from '@/react-query/queryClient'; -import { ChainId, Network } from '@/chains/types'; -import { getChainsName } from '@/chains'; +import { ChainId, Network } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export interface EnrichedExchangeAsset extends SwappableAsset { ens: boolean; @@ -314,8 +314,10 @@ export default function CurrencySelectModal() { const checkForRequiredAssets = useCallback( (item: any) => { if (type === CurrencySelectionTypes.output && currentChainId && currentChainId !== ChainId.mainnet) { + const chainsName = useBackendNetworksStore.getState().getChainsName(); + const currentL2WalletAssets = assetsInWallet.filter( - ({ network }) => network && network?.toLowerCase() === getChainsName()[currentChainId]?.toLowerCase() + ({ network }) => network && network?.toLowerCase() === chainsName[currentChainId]?.toLowerCase() ); if (currentL2WalletAssets?.length < 1) { Keyboard.dismiss(); @@ -342,6 +344,8 @@ export default function CurrencySelectModal() { let newAsset = item; const selectAsset = async () => { + const chainsName = useBackendNetworksStore.getState().getChainsName(); + if (!item?.balance) { const externalAsset = await queryClient.fetchQuery( externalTokenQueryKey({ @@ -364,7 +368,7 @@ export default function CurrencySelectModal() { ...newAsset, decimals: item?.networks?.[currentChainId]?.decimals || item.decimals, address: item?.address || item?.networks?.[currentChainId]?.address, - network: getChainsName()[currentChainId], + network: chainsName[currentChainId], ...externalAsset, }; } diff --git a/src/screens/ENSConfirmRegisterSheet.tsx b/src/screens/ENSConfirmRegisterSheet.tsx index 7db4480e300..2a1105933f4 100644 --- a/src/screens/ENSConfirmRegisterSheet.tsx +++ b/src/screens/ENSConfirmRegisterSheet.tsx @@ -30,7 +30,6 @@ import { useENSRegistrationForm, useENSRegistrationStepHandler, useENSSearch, - useWallets, } from '@/hooks'; import { ImgixImage } from '@/components/images'; import { useNavigation } from '@/navigation'; @@ -40,7 +39,7 @@ import { usePersistentDominantColorFromImage } from '@/hooks/usePersistentDomina import { handleReviewPromptAction } from '@/utils/reviewAlert'; import { ReviewPromptAction } from '@/storage/schema'; import { ActionTypes } from '@/hooks/useENSRegistrationActionHandler'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; export const ENSConfirmRegisterSheetHeight = 600; export const ENSConfirmRenewSheetHeight = 560; diff --git a/src/screens/ExchangeModal.tsx b/src/screens/ExchangeModal.tsx index 7699b7ae333..624430e87db 100644 --- a/src/screens/ExchangeModal.tsx +++ b/src/screens/ExchangeModal.tsx @@ -68,13 +68,13 @@ import { handleReviewPromptAction } from '@/utils/reviewAlert'; import { ReviewPromptAction } from '@/storage/schema'; import { SwapPriceImpactType } from '@/hooks/usePriceImpactDetails'; import { getNextNonce } from '@/state/nonces'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { AddressOrEth, ParsedAsset } from '@/__swaps__/types/assets'; import { TokenColors } from '@/graphql/__generated__/metadata'; import { estimateSwapGasLimit } from '@/raps/actions'; import { estimateCrosschainSwapGasLimit } from '@/raps/actions/crosschainSwap'; import { parseGasParamAmounts } from '@/parsers'; -import { getChainsName, getNeedsL1SecurityFeeChains, shouldDefaultToFastGasChainIds, supportedFlashbotsChainIds } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const DEFAULT_SLIPPAGE_BIPS = { [ChainId.mainnet]: 100, @@ -95,7 +95,7 @@ export const getDefaultSlippageFromConfig = (chainId: ChainId) => { const configSlippage = getRemoteConfig().default_slippage_bips as unknown as { [network: string]: number; }; - const network = getChainsName()[chainId]; + const network = useBackendNetworksStore.getState().getChainsName()[chainId]; const slippage = configSlippage?.[network] ?? DEFAULT_SLIPPAGE_BIPS[chainId] ?? 100; return slippage; }; @@ -205,7 +205,11 @@ export function ExchangeModal({ fromDiscover, ignoreInitialTypeCheck, testID, ty const speedUrgentSelected = useRef(false); useEffect(() => { - if (!speedUrgentSelected.current && !isEmpty(gasFeeParamsBySpeed) && shouldDefaultToFastGasChainIds.includes(currentChainId)) { + if ( + !speedUrgentSelected.current && + !isEmpty(gasFeeParamsBySpeed) && + useBackendNetworksStore.getState().getShouldDefaultToFastGasChainIds().includes(currentChainId) + ) { // Default to fast for networks with speed options updateGasFeeOption(gasUtils.FAST); speedUrgentSelected.current = true; @@ -240,7 +244,7 @@ export function ExchangeModal({ fromDiscover, ignoreInitialTypeCheck, testID, ty const [debouncedIsHighPriceImpact] = useDebounce(priceImpact.type !== SwapPriceImpactType.none, 1000); // For a limited period after the merge we need to block the use of flashbots. // This line should be removed after reenabling flashbots in remote config. - const swapSupportsFlashbots = supportedFlashbotsChainIds.includes(currentChainId); + const swapSupportsFlashbots = useBackendNetworksStore.getState().getFlashbotsSupportedChainIds().includes(currentChainId); const flashbots = swapSupportsFlashbots && flashbotsEnabled; const isDismissing = useRef(false); @@ -293,7 +297,7 @@ export function ExchangeModal({ fromDiscover, ignoreInitialTypeCheck, testID, ty }); if (gasLimit) { - if (getNeedsL1SecurityFeeChains().includes(currentChainId)) { + if (useBackendNetworksStore.getState().getNeedsL1SecurityFeeChains().includes(currentChainId)) { if (tradeDetails) { const l1GasFeeOptimism = await ethereumUtils.calculateL1FeeOptimism( // eslint-disable-next-line @typescript-eslint/ban-ts-comment @@ -407,7 +411,11 @@ export function ExchangeModal({ fromDiscover, ignoreInitialTypeCheck, testID, ty // Switch to the flashbots provider if enabled // TODO(skylarbarrera): need to check if ledger and handle differently here - if (flashbots && supportedFlashbotsChainIds.includes(currentChainId) && wallet instanceof Wallet) { + if ( + flashbots && + useBackendNetworksStore.getState().getFlashbotsSupportedChainIds().includes(currentChainId) && + wallet instanceof Wallet + ) { logger.debug('[ExchangeModal]: flashbots provider being set on mainnet'); const flashbotsProvider = await getFlashbotsProvider(); wallet = new Wallet(wallet.privateKey, flashbotsProvider); @@ -430,9 +438,11 @@ export function ExchangeModal({ fromDiscover, ignoreInitialTypeCheck, testID, ty logger.debug(`[ExchangeModal]: nonce for account ${accountAddress} is ${currentNonce}`); const { independentField, independentValue, slippageInBips, source } = store.getState().swap; + const chainsName = useBackendNetworksStore.getState().getChainsName(); + const transformedAssetToSell = { ...inputCurrency, - chainName: getChainsName()[inputCurrency.chainId], + chainName: chainsName[inputCurrency.chainId], address: inputCurrency.address as AddressOrEth, chainId: inputCurrency.chainId, colors: inputCurrency.colors as TokenColors, @@ -440,7 +450,7 @@ export function ExchangeModal({ fromDiscover, ignoreInitialTypeCheck, testID, ty const transformedAssetToBuy = { ...outputCurrency, - chainName: getChainsName()[outputCurrency.chainId], + chainName: chainsName[outputCurrency.chainId], address: outputCurrency.address as AddressOrEth, chainId: outputCurrency.chainId, colors: outputCurrency.colors as TokenColors, @@ -500,7 +510,7 @@ export function ExchangeModal({ fromDiscover, ignoreInitialTypeCheck, testID, ty legacyGasPrice: (selectedGasFee?.gasFeeParams as unknown as LegacyGasFeeParams)?.gasPrice?.amount || '', liquiditySources: JSON.stringify(tradeDetails?.protocols || []), maxNetworkFee: (selectedGasFee?.gasFee as GasFee)?.maxFee?.value?.amount || '', - network: getChainsName()[currentChainId], + network: chainsName[currentChainId], networkFee: selectedGasFee?.gasFee?.estimatedFee?.value?.amount || '', outputTokenAddress: outputCurrency?.address || '', outputTokenName: outputCurrency?.name || '', @@ -581,7 +591,7 @@ export function ExchangeModal({ fromDiscover, ignoreInitialTypeCheck, testID, ty legacyGasPrice: (selectedGasFee?.gasFeeParams as unknown as LegacyGasFeeParams)?.gasPrice?.amount || '', liquiditySources: JSON.stringify(tradeDetails?.protocols || []), maxNetworkFee: (selectedGasFee?.gasFee as GasFee)?.maxFee?.value?.amount || '', - network: getChainsName()[currentChainId], + network: useBackendNetworksStore.getState().getChainsName()[currentChainId], networkFee: selectedGasFee?.gasFee?.estimatedFee?.value?.amount || '', outputTokenAddress: outputCurrency?.address || '', outputTokenName: outputCurrency?.name || '', @@ -712,7 +722,7 @@ export function ExchangeModal({ fromDiscover, ignoreInitialTypeCheck, testID, ty setParams({ focused: false }); navigate(Routes.SWAP_DETAILS_SHEET, { confirmButtonProps, - currentNetwork: getChainsName()[currentChainId], + currentNetwork: useBackendNetworksStore.getState().getChainsName()[currentChainId], flashbotTransaction: flashbots, isRefuelTx, restoreFocusOnSwapModal: () => { diff --git a/src/screens/MintsSheet/card/Card.tsx b/src/screens/MintsSheet/card/Card.tsx index 0377bbe287d..a268ad94090 100644 --- a/src/screens/MintsSheet/card/Card.tsx +++ b/src/screens/MintsSheet/card/Card.tsx @@ -12,8 +12,8 @@ import * as i18n from '@/languages'; import ChainBadge from '@/components/coin-icon/ChainBadge'; import { navigateToMintCollection } from '@/resources/reservoir/mints'; import { EthCoinIcon } from '@/components/coin-icon/EthCoinIcon'; -import { ChainId } from '@/chains/types'; -import { getChainsNativeAsset } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export const NUM_NFTS = 3; @@ -28,7 +28,7 @@ export function Card({ collection }: { collection: MintableCollection }) { const separatorTertiary = useForegroundColor('separatorTertiary'); const price = convertRawAmountToRoundedDecimal(collection.mintStatus.price, 18, 6); - const currencySymbol = getChainsNativeAsset()[collection.chainId].symbol; + const currencySymbol = useBackendNetworksStore.getState().getChainsNativeAsset()[collection.chainId].symbol; const isFree = !price; // update elapsed time every minute if it's less than an hour diff --git a/src/screens/NFTOffersSheet/OfferRow.tsx b/src/screens/NFTOffersSheet/OfferRow.tsx index 59a47f0c0f6..7983c7edd33 100644 --- a/src/screens/NFTOffersSheet/OfferRow.tsx +++ b/src/screens/NFTOffersSheet/OfferRow.tsx @@ -14,11 +14,11 @@ import { CardSize } from '@/components/unique-token/CardSize'; import { View } from 'react-native'; import Svg, { Path } from 'react-native-svg'; import { useExternalToken } from '@/resources/assets/externalAssetsQuery'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; import { useAccountSettings } from '@/hooks'; import RainbowCoinIcon from '@/components/coin-icon/RainbowCoinIcon'; import { AddressOrEth } from '@/__swaps__/types/assets'; -import { getChainsIdByName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const NFT_SIZE = 50; const MARKETPLACE_ORB_SIZE = 18; @@ -99,7 +99,7 @@ export const OfferRow = ({ offer }: { offer: NftOffer }) => { const { colorMode } = useColorMode(); const theme = useTheme(); const bgColor = useBackgroundColor('surfaceSecondaryElevated'); - const chainId = getChainsIdByName()[offer.network as Network]; + const chainId = useBackendNetworksStore.getState().getChainsIdByName()[offer.network as Network]; const { data: externalAsset } = useExternalToken({ address: offer.paymentToken.address as AddressOrEth, chainId, diff --git a/src/screens/NFTSingleOfferSheet/index.tsx b/src/screens/NFTSingleOfferSheet/index.tsx index 87889ca93a8..7522650d1b6 100644 --- a/src/screens/NFTSingleOfferSheet/index.tsx +++ b/src/screens/NFTSingleOfferSheet/index.tsx @@ -39,7 +39,7 @@ import { createWalletClient, http } from 'viem'; import { RainbowError, logger } from '@/logger'; import { useTheme } from '@/theme'; -import { Network, ChainId } from '@/chains/types'; +import { Network, ChainId } from '@/state/backendNetworks/types'; import { CardSize } from '@/components/unique-token/CardSize'; import { queryClient } from '@/react-query'; import { nftOffersQueryKey } from '@/resources/reservoir/nftOffersQuery'; @@ -52,7 +52,7 @@ import { getNextNonce } from '@/state/nonces'; import { metadataPOSTClient } from '@/graphql'; import { ethUnits } from '@/references'; import { Transaction } from '@/graphql/__generated__/metadataPOST'; -import { getChainsIdByName, getChainsNativeAsset, getDefaultChains, getChainDefaultRpc } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const NFT_IMAGE_HEIGHT = 160; const TWO_HOURS_MS = 2 * 60 * 60 * 1000; @@ -94,7 +94,7 @@ export function NFTSingleOfferSheet() { } = useLegacyNFTs({ address: accountAddress }); const { offer } = params as { offer: NftOffer }; - const offerChainId = getChainsIdByName()[offer.network as Network]; + const offerChainId = useBackendNetworksStore.getState().getChainsIdByName()[offer.network as Network]; const { data: externalAsset } = useExternalToken({ address: offer.paymentToken.address, chainId: offerChainId, @@ -164,7 +164,7 @@ export function NFTSingleOfferSheet() { const feesPercentage = Math.floor(offer.feesPercentage * 10) / 10; const royaltiesPercentage = Math.floor(offer.royaltiesPercentage * 10) / 10; - const chain = getDefaultChains()[offerChainId]; + const chain = useBackendNetworksStore.getState().getDefaultChains()[offerChainId]; useEffect(() => { setParams({ longFormHeight: height }); @@ -185,7 +185,7 @@ export function NFTSingleOfferSheet() { // @ts-ignore account: accountAddress, chain, - transport: http(getChainDefaultRpc(offerChainId)), + transport: http(useBackendNetworksStore.getState().getChainDefaultRpc(offerChainId)), }); getClient()?.actions.acceptOffer({ items: [ @@ -243,7 +243,7 @@ export function NFTSingleOfferSheet() { } catch { logger.error(new RainbowError('[NFTSingleOfferSheet]: Failed to estimate gas')); } - }, [accountAddress, feeParam, offerChainId, offer, updateTxFee]); + }, [accountAddress, chain, offerChainId, offer.nft.contractAddress, offer.nft.tokenId, feeParam, updateTxFee]); // estimate gas useEffect(() => { @@ -285,7 +285,7 @@ export function NFTSingleOfferSheet() { const signer = createWalletClient({ account, chain, - transport: http(getChainDefaultRpc(offerChainId)), + transport: http(useBackendNetworksStore.getState().getChainDefaultRpc(offerChainId)), }); const nonce = await getNextNonce({ address: accountAddress, chainId: offerChainId }); try { @@ -431,7 +431,7 @@ export function NFTSingleOfferSheet() { if (!isAccepting) { if (insufficientEth) { buttonLabel = lang.t('button.confirm_exchange.insufficient_token', { - tokenName: getChainsNativeAsset()[offerChainId].symbol, + tokenName: useBackendNetworksStore.getState().getChainsNativeAsset()[offerChainId].symbol, }); } else { buttonLabel = i18n.t(i18n.l.nft_offers.single_offer_sheet.hold_to_sell); diff --git a/src/screens/SendConfirmationSheet.tsx b/src/screens/SendConfirmationSheet.tsx index 74930d0c3fc..3f55574d39c 100644 --- a/src/screens/SendConfirmationSheet.tsx +++ b/src/screens/SendConfirmationSheet.tsx @@ -61,8 +61,8 @@ import { IS_ANDROID, IS_IOS } from '@/env'; import { useConsolidatedTransactions } from '@/resources/transactions/consolidatedTransactions'; import RainbowCoinIcon from '@/components/coin-icon/RainbowCoinIcon'; import { performanceTracking, TimeToSignOperation, Screens } from '@/state/performance/performance'; -import { ChainId } from '@/chains/types'; -import { getChainsLabel } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const Container = styled(Centered).attrs({ direction: 'column', @@ -133,7 +133,7 @@ export function getDefaultCheckboxes({ checked: false, id: 'has-wallet-that-supports', label: lang.t('wallet.transaction.checkboxes.has_a_wallet_that_supports', { - networkName: getChainsLabel()[chainId], + networkName: useBackendNetworksStore.getState().getChainsLabel()[chainId], }), }, ]; @@ -601,7 +601,7 @@ export const SendConfirmationSheet = () => { onPress={handleL2DisclaimerPress} prominent customText={i18n.t(i18n.l.expanded_state.asset.l2_disclaimer_send, { - network: getChainsLabel()[asset.chainId], + network: useBackendNetworksStore.getState().getChainsLabel()[asset.chainId], })} symbol={asset.symbol} /> diff --git a/src/screens/SendSheet.tsx b/src/screens/SendSheet.tsx index e5300a12d2e..927028ac67e 100644 --- a/src/screens/SendSheet.tsx +++ b/src/screens/SendSheet.tsx @@ -63,8 +63,8 @@ import { getNextNonce } from '@/state/nonces'; import { usePersistentDominantColorFromImage } from '@/hooks/usePersistentDominantColorFromImage'; import { performanceTracking, Screens, TimeToSignOperation } from '@/state/performance/performance'; import { REGISTRATION_STEPS } from '@/helpers/ens'; -import { ChainId } from '@/chains/types'; -import { getChainsName, getChainsNativeAsset, getNeedsL1SecurityFeeChains } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { RootStackParamList } from '@/navigation/types'; import { ThemeContextProps, useTheme } from '@/theme'; import { StaticJsonRpcProvider } from '@ethersproject/providers'; @@ -416,7 +416,7 @@ export default function SendSheet() { }); if (!wallet) return; - const currentChainIdNetwork = getChainsName()[currentChainId ?? ChainId.mainnet]; + const currentChainIdNetwork = useBackendNetworksStore.getState().getChainsName()[currentChainId ?? ChainId.mainnet]; const validTransaction = isValidAddress && amountDetails.isSufficientBalance && isSufficientGas && isValidGas; if (!selectedGasFee?.gasFee?.estimatedFee || !validTransaction) { @@ -448,7 +448,7 @@ export default function SendSheet() { ); if (updatedGasLimit && !lessThan(updatedGasLimit, gasLimit)) { - if (getNeedsL1SecurityFeeChains().includes(currentChainId)) { + if (useBackendNetworksStore.getState().getNeedsL1SecurityFeeChains().includes(currentChainId)) { updateTxFeeForOptimism(updatedGasLimit); } else { updateTxFee(updatedGasLimit, null); @@ -670,14 +670,14 @@ export default function SendSheet() { !selectedGasFee || isEmpty(selectedGasFee?.gasFee) || !toAddress || - (getNeedsL1SecurityFeeChains().includes(currentChainId) && l1GasFeeOptimism === null) + (useBackendNetworksStore.getState().getNeedsL1SecurityFeeChains().includes(currentChainId) && l1GasFeeOptimism === null) ) { label = lang.t('button.confirm_exchange.loading'); disabled = true; } else if (!isZeroAssetAmount && !isSufficientGas) { disabled = true; label = lang.t('button.confirm_exchange.insufficient_token', { - tokenName: getChainsNativeAsset()[currentChainId || ChainId.mainnet].symbol, + tokenName: useBackendNetworksStore.getState().getChainsNativeAsset()[currentChainId || ChainId.mainnet].symbol, }); } else if (!isValidGas) { disabled = true; @@ -855,7 +855,7 @@ export default function SendSheet() { currentChainId ) .then(async gasLimit => { - if (gasLimit && getNeedsL1SecurityFeeChains().includes(currentChainId)) { + if (gasLimit && useBackendNetworksStore.getState().getNeedsL1SecurityFeeChains().includes(currentChainId)) { updateTxFeeForOptimism(gasLimit); } else { updateTxFee(gasLimit, null); diff --git a/src/screens/SettingsSheet/components/CurrencySection.tsx b/src/screens/SettingsSheet/components/CurrencySection.tsx index 337d3cd4c47..c523cebb00c 100644 --- a/src/screens/SettingsSheet/components/CurrencySection.tsx +++ b/src/screens/SettingsSheet/components/CurrencySection.tsx @@ -10,7 +10,7 @@ import { ETH_ADDRESS, WBTC_ADDRESS, emojis, supportedNativeCurrencies } from '@/ import { useExternalToken } from '@/resources/assets/externalAssetsQuery'; import RainbowCoinIcon from '@/components/coin-icon/RainbowCoinIcon'; import { useTheme } from '@/theme'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const emojiData = Object.entries(emojis).map(([emoji, { name }]) => [name, emoji]); diff --git a/src/screens/SettingsSheet/components/NetworkSection.tsx b/src/screens/SettingsSheet/components/NetworkSection.tsx index 2cdf7630b5c..fb3ead755fe 100644 --- a/src/screens/SettingsSheet/components/NetworkSection.tsx +++ b/src/screens/SettingsSheet/components/NetworkSection.tsx @@ -8,8 +8,8 @@ import { analytics } from '@/analytics'; import { Separator, Stack } from '@/design-system'; import { useAccountSettings, useLoadAccountData } from '@/hooks'; import { settingsUpdateNetwork } from '@/redux/settings'; -import { ChainId } from '@/chains/types'; -import { getDefaultChains } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { isL2Chain } from '@/handlers/web3'; interface NetworkSectionProps { @@ -33,7 +33,7 @@ const NetworkSection = ({ inDevSection }: NetworkSectionProps) => { ); const renderNetworkList = useCallback(() => { - return Object.values(getDefaultChains()) + return Object.values(useBackendNetworksStore.getState().getDefaultChains()) .filter(({ id }) => !isL2Chain({ chainId: id })) .map(({ name, id, testnet }) => ( { } catch (e) { logger.error(new RainbowError(`[SignTransactionSheet]: Error while ${sendInsteadOfSign ? 'sending' : 'signing'} transaction`)); } + const chainsName = useBackendNetworksStore.getState().getChainsName(); if (response?.result) { const signResult = response.result as string; @@ -387,7 +388,7 @@ export const SignTransactionSheet = () => { from: displayDetails?.request?.from, gasLimit, hash: sendResult.hash, - network: getChainsName()[chainId] as Network, + network: chainsName[chainId] as Network, nonce: sendResult.nonce, to: displayDetails?.request?.to, value: sendResult.value.toString(), @@ -410,7 +411,7 @@ export const SignTransactionSheet = () => { dappName: transactionDetails.dappName, dappUrl: transactionDetails.dappUrl, isHardwareWallet: accountInfo.isHardwareWallet, - network: getChainsName()[chainId] as Network, + network: chainsName[chainId] as Network, }); if (!sendInsteadOfSign) { @@ -443,7 +444,7 @@ export const SignTransactionSheet = () => { dappUrl: transactionDetails?.dappUrl, formattedDappUrl, rpcMethod: req?.method, - network: getChainsName()[chainId] as Network, + network: chainsName[chainId] as Network, }); // If the user is using a hardware wallet, we don't want to close the sheet on an error if (!accountInfo.isHardwareWallet) { @@ -519,7 +520,7 @@ export const SignTransactionSheet = () => { dappName: transactionDetails?.dappName, dappUrl: transactionDetails?.dappUrl, isHardwareWallet: accountInfo.isHardwareWallet, - network: getChainsName()[chainId] as Network, + network: useBackendNetworksStore.getState().getChainsName()[chainId] as Network, }); onSuccessCallback?.(response.result); @@ -707,7 +708,7 @@ export const SignTransactionSheet = () => { {`${walletBalance?.display} ${i18n.t(i18n.l.walletconnect.simulation.profile_section.on_network, { - network: getDefaultChains()[chainId]?.name, + network: useBackendNetworksStore.getState().getChainsName()[chainId], })}`} diff --git a/src/screens/SpeedUpAndCancelSheet.tsx b/src/screens/SpeedUpAndCancelSheet.tsx index 352df10fd8e..b24e7fbfa98 100644 --- a/src/screens/SpeedUpAndCancelSheet.tsx +++ b/src/screens/SpeedUpAndCancelSheet.tsx @@ -30,8 +30,8 @@ import { gasUtils, safeAreaInsetValues } from '@/utils'; import * as i18n from '@/languages'; import { updateTransaction } from '@/state/pendingTransactions'; import { logger, RainbowError } from '@/logger'; -import { supportedFlashbotsChainIds } from '@/chains'; -import { ChainId } from '@/chains/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; +import { ChainId } from '@/state/backendNetworks/types'; import { ThemeContextProps, useTheme } from '@/theme'; import { BigNumberish } from '@ethersproject/bignumber'; import { RootStackParamList } from '@/navigation/types'; @@ -314,7 +314,7 @@ export default function SpeedUpAndCancelSheet() { startPollingGasFees(currentChainId, tx.flashbots); const updateProvider = async () => { let provider; - if (supportedFlashbotsChainIds.includes(tx.chainId || ChainId.mainnet) && tx.flashbots) { + if (useBackendNetworksStore.getState().getFlashbotsSupportedChainIds().includes(tx.chainId) && tx.flashbots) { logger.debug(`[SpeedUpAndCancelSheet]: using flashbots provider for chainId ${tx?.chainId}`); provider = await getFlashbotsProvider(); } else { diff --git a/src/screens/WalletConnectApprovalSheet.tsx b/src/screens/WalletConnectApprovalSheet.tsx index e47a3d91b53..2e0a27d3e00 100644 --- a/src/screens/WalletConnectApprovalSheet.tsx +++ b/src/screens/WalletConnectApprovalSheet.tsx @@ -29,8 +29,8 @@ import { DAppStatus } from '@/graphql/__generated__/metadata'; import { InfoAlert } from '@/components/info-alert/info-alert'; import { EthCoinIcon } from '@/components/coin-icon/EthCoinIcon'; import { findWalletWithAccount } from '@/helpers/findWalletWithAccount'; -import { ChainId } from '@/chains/types'; -import { getChainsLabel, getChainsNativeAsset, getDefaultChains } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { ThemeContextProps, useTheme } from '@/theme'; import { noop } from 'lodash'; import { RootStackParamList } from '@/navigation/types'; @@ -132,7 +132,7 @@ const NetworkPill = ({ chainIds }: { chainIds: ChainId[] }) => { - {getChainsLabel()[availableNetworkChainIds[0]]} + {useBackendNetworksStore.getState().getChainsLabel()[availableNetworkChainIds[0]]} @@ -229,8 +229,8 @@ export function WalletConnectApprovalSheet() { * v2. */ const approvalNetworkInfo = useMemo(() => { - const chain = getDefaultChains()[approvalChainId || ChainId.mainnet]; - const nativeAsset = getChainsNativeAsset()[chain.id]; + const chain = useBackendNetworksStore.getState().getDefaultChains()[approvalChainId || ChainId.mainnet]; + const nativeAsset = useBackendNetworksStore.getState().getChainsNativeAsset()[chain.id]; return { chainId: chain.id, color: isDarkMode ? nativeAsset.colors.primary : nativeAsset.colors.fallback || nativeAsset.colors.primary, @@ -365,7 +365,9 @@ export function WalletConnectApprovalSheet() { {`${ - type === WalletConnectApprovalSheetType.connect ? approvalNetworkInfo.name : getChainsLabel()[chainId] + type === WalletConnectApprovalSheetType.connect + ? approvalNetworkInfo.name + : useBackendNetworksStore.getState().getChainsLabel()[chainId] } ${type === WalletConnectApprovalSheetType.connect && menuItems.length > 1 ? '􀁰' : ''}`} @@ -406,7 +408,7 @@ export function WalletConnectApprovalSheet() { {type === WalletConnectApprovalSheetType.connect ? lang.t(lang.l.walletconnect.wants_to_connect) : lang.t(lang.l.walletconnect.wants_to_connect_to_network, { - network: getChainsLabel()[chainId], + network: useBackendNetworksStore.getState().getChainsLabel()[chainId], })} diff --git a/src/screens/claimables/ClaimingClaimableSharedUI.tsx b/src/screens/claimables/ClaimingClaimableSharedUI.tsx index 42eec0efa42..d117e5b9cce 100644 --- a/src/screens/claimables/ClaimingClaimableSharedUI.tsx +++ b/src/screens/claimables/ClaimingClaimableSharedUI.tsx @@ -10,7 +10,7 @@ import { SponsoredClaimable, TransactionClaimable } from '@/resources/addys/clai import RainbowCoinIcon from '@/components/coin-icon/RainbowCoinIcon'; import { useTheme } from '@/theme'; import { FasterImageView } from '@candlefinance/faster-image'; -import { getChainsLabel } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { useNavigation } from '@/navigation'; import { TextColor } from '@/design-system/color/palettes'; import Animated, { useAnimatedStyle, useSharedValue, withTiming } from 'react-native-reanimated'; @@ -262,7 +262,7 @@ export const ClaimingClaimableSharedUI = ({ {i18n.t(i18n.l.claimables.panel.amount_to_claim_on_network, { amount: nativeCurrencyGasFeeDisplay, - network: getChainsLabel()[claimable.chainId], + network: useBackendNetworksStore.getState().getChainsLabel()[claimable.chainId], })} diff --git a/src/screens/claimables/ClaimingTransactionClaimable.tsx b/src/screens/claimables/ClaimingTransactionClaimable.tsx index 4738e7d51e7..c320467c28d 100644 --- a/src/screens/claimables/ClaimingTransactionClaimable.tsx +++ b/src/screens/claimables/ClaimingTransactionClaimable.tsx @@ -5,7 +5,7 @@ import { Claimable, TransactionClaimable } from '@/resources/addys/claimables/ty import { estimateGasWithPadding, getProvider } from '@/handlers/web3'; import { parseGasParamsForTransaction } from '@/parsers'; import { getNextNonce } from '@/state/nonces'; -import { getNeedsL1SecurityFeeChains } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { logger, RainbowError } from '@/logger'; import { ClaimingClaimableSharedUI, ClaimStatus } from './ClaimingClaimableSharedUI'; import { TransactionRequest } from '@ethersproject/providers'; @@ -108,7 +108,7 @@ export const ClaimingTransactionClaimable = ({ claimable }: { claimable: Transac return; } - if (getNeedsL1SecurityFeeChains().includes(claimable.chainId)) { + if (useBackendNetworksStore.getState().getNeedsL1SecurityFeeChains().includes(claimable.chainId)) { const l1SecurityFee = await ethereumUtils.calculateL1FeeOptimism( { to: claimable.action.to, diff --git a/src/screens/mints/MintSheet.tsx b/src/screens/mints/MintSheet.tsx index cc8903404e5..288de66bc10 100644 --- a/src/screens/mints/MintSheet.tsx +++ b/src/screens/mints/MintSheet.tsx @@ -55,8 +55,8 @@ import { getUniqueId } from '@/utils/ethereumUtils'; import { getNextNonce } from '@/state/nonces'; import { metadataPOSTClient } from '@/graphql'; import { Transaction } from '@/graphql/__generated__/metadataPOST'; -import { ChainId } from '@/chains/types'; -import { getChainsName, getDefaultChains, getChainDefaultRpc } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; const NFT_IMAGE_HEIGHT = 250; // inset * 2 -> 28 *2 @@ -247,10 +247,11 @@ const MintSheet = () => { // estimate gas limit useEffect(() => { const estimateMintGas = async () => { + const defaultChains = useBackendNetworksStore.getState().getDefaultChains(); const signer = createWalletClient({ account: accountAddress, - chain: getDefaultChains()[chainId], - transport: http(getChainDefaultRpc(chainId)), + chain: defaultChains[chainId], + transport: http(useBackendNetworksStore.getState().getChainDefaultRpc(chainId)), }); try { await getClient()?.actions.mintToken({ @@ -355,11 +356,11 @@ const MintSheet = () => { const privateKey = await loadPrivateKey(accountAddress, false); // @ts-ignore const account = privateKeyToAccount(privateKey); - const chain = getDefaultChains()[chainId]; + const chain = useBackendNetworksStore.getState().getDefaultChains()[chainId]; const signer = createWalletClient({ account, chain, - transport: http(getChainDefaultRpc(chainId)), + transport: http(useBackendNetworksStore.getState().getChainDefaultRpc(chainId)), }); const feeAddress = getRainbowFeeAddress(chainId); @@ -376,6 +377,7 @@ const MintSheet = () => { wallet: signer!, chainId, onProgress: (steps: Execute['steps']) => { + const chainsName = useBackendNetworksStore.getState().getChainsName(); steps.forEach(step => { if (step.error) { logger.error(new RainbowError(`[MintSheet]: Error minting NFT: ${step.error}`)); @@ -389,7 +391,7 @@ const MintSheet = () => { type: 'nft', icon_url: imageUrl, address: mintCollection.id || '', - network: getChainsName()[chainId], + network: chainsName[chainId], name: mintCollection.name || '', decimals: 18, symbol: 'NFT', @@ -399,7 +401,7 @@ const MintSheet = () => { const paymentAsset = { type: 'nft', address: ETH_ADDRESS, - network: getChainsName()[chainId], + network: chainsName[chainId], name: mintCollection.publicMintInfo?.price?.currency?.name || 'Ethereum', decimals: mintCollection.publicMintInfo?.price?.currency?.decimals || 18, symbol: ETH_SYMBOL, @@ -412,7 +414,7 @@ const MintSheet = () => { to: item.data?.to, from: item.data?.from, hash: item.txHashes[0].txHash, - network: getChainsName()[chainId], + network: chainsName[chainId], nonce, changes: [ { @@ -704,7 +706,7 @@ const MintSheet = () => { )} - {`${getDefaultChains()[chainId].name}`} + {`${useBackendNetworksStore.getState().getDefaultChains()[chainId].name}`} diff --git a/src/screens/points/claim-flow/ClaimRewardsPanel.tsx b/src/screens/points/claim-flow/ClaimRewardsPanel.tsx index 67d16a48d77..3332490cd23 100644 --- a/src/screens/points/claim-flow/ClaimRewardsPanel.tsx +++ b/src/screens/points/claim-flow/ClaimRewardsPanel.tsx @@ -5,7 +5,7 @@ import { Bleed, Box, Text, TextShadow, globalColors, useBackgroundColor, useColo import * as i18n from '@/languages'; import { ListHeader, ListPanel, Panel, TapToDismiss, controlPanelStyles } from '@/components/SmoothPager/ListPanel'; import { ChainImage } from '@/components/coin-icon/ChainImage'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import ethereumUtils, { useNativeAsset } from '@/utils/ethereumUtils'; import { useAccountAccentColor, useAccountProfile, useAccountSettings } from '@/hooks'; import { safeAreaInsetValues } from '@/utils'; @@ -34,7 +34,7 @@ import { useMeteorologySuggestions } from '@/__swaps__/utils/meteorology'; import { AnimatedSpinner } from '@/components/animations/AnimatedSpinner'; import { RainbowError, logger } from '@/logger'; import { RewardsActionButton } from '../components/RewardsActionButton'; -import { getChainsLabel, getChainsName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; type ClaimStatus = 'idle' | 'claiming' | 'success' | PointsErrorType | 'error' | 'bridge-error'; type ClaimNetwork = '10' | '8453' | '7777777'; @@ -93,7 +93,7 @@ export const ClaimRewardsPanel = () => { const NETWORK_LIST_ITEMS = CLAIM_NETWORKS.map(chainId => { return { IconComponent: , - label: getChainsLabel()[chainId], + label: useBackendNetworksStore.getState().getChainsLabel()[chainId], uniqueId: chainId.toString(), selected: false, }; @@ -209,11 +209,12 @@ const ClaimingRewards = ({ nonce: number | null; }>({ mutationFn: async () => { + const chainsName = useBackendNetworksStore.getState().getChainsName(); // Fetch the native asset from the origin chain const opEth_ = await ethereumUtils.getNativeAssetForNetwork({ chainId: ChainId.optimism }); const opEth = { ...opEth_, - chainName: getChainsName()[ChainId.optimism], + chainName: chainsName[ChainId.optimism], }; // Fetch the native asset from the destination chain @@ -229,7 +230,7 @@ const ClaimingRewards = ({ // Add missing properties to match types const destinationEth = { ...destinationEth_, - chainName: getChainsName()[chainId as ChainId], + chainName: chainsName[chainId as ChainId], }; const selectedGas = { @@ -337,18 +338,19 @@ const ClaimingRewards = ({ }, [claimStatus]); const panelTitle = useMemo(() => { + const chainsLabel = useBackendNetworksStore.getState().getChainsLabel(); switch (claimStatus) { case 'idle': return i18n.t(i18n.l.points.points.claim_on_network, { - network: chainId ? getChainsLabel()[chainId] : '', + network: chainId ? chainsLabel[chainId] : '', }); case 'claiming': return i18n.t(i18n.l.points.points.claiming_on_network, { - network: chainId ? getChainsLabel()[chainId] : '', + network: chainId ? chainsLabel[chainId] : '', }); case 'success': return i18n.t(i18n.l.points.points.claimed_on_network, { - network: chainId ? getChainsLabel()[chainId] : '', + network: chainId ? chainsLabel[chainId] : '', }); case 'bridge-error': return i18n.t(i18n.l.points.points.bridge_error); @@ -494,7 +496,7 @@ const ClaimingRewards = ({ {i18n.t(i18n.l.points.points.bridge_error_explainer, { - network: chainId ? getChainsLabel()[chainId] : '', + network: chainId ? useBackendNetworksStore.getState().getChainsLabel()[chainId] : '', })} diff --git a/src/screens/points/components/LeaderboardRow.tsx b/src/screens/points/components/LeaderboardRow.tsx index 8d2d451ba3e..fff29344f13 100644 --- a/src/screens/points/components/LeaderboardRow.tsx +++ b/src/screens/points/components/LeaderboardRow.tsx @@ -18,7 +18,7 @@ import { useTheme } from '@/theme'; import LinearGradient from 'react-native-linear-gradient'; import { ButtonPressAnimation } from '@/components/animations'; import { noop } from 'lodash'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const ACTIONS = { ADD_CONTACT: 'add-contact', diff --git a/src/screens/points/content/PointsContent.tsx b/src/screens/points/content/PointsContent.tsx index 220ce06a933..83e9a84e2b1 100644 --- a/src/screens/points/content/PointsContent.tsx +++ b/src/screens/points/content/PointsContent.tsx @@ -62,7 +62,7 @@ import { format, intervalToDuration, isToday } from 'date-fns'; import { useRemoteConfig } from '@/model/remoteConfig'; import { ETH_REWARDS, useExperimentalFlag } from '@/config'; import { RewardsActionButton } from '../components/RewardsActionButton'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const InfoCards = ({ points }: { points: GetPointsDataForWalletQuery | undefined }) => { const labelSecondary = useForegroundColor('labelSecondary'); diff --git a/src/screens/points/contexts/PointsProfileContext.tsx b/src/screens/points/contexts/PointsProfileContext.tsx index d54395db617..543062caec5 100644 --- a/src/screens/points/contexts/PointsProfileContext.tsx +++ b/src/screens/points/contexts/PointsProfileContext.tsx @@ -16,7 +16,7 @@ import { useNavigation } from '@/navigation'; import { getProvider } from '@/handlers/web3'; import { analyticsV2 } from '@/analytics'; import { delay } from '@/utils/delay'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; type PointsProfileContext = { step: RainbowPointsFlowSteps; diff --git a/src/screens/positions/SubPositionListItem.tsx b/src/screens/positions/SubPositionListItem.tsx index aa3cc16e8cb..78c5527763d 100644 --- a/src/screens/positions/SubPositionListItem.tsx +++ b/src/screens/positions/SubPositionListItem.tsx @@ -10,7 +10,7 @@ import { NativeDisplay, PositionAsset } from '@/resources/defi/types'; import { useExternalToken } from '@/resources/assets/externalAssetsQuery'; import { useAccountSettings } from '@/hooks'; import RainbowCoinIcon from '@/components/coin-icon/RainbowCoinIcon'; -import { getChainsIdByName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; type Props = { asset: PositionAsset; @@ -23,7 +23,7 @@ type Props = { export const SubPositionListItem: React.FC = ({ asset, apy, quantity, native, positionColor }) => { const theme = useTheme(); const { nativeCurrency } = useAccountSettings(); - const chainId = getChainsIdByName()[asset.network]; + const chainId = useBackendNetworksStore.getState().getChainsIdByName()[asset.network]; const { data: externalAsset } = useExternalToken({ address: asset.asset_code, chainId, currency: nativeCurrency }); const priceChangeColor = (asset.price?.relative_change_24h || 0) < 0 ? theme.colors.blueGreyDark60 : theme.colors.green; diff --git a/src/screens/transaction-details/components/TransactionDetailsValueAndFeeSection.tsx b/src/screens/transaction-details/components/TransactionDetailsValueAndFeeSection.tsx index 15216791567..5bb152da3f5 100644 --- a/src/screens/transaction-details/components/TransactionDetailsValueAndFeeSection.tsx +++ b/src/screens/transaction-details/components/TransactionDetailsValueAndFeeSection.tsx @@ -15,7 +15,7 @@ import ImgixImage from '@/components/images/ImgixImage'; import { View } from 'react-native'; import ChainBadge from '@/components/coin-icon/ChainBadge'; import { checkForPendingSwap } from '../helpers/checkForPendingSwap'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; type Props = { transaction: RainbowTransaction; diff --git a/src/screens/transaction-details/components/TransactionMasthead.tsx b/src/screens/transaction-details/components/TransactionMasthead.tsx index 6516a3179d0..95e7f078d6d 100644 --- a/src/screens/transaction-details/components/TransactionMasthead.tsx +++ b/src/screens/transaction-details/components/TransactionMasthead.tsx @@ -34,7 +34,7 @@ import ImageAvatar from '@/components/contacts/ImageAvatar'; import RainbowCoinIcon from '@/components/coin-icon/RainbowCoinIcon'; import * as lang from '@/languages'; import { checkForPendingSwap } from '../helpers/checkForPendingSwap'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const TransactionMastheadHeight = android ? 153 : 135; diff --git a/src/state/appSessions/index.test.ts b/src/state/appSessions/index.test.ts index 71ca5d15697..2cfd0c8399a 100644 --- a/src/state/appSessions/index.test.ts +++ b/src/state/appSessions/index.test.ts @@ -1,4 +1,4 @@ -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { useAppSessionsStore } from '.'; const UNISWAP_HOST = 'uniswap.org'; diff --git a/src/state/appSessions/index.ts b/src/state/appSessions/index.ts index 02128c94c47..ee5400779ca 100644 --- a/src/state/appSessions/index.ts +++ b/src/state/appSessions/index.ts @@ -1,6 +1,6 @@ import { Address } from 'viem'; -import { Network, ChainId } from '@/chains/types'; +import { Network, ChainId } from '@/state/backendNetworks/types'; import { createRainbowStore } from '../internal/createRainbowStore'; const chainsIdByNetwork: Record = { diff --git a/src/state/assets/userAssets.ts b/src/state/assets/userAssets.ts index e4e41f5d870..125ab01ba02 100644 --- a/src/state/assets/userAssets.ts +++ b/src/state/assets/userAssets.ts @@ -7,8 +7,8 @@ import { createRainbowStore } from '@/state/internal/createRainbowStore'; import { useStore } from 'zustand'; import { useCallback } from 'react'; import { swapsStore } from '@/state/swaps/swapsStore'; -import { ChainId } from '@/chains/types'; -import { getSupportedChainIds } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { useSelector } from 'react-redux'; const SEARCH_CACHE_MAX_ENTRIES = 50; @@ -20,7 +20,7 @@ const getDefaultCacheKeys = (): Set => { const queryKeysToPreserve = new Set(); queryKeysToPreserve.add('all'); - for (const chainId of getSupportedChainIds()) { + for (const chainId of useBackendNetworksStore.getState().getSupportedChainIds()) { queryKeysToPreserve.add(`${chainId}`); } return queryKeysToPreserve; @@ -281,12 +281,15 @@ export const createUserAssetsStore = (address: Address | string) => }); // Ensure all supported chains are in the map with a fallback value of 0 - getSupportedChainIds().forEach(chainId => { - if (!unsortedChainBalances.has(chainId)) { - unsortedChainBalances.set(chainId, 0); - idsByChain.set(chainId, []); - } - }); + useBackendNetworksStore + .getState() + .getSupportedChainIds() + .forEach(chainId => { + if (!unsortedChainBalances.has(chainId)) { + unsortedChainBalances.set(chainId, 0); + idsByChain.set(chainId, []); + } + }); // Sort the existing map by balance in descending order const sortedEntries = Array.from(unsortedChainBalances.entries()).sort(([, balanceA], [, balanceB]) => balanceB - balanceA); diff --git a/src/state/backendNetworks/backendNetworks.ts b/src/state/backendNetworks/backendNetworks.ts index 110d25766b1..e656c780bd5 100644 --- a/src/state/backendNetworks/backendNetworks.ts +++ b/src/state/backendNetworks/backendNetworks.ts @@ -3,19 +3,328 @@ import { queryClient } from '@/react-query'; import buildTimeNetworks from '@/references/networks.json'; import { backendNetworksQueryKey, BackendNetworksResponse } from '@/resources/metadata/backendNetworks'; import { createRainbowStore } from '@/state/internal/createRainbowStore'; +import { Chain } from 'viem/chains'; +import { transformBackendNetworksToChains } from '@/state/backendNetworks/utils'; +import { IS_TEST } from '@/env'; +import { BackendNetwork, BackendNetworkServices, chainHardhat, chainHardhatOptimism, ChainId } from '@/state/backendNetworks/types'; +import { GasSpeed } from '@/__swaps__/types/gas'; +import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; const INITIAL_BACKEND_NETWORKS = queryClient.getQueryData(backendNetworksQueryKey()) ?? buildTimeNetworks; export interface BackendNetworksState { backendNetworks: BackendNetworksResponse; backendNetworksSharedValue: SharedValue; + + getBackendChains: () => Chain[]; + getSupportedChains: () => Chain[]; + + getDefaultChains: () => Record; + getSupportedChainIds: () => ChainId[]; + getSupportedMainnetChains: () => Chain[]; + getSupportedMainnetChainIds: () => ChainId[]; + getNeedsL1SecurityFeeChains: () => ChainId[]; + getChainsNativeAsset: () => Record; + getChainsLabel: () => Record; + getChainsName: () => Record; + getChainsIdByName: () => Record; + + defaultGasSpeeds: (chainId: ChainId) => GasSpeed[]; + + getChainsGasSpeeds: () => Record; + defaultPollingInterval: (chainId: ChainId) => number; + getChainsPollingInterval: () => Record; + + defaultSimplehashNetwork: (chainId: ChainId) => string; + getChainsSimplehashNetwork: () => Record; + filterChainIdsByService: (servicePath: (services: BackendNetworkServices) => boolean) => ChainId[]; + + getMeteorologySupportedChainIds: () => ChainId[]; + getSwapSupportedChainIds: () => ChainId[]; + getSwapExactOutputSupportedChainIds: () => ChainId[]; + getBridgeExactOutputSupportedChainIds: () => ChainId[]; + getNotificationsSupportedChainIds: () => ChainId[]; + getApprovalsSupportedChainIds: () => ChainId[]; + getTransactionsSupportedChainIds: () => ChainId[]; + getSupportedAssetsChainIds: () => ChainId[]; + getSupportedPositionsChainIds: () => ChainId[]; + getTokenSearchSupportedChainIds: () => ChainId[]; + getNftSupportedChainIds: () => ChainId[]; + getFlashbotsSupportedChainIds: () => ChainId[]; + getShouldDefaultToFastGasChainIds: () => ChainId[]; + + getChainGasUnits: (chainId?: ChainId) => BackendNetwork['gasUnits']; + getChainDefaultRpc: (chainId: ChainId) => string; + setBackendNetworks: (backendNetworks: BackendNetworksResponse) => void; } -export const useBackendNetworksStore = createRainbowStore(set => ({ +export const useBackendNetworksStore = createRainbowStore((set, get) => ({ backendNetworks: INITIAL_BACKEND_NETWORKS, backendNetworksSharedValue: makeMutable(INITIAL_BACKEND_NETWORKS), + getBackendChains: () => { + const { backendNetworks } = get(); + return transformBackendNetworksToChains(backendNetworks.networks); + }, + + getSupportedChains: () => { + const backendChains = get().getBackendChains(); + return IS_TEST ? [...backendChains, chainHardhat, chainHardhatOptimism] : backendChains; + }, + + getDefaultChains: () => { + const supportedChains = get().getSupportedChains(); + return supportedChains.reduce( + (acc, chain) => { + acc[chain.id] = chain; + return acc; + }, + {} as Record + ); + }, + + getSupportedChainIds: () => { + const supportedChains = get().getSupportedChains(); + return supportedChains.map(chain => chain.id); + }, + + getSupportedMainnetChains: () => { + const supportedChains = get().getSupportedChains(); + return supportedChains.filter(chain => !chain.testnet); + }, + + getSupportedMainnetChainIds: () => { + const supportedMainnetChains = get().getSupportedMainnetChains(); + return supportedMainnetChains.map(chain => chain.id); + }, + + getNeedsL1SecurityFeeChains: () => { + const backendNetworks = get().backendNetworks; + return backendNetworks.networks + .filter((backendNetwork: BackendNetwork) => backendNetwork.opStack) + .map((backendNetwork: BackendNetwork) => parseInt(backendNetwork.id, 10)); + }, + + getChainsNativeAsset: () => { + const backendNetworks = get().backendNetworks; + return backendNetworks.networks.reduce( + (acc, backendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = backendNetwork.nativeAsset; + return acc; + }, + {} as Record + ); + }, + + getChainsLabel: () => { + const backendNetworks = get().backendNetworks; + return backendNetworks.networks.reduce( + (acc, backendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = backendNetwork.label; + return acc; + }, + {} as Record + ); + }, + + getChainsName: () => { + const backendNetworks = get().backendNetworks; + return backendNetworks.networks.reduce( + (acc, backendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = backendNetwork.name; + return acc; + }, + {} as Record + ); + }, + + getChainsIdByName: () => { + const backendNetworks = get().backendNetworks; + return backendNetworks.networks.reduce( + (acc, backendNetwork) => { + acc[backendNetwork.name] = parseInt(backendNetwork.id, 10); + return acc; + }, + {} as Record + ); + }, + + // TODO: This should come from the backend at some point + defaultGasSpeeds: chainId => { + switch (chainId) { + case ChainId.bsc: + case ChainId.goerli: + case ChainId.polygon: + return [GasSpeed.NORMAL, GasSpeed.FAST, GasSpeed.URGENT]; + case ChainId.gnosis: + return [GasSpeed.NORMAL]; + default: + return [GasSpeed.NORMAL, GasSpeed.FAST, GasSpeed.URGENT, GasSpeed.CUSTOM]; + } + }, + + getChainsGasSpeeds: () => { + const backendNetworks = get().backendNetworks; + return backendNetworks.networks.reduce( + (acc, backendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = get().defaultGasSpeeds(parseInt(backendNetwork.id, 10)); + return acc; + }, + {} as Record + ); + }, + + defaultPollingInterval: chainId => { + switch (chainId) { + case ChainId.polygon: + return 2_000; + case ChainId.arbitrum: + case ChainId.bsc: + return 3_000; + default: + return 5_000; + } + }, + + getChainsPollingInterval: () => { + const backendNetworks = get().backendNetworks; + return backendNetworks.networks.reduce( + (acc, backendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = get().defaultPollingInterval(parseInt(backendNetwork.id, 10)); + return acc; + }, + {} as Record + ); + }, + + // TODO: This should come from the backend at some point + defaultSimplehashNetwork: chainId => { + switch (chainId) { + case ChainId.apechain: + return 'apechain'; + case ChainId.arbitrum: + return 'arbitrum'; + case ChainId.avalanche: + return 'avalanche'; + case ChainId.base: + return 'base'; + case ChainId.blast: + return 'blast'; + case ChainId.bsc: + return 'bsc'; + case ChainId.degen: + return 'degen'; + case ChainId.gnosis: + return 'gnosis'; + case ChainId.goerli: + return 'ethereum-goerli'; + case ChainId.mainnet: + return 'ethereum'; + case ChainId.optimism: + return 'optimism'; + case ChainId.polygon: + return 'polygon'; + case ChainId.zora: + return 'zora'; + default: + return ''; + } + }, + + getChainsSimplehashNetwork: () => { + const backendNetworks = get().backendNetworks; + return backendNetworks.networks.reduce( + (acc, backendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = get().defaultSimplehashNetwork(parseInt(backendNetwork.id, 10)); + return acc; + }, + {} as Record + ); + }, + + filterChainIdsByService: servicePath => { + const backendNetworks = get().backendNetworks; + return backendNetworks.networks.filter(network => servicePath(network.enabledServices)).map(network => parseInt(network.id, 10)); + }, + + getMeteorologySupportedChainIds: () => { + return get().filterChainIdsByService(services => services.meteorology.enabled); + }, + + getSwapSupportedChainIds: () => { + return get().filterChainIdsByService(services => services.swap.enabled); + }, + + getSwapExactOutputSupportedChainIds: () => { + return get().filterChainIdsByService(services => services.swap.swapExactOutput); + }, + + getBridgeExactOutputSupportedChainIds: () => { + return get().filterChainIdsByService(services => services.swap.bridgeExactOutput); + }, + + getNotificationsSupportedChainIds: () => { + return get().filterChainIdsByService(services => services.notifications.enabled); + }, + + getApprovalsSupportedChainIds: () => { + return get().filterChainIdsByService(services => services.addys.approvals); + }, + + getTransactionsSupportedChainIds: () => { + return get().filterChainIdsByService(services => services.addys.transactions); + }, + + getSupportedAssetsChainIds: () => { + return get().filterChainIdsByService(services => services.addys.assets); + }, + + getSupportedPositionsChainIds: () => { + return get().filterChainIdsByService(services => services.addys.positions); + }, + + getTokenSearchSupportedChainIds: () => { + return get().filterChainIdsByService(services => services.tokenSearch.enabled); + }, + + getNftSupportedChainIds: () => { + return get().filterChainIdsByService(services => services.nftProxy.enabled); + }, + + getFlashbotsSupportedChainIds: () => { + return [ChainId.mainnet]; + }, + + getShouldDefaultToFastGasChainIds: () => { + return [ChainId.mainnet, ChainId.polygon, ChainId.goerli]; + }, + + getChainGasUnits: chainId => { + const backendNetworks = get().backendNetworks; + const chainsGasUnits = backendNetworks.networks.reduce( + (acc, backendNetwork: BackendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = backendNetwork.gasUnits; + return acc; + }, + {} as Record + ); + + return (chainId ? chainsGasUnits[chainId] : undefined) || chainsGasUnits[ChainId.mainnet]; + }, + + getChainDefaultRpc: chainId => { + const defaultChains = get().getDefaultChains(); + switch (chainId) { + case ChainId.mainnet: + return useConnectedToHardhatStore.getState().connectedToHardhat + ? 'http://127.0.0.1:8545' + : defaultChains[ChainId.mainnet].rpcUrls.default.http[0]; + default: + return defaultChains[chainId].rpcUrls.default.http[0]; + } + }, + setBackendNetworks: backendNetworks => set(state => { state.backendNetworksSharedValue.value = backendNetworks; @@ -25,3 +334,290 @@ export const useBackendNetworksStore = createRainbowStore( }; }), })); + +// ------ WORKLET FUNCTIONS ------ + +export const getBackendChainsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return transformBackendNetworksToChains(backendNetworks.value.networks); +}; + +export const getSupportedChainsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + const backendChains = getBackendChainsWorklet(backendNetworks); + return IS_TEST ? [...backendChains, chainHardhat, chainHardhatOptimism] : backendChains; +}; + +export const getDefaultChainsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + const supportedChains = getSupportedChainsWorklet(backendNetworks); + return supportedChains.reduce( + (acc, chain) => { + acc[chain.id] = chain; + return acc; + }, + {} as Record + ); +}; + +export const getSupportedChainIdsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + const supportedChains = getSupportedChainsWorklet(backendNetworks); + return supportedChains.map(chain => chain.id); +}; + +export const getSupportedMainnetChainsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + const supportedChains = getSupportedChainsWorklet(backendNetworks); + return supportedChains.filter(chain => !chain.testnet); +}; + +export const getSupportedMainnetChainIdsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + const supportedMainnetChains = getSupportedMainnetChainsWorklet(backendNetworks); + return supportedMainnetChains.map(chain => chain.id); +}; + +export const getNeedsL1SecurityFeeChainsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return backendNetworks.value.networks + .filter((backendNetwork: BackendNetwork) => backendNetwork.opStack) + .map((backendNetwork: BackendNetwork) => parseInt(backendNetwork.id, 10)); +}; + +export const getChainsNativeAssetWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return backendNetworks.value.networks.reduce( + (acc, backendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = backendNetwork.nativeAsset; + return acc; + }, + {} as Record + ); +}; + +export const getChainsLabelWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return backendNetworks.value.networks.reduce( + (acc, backendNetwork: BackendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = backendNetwork.label; + return acc; + }, + {} as Record + ); +}; + +export const getChainsNameWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return backendNetworks.value.networks.reduce( + (acc, backendNetwork: BackendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = backendNetwork.name; + return acc; + }, + {} as Record + ); +}; + +export const getChainsIdByNameWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return backendNetworks.value.networks.reduce( + (acc, backendNetwork) => { + acc[backendNetwork.name] = parseInt(backendNetwork.id, 10); + return acc; + }, + {} as Record + ); +}; + +export const defaultGasSpeedsWorklet = (chainId: ChainId) => { + 'worklet'; + switch (chainId) { + case ChainId.bsc: + case ChainId.goerli: + case ChainId.polygon: + return [GasSpeed.NORMAL, GasSpeed.FAST, GasSpeed.URGENT]; + case ChainId.gnosis: + return [GasSpeed.NORMAL]; + default: + return [GasSpeed.NORMAL, GasSpeed.FAST, GasSpeed.URGENT, GasSpeed.CUSTOM]; + } +}; + +export const getChainsGasSpeedsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return backendNetworks.value.networks.reduce( + (acc, backendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = defaultGasSpeedsWorklet(parseInt(backendNetwork.id, 10)); + return acc; + }, + {} as Record + ); +}; + +export const defaultPollingIntervalWorklet = (chainId: ChainId) => { + 'worklet'; + switch (chainId) { + case ChainId.polygon: + return 2_000; + case ChainId.arbitrum: + case ChainId.bsc: + return 3_000; + default: + return 5_000; + } +}; + +export const getChainsPollingIntervalWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return backendNetworks.value.networks.reduce( + (acc, backendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = defaultPollingIntervalWorklet(parseInt(backendNetwork.id, 10)); + return acc; + }, + {} as Record + ); +}; + +export const defaultSimplehashNetworkWorklet = (chainId: ChainId) => { + 'worklet'; + switch (chainId) { + case ChainId.apechain: + return 'apechain'; + case ChainId.arbitrum: + return 'arbitrum'; + case ChainId.avalanche: + return 'avalanche'; + case ChainId.base: + return 'base'; + case ChainId.blast: + return 'blast'; + case ChainId.bsc: + return 'bsc'; + case ChainId.degen: + return 'degen'; + case ChainId.gnosis: + return 'gnosis'; + case ChainId.goerli: + return 'ethereum-goerli'; + case ChainId.mainnet: + return 'ethereum'; + case ChainId.optimism: + return 'optimism'; + case ChainId.polygon: + return 'polygon'; + case ChainId.zora: + return 'zora'; + default: + return ''; + } +}; + +export const getChainsSimplehashNetworkWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return backendNetworks.value.networks.reduce( + (acc, backendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = defaultSimplehashNetworkWorklet(parseInt(backendNetwork.id, 10)); + return acc; + }, + {} as Record + ); +}; + +export const filterChainIdsByServiceWorklet = ( + backendNetworks: SharedValue, + servicePath: (services: BackendNetworkServices) => boolean +) => { + 'worklet'; + return backendNetworks.value.networks.filter(network => servicePath(network.enabledServices)).map(network => parseInt(network.id, 10)); +}; + +export const getMeteorologySupportedChainIdsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return filterChainIdsByServiceWorklet(backendNetworks, services => services.meteorology.enabled); +}; + +export const getSwapSupportedChainIdsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return filterChainIdsByServiceWorklet(backendNetworks, services => services.swap.enabled); +}; + +export const getSwapExactOutputSupportedChainIdsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return filterChainIdsByServiceWorklet(backendNetworks, services => services.swap.swapExactOutput); +}; + +export const getBridgeExactOutputSupportedChainIdsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return filterChainIdsByServiceWorklet(backendNetworks, services => services.swap.bridgeExactOutput); +}; + +export const getNotificationsSupportedChainIdsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return filterChainIdsByServiceWorklet(backendNetworks, services => services.notifications.enabled); +}; + +export const getApprovalsSupportedChainIdsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return filterChainIdsByServiceWorklet(backendNetworks, services => services.addys.approvals); +}; + +export const getTransactionsSupportedChainIdsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return filterChainIdsByServiceWorklet(backendNetworks, services => services.addys.transactions); +}; + +export const getSupportedAssetsChainIdsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return filterChainIdsByServiceWorklet(backendNetworks, services => services.addys.assets); +}; + +export const getSupportedPositionsChainIdsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return filterChainIdsByServiceWorklet(backendNetworks, services => services.addys.positions); +}; + +export const getTokenSearchSupportedChainIdsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return filterChainIdsByServiceWorklet(backendNetworks, services => services.tokenSearch.enabled); +}; + +export const getNftSupportedChainIdsWorklet = (backendNetworks: SharedValue) => { + 'worklet'; + return filterChainIdsByServiceWorklet(backendNetworks, services => services.nftProxy.enabled); +}; + +export const getFlashbotsSupportedChainIdsWorklet = (_?: SharedValue) => { + 'worklet'; + return [ChainId.mainnet]; +}; + +export const getShouldDefaultToFastGasChainIdsWorklet = (_?: SharedValue) => { + 'worklet'; + return [ChainId.mainnet, ChainId.polygon, ChainId.goerli]; +}; + +export const getChainGasUnitsWorklet = (backendNetworks: SharedValue, chainId?: ChainId) => { + 'worklet'; + const chainsGasUnits = backendNetworks.value.networks.reduce( + (acc, backendNetwork: BackendNetwork) => { + acc[parseInt(backendNetwork.id, 10)] = backendNetwork.gasUnits; + return acc; + }, + {} as Record + ); + + return (chainId ? chainsGasUnits[chainId] : undefined) || chainsGasUnits[ChainId.mainnet]; +}; + +export const getChainDefaultRpcWorklet = (backendNetworks: SharedValue, chainId: ChainId) => { + 'worklet'; + const defaultChains = getDefaultChainsWorklet(backendNetworks); + switch (chainId) { + case ChainId.mainnet: + return useConnectedToHardhatStore.getState().connectedToHardhat + ? 'http://127.0.0.1:8545' + : defaultChains[ChainId.mainnet].rpcUrls.default.http[0]; + default: + return defaultChains[chainId].rpcUrls.default.http[0]; + } +}; diff --git a/src/chains/types.ts b/src/state/backendNetworks/types.ts similarity index 100% rename from src/chains/types.ts rename to src/state/backendNetworks/types.ts diff --git a/src/chains/utils/backendNetworks.ts b/src/state/backendNetworks/utils.ts similarity index 96% rename from src/chains/utils/backendNetworks.ts rename to src/state/backendNetworks/utils.ts index 0082b40abd0..2242f3042c1 100644 --- a/src/chains/utils/backendNetworks.ts +++ b/src/state/backendNetworks/utils.ts @@ -2,7 +2,7 @@ import { Chain } from 'viem'; import { mainnet } from 'viem/chains'; import { IS_DEV, RPC_PROXY_API_KEY } from '@/env'; -import { BackendNetwork } from '../types'; +import { BackendNetwork } from './types'; const proxyBackendNetworkRpcEndpoint = (endpoint: string) => { return `${endpoint}${RPC_PROXY_API_KEY}`; diff --git a/src/state/nonces/index.ts b/src/state/nonces/index.ts index cc011f369e5..100a3659aea 100644 --- a/src/state/nonces/index.ts +++ b/src/state/nonces/index.ts @@ -1,8 +1,8 @@ import create from 'zustand'; import { createStore } from '../internal/createStore'; -import { Network, ChainId } from '@/chains/types'; +import { Network, ChainId } from '@/state/backendNetworks/types'; import { getProvider } from '@/handlers/web3'; -import { getChainsIdByName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; type NonceData = { currentNonce?: number; @@ -75,6 +75,7 @@ export const nonceStore = createStore>( version: 1, migrate: (persistedState: unknown, version: number) => { if (version === 0) { + const chainsIdByName = useBackendNetworksStore.getState().getChainsIdByName(); const oldState = persistedState as CurrentNonceState; const newNonces: CurrentNonceState['nonces'] = {}; for (const [address, networkNonces] of Object.entries(oldState.nonces)) { @@ -82,7 +83,7 @@ export const nonceStore = createStore>( if (!newNonces[address]) { newNonces[address] = {} as Record; } - newNonces[address][getChainsIdByName()[network as Network]] = nonceData; + newNonces[address][chainsIdByName[network as Network]] = nonceData; } } return { diff --git a/src/state/pendingTransactions/index.ts b/src/state/pendingTransactions/index.ts index 34896c3d006..07ab62618e2 100644 --- a/src/state/pendingTransactions/index.ts +++ b/src/state/pendingTransactions/index.ts @@ -3,7 +3,7 @@ import { createStore } from '../internal/createStore'; import create from 'zustand'; import { convertNewTransactionToRainbowTransaction } from '@/parsers/transactions'; import { nonceStore } from '../nonces'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; export interface PendingTransactionsState { pendingTransactions: Record; diff --git a/src/state/staleBalances/index.test.ts b/src/state/staleBalances/index.test.ts index 02cc65c3c24..f911b5ac423 100644 --- a/src/state/staleBalances/index.test.ts +++ b/src/state/staleBalances/index.test.ts @@ -3,7 +3,7 @@ import { Address } from 'viem'; import { staleBalancesStore } from '.'; import { DAI_ADDRESS, OP_ADDRESS } from '@/references'; import { ETH_ADDRESS } from '@rainbow-me/swaps'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const TEST_ADDRESS_1 = '0xFOO'; const TEST_ADDRESS_2 = '0xBAR'; diff --git a/src/state/swaps/swapsStore.ts b/src/state/swaps/swapsStore.ts index 1ff21fe247a..3651156ba11 100644 --- a/src/state/swaps/swapsStore.ts +++ b/src/state/swaps/swapsStore.ts @@ -2,7 +2,7 @@ import { MIN_FLASHBOTS_PRIORITY_FEE } from '@/__swaps__/screens/Swap/constants'; import { getCustomGasSettings, setCustomMaxPriorityFee } from '@/__swaps__/screens/Swap/hooks/useCustomGas'; import { getSelectedGasSpeed } from '@/__swaps__/screens/Swap/hooks/useSelectedGas'; import { ExtendedAnimatedAssetWithColors, ParsedSearchAsset } from '@/__swaps__/types/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { GasSpeed } from '@/__swaps__/types/gas'; import { RecentSwap } from '@/__swaps__/types/swap'; import { getCachedGasSuggestions } from '@/__swaps__/utils/meteorology'; diff --git a/src/state/sync/UserAssetsSync.tsx b/src/state/sync/UserAssetsSync.tsx index 0eb9dff87be..48c2e137597 100644 --- a/src/state/sync/UserAssetsSync.tsx +++ b/src/state/sync/UserAssetsSync.tsx @@ -4,7 +4,7 @@ import { useSwapsStore } from '@/state/swaps/swapsStore'; import { selectUserAssetsList, selectorFilterByUserChains } from '@/__swaps__/screens/Swap/resources/_selectors/assets'; import { ParsedSearchAsset } from '@/__swaps__/types/assets'; import { useUserAssets } from '@/__swaps__/screens/Swap/resources/assets'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; export const UserAssetsSync = function UserAssetsSync() { const { accountAddress, nativeCurrency: currentCurrency } = useAccountSettings(); diff --git a/src/storage/index.ts b/src/storage/index.ts index 1014ce03dbf..db4e2d88ca1 100644 --- a/src/storage/index.ts +++ b/src/storage/index.ts @@ -3,7 +3,7 @@ import { MMKV } from 'react-native-mmkv'; import { Account, Cards, Campaigns, Device, Review, WatchedWalletCohort } from '@/storage/schema'; import { EthereumAddress, RainbowTransaction } from '@/entities'; import { SecureStorage } from '@coinbase/mobile-wallet-protocol-host'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; /** * Generic storage class. DO NOT use this directly. Instead, use the exported diff --git a/src/styles/colors.ts b/src/styles/colors.ts index b1bfe39c376..0cdac9387af 100644 --- a/src/styles/colors.ts +++ b/src/styles/colors.ts @@ -3,7 +3,7 @@ import PropTypes from 'prop-types'; import { globalColors } from '@/design-system'; import currentColors from '../theme/currentColors'; import { memoFn } from '../utils/memoFn'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; export type Colors = ReturnType; diff --git a/src/utils/ethereumUtils.ts b/src/utils/ethereumUtils.ts index 85ee57d39ab..854a08646b8 100644 --- a/src/utils/ethereumUtils.ts +++ b/src/utils/ethereumUtils.ts @@ -49,13 +49,13 @@ import { fetchExternalToken, useExternalToken, } from '@/resources/assets/externalAssetsQuery'; -import { ChainId, Network } from '@/chains/types'; +import { ChainId, Network } from '@/state/backendNetworks/types'; import { AddressOrEth } from '@/__swaps__/types/assets'; -import { getChainsIdByName, getChainsName, getChainsNativeAsset, getDefaultChains, getChainGasUnits } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; const getNetworkNativeAsset = ({ chainId }: { chainId: ChainId }) => { - const nativeAssetAddress = getChainsNativeAsset()[chainId].address; + const nativeAssetAddress = useBackendNetworksStore.getState().getChainsNativeAsset()[chainId].address; const nativeAssetUniqueId = getUniqueId(nativeAssetAddress, chainId); return getAccountAsset(nativeAssetUniqueId); }; @@ -74,7 +74,7 @@ export const getNativeAssetForNetwork = async ({ // If the asset is on a different wallet, or not available in this wallet if (differentWallet || !nativeAsset) { - const chainNativeAsset = getChainsNativeAsset()[chainId]; + const chainNativeAsset = useBackendNetworksStore.getState().getChainsNativeAsset()[chainId]; const mainnetAddress = chainNativeAsset?.address || ETH_ADDRESS; const nativeAssetAddress = chainNativeAsset.address as AddressOrEth; @@ -89,7 +89,7 @@ export const getNativeAssetForNetwork = async ({ // @ts-ignore nativeAsset = { ...externalAsset, - network: getChainsName()[chainId], + network: useBackendNetworksStore.getState().getChainsName()[chainId], uniqueId: getUniqueId(chainNativeAsset.address, chainId), address: chainNativeAsset.address, decimals: chainNativeAsset.decimals, @@ -177,7 +177,7 @@ const getAssetPrice = (address: EthereumAddress = ETH_ADDRESS): number => { export const useNativeAsset = ({ chainId }: { chainId: ChainId }) => { const { nativeCurrency } = store.getState().settings; - const address = (getChainsNativeAsset()[chainId]?.address || ETH_ADDRESS) as AddressOrEth; + const address = (useBackendNetworksStore.getState().getChainsNativeAsset()[chainId]?.address || ETH_ADDRESS) as AddressOrEth; const { data: nativeAsset } = useExternalToken({ address, @@ -280,8 +280,8 @@ const getDataString = (func: string, arrVals: string[]) => { */ function getEtherscanHostForNetwork({ chainId }: { chainId: ChainId }): string { const base_host = 'etherscan.io'; - const blockExplorer = getDefaultChains()[chainId]?.blockExplorers?.default?.url; - const network = getChainsName()[chainId]; + const blockExplorer = useBackendNetworksStore.getState().getDefaultChains()[chainId]?.blockExplorers?.default?.url; + const network = useBackendNetworksStore.getState().getChainsName()[chainId]; if (network && isTestnetChain({ chainId })) { return `${network}.${base_host}`; @@ -356,29 +356,29 @@ export const getFirstTransactionTimestamp = async (address: EthereumAddress): Pr }; function getBlockExplorer({ chainId }: { chainId: ChainId }) { - return getDefaultChains()[chainId]?.blockExplorers?.default.name || 'etherscan'; + return useBackendNetworksStore.getState().getDefaultChains()[chainId]?.blockExplorers?.default.name || 'etherscan'; } function openAddressInBlockExplorer({ address, chainId }: { address: EthereumAddress; chainId: ChainId }) { - const explorer = getDefaultChains()[chainId]?.blockExplorers?.default?.url; + const explorer = useBackendNetworksStore.getState().getDefaultChains()[chainId]?.blockExplorers?.default?.url; Linking.openURL(`${explorer}/address/${address}`); } function openTokenEtherscanURL({ address, chainId }: { address: EthereumAddress; chainId: ChainId }) { if (!isString(address)) return; - const explorer = getDefaultChains()[chainId]?.blockExplorers?.default?.url; + const explorer = useBackendNetworksStore.getState().getDefaultChains()[chainId]?.blockExplorers?.default?.url; Linking.openURL(`${explorer}/token/${address}`); } function openNftInBlockExplorer({ contractAddress, tokenId, chainId }: { contractAddress: string; tokenId: string; chainId: ChainId }) { - const explorer = getDefaultChains()[chainId]?.blockExplorers?.default?.url; + const explorer = useBackendNetworksStore.getState().getDefaultChains()[chainId]?.blockExplorers?.default?.url; Linking.openURL(`${explorer}/token/${contractAddress}?a=${tokenId}`); } function openTransactionInBlockExplorer({ hash, chainId }: { hash: string; chainId: ChainId }) { const normalizedHash = hash.replace(/-.*/g, ''); if (!isString(hash)) return; - const explorer = getDefaultChains()[chainId]?.blockExplorers?.default?.url; + const explorer = useBackendNetworksStore.getState().getDefaultChains()[chainId]?.blockExplorers?.default?.url; Linking.openURL(`${explorer}/tx/${normalizedHash}`); } @@ -394,14 +394,14 @@ async function parseEthereumUrl(data: string) { const functionName = ethUrl.function_name; let asset = null; const chainId = (ethUrl.chain_id as ChainId) || ChainId.mainnet; - const network = getChainsName()[chainId]; + const network = useBackendNetworksStore.getState().getChainsName()[chainId]; let address: any = null; let nativeAmount: any = null; const { nativeCurrency } = store.getState().settings; if (!functionName) { // Send native asset - const chainId = getChainsIdByName()[network]; + const chainId = useBackendNetworksStore.getState().getChainsIdByName()[network]; asset = getNetworkNativeAsset({ chainId }); // @ts-ignore @@ -457,7 +457,7 @@ export const getAddressAndChainIdFromUniqueId = (uniqueId: string): { address: A // If the unique ID contains '_', the last part is the network and the rest is the address const network = parts[1] as Network; // Assuming the last part is a valid Network enum value const address = parts[0] as AddressOrEth; - const chainId = getChainsIdByName()[network]; + const chainId = useBackendNetworksStore.getState().getChainsIdByName()[network]; return { address, chainId }; }; @@ -509,7 +509,7 @@ const calculateL1FeeOptimism = async ( }; const getBasicSwapGasLimit = (chainId: ChainId) => { - return Number(getChainGasUnits(chainId).basic.swap); + return Number(useBackendNetworksStore.getState().getChainGasUnits(chainId).basic.swap); }; export default { diff --git a/src/utils/getUrlForTrustIconFallback.ts b/src/utils/getUrlForTrustIconFallback.ts index e2768840d2d..53509e2b121 100644 --- a/src/utils/getUrlForTrustIconFallback.ts +++ b/src/utils/getUrlForTrustIconFallback.ts @@ -1,6 +1,6 @@ -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { EthereumAddress } from '@/entities'; -import { getChainsName } from '@/chains'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; export default function getUrlForTrustIconFallback(address: EthereumAddress, chainId: ChainId): string | null { if (!address) return null; @@ -13,7 +13,7 @@ export default function getUrlForTrustIconFallback(address: EthereumAddress, cha networkPath = 'smartchain'; break; default: - networkPath = getChainsName()[chainId]; + networkPath = useBackendNetworksStore.getState().getChainsName()[chainId]; } return `https://rainbowme-res.cloudinary.com/image/upload/assets/${networkPath}/${address}.png`; } diff --git a/src/utils/requestNavigationHandlers.ts b/src/utils/requestNavigationHandlers.ts index c48d68ef87a..7d4f67ba750 100644 --- a/src/utils/requestNavigationHandlers.ts +++ b/src/utils/requestNavigationHandlers.ts @@ -34,8 +34,8 @@ import { noop } from 'lodash'; import { toUtf8String } from '@ethersproject/strings'; import { BigNumber } from '@ethersproject/bignumber'; import { Address } from 'viem'; -import { ChainId } from '@/chains/types'; -import { getChainsName, getSupportedMainnetChainIds } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { MobileWalletProtocolUserErrors } from '@/components/MobileWalletProtocolListener'; import { hideWalletConnectToast } from '@/components/toasts/WalletConnectToast'; @@ -123,7 +123,7 @@ export const handleMobileWalletProtocolRequest = async ({ const routeParams: WalletconnectApprovalSheetRouteParams = { receivedTimestamp, meta: { - chainIds: getSupportedMainnetChainIds(), + chainIds: useBackendNetworksStore.getState().getSupportedMainnetChainIds(), dappName: dappMetadata?.appName || dappMetadata?.appUrl || action.appName || action.appIconUrl || action.appId || '', dappUrl: dappMetadata?.appUrl || action.appId || '', imageUrl: maybeSignUri(dappMetadata?.iconUrl || action.appIconUrl), @@ -169,7 +169,10 @@ export const handleMobileWalletProtocolRequest = async ({ } if (action.method === 'wallet_switchEthereumChain') { - const isSupportedChain = getSupportedMainnetChainIds().includes(BigNumber.from(action.params.chainId).toNumber()); + const isSupportedChain = useBackendNetworksStore + .getState() + .getSupportedMainnetChainIds() + .includes(BigNumber.from(action.params.chainId).toNumber()); if (!isSupportedChain) { await rejectAction(action, { message: 'Unsupported chain', @@ -301,7 +304,7 @@ export const handleDappBrowserConnectionPrompt = ( const routeParams: WalletconnectApprovalSheetRouteParams = { receivedTimestamp, meta: { - chainIds: getSupportedMainnetChainIds(), + chainIds: useBackendNetworksStore.getState().getSupportedMainnetChainIds(), dappName: dappData?.dappName || dappData.dappUrl, dappUrl: dappData.dappUrl, imageUrl: maybeSignUri(dappData.imageUrl), @@ -404,7 +407,7 @@ export const handleWalletConnectRequest = async (request: WalletconnectRequestDa // @ts-expect-error Property '_chainId' is private and only accessible within class 'Connector'.ts(2341) const chainId = request?.walletConnectV2RequestValues?.chainId || walletConnector?._chainId; - const network = getChainsName()[chainId]; + const network = useBackendNetworksStore.getState().getChainsName()[chainId]; // @ts-expect-error Property '_accounts' is private and only accessible within class 'Connector'.ts(2341) const address = request?.walletConnectV2RequestValues?.address || walletConnector?._accounts?.[0]; diff --git a/src/walletConnect/index.tsx b/src/walletConnect/index.tsx index a6f58994df2..8e16c7760e5 100644 --- a/src/walletConnect/index.tsx +++ b/src/walletConnect/index.tsx @@ -43,8 +43,8 @@ import { DAppStatus } from '@/graphql/__generated__/metadata'; import { handleWalletConnectRequest } from '@/utils/requestNavigationHandlers'; import { PerformanceMetrics } from '@/performance/tracking/types/PerformanceMetrics'; import { PerformanceTracking } from '@/performance/tracking'; -import { ChainId } from '@/chains/types'; -import { getSupportedChainIds } from '@/chains'; +import { ChainId } from '@/state/backendNetworks/types'; +import { useBackendNetworksStore } from '@/state/backendNetworks/backendNetworks'; import { hideWalletConnectToast } from '@/components/toasts/WalletConnectToast'; const SUPPORTED_SESSION_EVENTS = ['chainChanged', 'accountsChanged']; @@ -447,7 +447,8 @@ export async function onSessionProposal(proposal: WalletKitTypes.SessionProposal // we already checked for eip155 namespace above const chainIds = chains?.map(chain => parseInt(chain.split('eip155:')[1])); - const supportedChainIds = chainIds.filter(chainId => getSupportedChainIds().includes(chainId)); + const supportedChainIds = useBackendNetworksStore.getState().getSupportedChainIds(); + const chainIdsToUse = chainIds.filter(chainId => supportedChainIds.includes(chainId)); const peerMeta = proposer.metadata; const metadata = await fetchDappMetadata({ url: peerMeta.url, status: true }); @@ -458,7 +459,7 @@ export async function onSessionProposal(proposal: WalletKitTypes.SessionProposal const routeParams: WalletconnectApprovalSheetRouteParams = { receivedTimestamp, meta: { - chainIds: supportedChainIds, + chainIds: chainIdsToUse, dappName, dappScheme: 'unused in WC v2', // only used for deeplinks from WC v1 dappUrl: peerMeta.url || lang.t(lang.l.walletconnect.unknown_url), @@ -488,7 +489,7 @@ export async function onSessionProposal(proposal: WalletKitTypes.SessionProposal const supportedEvents = requiredNamespaces?.eip155?.events || SUPPORTED_SESSION_EVENTS; /** @see https://chainagnostic.org/CAIPs/caip-2 */ - const caip2ChainIds = getSupportedChainIds().map(id => `eip155:${id}`); + const caip2ChainIds = supportedChainIds.map(id => `eip155:${id}`); const namespaces = getApprovedNamespaces({ proposal: proposal.params, supportedNamespaces: { From f753ca82a56e848fec5c8325cfd339bf22b69c7a Mon Sep 17 00:00:00 2001 From: Matthew Wall Date: Thu, 7 Nov 2024 09:58:42 -0500 Subject: [PATCH 08/11] refresh podlock --- ios/Podfile.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ios/Podfile.lock b/ios/Podfile.lock index af7eb5f5407..8621c8b854b 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -2529,4 +2529,4 @@ SPEC CHECKSUMS: PODFILE CHECKSUM: 98c3fc206d7041ac7388693bb0753109d1884b57 -COCOAPODS: 1.14.3 +COCOAPODS: 1.16.1 From d47bb5c459b1a8946ff2bad01f6e69333a315c3e Mon Sep 17 00:00:00 2001 From: Matthew Wall Date: Thu, 7 Nov 2024 14:58:01 -0500 Subject: [PATCH 09/11] no clue what happened during merge --- src/components/AddFundsInterstitial.js | 2 +- src/components/ChainLogo.js | 2 +- src/components/coin-icon/ChainBadge.js | 2 +- src/components/coin-icon/ChainIcon.js | 2 +- src/components/toasts/OfflineToast.js | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/components/AddFundsInterstitial.js b/src/components/AddFundsInterstitial.js index 01128c72803..4a7c315a0b6 100644 --- a/src/components/AddFundsInterstitial.js +++ b/src/components/AddFundsInterstitial.js @@ -19,7 +19,7 @@ import styled from '@/styled-thing'; import { padding, position } from '@/styles'; import ShadowStack from '@/react-native-shadow-stack'; import { useRoute } from '@react-navigation/native'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; const ContainerWidth = 261; diff --git a/src/components/ChainLogo.js b/src/components/ChainLogo.js index 04b56e1e2b4..3c7efd4c8ff 100644 --- a/src/components/ChainLogo.js +++ b/src/components/ChainLogo.js @@ -21,7 +21,7 @@ import BaseBadgeNoShadow from '../assets/badges/baseBadgeNoShadow.png'; import { Centered } from './layout'; import styled from '@/styled-thing'; import { position } from '@/styles'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const ChainIcon = styled(FastImage)({ height: ({ size }) => size, diff --git a/src/components/coin-icon/ChainBadge.js b/src/components/coin-icon/ChainBadge.js index 7aa789def16..0eafa651841 100644 --- a/src/components/coin-icon/ChainBadge.js +++ b/src/components/coin-icon/ChainBadge.js @@ -44,7 +44,7 @@ import { Centered } from '../layout'; import styled from '@/styled-thing'; import { position as positions } from '@/styles'; import { ChainBadgeSizeConfigs } from '@/components/coin-icon/ChainBadgeSizeConfigs'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; const ChainIcon = styled(FastImage)({ height: ({ containerSize }) => containerSize, diff --git a/src/components/coin-icon/ChainIcon.js b/src/components/coin-icon/ChainIcon.js index 626ef5f53d7..2cf0988854a 100644 --- a/src/components/coin-icon/ChainIcon.js +++ b/src/components/coin-icon/ChainIcon.js @@ -10,7 +10,7 @@ import BscBadge from '../../assets/badges/bscBadge.png'; import BscBadgeDark from '../../assets/badges/bscBadgeDark.png'; import { Centered } from '../layout'; import styled from '@/styled-thing'; -import { Network } from '@/chains/types'; +import { Network } from '@/state/backendNetworks/types'; const sizeConfigs = { large: { diff --git a/src/components/toasts/OfflineToast.js b/src/components/toasts/OfflineToast.js index b86c3904823..053791ce854 100644 --- a/src/components/toasts/OfflineToast.js +++ b/src/components/toasts/OfflineToast.js @@ -2,7 +2,7 @@ import lang from 'i18n-js'; import React from 'react'; import Toast from './Toast'; import { useAccountSettings, useInternetStatus } from '@/hooks'; -import { ChainId } from '@/chains/types'; +import { ChainId } from '@/state/backendNetworks/types'; import { useConnectedToHardhatStore } from '@/state/connectedToHardhat'; const OfflineToast = () => { From 2669f0630c5f9da452383c65fcde681d48115d31 Mon Sep 17 00:00:00 2001 From: Matthew Wall Date: Fri, 8 Nov 2024 11:31:47 -0500 Subject: [PATCH 10/11] fix: APP-2021 --- src/components/expanded-state/asset/ChartExpandedState.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/expanded-state/asset/ChartExpandedState.js b/src/components/expanded-state/asset/ChartExpandedState.js index 9fecf8ece49..2913d2a3967 100644 --- a/src/components/expanded-state/asset/ChartExpandedState.js +++ b/src/components/expanded-state/asset/ChartExpandedState.js @@ -243,7 +243,7 @@ export default function ChartExpandedState({ asset }) { const assetChainId = assetWithPrice.chainId; const { swagg_enabled, f2c_enabled } = useRemoteConfig(); - const swapEnabled = swagg_enabled && useBackendNetworksStore.getState().getSupportedSwapChainIds().includes(assetChainId); + const swapEnabled = swagg_enabled && useBackendNetworksStore.getState().getSwapSupportedChainIds().includes(assetChainId); const addCashEnabled = f2c_enabled; const format = useCallback( From 08b11a26d29b2a37c0b1dad80b997df8be0aa7a9 Mon Sep 17 00:00:00 2001 From: Matthew Wall Date: Fri, 8 Nov 2024 11:32:10 -0500 Subject: [PATCH 11/11] fix: APP-2022 --- src/screens/NFTSingleOfferSheet/index.tsx | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/screens/NFTSingleOfferSheet/index.tsx b/src/screens/NFTSingleOfferSheet/index.tsx index 636eb7b35de..89dc64f2fa6 100644 --- a/src/screens/NFTSingleOfferSheet/index.tsx +++ b/src/screens/NFTSingleOfferSheet/index.tsx @@ -164,8 +164,6 @@ export function NFTSingleOfferSheet() { const feesPercentage = Math.floor(offer.feesPercentage * 10) / 10; const royaltiesPercentage = Math.floor(offer.royaltiesPercentage * 10) / 10; - const chain = useBackendNetworksStore.getState().getDefaultChains()[offerChainId]; - useEffect(() => { setParams({ longFormHeight: height }); }, [height, setParams]); @@ -184,7 +182,7 @@ export function NFTSingleOfferSheet() { const signer = createWalletClient({ // @ts-ignore account: accountAddress, - chain, + chain: useBackendNetworksStore.getState().getDefaultChains()[offerChainId], transport: http(useBackendNetworksStore.getState().getChainDefaultRpc(offerChainId)), }); getClient()?.actions.acceptOffer({ @@ -243,7 +241,7 @@ export function NFTSingleOfferSheet() { } catch { logger.error(new RainbowError('[NFTSingleOfferSheet]: Failed to estimate gas')); } - }, [accountAddress, chain, offerChainId, offer.nft.contractAddress, offer.nft.tokenId, feeParam, updateTxFee]); + }, [accountAddress, feeParam, offer.nft.contractAddress, offer.nft.tokenId, offerChainId, updateTxFee]); // estimate gas useEffect(() => { @@ -254,7 +252,7 @@ export function NFTSingleOfferSheet() { return () => { stopPollingGasFees(); }; - }, [estimateGas, isExpired, isReadOnlyWallet, offer.network, offerChainId, startPollingGasFees, stopPollingGasFees, updateTxFee]); + }, [estimateGas, isExpired, isReadOnlyWallet, offerChainId, startPollingGasFees, stopPollingGasFees]); const acceptOffer = useCallback(async () => { logger.debug(`[NFTSingleOfferSheet]: Initiating sale of NFT ${offer.nft.contractAddress}:${offer.nft.tokenId}`); @@ -284,7 +282,7 @@ export function NFTSingleOfferSheet() { const signer = createWalletClient({ account, - chain, + chain: useBackendNetworksStore.getState().getDefaultChains()[offerChainId], transport: http(useBackendNetworksStore.getState().getChainDefaultRpc(offerChainId)), }); const nonce = await getNextNonce({ address: accountAddress, chainId: offerChainId }); @@ -425,7 +423,7 @@ export function NFTSingleOfferSheet() { } finally { setIsAccepting(false); } - }, [offer, rainbowFeeDecimal, accountAddress, chain, offerChainId, feeParam, navigate, nft]); + }, [offer, rainbowFeeDecimal, accountAddress, offerChainId, feeParam, navigate, nft]); let buttonLabel = ''; if (!isAccepting) {