Skip to content

Commit

Permalink
Bugfix/countdown timer refresh swap form (#6178)
Browse files Browse the repository at this point in the history
* fix(LIVE-11267): regression on analytics refreshing every 1 sec

* fix(LIVE-11267): add changeset

* Revert "[fix/LIVE-11122]: update quotes when timeout reaches 0 in swap. (#6118)"

This reverts commit 63099cc.

* fix(LIVE-11267): remove useless files
  • Loading branch information
lpaquet-ledger authored and jdabbech-ledger committed Feb 19, 2024
1 parent 328573a commit ff54d02
Show file tree
Hide file tree
Showing 14 changed files with 104 additions and 72 deletions.
6 changes: 0 additions & 6 deletions .changeset/brown-experts-fly.md

This file was deleted.

5 changes: 5 additions & 0 deletions .changeset/early-turtles-join.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"ledger-live-desktop": patch
---

Revert counter and refresh rate changes and fix moonpay not refreshing
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,17 @@ export type SectionRateProps = {
ratesState: RatesReducerState;
fromCurrency: SwapSelectorStateType["currency"];
toCurrency: SwapSelectorStateType["currency"];
countdownSecondsToRefresh: number | undefined;
refreshTime: number;
countdown: boolean;
};

const SectionRate = ({
provider,
fromCurrency,
toCurrency,
ratesState,
countdownSecondsToRefresh,
refreshTime,
countdown,
}: SectionRateProps) => {
const rates = ratesState.value;

Expand All @@ -31,7 +33,8 @@ const SectionRate = ({
toCurrency,
rates,
provider,
countdownSecondsToRefresh,
refreshTime,
countdown,
}}
/>
</ProvidersSection>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from "react";
import React, { useMemo } from "react";
import styled from "styled-components";
import SectionRate from "./SectionRate";
import { SwapDataType } from "@ledgerhq/live-common/exchange/swap/types";
Expand All @@ -10,26 +10,28 @@ const Form = styled.section`
`;
type SwapFormProvidersProps = {
swap: SwapDataType;
countdownSecondsToRefresh: number | undefined;
provider?: string;
refreshTime: number;
countdown: boolean;
};

const SwapFormProviders = ({
swap,
provider,
countdownSecondsToRefresh,
}: SwapFormProvidersProps) => {
const SwapFormProviders = ({ swap, provider, refreshTime, countdown }: SwapFormProvidersProps) => {
const { currency: fromCurrency } = swap.from;
const { currency: toCurrency } = swap.to;

const updatedRatesState = useMemo(() => {
return swap.rates;
}, [swap.rates]);

return (
<Form>
<SectionRate
provider={provider}
fromCurrency={fromCurrency}
toCurrency={toCurrency}
ratesState={swap.rates}
countdownSecondsToRefresh={countdownSecondsToRefresh}
ratesState={updatedRatesState}
refreshTime={refreshTime}
countdown={countdown}
/>
</Form>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ type SwapMigrationUIProps = {
pageState: ReturnType<typeof usePageState>;
swapTransaction: SwapTransactionType;
provider?: string;
refreshTime: number;
countdown: boolean;
// Demo 0 props
disabled: boolean;
onClick: () => void;
Expand All @@ -35,6 +37,8 @@ export const SwapMigrationUI = (props: SwapMigrationUIProps) => {
pageState,
swapTransaction,
provider,
refreshTime,
countdown,
disabled,
onClick,
} = props;
Expand All @@ -45,7 +49,8 @@ export const SwapMigrationUI = (props: SwapMigrationUIProps) => {
<SwapFormRates
swap={swapTransaction.swap}
provider={provider}
countdownSecondsToRefresh={swapTransaction.swap.countdown}
refreshTime={refreshTime}
countdown={countdown}
/>
) : null;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,30 +1,49 @@
import React from "react";
import React, { useEffect, useState } from "react";
import { Trans } from "react-i18next";
import styled from "styled-components";
import Box from "~/renderer/components/Box";
import Text from "~/renderer/components/Text";
import AnimatedCountdown from "~/renderer/components/AnimatedCountdown";
import { formatCountdown } from "~/renderer/screens/exchange/Swap2/Form/Rates/utils/formatCountdown";
import { DEFAULT_SWAP_RATES_INTERVAL_MS } from "@ledgerhq/live-common/exchange/swap/const/timeout";
import { RatesReducerState } from "@ledgerhq/live-common/exchange/swap/types";

export type Props = {
countdown: number;
rates: RatesReducerState["value"];
refreshTime: number;
};

const CountdownText = styled(Text)`
color: ${p => p.theme.colors.neutral.c70};
`;

export default function Countdown({ countdown }: Props) {
export default function Countdown({ refreshTime, rates }: Props) {
const getSeconds = (time: number) => Math.round(time / 1000);
const [countdown, setCountdown] = useState(getSeconds(refreshTime));
const [iconKey, setIconKey] = useState(0);

useEffect(() => {
setIconKey(key => key + 1);
const startTime = new Date().getTime();
setCountdown(getSeconds(refreshTime));
const countdownInterval = window.setInterval(() => {
const now = new Date().getTime();
const newCountdown = refreshTime + startTime - now;
setCountdown(getSeconds(newCountdown));
}, 1000);
return () => {
clearInterval(countdownInterval);
};
}, [rates, refreshTime]);

return (
<>
{countdown >= 0 ? (
<Box horizontal fontSize={3}>
<CountdownText>
<Trans i18nKey="swap2.form.rates.update" />
</CountdownText>
<Box horizontal fontSize={3} mx={1} key={1}>
<AnimatedCountdown size={15} duration={DEFAULT_SWAP_RATES_INTERVAL_MS} />
<Box horizontal fontSize={3} mx={1} key={iconKey}>
<AnimatedCountdown size={15} duration={refreshTime} />
</Box>
<Box
color="neutral.c100"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ type Props = {
toCurrency: SwapSelectorStateType["currency"];
rates: RatesReducerState["value"];
provider: string | undefined | null;
countdownSecondsToRefresh: number | undefined;
refreshTime: number;
countdown: boolean;
};

const TableHeader = styled(Box).attrs({
Expand All @@ -53,20 +54,20 @@ export default function ProviderRate({
toCurrency,
rates,
provider,
countdownSecondsToRefresh,
refreshTime,
countdown,
}: Props) {
const swapDefaultTrack = useGetSwapTrackingProperties();
const dispatch = useDispatch();
const [filter, setFilter] = useState<string[]>([]);
const [defaultPartner, setDefaultPartner] = useState<string | null>(null);
const selectedRate = useSelector(rateSelector);
const filteredRates = useMemo(() => filterRates(rates, filter), [rates, filter]);
const providers = useMemo(() => [...new Set(rates?.map(rate => rate.provider) ?? [])], [rates]);
const exchangeRates = useMemo(() => {
return toCurrency && rates
const providers = [...new Set(rates?.map(rate => rate.provider) ?? [])];
const exchangeRates =
toCurrency && rates
? rates.map(({ toAmount }) => formatCurrencyUnit(getFeesUnit(toCurrency), toAmount))
: [];
}, [toCurrency, rates]);
const updateRate = useCallback(
(rate: ExchangeRate) => {
const value = rate.rate ?? rate.provider;
Expand Down Expand Up @@ -146,9 +147,9 @@ export default function ProviderRate({
>
<Trans i18nKey="swap2.form.rates.title" />
</Text>
{countdownSecondsToRefresh && (
{countdown && (
<Box horizontal fontSize={3}>
<Countdown countdown={countdownSecondsToRefresh} />
<Countdown refreshTime={refreshTime} rates={rates} />
</Box>
)}
</Box>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { useRef, useEffect } from "react";
import { SwapDataType } from "@ledgerhq/live-common/exchange/swap/types";
import { DEFAULT_SWAP_RATES_INTERVAL_MS } from "@ledgerhq/live-common/exchange/swap/const/timeout";

const useRefreshRates = (
swap: SwapDataType,
{
pause,
}: {
pause: boolean;
},
) => {
const refreshInterval = useRef<NodeJS.Timeout>();
const refreshTime = DEFAULT_SWAP_RATES_INTERVAL_MS;

useEffect(() => {
clearTimeout(refreshInterval.current);
refreshInterval.current = setTimeout(() => {
if (!pause) {
swap.refetchRates();
}
}, refreshTime);
return () => {
clearTimeout(refreshInterval.current);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pause, refreshTime, swap.rates?.value]);

return refreshTime;
};

export default useRefreshRates;
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import ExchangeDrawer from "./ExchangeDrawer/index";
import SwapFormSelectors from "./FormSelectors";
import useFeature from "@ledgerhq/live-common/featureFlags/useFeature";
import { accountToWalletAPIAccount } from "@ledgerhq/live-common/wallet-api/converters";
import useRefreshRates from "./hooks/useRefreshRates";
import LoadingState from "./Rates/LoadingState";
import EmptyState from "./Rates/EmptyState";
import { AccountLike } from "@ledgerhq/types-live";
Expand Down Expand Up @@ -123,6 +124,11 @@ const SwapForm = () => {
);
const { setDrawer } = React.useContext(context);

const pauseRefreshing = !!swapError || idleState;
const refreshTime = useRefreshRates(swapTransaction.swap, {
pause: pauseRefreshing,
});

const getExchangeSDKParams = useCallback(() => {
const { swap, transaction } = swapTransaction;
const { to, from } = swap;
Expand Down Expand Up @@ -462,6 +468,8 @@ const SwapForm = () => {
pageState={pageState}
swapTransaction={swapTransaction}
provider={provider}
refreshTime={refreshTime}
countdown={!pauseRefreshing}
// Demo 0 props
disabled={!isSwapReady}
onClick={onSubmit}
Expand Down
1 change: 0 additions & 1 deletion libs/ledger-live-common/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,6 @@
"thor-devkit": "^2.0.6",
"triple-beam": "^1.3.0",
"tronweb": "^5.2.0",
"usehooks-ts": "^2.13.0",
"utility-types": "^3.10.0",
"varuint-bitcoin": "1.1.2",
"winston": "^3.4.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ export const useSwapTransaction = ({
bridge: bridgeTransaction,
});

const { rates, refetchRates, updateSelectedRate, countdown } = useProviderRates({
const { rates, refetchRates, updateSelectedRate } = useProviderRates({
fromState,
toState,
onNoRates,
Expand All @@ -176,7 +176,6 @@ export const useSwapTransaction = ({
value: rates.value.filter(v => v.tradeMethod !== "fixed"),
}
: rates,
countdown,
refetchRates,
updateSelectedRate,
targetAccounts,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import { OnNoRatesCallback, RatesReducerState, SwapSelectorStateType } from "../
import { useFetchRates } from "./useFetchRates";
import { SetExchangeRateCallback } from "../useSwapTransaction";
import { useFeature } from "../../../../featureFlags";
import { useCallback, useEffect } from "react";
import { useCountdown } from "usehooks-ts";
import { DEFAULT_SWAP_RATES_INTERVAL_MS } from "../../const/timeout";
import { useCallback } from "react";

type Props = {
fromState: SwapSelectorStateType;
Expand All @@ -18,7 +16,6 @@ export type UseProviderRatesResponse = {
rates: RatesReducerState;
refetchRates(): void;
updateSelectedRate(): void;
countdown: undefined | number;
};

export function useProviderRates({
Expand All @@ -27,10 +24,6 @@ export function useProviderRates({
onNoRates,
setExchangeRate,
}: Props): UseProviderRatesResponse {
const [countdown, { startCountdown, resetCountdown, stopCountdown }] = useCountdown({
countStart: DEFAULT_SWAP_RATES_INTERVAL_MS / 1000,
countStop: 0,
});
const ptxSwapMoonpayProviderFlag = useFeature("ptxSwapMoonpayProvider");
const filterMoonpay = useCallback(
rates => {
Expand All @@ -45,24 +38,15 @@ export function useProviderRates({
toCurrency: toState.currency,
fromCurrencyAmount: fromState.amount ?? BigNumber(0),
onSuccess(data) {
resetCountdown();
const rates = filterMoonpay(data);
if (rates.length === 0) {
stopCountdown();
onNoRates?.({ fromState, toState });
} else {
startCountdown();
setExchangeRate?.(rates[0]);
}
},
});

useEffect(() => {
if (countdown <= 0) {
refetch();
}
}, [countdown, refetch]);

if (!fromState.amount || fromState.amount.lte(0)) {
setExchangeRate?.(undefined);
return {
Expand All @@ -73,7 +57,6 @@ export function useProviderRates({
},
refetchRates: () => undefined,
updateSelectedRate: () => undefined,
countdown: undefined,
};
}

Expand All @@ -87,7 +70,6 @@ export function useProviderRates({
},
refetchRates: () => undefined,
updateSelectedRate: () => undefined,
countdown: undefined,
};
}
if (error) {
Expand All @@ -100,7 +82,6 @@ export function useProviderRates({
},
refetchRates: () => undefined,
updateSelectedRate: () => undefined,
countdown: undefined,
};
}

Expand All @@ -113,7 +94,6 @@ export function useProviderRates({
},
refetchRates: refetch,
updateSelectedRate: () => undefined,
countdown,
};
}

Expand All @@ -125,6 +105,5 @@ export function useProviderRates({
},
refetchRates: () => undefined,
updateSelectedRate: () => undefined,
countdown: undefined,
};
}
Loading

0 comments on commit ff54d02

Please sign in to comment.