Skip to content

Commit

Permalink
userAssetsStore refactor (#6015)
Browse files Browse the repository at this point in the history
* done

* change userAssetsStoreCache type

* mid refactor

* refactor

* dont cast to Address

* more

* more

* rm address param

* fix caching

* select address

* comments

* hardhat

* lint
  • Loading branch information
benisgold authored Sep 10, 2024
1 parent deb25f2 commit 503723b
Show file tree
Hide file tree
Showing 12 changed files with 264 additions and 230 deletions.
5 changes: 3 additions & 2 deletions src/__swaps__/screens/Swap/Swap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { useSwapsStore } from '@/state/swaps/swapsStore';
import { SwapWarning } from './components/SwapWarning';
import { clearCustomGasSettings } from './hooks/useCustomGas';
import { SwapProvider, useSwapContext } from './providers/swap-provider';
import { useAccountSettings } from '@/hooks';
import { NavigateToSwapSettingsTrigger } from './components/NavigateToSwapSettingsTrigger';

/** README
Expand Down Expand Up @@ -133,7 +134,7 @@ const useCleanupOnUnmount = () => {
};

const WalletAddressObserver = () => {
const currentWalletAddress = userAssetsStore(state => state.associatedWalletAddress);
const { accountAddress } = useAccountSettings();
const { setAsset } = useSwapContext();

const setNewInputAsset = useCallback(() => {
Expand All @@ -157,7 +158,7 @@ const WalletAddressObserver = () => {
}, [setAsset]);

useAnimatedReaction(
() => currentWalletAddress,
() => accountAddress,
(current, previous) => {
const didWalletAddressChange = previous && current !== previous;

Expand Down
4 changes: 2 additions & 2 deletions src/__swaps__/screens/Swap/components/CoinRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import * as i18n from '@/languages';
import { RainbowNetworkObjects } from '@/networks';
import { BASE_DEGEN_ADDRESS, DEGEN_CHAIN_DEGEN_ADDRESS, ETH_ADDRESS } from '@/references';
import { toggleFavorite } from '@/resources/favorites';
import { userAssetsStore } from '@/state/assets/userAssets';
import { useUserAssetsStore } from '@/state/assets/userAssets';
import { ethereumUtils, haptics, showActionSheetWithOptions } from '@/utils';
import { startCase } from 'lodash';
import React, { useCallback, useMemo } from 'react';
Expand Down Expand Up @@ -69,7 +69,7 @@ interface OutputCoinRowProps extends PartialAsset {
type CoinRowProps = InputCoinRowProps | OutputCoinRowProps;

export function CoinRow({ isFavorite, onPress, output, uniqueId, testID, ...assetProps }: CoinRowProps) {
const inputAsset = userAssetsStore(state => (output ? undefined : state.getUserAsset(uniqueId)));
const inputAsset = useUserAssetsStore(state => (output ? undefined : state.getUserAsset(uniqueId)));
const outputAsset = output ? (assetProps as PartialAsset) : undefined;

const asset = output ? outputAsset : inputAsset;
Expand Down
4 changes: 2 additions & 2 deletions src/__swaps__/screens/Swap/components/SearchInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { opacity } from '@/__swaps__/utils/swaps';
import { Input } from '@/components/inputs';
import { Bleed, Box, Column, Columns, Text, useColorMode, useForegroundColor } from '@/design-system';
import * as i18n from '@/languages';
import { userAssetsStore } from '@/state/assets/userAssets';
import { userAssetsStore, useUserAssetsStore } from '@/state/assets/userAssets';
import { useSwapsStore } from '@/state/swaps/swapsStore';
import React from 'react';
import Animated, {
Expand Down Expand Up @@ -39,7 +39,7 @@ export const SearchInput = ({
const label = useForegroundColor('label');
const labelQuaternary = useForegroundColor('labelQuaternary');

const onInputSearchQueryChange = userAssetsStore(state => state.setSearchQuery);
const onInputSearchQueryChange = useUserAssetsStore(state => state.setSearchQuery);

const onOutputSearchQueryChange = useDebouncedCallback((text: string) => useSwapsStore.setState({ outputSearchQuery: text }), 100, {
leading: false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { ContextMenuButton } from '@/components/context-menu';
import { AnimatedText, Bleed, Box, Inline, Text, TextIcon, globalColors, useColorMode } from '@/design-system';
import { useAccountAccentColor } from '@/hooks';
import { useSharedValueState } from '@/hooks/reanimated/useSharedValueState';
import { userAssetsStore } from '@/state/assets/userAssets';
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';
Expand All @@ -31,8 +31,11 @@ export const ChainSelection = memo(function ChainSelection({ allText, output }:
const { selectedOutputChainId, setSelectedOutputChainId } = useSwapContext();

// chains sorted by balance on output, chains without balance hidden on input
const balanceSortedChainList = userAssetsStore(state => (output ? state.getBalanceSortedChainList() : state.getChainsWithBalance()));
const inputListFilter = useSharedValue(userAssetsStore.getState().filter);
const { balanceSortedChainList, filter } = useUserAssetsStore(state => ({
balanceSortedChainList: output ? state.getBalanceSortedChainList() : state.getChainsWithBalance(),
filter: state.filter,
}));
const inputListFilter = useSharedValue(filter);

const accentColor = useMemo(() => {
if (c.contrast(accountColor, isDarkMode ? '#191A1C' : globalColors.white100) < (isDarkMode ? 2.125 : 1.5)) {
Expand Down Expand Up @@ -189,7 +192,7 @@ export const ChainSelection = memo(function ChainSelection({ allText, output }:
const ChainButtonIcon = ({ output }: { output: boolean | undefined }) => {
const { selectedOutputChainId: animatedSelectedOutputChainId } = useSwapContext();

const userAssetsFilter = userAssetsStore(state => (output ? undefined : state.filter));
const userAssetsFilter = useUserAssetsStore(state => (output ? undefined : state.filter));
const selectedOutputChainId = useSharedValueState(animatedSelectedOutputChainId, { pauseSync: !output });

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { getStandardizedUniqueIdWorklet } from '@/__swaps__/utils/swaps';
import { analyticsV2 } from '@/analytics';
import { useDelayedMount } from '@/hooks/useDelayedMount';
import * as i18n from '@/languages';
import { userAssetsStore } from '@/state/assets/userAssets';
import { userAssetsStore, useUserAssetsStore } from '@/state/assets/userAssets';
import { swapsStore } from '@/state/swaps/swapsStore';
import { DEVICE_WIDTH } from '@/utils/deviceUtils';
import React, { useCallback, useMemo } from 'react';
Expand Down Expand Up @@ -38,7 +38,7 @@ export const TokenToSellList = () => {
const TokenToSellListComponent = () => {
const { inputProgress, internalSelectedInputAsset, internalSelectedOutputAsset, isFetching, isQuoteStale, setAsset } = useSwapContext();

const userAssetIds = userAssetsStore(state => state.getFilteredUserAssetIds());
const userAssetIds = useUserAssetsStore(state => state.getFilteredUserAssetIds());

const handleSelectToken = useCallback(
(token: ParsedSearchAsset | null) => {
Expand Down
15 changes: 6 additions & 9 deletions src/__swaps__/screens/Swap/hooks/useAssetsToSell.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { useMemo } from 'react';
import { Address } from 'viem';

import {
selectUserAssetsList,
Expand All @@ -9,8 +8,7 @@ import {
import { useUserAssets } from '@/__swaps__/screens/Swap/resources/assets';
import { ParsedAssetsDictByChain, ParsedSearchAsset, UserAssetFilter } from '@/__swaps__/types/assets';
import { useAccountSettings, useDebounce } from '@/hooks';
import { userAssetsStore } from '@/state/assets/userAssets';
import { useConnectedToHardhatStore } from '@/state/connectedToHardhat';
import { useUserAssetsStore } from '@/state/assets/userAssets';

const sortBy = (by: UserAssetFilter) => {
switch (by) {
Expand All @@ -24,18 +22,17 @@ const sortBy = (by: UserAssetFilter) => {
export const useAssetsToSell = () => {
const { accountAddress: currentAddress, nativeCurrency: currentCurrency } = useAccountSettings();

const filter = userAssetsStore(state => state.filter);
const searchQuery = userAssetsStore(state => state.inputSearchQuery);
const { filter, searchQuery } = useUserAssetsStore(state => ({
filter: state.filter,
searchQuery: state.inputSearchQuery,
}));

const debouncedAssetToSellFilter = useDebounce(searchQuery, 200);

const { connectedToHardhat } = useConnectedToHardhatStore();

const { data: userAssets = [] } = useUserAssets(
{
address: currentAddress as Address,
address: currentAddress,
currency: currentCurrency,
testnetMode: connectedToHardhat,
},
{
select: data =>
Expand Down
5 changes: 4 additions & 1 deletion src/__swaps__/screens/Swap/providers/swap-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -599,7 +599,10 @@ export const SwapProvider = ({ children }: SwapProviderProps) => {

if (didSelectedAssetChange) {
const assetToSet = insertUserAssetBalance
? { ...asset, balance: (asset && userAssetsStore.getState().getUserAsset(asset.uniqueId)?.balance) || asset?.balance }
? {
...asset,
balance: (asset && userAssetsStore.getState().getUserAsset(asset.uniqueId)?.balance) || asset?.balance,
}
: asset;

if (isSameAsOtherAsset) {
Expand Down
17 changes: 10 additions & 7 deletions src/__swaps__/screens/Swap/resources/assets/userAssets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { greaterThan } from '@/__swaps__/utils/numbers';

import { fetchUserAssetsByChain } from './userAssetsByChain';
import { fetchHardhatBalances, fetchHardhatBalancesByChainId } from '@/resources/assets/hardhatAssets';
import { useConnectedToHardhatStore } from '@/state/connectedToHardhat';

const addysHttp = new RainbowFetchClient({
baseURL: 'https://addys.p.rainbow.me/v3',
Expand All @@ -31,27 +32,27 @@ export const USER_ASSETS_STALE_INTERVAL = 30000;
// Query Types

export type UserAssetsArgs = {
address: Address;
address: Address | string;
currency: SupportedCurrencyKey;
testnetMode?: boolean;
};

type SetUserAssetsArgs = {
address: Address;
address: Address | string;
currency: SupportedCurrencyKey;
userAssets?: UserAssetsResult;
testnetMode?: boolean;
};

type SetUserDefaultsArgs = {
address: Address;
address: Address | string;
currency: SupportedCurrencyKey;
staleTime: number;
testnetMode?: boolean;
};

type FetchUserAssetsArgs = {
address: Address;
address: Address | string;
currency: SupportedCurrencyKey;
testnetMode?: boolean;
};
Expand Down Expand Up @@ -160,7 +161,7 @@ async function userAssetsQueryFunctionRetryByChain({
currency,
testnetMode,
}: {
address: Address;
address: Address | string;
chainIds: ChainId[];
currency: SupportedCurrencyKey;
testnetMode?: boolean;
Expand Down Expand Up @@ -230,10 +231,12 @@ export async function parseUserAssets({
// Query Hook

export function useUserAssets<TSelectResult = UserAssetsResult>(
{ address, currency, testnetMode }: UserAssetsArgs,
{ address, currency }: UserAssetsArgs,
config: QueryConfigWithSelect<UserAssetsResult, Error, TSelectResult, UserAssetsQueryKey> = {}
) {
return useQuery(userAssetsQueryKey({ address, currency, testnetMode }), userAssetsQueryFunction, {
const { connectedToHardhat } = useConnectedToHardhatStore();

return useQuery(userAssetsQueryKey({ address, currency, testnetMode: connectedToHardhat }), userAssetsQueryFunction, {
...config,
refetchInterval: USER_ASSETS_REFETCH_INTERVAL,
staleTime: process.env.IS_TESTING === 'true' ? 0 : 1000,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const addysHttp = new RainbowFetchClient({
// Query Types

export type UserAssetsByChainArgs = {
address: Address;
address: Address | string;
chainId: ChainId;
currency: SupportedCurrencyKey;
};
Expand Down
4 changes: 2 additions & 2 deletions src/components/context-menu-buttons/ChainContextMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { ContextMenuButton } from '@/components/context-menu';
import { Bleed, Box, Inline, Text, TextProps } from '@/design-system';
import * as i18n from '@/languages';
import { ChainId, ChainNameDisplay } from '@/networks/types';
import { useUserAssetsStore } from '@/state/assets/userAssets';
import { showActionSheetWithOptions } from '@/utils';
import { userAssetsStore } from '@/state/assets/userAssets';
import { chainNameForChainIdWithMainnetSubstitution } from '@/__swaps__/utils/chains';

interface DefaultButtonOptions {
Expand Down Expand Up @@ -49,7 +49,7 @@ export const ChainContextMenu = ({
textWeight = 'heavy',
} = defaultButtonOptions;

const balanceSortedChains = userAssetsStore(state =>
const balanceSortedChains = useUserAssetsStore(state =>
// eslint-disable-next-line no-nested-ternary
chainsToDisplay ? chainsToDisplay : excludeChainsWithNoBalance ? state.getChainsWithBalance() : state.getBalanceSortedChainList()
);
Expand Down
Loading

0 comments on commit 503723b

Please sign in to comment.