[TASK-6560] + [TASK-6688] fix: update formatAmount function #583
[TASK-6560] + [TASK-6688] fix: update formatAmount function #583
Conversation
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
WalkthroughThe pull request introduces modifications to amount formatting across multiple files. The primary change is the introduction of a new Changes
Possibly related PRs
Suggested reviewers
Poem
Tip CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command 📜 Recent review detailsConfiguration used: CodeRabbit UI ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (3)
🔇 Additional comments (9)src/utils/__mocks__/wagmi.ts (2)
These details seem aligned with standard Ethereum mainnet configs. The structured format for
Using a separate constant for Sepolia ensures better clarity when mocking different chains in tests. The structure mirrors mainnet, which fosters consistency. src/utils/__mocks__/peanut-sdk.ts (2)
The object structure under
Defining token metadata (like package.json (5)
Setting
Allowing transformation of modules under
Redirecting imports of
Listing these extensions is crucial for consistent ESM behavior in test environments, particularly when dealing with modern JavaScript features. This is a solid step for ensuring TypeScript ESM compatibility. 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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/utils/general.utils.ts (1)
234-284: Well-documented and robust number formatting implementation.The implementation is thorough and handles various edge cases effectively:
- Comprehensive input validation
- Special handling for small numbers
- Intelligent trailing zero removal
- Clear documentation with examples
Consider adding example inputs and outputs in the JSDoc comments to make the behavior more explicit:
/** * formats a number by removing unnecessary trailing zeros after decimal point * if all decimal places are zeros, returns the whole number * preserves small decimal numbers * @param amount - number or string to format * @returns formatted string representation of the number + * @example + * formatAmount("123.4500") => "123.45" + * formatAmount(0.00123) => "0.00123" + * formatAmount("123.00") => "123" */🧰 Tools
🪛 Biome (1.9.4)
[error] 249-249: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.
See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.(lint/suspicious/noGlobalIsNan)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (3)
src/components/Global/ImageGeneration/LinkPreview.tsx(1 hunks)src/components/Request/Pay/Views/Initial.view.tsx(4 hunks)src/utils/general.utils.ts(1 hunks)
🧰 Additional context used
📓 Learnings (2)
src/components/Global/ImageGeneration/LinkPreview.tsx (1)
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#460
File: src/components/Global/ImageGeneration/LinkPreview.tsx:125-128
Timestamp: 2024-11-12T09:39:20.720Z
Learning: 'tokenPrice' is not used currently and will be removed in future PRs.
src/components/Request/Pay/Views/Initial.view.tsx (3)
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#422
File: src/components/Request/Pay/Views/Initial.view.tsx:76-78
Timestamp: 2024-11-12T09:39:20.720Z
Learning: In `src/components/Request/Pay/Views/Initial.view.tsx`, both `txFee` and `utils.formatTokenAmount(estimatedGasCost, 3)` return strings, ensuring consistent return types for `calculatedFee`.
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#422
File: src/components/Request/Pay/Views/Initial.view.tsx:76-78
Timestamp: 2024-11-12T09:39:20.720Z
Learning: In `src/components/Request/Pay/Views/Initial.view.tsx`, both `txFee` and `utils.formatTokenAmount(...)` return strings, ensuring that `calculatedFee` consistently returns a string without the need for additional type conversion.
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#410
File: src/components/Request/Pay/Views/Initial.view.tsx:87-93
Timestamp: 2024-11-12T09:39:20.720Z
Learning: When refactoring to eliminate code duplication, prioritize readability and consider whether the change significantly improves the code. If it doesn't enhance readability or maintainability, it's acceptable to keep the existing code structure.
🪛 Biome (1.9.4)
src/utils/general.utils.ts
[error] 249-249: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.
See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.
(lint/suspicious/noGlobalIsNan)
🔇 Additional comments (3)
src/components/Global/ImageGeneration/LinkPreview.tsx (1)
136-136: LGTM! Appropriate usage of formatAmount.
The change correctly adopts the new formatAmount function while maintaining the parseFloat conversion for type safety.
src/components/Request/Pay/Views/Initial.view.tsx (2)
23-23: LGTM! Consistent adoption of formatAmount.
The import and usage of formatAmount is consistent with the PR objectives. The conditional formatting for USD and token amounts is handled appropriately.
Also applies to: 124-126
358-358: LGTM! Display formatting is consistent.
The display formatting changes correctly utilize the new formatAmount function for both the main amount display and the token amount display.
Also applies to: 373-373
| }} | ||
| > | ||
| {utils.formatTokenAmount(parseFloat(amount), 2)} {tokenSymbol} | ||
| {utils.formatAmount(amount)} {tokenSymbol} |
There was a problem hiding this comment.
@Hugo0 i tired to update the codebase to use the updated function in link preview component too, but unfortunately the fix didn't work as expected, it looks like a caching issue to me, i'm looking into this more deeply
There was a problem hiding this comment.
@Hugo0 nothing sofar, tried changing the font size in a test commit, results are still same, can you try clearing the cache from vercel dashboard once?

| * @returns formatted string representation of the number | ||
| */ | ||
| export const formatAmount = (amount: string | number): string => { | ||
| // handle undefined, null, or empty string |
There was a problem hiding this comment.
Issue, blocking: It'd be nice to test this function under various examples. Can we add test cases for it? Should be simple, we already have jest setup
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/utils/general.utils.ts (1)
242-250:⚠️ Potential issueReplace unsafe isNaN with Number.isNaN.
The current implementation uses the global
isNaNwhich performs type coercion. This can lead to unexpected results.Apply this fix:
- if (isNaN(num)) return '0' + if (Number.isNaN(num)) return '0'🧰 Tools
🪛 Biome (1.9.4)
[error] 250-250: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.
See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.(lint/suspicious/noGlobalIsNan)
🧹 Nitpick comments (1)
src/utils/general.utils.ts (1)
234-241: Add examples to the documentation.While the documentation clearly explains the function's behavior, adding examples would make it even more helpful:
/** * formats a number by: * - displaying 2 significant digits for small numbers (<0.01) + * Example: 0.00123 -> "0.0012" * - removing unnecessary trailing zeros after decimal point + * Example: 1.2300 -> "1.23" * - if all decimal places are zeros, returns the whole number + * Example: 1.000 -> "1" * @param amount - number or string to format * @returns formatted string representation of the number */
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/utils/general.utils.ts(1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/utils/general.utils.ts
[error] 250-250: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.
See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.
(lint/suspicious/noGlobalIsNan)
🔇 Additional comments (1)
src/utils/general.utils.ts (1)
252-259: LGTM! Small numbers handling is well implemented.
The logic correctly handles small numbers by:
- Using exponential notation for precision control
- Converting back to decimal notation
- Maintaining 2 significant digits
| // for normal numbers, round to 2 decimals | ||
| const rounded = Number(num.toFixed(2)) | ||
| const stringValue = rounded.toString() | ||
|
|
||
| // return as is if no decimal point | ||
| if (!stringValue.includes('.')) { | ||
| return stringValue | ||
| } | ||
|
|
||
| const [integerPart, decimalPart] = stringValue.split('.') | ||
|
|
||
| // return integer if decimal part is all zeros | ||
| if (!decimalPart || !/[1-9]/.test(decimalPart)) { | ||
| return integerPart | ||
| } | ||
|
|
||
| // remove trailing zeros from decimal part | ||
| const trimmedDecimal = decimalPart.replace(/0+$/, '') | ||
|
|
||
| // combine integer part with trimmed decimal | ||
| return `${integerPart}.${trimmedDecimal}` |
There was a problem hiding this comment.
💡 Codebase verification
Now I have enough context to provide the final response.
Add unit tests for formatAmount function
The formatAmount function in src/utils/general.utils.ts currently lacks test coverage. Please add unit tests to verify:
- Small number handling (< 0.01)
expect(formatAmount(0.001)).toBe('0.001')
- Normal number rounding
expect(formatAmount(1.2345)).toBe('1.23')
- Trailing zeros removal
expect(formatAmount(1.2300)).toBe('1.23') expect(formatAmount(1.0000)).toBe('1')
- Edge cases
expect(formatAmount(undefined)).toBe('0') expect(formatAmount('')).toBe('0') expect(formatAmount('invalid')).toBe('0')
🔗 Analysis chain
Add unit tests to verify formatting behavior.
The implementation looks good, but it would benefit from comprehensive unit tests to verify:
- Rounding behavior for normal numbers
- Trailing zeros removal
- Whole numbers handling
- Edge cases
Would you like me to help generate unit tests for this function? Here's a sample test case to get started:
describe('formatAmount', () => {
test('formats normal numbers correctly', () => {
expect(formatAmount(1.2300)).toBe('1.23')
expect(formatAmount(1.000)).toBe('1')
expect(formatAmount(1.230)).toBe('1.23')
})
})Let me verify if there are existing tests for this functionality.
Let me try a different approach to find the function and related tests.
Let me check the existing test file to see if it contains tests for this functionality.
Let me find the complete function definition to determine its name.
Let me try one more search to find the function name and any existing tests for it.
🏁 Scripts executed
The following scripts were executed for the analysis:
Error: No shell scripts found
Script:
#!/bin/bash
# Search for test files related to general.utils
fd "general.utils.*test" --type f
# Search for test cases related to formatAmount function
rg -l "formatAmount.*test|test.*formatAmount"
# Look for the actual implementation to understand the function name and location
ast-grep --pattern 'function formatAmount($_) {
$$$
}'
Length of output: 142
Script:
#!/bin/bash
# Find the actual function name from the implementation file
rg -A 5 "toFixed\(2\)" src/utils/general.utils.ts
# Search for any test files in the utils directory
fd "\.test\." src/utils/
# Search for test files containing number formatting tests
rg -l "test.*number.*format|format.*number.*test"
Length of output: 363
Script:
#!/bin/bash
# Check the content of the test file
cat src/utils/__tests__/format.utils.test.ts
# Also check the function name from the implementation file
rg -B 5 "toFixed\(2\)" src/utils/general.utils.ts
Length of output: 2960
Script:
#!/bin/bash
# Get more context around the number formatting function
rg -B 10 -A 15 "toFixed\(2\)" src/utils/general.utils.ts
Length of output: 935
Script:
#!/bin/bash
# Search for the function definition with more context
rg -B 15 -A 20 "Math\.abs\(num\) < 0\.01" src/utils/general.utils.ts
# Search for any test files that might contain number formatting tests
fd "general" --type f --exec grep -l "test" {}
Length of output: 1546
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/utils/__tests__/general.utils.test.ts (1)
1-73: Consider adding tests for extremes (e.g., Infinity, scientific notation).Currently, the test suite does not cover extremely large numerical values or scientific notation inputs like
'1e-8'or'1e8'. Similarly, Infinity and -Infinity inputs are untested. Adding these cases may help ensure robust handling of extreme float scenarios.Would you like me to propose additional test cases covering Infinity, scientific notation, and other extreme values?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/utils/__tests__/general.utils.test.ts(1 hunks)
🔇 Additional comments (6)
src/utils/__tests__/general.utils.test.ts (6)
1-1: Well-structured test imports.
The file correctly imports formatAmount from the relevant module. No issues here.
3-4: Good top-level description blocks.
The nested describe blocks for 'Amount Formatting Utilities' and 'formatAmount' establish a clear, organized structure for test categorization. This approach enhances readability and makes maintenance easier.
5-17: Comprehensive coverage of edge cases.
The tests for empty strings, invalid strings, and NaN correctly verify fallback behavior returning '0'. This is a robust approach for handling malformed or unexpected input.
19-35: Thorough testing of small number handling.
The suite checks various small magnitudes, both positive and negative, as well as string inputs, ensuring that the function correctly formats them to two significant digits. This set of tests is well-designed to catch precision issues.
37-54: Clear coverage for regular numbers.
These tests verify decimal rounding up to two places, the removal of trailing zeros, and correct handling of negative values. The coverage is broad and exemplifies good testing practices.
56-71: Excellent handling of whole numbers and zero.
By confirming that decimals are removed if they are all zeros, and that zero is displayed consistently as '0', these tests ensure that formatting aligns with user expectations for whole number representation.
Summary by CodeRabbit
New Features
Bug Fixes
delteFromLocalStoragetodeleteFromLocalStorage.Chores
formatAmountfunction to handle various input types and improve error handling, including better management of small decimal numbers.formatAmountfunction to ensure robust performance across various scenarios.