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

Feat/add cbbtc recurring #4955

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open

Feat/add cbbtc recurring #4955

wants to merge 6 commits into from

Conversation

kkatusic
Copy link
Collaborator

@kkatusic kkatusic commented Jan 21, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced support for tokens with 8 decimal places in deposit and donation functionality
  • Bug Fixes

    • Adjusted decimal precision handling for token amounts
    • Modified maximum decimal input validation for user inputs
    • Updated token balance display logic to ensure accuracy based on decimal configuration
  • Performance

    • Refined token amount calculation and scaling mechanisms for improved accuracy

@kkatusic kkatusic self-assigned this Jan 21, 2025
Copy link

vercel bot commented Jan 21, 2025

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

Name Status Preview Comments Updated (UTC)
giveth-dapps-v2 🛑 Canceled (Inspect) Jan 24, 2025 0:36am
giveth-dapps-v2 (feature-tests) ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 24, 2025 0:36am

Copy link
Contributor

coderabbitai bot commented Jan 21, 2025

Walkthrough

This pull request focuses on modifying the handling of tokens with 8 decimal places across multiple components. The changes primarily involve adjusting decimal place calculations, scaling factors, and input validation for tokens with 8 decimals. The modifications ensure more consistent and precise processing of token amounts, particularly for tokens that have 8 decimal places, by updating the logic in deposit, input, and display components.

Changes

File Change Summary
src/components/views/donate/Recurring/ModifySuperToken/DepositSuperToken.tsx Updated conditional logic to handle tokens with 6 or 8 decimal places, modifying amount calculation and formatting
src/components/AmountInput/AmountInput.tsx Reduced maximum decimal places from 8 to 6 for tokens with 8 decimals, affecting input validation and display
src/components/views/donate/Recurring/RecurringDonationCard.tsx Modified scaling factor for 8-decimal tokens from 100n to 1000000n, and updated balance display logic
src/components/views/userProfile/donationsTab/recurringTab/EndStreamModal.tsx Introduced logic to find the correct contract based on recurringNetworkId for the receiver parameter in deleteFlow method

Possibly related PRs

Suggested labels

Code Review

Suggested reviewers

  • Meriem-BM
  • lovelgeorge99
  • mateodaza

Poem

🐰 Decimal dance, tokens so fine,
Eight places trimmed to six in line,
Scaling factors shift with care,
Precision balanced everywhere,
A rabbit's math, both smart and divine! 🧮


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: 0

🔭 Outside diff range comments (1)
src/components/views/donate/Recurring/ModifySuperToken/DepositSuperToken.tsx (1)

Line range hint 138-144: Avoid potential precision loss in token amount conversion.

The current implementation has several concerns:

  1. Converting BigInt to Number using Number(amount) could lead to precision loss for large amounts.
  2. The decimal handling is limited to only 6 and 8 decimals, which might not cover all token types.
  3. There's no validation for the decimals value.

Consider this safer implementation:

-			if (token && (token.decimals === 6 || token.decimals === 8)) {
-				const divisor = BigInt(10 ** token.decimals);
-				const currentAmount = Number(amount) / Number(divisor);
-				newAmount = ethers.utils
-					.parseUnits(currentAmount.toString(), 18)
-					.toBigInt();
+			if (token?.decimals != null) {
+				// Validate decimals
+				if (token.decimals < 0 || token.decimals > 18) {
+					throw new Error('Invalid token decimals');
+				}
+				
+				// Convert from token decimals to 18 decimals while preserving precision
+				if (token.decimals < 18) {
+					newAmount = amount * BigInt(10 ** (18 - token.decimals));
+				} else if (token.decimals > 18) {
+					newAmount = amount / BigInt(10 ** (token.decimals - 18));
+				}
+			}

This implementation:

  1. Preserves precision by using BigInt arithmetic
  2. Supports any valid number of decimals
  3. Validates the decimals value
  4. Handles both scaling up and down to 18 decimals
🧹 Nitpick comments (1)
src/components/views/donate/Recurring/ModifySuperToken/DepositSuperToken.tsx (1)

Line range hint 145-157: Consider adding error details to improve debugging.

The error handling could be more informative to help diagnose issues in production.

 			const upgradeOperation = await superTokenAsset.upgrade({
 				amount: newAmount.toString(),
 			});
 			const tx = await upgradeOperation.exec(signer);
 			const res = await tx.wait();
 			if (!res.status) {
-				throw new Error('Deposit failed');
+				throw new Error(`Deposit failed: Transaction reverted. Hash: ${tx.hash}`);
 			}
 			refreshBalance();
 			setStep(EModifySuperTokenSteps.DEPOSIT_CONFIRMED);
 		} catch (error: any) {
 			if (error?.code === 'ACTION_REJECTED') {
 				setStep(EModifySuperTokenSteps.MODIFY);
 			} else {
+				console.error('Deposit error:', {
+					error,
+					token: token?.symbol,
+					decimals: token?.decimals,
+					amount: amount.toString(),
+					newAmount: newAmount.toString(),
+				});
 				showToastError(error);
 				setStep(EModifySuperTokenSteps.DEPOSIT);
 			}
-			console.error('error', error);
 		}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 73c3958 and fc95b16.

📒 Files selected for processing (1)
  • src/components/views/donate/Recurring/ModifySuperToken/DepositSuperToken.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (1)
src/components/views/donate/Recurring/ModifySuperToken/DepositSuperToken.tsx (1)

Line range hint 138-144: Verify consistent decimal handling across the codebase.

Let's check if there are other components that need similar updates for handling different token decimals.

✅ Verification successful

Decimal handling implementation is consistent with codebase patterns

The implementation follows the established patterns for handling tokens with 6 and 8 decimals, matching similar implementations in RecurringDonationCard, RecurringDonationModal, and AmountInput components.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar token decimal handling patterns
echo "Searching for token decimal comparisons..."
rg "decimals === 6" --type ts
rg "decimals === 8" --type ts
rg "token\.decimals" -B 2 -A 2 --type ts

echo "Searching for potential test files..."
fd "test|spec" -e ts -e tsx | grep -i "token\|deposit"

Length of output: 13692

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: 0

🧹 Nitpick comments (1)
src/components/AmountInput/AmountInput.tsx (1)

83-85: Fix outdated comment.

The comment states "Limit to 8 decimals" but the code actually limits to 6 decimals.

-				if (_decimals?.length > 6) return; // Limit to 8 decimals
+				if (_decimals?.length > 6) return; // Limit to 6 decimals
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4b02a86 and d26bf42.

📒 Files selected for processing (2)
  • src/components/AmountInput/AmountInput.tsx (2 hunks)
  • src/components/views/donate/Recurring/RecurringDonationCard.tsx (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (3)
src/components/AmountInput/AmountInput.tsx (1)

55-55: Verify the impact of reducing decimal precision for 8-decimal tokens.

The change reduces the maximum allowed decimals from 8 to 6 for tokens with 8 decimal places. While this might improve UI readability, it could affect precision in certain scenarios.

✅ Verification successful

Display precision change for 8-decimal tokens is aligned with industry standards

The reduction from 8 to 6 decimal places only affects the display/input formatting and not the underlying token precision. This change:

  • Improves readability while maintaining sufficient precision for all practical use cases
  • Matches the standard Bitcoin display format of 6 decimal places
  • Only impacts one token (cbBTC) in the entire codebase
  • Does not affect actual transaction precision
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any token declarations or configurations with 8 decimals
# to understand the impact scope

rg -A 5 'decimals.*8' .

Length of output: 23939

src/components/views/donate/Recurring/RecurringDonationCard.tsx (2)

363-377: LGTM! Consistent decimal handling across components.

The balance display logic now aligns with the decimal precision changes in AmountInput.tsx, ensuring consistent display of token amounts throughout the application.


160-160: ⚠️ Potential issue

Verify the scale factor adjustment for 8-decimal tokens.

The scale factor for 8-decimal tokens has been significantly increased from 100n to 1000000n. This change affects flow rate calculations and should be carefully validated.

Please verify:

  1. The impact on existing streams
  2. The alignment with Superfluid's flow rate calculations
  3. The relationship with the decimal precision changes in AmountInput.tsx
✅ Verification successful

Scale factor change for 8-decimal tokens is correct

The change from 100n to 1000000n for 8-decimal tokens is a proper fix that:

  • Maintains proportional scaling with 6-decimal tokens (10000n vs 1000000n)
  • Aligns with the 6-decimal place precision limit in AmountInput.tsx
  • Preserves calculation accuracy as scale factors cancel out in final flow rates
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for flow rate calculations to understand the impact
rg -A 5 'flowRate|scaleFactor' .

Length of output: 34582


Script:

#!/bin/bash
# Search for decimal-specific token handling and scale factors
rg -A 3 "decimals.*[68]|scaleFactor" .

Length of output: 18988

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: 0

🧹 Nitpick comments (2)
src/components/views/userProfile/donationsTab/recurringTab/EndStreamModal.tsx (2)

120-123: Consider explicitly handling missing contracts for this network.

If find doesn’t return a matching contract (e.g., no anchorContracts for this network), the code falls back to an empty string at line 126. This may cause errors if the flow requires a valid address. Consider raising an error or providing a more informative fallback.

You might use something like:

 const matchingContract = donation.project.anchorContracts.find(
   contract => contract.networkId === recurringNetworkId,
 );

+if (!matchingContract) {
+  throw new Error(`No anchor contract found for network ${recurringNetworkId}.`);
+}

126-126: Double-check fallback to empty string as receiver.

If no matching address is found, passing '' as a receiver may produce unintended behavior. Consider using a zero address (0x000…) or throwing an error instead of using an empty string to avoid potentially ambiguous scenarios in your flow logic.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d26bf42 and 5040e3d.

📒 Files selected for processing (1)
  • src/components/views/userProfile/donationsTab/recurringTab/EndStreamModal.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build

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.

2 participants