Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

πŸ¦β€πŸ”₯ [FIX]: Refresh ledger sync QR code on expiration #7690

Merged
merged 3 commits into from
Aug 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/sweet-spies-sell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@ledgerhq/errors": patch
"ledger-live-desktop": patch
"live-mobile": patch
"@ledgerhq/trustchain": patch
---

Refresh ledger sync QR code on expiration
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { useCallback, useState } from "react";
import { createQRCodeHostInstance } from "@ledgerhq/trustchain/qrcode/index";
import { InvalidDigitsError, NoTrustchainInitialized } from "@ledgerhq/trustchain/errors";
import {
InvalidDigitsError,
NoTrustchainInitialized,
QRCodeWSClosed,
} from "@ledgerhq/trustchain/errors";
import { MemberCredentials } from "@ledgerhq/trustchain/types";
import { useDispatch, useSelector } from "react-redux";
import { setFlow, setQrCodePinCode } from "~/renderer/actions/walletSync";
import { Flow, Step } from "~/renderer/reducers/walletSync";
Expand All @@ -12,10 +17,12 @@ import {
import { useTrustchainSdk } from "./useTrustchainSdk";
import { useFeature } from "@ledgerhq/live-common/featureFlags/index";
import getWalletSyncEnvironmentParams from "@ledgerhq/live-common/walletSync/getEnvironmentParams";
import { useQueryClient } from "@tanstack/react-query";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { QueryKey } from "./type.hooks";
import { useInstanceName } from "./useInstanceName";

const MIN_TIME_TO_REFRESH = 30_000;

export function useQRCode() {
const queryClient = useQueryClient();
const dispatch = useDispatch();
Expand All @@ -26,73 +33,76 @@ export function useQRCode() {
const { trustchainApiBaseUrl } = getWalletSyncEnvironmentParams(
featureWalletSync?.params?.environment,
);
const [isLoading, setIsLoading] = useState(false);
const [url, setUrl] = useState<string | null>(null);
const [error, setError] = useState<Error | null>(null);
const memberName = useInstanceName();

const goToActivation = useCallback(() => {
dispatch(setFlow({ flow: Flow.Activation, step: Step.DeviceAction }));
}, [dispatch]);

const startQRCodeProcessing = useCallback(() => {
if (!memberCredentials) return;
const { mutate, isPending, error } = useMutation({
mutationFn: (memberCredentials: MemberCredentials) =>
createQRCodeHostInstance({
trustchainApiBaseUrl,
onDisplayQRCode: url => {
setUrl(url);
},
onDisplayDigits: digits => {
dispatch(setQrCodePinCode(digits));
dispatch(setFlow({ flow: Flow.Synchronize, step: Step.PinCode }));
},
addMember: async member => {
if (trustchain) {
await sdk.addMember(trustchain, memberCredentials, member);
return trustchain;
}
throw new NoTrustchainInitialized();
},
memberCredentials,
memberName,
alreadyHasATrustchain: !!trustchain,
}),

setError(null);
setIsLoading(true);
createQRCodeHostInstance({
trustchainApiBaseUrl,
onDisplayQRCode: url => {
setUrl(url);
},
onDisplayDigits: digits => {
dispatch(setQrCodePinCode(digits));
dispatch(setFlow({ flow: Flow.Synchronize, step: Step.PinCode }));
},
addMember: async member => {
if (trustchain) {
await sdk.addMember(trustchain, memberCredentials, member);
return trustchain;
}
throw new NoTrustchainInitialized();
},
memberCredentials,
memberName,
alreadyHasATrustchain: !!trustchain,
})
.catch(e => {
if (e instanceof InvalidDigitsError) {
dispatch(setFlow({ flow: Flow.Synchronize, step: Step.PinCodeError }));
} else if (e instanceof NoTrustchainInitialized) {
dispatch(setFlow({ flow: Flow.Synchronize, step: Step.UnbackedError }));
}
setError(e);
throw e;
})
.then(newTrustchain => {
if (newTrustchain) {
dispatch(setTrustchain(newTrustchain));
}
dispatch(
setFlow({
flow: Flow.Synchronize,
step: Step.SynchronizeLoading,
nextStep: Step.Synchronized,
hasTrustchainBeenCreated: false,
}),
);
queryClient.invalidateQueries({ queryKey: [QueryKey.getMembers] });
setUrl(null);
dispatch(setQrCodePinCode(null));
setIsLoading(false);
setError(null);
});
}, [memberCredentials, trustchainApiBaseUrl, memberName, dispatch, trustchain, sdk, queryClient]);
// Don't use retry here because it always uses a delay despite setting it to 0
onError(e) {
if (e instanceof QRCodeWSClosed) {
const { time } = e as unknown as { time: number };
if (time >= MIN_TIME_TO_REFRESH) startQRCodeProcessing();
}
if (e instanceof InvalidDigitsError) {
dispatch(setFlow({ flow: Flow.Synchronize, step: Step.PinCodeError }));
}
if (e instanceof NoTrustchainInitialized) {
dispatch(setFlow({ flow: Flow.Synchronize, step: Step.UnbackedError }));
}
Copy link
Contributor

Choose a reason for hiding this comment

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

we need to add

setError(e); throw e; also no? Like before

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The setError is not needed because react-query manages the error (that's why I removed the useState).

For the throw I don't think it's needed either. From my understanding it was here to avoid the then that follows. Or am I missing something ?

},

onSuccess(newTrustchain) {
if (newTrustchain) {
dispatch(setTrustchain(newTrustchain));
}
dispatch(
setFlow({
flow: Flow.Synchronize,
step: Step.SynchronizeLoading,
nextStep: Step.Synchronized,
hasTrustchainBeenCreated: false,
}),
);
queryClient.invalidateQueries({ queryKey: [QueryKey.getMembers] });
setUrl(null);
dispatch(setQrCodePinCode(null));
},
});

const startQRCodeProcessing = useCallback(() => {
if (memberCredentials) mutate(memberCredentials);
}, [mutate, memberCredentials]);

return {
url,
error,
isLoading,
isLoading: isPending,
startQRCodeProcessing,
goToActivation,
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { useCallback, useEffect, useState } from "react";
import { createQRCodeHostInstance } from "@ledgerhq/trustchain/qrcode/index";
import { InvalidDigitsError, NoTrustchainInitialized } from "@ledgerhq/trustchain/errors";
import {
InvalidDigitsError,
NoTrustchainInitialized,
QRCodeWSClosed,
} from "@ledgerhq/trustchain/errors";
import { MemberCredentials } from "@ledgerhq/trustchain/types";
import { useDispatch, useSelector } from "react-redux";
import {
trustchainSelector,
Expand All @@ -13,10 +18,12 @@ import { useNavigation } from "@react-navigation/native";
import { NavigatorName, ScreenName } from "~/const";
import { useFeature } from "@ledgerhq/live-common/featureFlags/index";
import getWalletSyncEnvironmentParams from "@ledgerhq/live-common/walletSync/getEnvironmentParams";
import { useQueryClient } from "@tanstack/react-query";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { QueryKey } from "./type.hooks";
import { useInstanceName } from "./useInstanceName";

const MIN_TIME_TO_REFRESH = 30_000;

interface Props {
setCurrentStep: (step: Steps) => void;
currentStep: Steps;
Expand All @@ -36,77 +43,68 @@ export function useQRCodeHost({ setCurrentStep, currentStep, currentOption }: Pr
);
const memberName = useInstanceName();

const [isLoading, setIsLoading] = useState(false);
const [url, setUrl] = useState<string | null>(null);
const [error, setError] = useState<Error | null>(null);
const [pinCode, setPinCode] = useState<string | null>(null);

const navigation = useNavigation();

const startQRCodeProcessing = useCallback(() => {
if (!memberCredentials || isLoading) return;

setError(null);
setIsLoading(true);
createQRCodeHostInstance({
trustchainApiBaseUrl,
onDisplayQRCode: url => {
setUrl(url);
},
onDisplayDigits: digits => {
setPinCode(digits);
setCurrentStep(Steps.PinDisplay);
},
addMember: async member => {
if (trustchain) {
await sdk.addMember(trustchain, memberCredentials, member);
return trustchain;
}
throw new NoTrustchainInitialized();
},
memberCredentials,
memberName,
alreadyHasATrustchain: !!trustchain,
})
.then(newTrustchain => {
if (newTrustchain) {
dispatch(setTrustchain(newTrustchain));
}
queryClient.invalidateQueries({ queryKey: [QueryKey.getMembers] });
navigation.navigate(NavigatorName.WalletSync, {
screen: ScreenName.WalletSyncLoading,
params: {
created: false,
},
});
const { mutate, isPending, error } = useMutation({
mutationFn: (memberCredentials: MemberCredentials) =>
createQRCodeHostInstance({
trustchainApiBaseUrl,
onDisplayQRCode: url => {
setUrl(url);
},
onDisplayDigits: digits => {
setPinCode(digits);
setCurrentStep(Steps.PinDisplay);
},
addMember: async member => {
if (trustchain) {
await sdk.addMember(trustchain, memberCredentials, member);
return trustchain;
}
throw new NoTrustchainInitialized();
},
memberCredentials,
memberName,
alreadyHasATrustchain: !!trustchain,
}),

setUrl(null);
setPinCode(null);
setIsLoading(false);
})
.catch(e => {
if (e instanceof InvalidDigitsError) {
setCurrentStep(Steps.SyncError);
return;
} else if (e instanceof NoTrustchainInitialized) {
setCurrentStep(Steps.UnbackedError);
return;
}
setError(e);
throw e;
onSuccess: newTrustchain => {
if (newTrustchain) {
dispatch(setTrustchain(newTrustchain));
}
queryClient.invalidateQueries({ queryKey: [QueryKey.getMembers] });
navigation.navigate(NavigatorName.WalletSync, {
screen: ScreenName.WalletSyncLoading,
params: {
created: false,
},
});
}, [
trustchain,
memberCredentials,
isLoading,
trustchainApiBaseUrl,
memberName,
setCurrentStep,
sdk,
queryClient,
navigation,
dispatch,
]);

setUrl(null);
setPinCode(null);
},

// Don't use retry here because it always uses a delay despite setting it to 0
onError: e => {
if (e instanceof QRCodeWSClosed) {
const { time } = e as unknown as { time: number };
if (time >= MIN_TIME_TO_REFRESH) startQRCodeProcessing();
}
if (e instanceof InvalidDigitsError) {
setCurrentStep(Steps.SyncError);
}
if (e instanceof NoTrustchainInitialized) {
setCurrentStep(Steps.UnbackedError);
}
},
Copy link
Contributor

Choose a reason for hiding this comment

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

same here?

});

const startQRCodeProcessing = useCallback(() => {
if (memberCredentials) mutate(memberCredentials);
}, [mutate, memberCredentials]);

useEffect(() => {
if (currentStep === Steps.QrCodeMethod && currentOption === Options.SHOW_QR) {
Expand All @@ -117,7 +115,7 @@ export function useQRCodeHost({ setCurrentStep, currentStep, currentOption }: Pr
return {
url,
error,
isLoading,
isLoading: isPending,
startQRCodeProcessing,
pinCode,
};
Expand Down
2 changes: 1 addition & 1 deletion libs/ledgerjs/packages/errors/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export interface LedgerErrorConstructor<F extends { [key: string]: unknown }>

export const createCustomErrorClass = <
F extends { [key: string]: unknown },
T extends LedgerErrorConstructor<F>,
T extends LedgerErrorConstructor<F> = LedgerErrorConstructor<F>,
>(
name: string,
): T => {
Expand Down
2 changes: 2 additions & 0 deletions libs/trustchain/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ export const TrustchainAlreadyInitialized = createCustomErrorClass("TrustchainAl
export const TrustchainAlreadyInitializedWithOtherSeed = createCustomErrorClass(
"TrustchainAlreadyInitializedWithOtherSeed",
);

export const QRCodeWSClosed = createCustomErrorClass<{ time: number }>("QRCodeWSClosed");
8 changes: 6 additions & 2 deletions libs/trustchain/src/qrcode/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Message } from "./types";
import {
InvalidDigitsError,
NoTrustchainInitialized,
QRCodeWSClosed,
TrustchainAlreadyInitialized,
} from "../errors";
import { log } from "@ledgerhq/logs";
Expand Down Expand Up @@ -149,11 +150,14 @@ export async function createQRCodeHostInstance({

onDisplayQRCode(url);
return new Promise((resolve, reject) => {
const startedAt = Date.now();

ws.addEventListener("error", reject);
ws.addEventListener("close", () => {
if (finished) return;
// this error would reflect a protocol error. because otherwise, we would get the "error" event. it shouldn't be visible to user, but we use it to ensure the promise ends.
setTimeout(() => reject(new Error("qrcode websocket prematurely closed")), CLOSE_TIMEOUT);
// this error would reflect a protocol error. because otherwise, we would get the "error" event.
const time = Date.now() - startedAt;
reject(new QRCodeWSClosed("qrcode websocket prematurely closed", { time }));
});
ws.addEventListener("message", async e => {
try {
Expand Down
Loading