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(synapse-interface): Generalizes airdrop decimal display based on SDK gasAirdropAmount [SLT-269] #3196

Merged
merged 5 commits into from
Sep 26, 2024

Conversation

abtestingalpha
Copy link
Collaborator

@abtestingalpha abtestingalpha commented Sep 26, 2024

Description
Generalizes the gas airdrop shown based on size and format of amount.

Summary by CodeRabbit

  • New Features

    • Introduced a utility function for dynamically calculating significant decimal places in numbers.
  • Improvements

    • Enhanced the display logic for gas drop amounts to allow for flexible decimal representation.
    • Adjusted the precision of airdrop dollar amounts based on currency type for more accurate financial calculations.
  • Bug Fixes

    • Corrected the key casing for the cryptocurrency "Metis" to ensure consistency in references.

429cd63: synapse-interface preview link
9937a7a: synapse-interface preview link
357e2f6: synapse-interface preview link
a0a1d5a: synapse-interface preview link
d8e9d7b: synapse-interface preview link

Copy link
Contributor

coderabbitai bot commented Sep 26, 2024

Walkthrough

The changes involve updates to the BridgeExchangeRateInfo.tsx file, where the logic for displaying gas drop amounts and airdrop values has been refined. A new utility function, getSignificantDecimals, is introduced to dynamically determine decimal precision. Additionally, a minor modification is made in the useCoingeckoPrice.ts file to change the casing of a cryptocurrency key.

Changes

File Change Summary
packages/synapse-interface/components/StateManagedBridge/BridgeExchangeRateInfo.tsx Updated GasDropLabel to use getSignificantDecimals for dynamic decimal display; modified getAirdropInDollars for conditional decimal precision based on symbol.
packages/synapse-interface/utils/getSignificantDecimals.ts Introduced getSignificantDecimals utility function to calculate significant decimal places.
packages/synapse-interface/utils/hooks/useCoingeckoPrice.ts Changed key for "Metis" from "METIS" to "Metis" in the ID_MAP object.

Possibly related PRs

Suggested labels

M-synapse-interface, size/m, Typescript

Suggested reviewers

  • bigboydiamonds
  • aureliusbtc

🐰 In the land of code so bright,
Changes hop with pure delight.
Gas drops now dance with flair,
Significant decimals everywhere!
Airdrops shine, their worth is clear,
With each tweak, we cheer and cheer! 🌟


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 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.

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 and nitpick comments (4)
packages/synapse-interface/utils/getSignificantDecimals.ts (2)

8-12: LGTM: Edge cases are handled correctly.

The function properly handles cases where there's no decimal part or the decimal part consists only of zeros. The use of a regular expression for checking all zeros is efficient.

Consider combining the two checks for a slight optimization:

- if (!decimalPart) return 0
- 
- if (/^0*$/.test(decimalPart)) {
-   return defaultDecimals
- }
+ if (!decimalPart || /^0*$/.test(decimalPart)) {
+   return decimalPart ? defaultDecimals : 0
+ }

This change reduces the number of early returns and combines related logic.


14-20: LGTM: Main logic for counting significant decimals is correct.

The function correctly iterates through the decimal part, updating significantDecimals when a non-zero digit is found. This approach accurately identifies the last non-zero digit, which determines the number of significant decimal places.

Consider using a reverse iteration for a potential optimization:

- let significantDecimals = 0
- 
- for (let i = 0; i < decimalPart.length; i++) {
-   if (decimalPart[i] !== '0') {
-     significantDecimals = i + 1
-   }
- }
+ for (let i = decimalPart.length - 1; i >= 0; i--) {
+   if (decimalPart[i] !== '0') {
+     return i + 1
+   }
+ }
+ return 0

This change allows the function to return as soon as it finds the last non-zero digit, potentially improving performance for large decimal parts.

packages/synapse-interface/components/StateManagedBridge/BridgeExchangeRateInfo.tsx (2)

14-14: Improved flexibility in gas drop amount display

The changes to dynamically calculate significant decimals for the gas drop amount display are a good improvement. This approach is more adaptable to different gas drop amounts and chains, aligning well with the PR objective.

Consider extracting the gas drop amount formatting logic into a separate utility function for better reusability and testability. For example:

const formatGasDropAmount = (amount: bigint): string => {
  const stringifiedAmount = formatBigIntToString(amount, 18);
  const significantDecimals = getSignificantDecimals(stringifiedAmount);
  return formatBigIntToString(amount, 18, significantDecimals);
};

Then you can use it in the component like this:

const formattedGasDropAmount = formatGasDropAmount(gasDropAmount);

This would make the component cleaner and the formatting logic easier to test and maintain.

Also applies to: 146-147, 152-152


210-210: Improved precision for airdrop value display

The changes to dynamically set the decimal precision based on the symbol are a good improvement. This allows for more accurate representation of the airdrop value, especially for the 'JEWEL' symbol.

While this change is good, consider future-proofing this approach:

  1. Instead of hardcoding the decimal places, consider creating a configuration object or function that maps symbols to their required decimal places. This would make it easier to add or modify precision for different symbols in the future.
  2. You might want to add a default case for unknown symbols. For example:
const getSymbolDecimals = (symbol: string): number => {
  const decimalMap: Record<string, number> = {
    JEWEL: 4,
    // Add other symbols here as needed
  };
  return decimalMap[symbol] || 2; // Default to 2 decimals if symbol is not found
};

const decimals = getSymbolDecimals(symbol);

This approach would make the code more maintainable and extensible for future symbol additions or changes.

Also applies to: 216-216

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between abeea4d and d49af6a.

📒 Files selected for processing (3)
  • packages/synapse-interface/components/StateManagedBridge/BridgeExchangeRateInfo.tsx (3 hunks)
  • packages/synapse-interface/utils/getSignificantDecimals.ts (1 hunks)
  • packages/synapse-interface/utils/hooks/useCoingeckoPrice.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/synapse-interface/utils/hooks/useCoingeckoPrice.ts
🔇 Additional comments (3)
packages/synapse-interface/utils/getSignificantDecimals.ts (3)

1-7: LGTM: Function signature and initial parsing are well-defined.

The function signature is clear, uses proper TypeScript types, and provides a sensible default for defaultDecimals. The initial parsing of the input string is correct for isolating the decimal part.


22-23: LGTM: Return statement is correct.

The function properly returns the calculated significantDecimals.


1-23: Overall, the implementation is solid and aligns with the PR objectives.

The getSignificantDecimals function provides a flexible way to determine significant decimals, which can effectively improve the display of gas airdrop amounts. It handles various edge cases and should work correctly for different input formats. The implementation is clear and maintainable.

To ensure the function works as expected, consider adding the following test cases:

console.log(getSignificantDecimals('1.00000')); // Expected: 0
console.log(getSignificantDecimals('1.10000')); // Expected: 1
console.log(getSignificantDecimals('1.10001')); // Expected: 5
console.log(getSignificantDecimals('1')); // Expected: 0
console.log(getSignificantDecimals('1.000', 4)); // Expected: 4

These test cases cover various scenarios including trailing zeros, no decimal part, and custom default decimals.

Copy link

cloudflare-workers-and-pages bot commented Sep 26, 2024

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: a02f800
Status: ✅  Deploy successful!
Preview URL: https://8f3ea9f2.sanguine-fe.pages.dev
Branch Preview URL: https://fe-airdrop-decimals.sanguine-fe.pages.dev

View logs

Copy link

cloudflare-workers-and-pages bot commented Sep 26, 2024

Deploying sanguine with  Cloudflare Pages  Cloudflare Pages

Latest commit: d96f06d
Status: ✅  Deploy successful!
Preview URL: https://426097fc.sanguine.pages.dev
Branch Preview URL: https://fe-airdrop-decimals.sanguine.pages.dev

View logs

Copy link

codecov bot commented Sep 26, 2024

Bundle Report

Changes will increase total bundle size by 155.06kB (0.43%) ⬆️. This is within the configured threshold ✅

Detailed changes
Bundle name Size Change
explorer-ui-server-cjs* 865.78kB 283 bytes (-0.03%) ⬇️
explorer-ui-client-array-push* 2.31MB 750 bytes (-0.03%) ⬇️
synapse-interface-client-array-push* 7.28MB 147 bytes (0.0%) ⬆️
synapse-interface-server-cjs 1.64MB 147.32kB (9.86%) ⬆️
widget-cjs-esm* 281.92kB 8.62kB (3.15%) ⬆️

ℹ️ *Bundle size includes cached data from a previous commit

Copy link

codecov bot commented Sep 26, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 90.56974%. Comparing base (f0b13bc) to head (a02f800).
Report is 7 commits behind head on master.

Additional details and impacted files
@@                 Coverage Diff                  @@
##              master       #3196          +/-   ##
====================================================
+ Coverage   40.97804%   90.56974%   +49.59169%     
====================================================
  Files            459          54         -405     
  Lines          25643        1018       -24625     
  Branches         343          82         -261     
====================================================
- Hits           10508         922        -9586     
+ Misses         14383          93       -14290     
+ Partials         752           3         -749     
Flag Coverage Δ
cctp-relayer ?
core ?
ethergo ?
git-changes-action ?
omnirpc ?
opbot ?
packages 90.56974% <ø> (ø)
screener-api ?
scribe ?
solidity ?
tools ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Collaborator

@ChiTimesChi ChiTimesChi Sep 26, 2024

Choose a reason for hiding this comment

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

Just to confirm, we are returning the last non-zero decimal number digit here?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

The function counts how many digits are important, starting from the left and then stops at the last important non-zero number. So, it returns how many important digits there are.

Couple examples

  1. For 0.002000000000000000:
  • The decimal part is 002000000000000000
  • The last non-zero digit is 2 (in 3rd position)
  • So function returns 3
  1. For 1.000000000000000000:
  • Decimal part is 000000000000000000
  • Since all decimal digits are zero it returns defaultDecimals (2). This is for Canto, so the airdrop shows 1.00 instead of just 1.

@abtestingalpha abtestingalpha merged commit aa37b50 into master Sep 26, 2024
46 checks passed
@abtestingalpha abtestingalpha deleted the fe/airdrop-decimals branch September 26, 2024 18:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants