Skip to content

Commit

Permalink
Fix missing pricing swaps (#6023)
Browse files Browse the repository at this point in the history
* fetch prices again until BE returns it

* clean log
  • Loading branch information
brunobar79 authored Aug 21, 2024
1 parent eb095ed commit fe10fd7
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 6 deletions.
83 changes: 79 additions & 4 deletions src/__swaps__/screens/Swap/hooks/useSwapInputsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,16 @@ import { analyticsV2 } from '@/analytics';
import { SPRING_CONFIGS } from '@/components/animations/animationConfigs';
import { useAccountSettings } from '@/hooks';
import { useAnimatedInterval } from '@/hooks/reanimated/useAnimatedInterval';
import { logger } from '@/logger';
import { logger, RainbowError } from '@/logger';
import { getRemoteConfig } from '@/model/remoteConfig';
import { queryClient } from '@/react-query';
import store from '@/redux/store';
import {
EXTERNAL_TOKEN_STALE_TIME,
ExternalTokenQueryFunctionResult,
externalTokenQueryKey,
fetchExternalToken,
} from '@/resources/assets/externalAssetsQuery';
import { triggerHapticFeedback } from '@/screens/points/constants';
import { swapsStore } from '@/state/swaps/swapsStore';
import { CrosschainQuote, Quote, QuoteError, SwapType, getCrosschainQuote, getQuote } from '@rainbow-me/swaps';
Expand Down Expand Up @@ -337,6 +344,68 @@ export function useSwapInputsController({
]
);

const getAssetNativePrice = useCallback(async ({ asset }: { asset: ExtendedAnimatedAssetWithColors | null }) => {
if (!asset) return null;

const address = asset.address;
const chainId = asset.chainId;
const currency = store.getState().settings.nativeCurrency;

try {
const tokenData = await fetchExternalToken({
address,
chainId,
currency,
});

if (tokenData?.price.value) {
queryClient.setQueryData(externalTokenQueryKey({ address, chainId, currency }), tokenData);
return tokenData.price.value;
}
} catch (error) {
logger.error(new RainbowError('[useSwapInputsController]: get asset prices failed'));

const now = Date.now();
const state = queryClient.getQueryState<ExternalTokenQueryFunctionResult>(externalTokenQueryKey({ address, chainId, currency }));
const price = state?.data?.price.value;
if (price) {
const updatedAt = state.dataUpdatedAt;
// NOTE: if the data is older than 60 seconds, we need to invalidate it and not use it
if (now - updatedAt > EXTERNAL_TOKEN_STALE_TIME) {
queryClient.invalidateQueries(externalTokenQueryKey({ address, chainId, currency }));
return null;
}
return price;
}
}
return null;
}, []);

const fetchAssetPrices = useCallback(
async ({
inputAsset,
outputAsset,
}: {
inputAsset: ExtendedAnimatedAssetWithColors | null;
outputAsset: ExtendedAnimatedAssetWithColors | null;
}) => {
const assetsToFetch = [];

assetsToFetch.push({
asset: inputAsset,
type: 'inputAsset',
});

assetsToFetch.push({
asset: outputAsset,
type: 'outputAsset',
});

return Promise.all(assetsToFetch.map(getAssetNativePrice)).then(([inputPrice, outputPrice]) => ({ inputPrice, outputPrice }));
},
[getAssetNativePrice]
);

const fetchAndUpdateQuote = async ({ inputAmount, lastTypedInput: lastTypedInputParam, outputAmount }: RequestNewQuoteParams) => {
const originalInputAssetUniqueId = internalSelectedInputAsset.value?.uniqueId;
const originalOutputAssetUniqueId = internalSelectedOutputAsset.value?.uniqueId;
Expand Down Expand Up @@ -372,7 +441,13 @@ export function useSwapInputsController({
};

try {
const quoteResponse = await (params.swapType === SwapType.crossChain ? getCrosschainQuote(params) : getQuote(params));
const [quoteResponse, fetchedPrices] = await Promise.all([
params.swapType === SwapType.crossChain ? getCrosschainQuote(params) : getQuote(params),
fetchAssetPrices({
inputAsset: internalSelectedInputAsset.value,
outputAsset: internalSelectedOutputAsset.value,
}),
]);

const inputAsset = internalSelectedInputAsset.value;
const outputAsset = internalSelectedOutputAsset.value;
Expand Down Expand Up @@ -423,9 +498,9 @@ export function useSwapInputsController({
setQuote({
data: quoteResponse,
inputAmount: quotedInputAmount,
inputPrice: quoteResponse?.sellTokenAsset?.price?.value,
inputPrice: quoteResponse?.sellTokenAsset?.price?.value || fetchedPrices.inputPrice,
outputAmount: quotedOutputAmount,
outputPrice: quoteResponse?.buyTokenAsset?.price?.value,
outputPrice: quoteResponse?.buyTokenAsset?.price?.value || fetchedPrices.outputPrice,
originalQuoteParams,
quoteFetchingInterval,
});
Expand Down
2 changes: 0 additions & 2 deletions src/resources/favorites.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,6 @@ export function useFavorites(): {
const favoritesMetadata = query.data ?? {};
const favorites = Object.keys(favoritesMetadata);

console.log('favoritesMetadata', favoritesMetadata);

return {
favorites,
favoritesMetadata,
Expand Down

0 comments on commit fe10fd7

Please sign in to comment.