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

add a fix for conflicting Stellar transactions #5031

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

Meriem-BM
Copy link
Member

@Meriem-BM Meriem-BM commented Feb 21, 2025

Summary by CodeRabbit

  • New Features

    • Dynamic QR code generation has been introduced on the donation interface, ensuring that QR codes automatically update as donation details change.
  • Refactor

    • Enhanced modularity by extracting the QR code generation process into a separate utility, allowing for consistent and flexible usage across the donation workflow.

Copy link

vercel bot commented Feb 21, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
giveth-dapps-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 21, 2025 2:59pm

Copy link
Contributor

coderabbitai bot commented Feb 21, 2025

Walkthrough

This pull request introduces asynchronous QR code generation within the donation view. A new state variable (qrData) is added to the QR donation card component, along with a useEffect hook that triggers QR code generation upon changes to projectAddress or draftDonationData. Meanwhile, the QR code generation logic is refactored into a new, exported function (generateStellarPaymentQRCode) in the QR code donation hook, allowing for flexible reuse and an extended parameter list.

Changes

File Change Summary
src/components/.../QRDonationCardContent.tsx Added qrData state, introduced useEffect to asynchronously generate QR codes on projectAddress/draftDonationData changes, and updated ImageComponent usage.
src/hooks/useQRCodeDonation.ts Extracted and exported generateStellarPaymentQRCode function with an additional optional draftDonationId parameter; removed the previous inline implementation.

Sequence Diagram(s)

sequenceDiagram
    participant C as QRDonationCardContent
    participant E as useEffect
    participant F as generateStellarPaymentQRCode
    participant S as State (qrData)
    participant I as ImageComponent

    C->>E: On mount / data change
    E->>F: Call generateStellarPaymentQRCode(params)
    F-->>E: Return QR code data URL
    E->>S: Update qrData state
    C->>I: Render with new dataUrl (qrData)
Loading

Possibly related PRs

Suggested reviewers

  • kkatusic
  • MohammadPCh

Poem

I'm a bunny on the code trail so bright,
Hopping through QR bytes with sheer delight,
Generating codes with nimble little paws,
Updating states without a single flaw,
Cheers to changes — carrots and code unite! 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🔭 Outside diff range comments (1)
src/hooks/useQRCodeDonation.ts (1)

113-116: ⚠️ Potential issue

Improve error handling to prevent information leakage.

The current error handling could expose sensitive information by directly throwing the error message.

Apply this diff to improve error handling:

 		} catch (error: any) {
-			console.error('Error creating draft donation', error.message);
-			throw error.message;
+			console.error('Error creating draft donation:', error);
+			throw new Error('Failed to create draft donation. Please try again.');
 		}
🧹 Nitpick comments (2)
src/hooks/useQRCodeDonation.ts (1)

93-111: Add cleanup mechanism for local storage.

The local storage could grow indefinitely as new draft donations are added without removing old ones.

Consider adding a cleanup mechanism to remove expired draft donations from local storage. Here's a suggested implementation:

+	const cleanupOldDraftDonations = (storageData: Record<string, any>) => {
+		const now = new Date().getTime();
+		return Object.entries(storageData).reduce((acc, [key, value]) => {
+			if (value.expiresAt && new Date(value.expiresAt).getTime() > now) {
+				acc[key] = value;
+			}
+			return acc;
+		}, {} as Record<string, any>);
+	};
+
 	const localStorageItem = localStorage.getItem(
 		StorageLabel.DRAFT_DONATIONS,
 	);
 	if (localStorageItem) {
 		const parsedLocalStorageItem = JSON.parse(localStorageItem);
+		const cleanedStorageItem = cleanupOldDraftDonations(parsedLocalStorageItem);
 		parsedLocalStorageItem[walletAddress] = createDraftDonation;
 		localStorage.setItem(
 			StorageLabel.DRAFT_DONATIONS,
-			JSON.stringify(parsedLocalStorageItem),
+			JSON.stringify(cleanedStorageItem),
 		);
src/components/views/donate/OneTime/SelectTokenModal/QRCodeDonation/QRDonationCardContent.tsx (1)

33-78: Improve accessibility of the ImageComponent.

The component needs better accessibility support for screen readers.

Apply this diff to improve accessibility:

 const ImageComponent = ({
 	dataUrl,
 	isExpired,
+	error,
+	isLoading,
 }: {
 	dataUrl: string;
 	isExpired?: boolean;
+	error?: string | null;
+	isLoading?: boolean;
 }) => {
 	const { formatMessage } = useIntl();

+	if (isLoading) {
+		return (
+			<Flex
+				$justifyContent='center'
+				$alignItems='center'
+				style={{ marginBlock: '2rem' }}
+				role="status"
+				aria-label={formatMessage({ id: 'label.generating_qr_code' })}
+			>
+				<Spinner />
+			</Flex>
+		);
+	}

 	return dataUrl ? (
 		<ImageWrapper>
 			{isExpired && (
-				<Overlay>
+				<Overlay role="alert" aria-live="polite">
 					<Flex $justifyContent='center' $alignItems='center'>
 						<InlineToast
 							type={EToastType.Info}
 							message={formatMessage({
 								id: 'label.qr_code_expired',
 							})}
 						/>
 					</Flex>
 				</Overlay>
 			)}
 			<Image
 				src={dataUrl}
 				alt='QR Code'
+				aria-label={formatMessage({ id: 'label.qr_code_for_payment' })}
 				width={200}
 				height={200}
 				unoptimized
 			/>
 		</ImageWrapper>
 	) : (
 		<Flex
 			$justifyContent='center'
 			$alignItems='center'
 			style={{ marginBlock: '2rem' }}
+			role="alert"
+			aria-live="polite"
 		>
 			<InlineToast
 				type={EToastType.Error}
 				message={formatMessage({
-					id: 'label.qr_code_error',
+					id: error ? 'label.qr_code_error' : 'label.qr_code_not_available',
 				})}
 			/>
 		</Flex>
 	);
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c13fb8e and 86de00f.

📒 Files selected for processing (2)
  • src/components/views/donate/OneTime/SelectTokenModal/QRCodeDonation/QRDonationCardContent.tsx (4 hunks)
  • src/hooks/useQRCodeDonation.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build

Comment on lines +18 to +36
export const generateStellarPaymentQRCode = async (
toWalletAddress: string,
amount: number,
memo = '',
draftDonationId?: number,
) => {
const formattedAddress = toWalletAddress.toUpperCase();

const paymentData = `stellar:${formattedAddress}?amount=${amount}&memo=${memo || draftDonationId}`;

try {
// Generate the QR code as a data URL
const qrCodeDataURL = await QRCode.toDataURL(paymentData);
return qrCodeDataURL;
} catch (error) {
console.error('Error generating QR code:', error);
throw error;
}
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add input validation and sanitization.

The function needs validation for its parameters to prevent invalid QR codes and potential security issues.

Apply this diff to add input validation and sanitization:

 export const generateStellarPaymentQRCode = async (
 	toWalletAddress: string,
 	amount: number,
 	memo = '',
 	draftDonationId?: number,
 ) => {
+	if (!toWalletAddress?.trim()) {
+		throw new Error('Wallet address is required');
+	}
+	if (amount <= 0) {
+		throw new Error('Amount must be greater than 0');
+	}
+
 	const formattedAddress = toWalletAddress.toUpperCase();
+	const sanitizedMemo = (memo || draftDonationId || '').toString()
+		.replace(/[<>'"&]/g, ''); // Basic XSS prevention
 
-	const paymentData = `stellar:${formattedAddress}?amount=${amount}&memo=${memo || draftDonationId}`;
+	const paymentData = `stellar:${formattedAddress}?amount=${amount}&memo=${sanitizedMemo}`;
 
 	try {
 		// Generate the QR code as a data URL
 		const qrCodeDataURL = await QRCode.toDataURL(paymentData);
 		return qrCodeDataURL;
 	} catch (error) {
-		console.error('Error generating QR code:', error);
+		const errorMessage = error instanceof Error ? error.message : 'Unknown error';
+		console.error('Error generating QR code:', errorMessage);
 		throw error;
 	}
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const generateStellarPaymentQRCode = async (
toWalletAddress: string,
amount: number,
memo = '',
draftDonationId?: number,
) => {
const formattedAddress = toWalletAddress.toUpperCase();
const paymentData = `stellar:${formattedAddress}?amount=${amount}&memo=${memo || draftDonationId}`;
try {
// Generate the QR code as a data URL
const qrCodeDataURL = await QRCode.toDataURL(paymentData);
return qrCodeDataURL;
} catch (error) {
console.error('Error generating QR code:', error);
throw error;
}
};
export const generateStellarPaymentQRCode = async (
toWalletAddress: string,
amount: number,
memo = '',
draftDonationId?: number,
) => {
if (!toWalletAddress?.trim()) {
throw new Error('Wallet address is required');
}
if (amount <= 0) {
throw new Error('Amount must be greater than 0');
}
const formattedAddress = toWalletAddress.toUpperCase();
const sanitizedMemo = (memo || draftDonationId || '').toString().replace(/[<>'"&]/g, ''); // Basic XSS prevention
const paymentData = `stellar:${formattedAddress}?amount=${amount}&memo=${sanitizedMemo}`;
try {
// Generate the QR code as a data URL
const qrCodeDataURL = await QRCode.toDataURL(paymentData);
return qrCodeDataURL;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
console.error('Error generating QR code:', errorMessage);
throw error;
}
};

Comment on lines +91 to +106
const [qrData, setQRData] = React.useState<string | null>(null);

useEffect(() => {
const generateQRImage = async () => {
const qrImg = await generateStellarPaymentQRCode(
projectAddress?.address ?? '',
draftDonationData?.amount ?? 0,
projectAddress?.memo ?? '',
draftDonationData?.id,
);

setQRData(qrImg);
};

generateQRImage();
}, [projectAddress, draftDonationData]);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling and prevent race conditions in QR code generation.

The current implementation lacks error handling and could lead to race conditions with stale QR codes.

Apply this diff to improve the implementation:

-	const [qrData, setQRData] = React.useState<string | null>(null);
+	const [qrData, setQRData] = React.useState<{ url: string | null; error: string | null }>({
+		url: null,
+		error: null
+	});
+	const [isGeneratingQR, setIsGeneratingQR] = React.useState(false);

 	useEffect(() => {
+		let mounted = true;
 		const generateQRImage = async () => {
+			if (!projectAddress?.address || !draftDonationData?.amount) {
+				return;
+			}
+			setIsGeneratingQR(true);
 			try {
 				const qrImg = await generateStellarPaymentQRCode(
 					projectAddress?.address ?? '',
 					draftDonationData?.amount ?? 0,
 					projectAddress?.memo ?? '',
 					draftDonationData?.id,
 				);
-				setQRData(qrImg);
+				if (mounted) {
+					setQRData({ url: qrImg, error: null });
+				}
 			} catch (error) {
+				console.error('Failed to generate QR code:', error);
+				if (mounted) {
+					setQRData({ url: null, error: 'Failed to generate QR code' });
+				}
+			} finally {
+				if (mounted) {
+					setIsGeneratingQR(false);
+				}
 			}
 		};

 		generateQRImage();
+		return () => {
+			mounted = false;
+		};
 	}, [projectAddress, draftDonationData]);

Then update the ImageComponent usage:

 				<ImageComponent
-					dataUrl={qrData ?? ''}
+					dataUrl={qrData.url ?? ''}
 					isExpired={
 						!!qrDonationStatus &&
 						['expired', 'failed'].includes(qrDonationStatus)
 					}
+					error={qrData.error}
+					isLoading={isGeneratingQR}
 				/>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const [qrData, setQRData] = React.useState<string | null>(null);
useEffect(() => {
const generateQRImage = async () => {
const qrImg = await generateStellarPaymentQRCode(
projectAddress?.address ?? '',
draftDonationData?.amount ?? 0,
projectAddress?.memo ?? '',
draftDonationData?.id,
);
setQRData(qrImg);
};
generateQRImage();
}, [projectAddress, draftDonationData]);
const [qrData, setQRData] = React.useState<{ url: string | null; error: string | null }>({
url: null,
error: null
});
const [isGeneratingQR, setIsGeneratingQR] = React.useState(false);
useEffect(() => {
let mounted = true;
const generateQRImage = async () => {
if (!projectAddress?.address || !draftDonationData?.amount) {
return;
}
setIsGeneratingQR(true);
try {
const qrImg = await generateStellarPaymentQRCode(
projectAddress?.address ?? '',
draftDonationData?.amount ?? 0,
projectAddress?.memo ?? '',
draftDonationData?.id,
);
if (mounted) {
setQRData({ url: qrImg, error: null });
}
} catch (error) {
console.error('Failed to generate QR code:', error);
if (mounted) {
setQRData({ url: null, error: 'Failed to generate QR code' });
}
} finally {
if (mounted) {
setIsGeneratingQR(false);
}
}
};
generateQRImage();
return () => {
mounted = false;
};
}, [projectAddress, draftDonationData]);
/* ... other component code ... */
<ImageComponent
dataUrl={qrData.url ?? ''}
isExpired={
!!qrDonationStatus &&
['expired', 'failed'].includes(qrDonationStatus)
}
error={qrData.error}
isLoading={isGeneratingQR}
/>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: No status
Development

Successfully merging this pull request may close these issues.

1 participant