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

chalabi/safe truncation #204

Merged
merged 4 commits into from
Jan 13, 2025
Merged

chalabi/safe truncation #204

merged 4 commits into from
Jan 13, 2025

Conversation

chalabi2
Copy link
Collaborator

@chalabi2 chalabi2 commented Jan 11, 2025

  • fix: no manual chainNames
  • fix: safe truncation

Fixes #200

Summary by CodeRabbit

Release Notes

  • New Features

    • None
  • Improvements

    • Enhanced address display across multiple components with a consistent 24-character truncation.
    • Introduced dynamic chain configuration using environment variables for address retrieval and transaction handling.
    • Simplified error handling in group-related components.
  • Bug Fixes

    • None
  • Chores

    • Updated address handling and truncation logic in wallet and address-related components.
    • Replaced hardcoded chain identifiers with environment-based configuration throughout the application.
    • Streamlined testing for the Success component to focus on partial string matches.

Copy link
Contributor

coderabbitai bot commented Jan 11, 2025

Walkthrough

The pull request introduces a series of changes across multiple components, focusing on enhancing the flexibility of chain configuration and address display. The primary modifications involve replacing hardcoded 'manifest' chain references with a dynamic env.chain configuration and standardizing address truncation to a consistent 24-character format. These changes aim to improve the application's adaptability to different environments and provide a more uniform user experience when displaying wallet addresses.

Changes

File Change Summary
components/groups/components/groupControls.tsx Updated useChain hook to use env.chain instead of hardcoded 'manifest'
components/groups/components/myGroups.tsx Modified address retrieval to use env.chain and simplified error handling
components/groups/forms/groups/ConfirmationForm.tsx Integrated env.chain in transaction-related hooks
components/groups/modals/voteModal.tsx Replaced hardcoded chain references with env.chain in hooks
components/react/addressCopy.tsx Fixed address truncation to always use first 24 characters
components/wallet.tsx Updated wallet address display to use truncateAddress for formatting
utils/string.ts Modified truncateString function to accept prefix and suffix lengths; added truncateAddress function
components/groups/modals/memberManagementModal.tsx Updated address input to use truncateAddress for display
components/react/views/Connected.tsx Replaced truncateString with truncateAddress for address display
components/admins/components/validatorList.tsx Updated slice prop for address display to 24 characters
components/bank/components/historyBox.tsx Updated slice prop for address display to 24 characters
components/bank/modals/txInfo.tsx Updated slice prop for address display to 24 characters
components/groups/forms/groups/__tests__/Success.test.tsx Updated tests to check for truncated address strings

Assessment against linked issues

Objective Addressed Explanation
Secure Bech32 truncation [#200]

Possibly related PRs

  • fix: long account name render #39: The changes in this PR involve updating the method of obtaining the address from a hardcoded string to using env.chain, which is similar to the changes made in the main PR regarding the dynamic retrieval of the address variable.
  • fix: admin theme #42: This PR includes updates to the VotingPopup component where the hardcoded string 'manifest' is replaced with env.chain in the useChain hook, aligning with the changes in the main PR that also modify how the chain address is retrieved.
  • feat: enable ledger #143: This PR introduces modifications to the WalletList component, including the addition of env.chain for dynamic wallet handling, which is consistent with the changes made in the main PR regarding the use of environment variables.

Suggested Labels

enhancement, render

Suggested Reviewers

  • chalabi2

Poem

🐰 A rabbit's tale of code so bright,
Where addresses dance with might,
Twenty-four chars, no more, no less,
Env config brings coding finesse!
Truncate with grace, deploy with glee! 🌟

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

🔭 Outside diff range comments (2)
components/groups/components/myGroups.tsx (1)

Line range hint 132-140: Standardize group name parsing logic.

The group name parsing logic is duplicated and inconsistent between different parts of the code. Consider extracting this into a utility function for better maintainability and consistency.

Create a utility function:

function parseGroupName(metadata: string | null): string {
  if (!metadata) return 'Untitled Group';
  try {
    const parsed = JSON.parse(metadata);
    return parsed?.title || 'Untitled Group';
  } catch (e) {
    console.warn('Failed to parse group metadata:', e);
    return 'Untitled Group';
  }
}

Then use it consistently throughout the code:

-    try {
-      const metadata = group.metadata ? JSON.parse(group.metadata) : null;
-      groupName = metadata?.title ?? 'Untitled Group';
-    } catch (e) {
-      // If JSON parsing fails, fall back to default name
-      // console.warn('Failed to parse group metadata:', e);
-    }
+    groupName = parseGroupName(group.metadata);

Also applies to: 476-484

components/react/addressCopy.tsx (1)

Line range hint 4-11: Remove unused slice parameter and utilize truncateString utility

The component accepts a slice parameter that's no longer used, and it duplicates truncation logic that exists in utils/string.ts.

Consider this improvement:

-  slice: number;
   size?: string;
 }) => {
   // ...
-  const truncatedAddress = `${address?.slice(0, 24)}...`;
+  const truncatedAddress = truncateString(address);

Also applies to: 34-34

🧹 Nitpick comments (2)
components/groups/components/myGroups.tsx (1)

Line range hint 106-113: Restore error logging for better debuggability.

The commented-out error logging reduces our ability to debug metadata parsing issues in production. Consider using a proper logging service or error tracking system instead of removing the logs.

     } catch (e) {
-      // console.warn('Failed to parse group metadata:', e);
+      console.warn('Failed to parse group metadata:', e);
+      // TODO: Consider sending to error tracking service
       return 'Untitled Group'.toLowerCase().includes(searchTerm.toLowerCase());
     }
components/wallet.tsx (1)

Line range hint 1-1: Consider centralizing address truncation logic

To improve maintainability and consistency, consider:

  1. Making truncateString in utils/string.ts the single source of truth for address truncation
  2. Adding a new truncateAddress utility specifically for wallet addresses
  3. Creating constants for common values like the truncation length

Example implementation:

// utils/constants.ts
export const ADDRESS_TRUNCATE_LENGTH = 24;

// utils/string.ts
export function truncateAddress(address: string): string {
  return truncateString(address, ADDRESS_TRUNCATE_LENGTH);
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 738ad4e and 361197a.

📒 Files selected for processing (7)
  • components/groups/components/groupControls.tsx (2 hunks)
  • components/groups/components/myGroups.tsx (1 hunks)
  • components/groups/forms/groups/ConfirmationForm.tsx (2 hunks)
  • components/groups/modals/voteModal.tsx (2 hunks)
  • components/react/addressCopy.tsx (1 hunks)
  • components/wallet.tsx (1 hunks)
  • utils/string.ts (1 hunks)
🔇 Additional comments (4)
components/groups/modals/voteModal.tsx (1)

7-7: LGTM! Chain configuration changes look good.

The replacement of hardcoded chain name with environment configuration improves flexibility and maintainability.

Also applies to: 17-19

components/groups/forms/groups/ConfirmationForm.tsx (1)

9-9: LGTM! Chain configuration changes look good.

The replacement of hardcoded chain name with environment configuration improves flexibility and maintainability.

Also applies to: 33-34

components/groups/components/groupControls.tsx (1)

29-29: LGTM! Chain configuration changes look good.

The replacement of hardcoded chain name with environment configuration improves flexibility and maintainability.

Also applies to: 235-235

components/groups/components/myGroups.tsx (1)

103-103: LGTM! Chain configuration changes look good.

The replacement of hardcoded chain name with environment configuration improves flexibility and maintainability.

Copy link
Contributor

@fmorency fmorency left a comment

Choose a reason for hiding this comment

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

Hey @chalabi2, I pushed some fixes. Can you review please?

Copy link

codecov bot commented Jan 13, 2025

Codecov Report

Attention: Patch coverage is 83.33333% with 6 lines in your changes missing coverage. Please review.

Project coverage is 54.39%. Comparing base (738ad4e) to head (6af1718).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...omponents/groups/forms/groups/ConfirmationForm.tsx 77.77% 2 Missing ⚠️
components/wallet.tsx 33.33% 2 Missing ⚠️
components/bank/components/historyBox.tsx 0.00% 1 Missing ⚠️
components/react/views/Connected.tsx 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #204      +/-   ##
==========================================
+ Coverage   54.24%   54.39%   +0.14%     
==========================================
  Files         153      153              
  Lines       15982    15960      -22     
==========================================
+ Hits         8670     8681      +11     
+ Misses       7312     7279      -33     

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

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

🧹 Nitpick comments (4)
components/groups/forms/groups/__tests__/Success.test.tsx (1)

26-28: Strengthen test assertions for address truncation.

The current test assertions only verify the prefix of truncated addresses. Consider using exact string matching to ensure the truncation behavior is precisely as expected.

-    expect(screen.getByText('manifest1autho...')).toBeInTheDocument();
-    expect(screen.getByText('manifest1efd63...')).toBeInTheDocument();
-    expect(screen.getByText('manifest1hj5fv...')).toBeInTheDocument();
+    expect(screen.getByText('manifest1autho...', { exact: false })).toBeInTheDocument();
+    const addresses = screen.getAllByText(/^manifest1[a-z0-9]+\.{3}$/);
+    expect(addresses).toHaveLength(3);
components/react/addressCopy.tsx (1)

3-3: LGTM! Consider adding error boundary.

The refactoring to use the truncateAddress utility and adding a default value for the address prop improves code maintainability and robustness.

Consider wrapping the clipboard operations in an error boundary to gracefully handle cases where the clipboard API is not available:

+const useClipboard = () => {
+  const copyToClipboard = async (text: string) => {
+    if (!navigator.clipboard) {
+      throw new Error('Clipboard API not available');
+    }
+    return navigator.clipboard.writeText(text);
+  };
+  return { copyToClipboard };
+};

 export const TruncatedAddressWithCopy = ({
   address = '',
   slice,
   size,
 }: {
   address: string;
   slice: number;
   size?: string;
 }) => {
   const [copied, setCopied] = useState(false);
+  const { copyToClipboard } = useClipboard();

   // ... rest of the component

   const handleCopy = async (e: React.MouseEvent<HTMLDivElement>) => {
     e.stopPropagation();
     e.preventDefault();
     try {
-      await navigator.clipboard.writeText(address);
+      await copyToClipboard(address);
       setCopied(true);
     } catch (err) {
       console.error('Failed to copy: ', err);
+      // Optionally show a user-friendly error message
     }
   };

Also applies to: 6-6, 35-35

utils/string.ts (2)

3-7: Add input validation to prevent edge cases.

The function should validate its inputs to handle edge cases gracefully.

 export function truncateString(str: string, prefixLen: number = 6, suffixLen: number = 6): string {
+  if (!str) return '';
+  if (prefixLen < 0 || suffixLen < 0) return str;
   if (str.length <= prefixLen + suffixLen) return str;
 
   return str.slice(0, prefixLen) + '...' + str.slice(-suffixLen);
 }

9-12: Add address validation and format checking.

The function should validate the input address and its format.

 export function truncateAddress(address: string, num: number = 24) {
+  if (!address) return '';
+  if (num < 0) return address;
+  // Optional: Add address format validation if needed
+  // if (!isValidManifestAddress(address)) return address;
   if (address.length <= num) return address;
 
   return address.slice(0, num) + '...';
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d5ce8dd and 6af1718.

📒 Files selected for processing (12)
  • components/admins/components/validatorList.tsx (1 hunks)
  • components/bank/components/__tests__/historyBox.test.tsx (2 hunks)
  • components/bank/components/historyBox.tsx (1 hunks)
  • components/bank/modals/txInfo.tsx (1 hunks)
  • components/groups/components/myGroups.tsx (2 hunks)
  • components/groups/forms/groups/ConfirmationForm.tsx (2 hunks)
  • components/groups/forms/groups/__tests__/Success.test.tsx (1 hunks)
  • components/groups/modals/memberManagementModal.tsx (2 hunks)
  • components/react/addressCopy.tsx (2 hunks)
  • components/react/views/Connected.tsx (2 hunks)
  • components/wallet.tsx (2 hunks)
  • utils/string.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • components/groups/components/myGroups.tsx
🧰 Additional context used
🪛 GitHub Check: codecov/patch
components/bank/components/historyBox.tsx

[warning] 251-251: components/bank/components/historyBox.tsx#L251
Added line #L251 was not covered by tests

components/react/views/Connected.tsx

[warning] 86-86: components/react/views/Connected.tsx#L86
Added line #L86 was not covered by tests

components/groups/forms/groups/ConfirmationForm.tsx

[warning] 34-35: components/groups/forms/groups/ConfirmationForm.tsx#L34-L35
Added lines #L34 - L35 were not covered by tests

components/wallet.tsx

[warning] 134-134: components/wallet.tsx#L134
Added line #L134 was not covered by tests


[warning] 138-138: components/wallet.tsx#L138
Added line #L138 was not covered by tests

🔇 Additional comments (5)
components/bank/components/__tests__/historyBox.test.tsx (1)

10-17: LGTM! Clean router mock implementation.

The router mock is well-implemented with proper cleanup in the afterEach block.

components/bank/modals/txInfo.tsx (1)

120-120: LGTM! Consistent address truncation length.

The update to use 24 characters for address truncation aligns with the standardization effort across the application.

components/admins/components/validatorList.tsx (1)

229-229: LGTM!

The change to standardize address truncation to 24 characters is consistent with the application-wide update. The component maintains good accessibility with proper ARIA attributes.

components/groups/modals/memberManagementModal.tsx (1)

14-14: Verify form submission with truncated address display.

While the UI change to display truncated addresses is consistent with the application-wide update, ensure that the form submission still uses the full address value.

Let's verify the form submission behavior:

Also applies to: 325-325

✅ Verification successful

Form submission correctly uses full addresses

The truncateAddress function is only used for display purposes in the input field UI. The form submission logic in handleConfirm uses the raw, untruncated addresses from the form state when building the transaction messages.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the full address is preserved during form submission
# Test: Search for form submission handling code
ast-grep --pattern 'handleConfirm = async (values: { members: ExtendedMember[] }) => {
  $$$
  const encodedMessages = buildMessages(values.members);
  $$$
}'

Length of output: 160


Script:

#!/bin/bash
# Find usage of truncateAddress
rg "truncateAddress" -A 5

# Look for form submission patterns
ast-grep --pattern 'const $_ = async ($_) => {
  $$$
}'

# Also search for form submission related terms
rg "onSubmit|handleSubmit|formik" -A 5

Length of output: 66321

components/groups/forms/groups/ConfirmationForm.tsx (1)

38-39: LGTM! Good use of environment configuration.

The replacement of hardcoded chain name with env.chain improves flexibility and maintainability.

@@ -5,7 +5,7 @@
import ProfileAvatar from '@/utils/identicon';
import { useBalance } from '@/hooks/useQueries';
import { CopyIcon } from '@/components/icons';
import { getRealLogo, shiftDigits, truncateString } from '@/utils';
import { getRealLogo, shiftDigits, truncateAddress } from '@/utils';
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Add basic test coverage for truncateAddress utility

The truncateAddress function in utils/string.ts lacks test coverage. While the implementation is straightforward, tests should verify:

  • Handling of addresses shorter than the limit
  • Truncation of addresses longer than the default 24 characters
  • Empty string handling
🔗 Analysis chain

Add test coverage for address truncation.

The address truncation implementation looks good, but the static analysis indicates that line 86 lacks test coverage. Consider adding test cases to verify the truncation behavior.

Would you like me to help generate test cases for the address truncation functionality?

Also applies to: 86-86

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for existing tests of Connected component
fd -e tsx -e ts "Connected.test" components/react/views/

Length of output: 56


Script:

#!/bin/bash
# Find all test files in views directory
echo "=== Test files in views ==="
fd -e test.tsx -e test.ts . components/react/views/

# Find truncateAddress tests
echo -e "\n=== truncateAddress tests ==="
fd -e test.tsx -e test.ts . utils/

# Find actual usage of truncateAddress
echo -e "\n=== truncateAddress usage in Connected ==="
rg -C 2 "truncateAddress" components/react/views/Connected.tsx

Length of output: 848


Script:

#!/bin/bash
# Find truncateAddress tests using ripgrep
echo "=== Searching for truncateAddress tests ==="
rg -l "truncateAddress.*test"

# Find truncateAddress implementation
echo -e "\n=== truncateAddress implementation ==="
rg -C 4 "export.*truncateAddress"

Length of output: 628

@@ -248,7 +248,7 @@
? tx.data.to_address
: tx.data.from_address
}
slice={6}
slice={24}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Add test coverage for address truncation behavior

The existing test suite in components/bank/components/__tests__/historyBox.test.tsx lacks coverage for the address truncation functionality. Consider adding a test case that verifies addresses are correctly truncated to 24 characters.

🔗 Analysis chain

LGTM! Consider adding test coverage.

The change to standardize address truncation to 24 characters aligns with the broader effort to ensure consistent address display across the application.

The line is flagged as not covered by tests. Consider adding test coverage to ensure the address truncation behavior works as expected:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for existing test files and patterns
# Test: Search for test files that might need updating
fd -e test.tsx -e spec.tsx -e test.ts -e spec.ts | rg -i "historybox|address"

Length of output: 136


Script:

#!/bin/bash
# Check the content of historyBox test file for address-related test cases
cat components/bank/components/__tests__/historyBox.test.tsx

Length of output: 3679

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 251-251: components/bank/components/historyBox.tsx#L251
Added line #L251 was not covered by tests

Comment on lines +31 to +37
let jsonString: string;
try {
jsonString = JSON.stringify(groupMetadata);
} catch (error) {
console.error('Failed to serialize group metadata:', error);
throw new Error('Invalid group metadata format');
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Add test coverage for JSON serialization error handling

The test file lacks coverage for the JSON serialization error handling. Consider adding these test cases:

  • Test successful serialization of valid group metadata
  • Test error handling when serialization fails (e.g., with circular references)
🔗 Analysis chain

Add test coverage for error handling.

The error handling for JSON serialization is good, but it lacks test coverage.

Could you add test cases to cover the error handling scenario? Here's a verification script to check current test coverage:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check test coverage for the error handling block
rg -l "test.*ConfirmationForm.*metadata.*serialization" -t ts

Length of output: 63


Script:

#!/bin/bash
# Find test files related to ConfirmationForm
fd "ConfirmationForm.*test" --type f

# If no direct test file found, check for test files in the same directory
fd ".*test.*\.(ts|tsx)$" --type f --exec grep -l "ConfirmationForm"

Length of output: 366


Script:

#!/bin/bash
# Check content of the relevant test file
cat "components/groups/forms/groups/__tests__/ConfirmationForm.test.tsx"

Length of output: 2752

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 34-35: components/groups/forms/groups/ConfirmationForm.tsx#L34-L35
Added lines #L34 - L35 were not covered by tests

? `${username.slice(0, 20)}...`
: username
: 'Connected User'}
{username ? truncateString(username, 20) : 'Connected User'}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Add comprehensive test coverage for wallet component and utilities

The verification confirms that test coverage is missing for:

  • The wallet component functionality
  • The truncateString utility function
  • Username truncation behavior

Please add test cases covering both the component behavior and the utility function, ensuring various scenarios like:

  • Username truncation with different lengths
  • Empty username handling
  • Edge cases for the truncation function
🔗 Analysis chain

Add test coverage for username truncation.

The username truncation implementation lacks test coverage.

Could you add test cases for the username truncation? Here's a verification script to check current test coverage:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check test coverage for username truncation
rg -l "test.*WalletSection.*username.*truncate" -t ts

Length of output: 55


Script:

#!/bin/bash
# Find all test files related to wallet
echo "=== Wallet-related test files ==="
fd -e test.tsx -e test.ts -e spec.tsx -e spec.ts | rg -i "wallet"

# Find truncateString utility tests
echo -e "\n=== TruncateString utility tests ==="
rg -l "truncateString" -t ts | rg "test|spec"

# Find any username truncation tests
echo -e "\n=== Username truncation tests ==="
rg -l "username.*truncate|truncate.*username" -t ts

Length of output: 436

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 134-134: components/wallet.tsx#L134
Added line #L134 was not covered by tests

{address
? `${address.slice(0, 12)}...${address.slice(-6)}`
: 'Address not available'}
{address ? truncateAddress(address) : 'Address not available'}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Add test coverage for address truncation utility

The address truncation functionality requires test coverage at two levels:

  • Unit tests for the truncateAddress utility function in the utils directory
  • Integration tests for address display in the WalletSection component

Example test cases should cover:

  • Different address lengths
  • Edge cases (empty string, null, undefined)
  • Correct truncation pattern
🔗 Analysis chain

Add test coverage for address truncation.

The address truncation implementation lacks test coverage.

Could you add test cases for the address truncation? Here's a verification script to check current test coverage:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check test coverage for address truncation
rg -l "test.*WalletSection.*address.*truncate" -t ts

Length of output: 54


Script:

#!/bin/bash
# Find truncateAddress function definition
ast-grep --pattern 'function truncateAddress($_) { $$$ }'

# Find all test files related to wallet
fd -e test.tsx -e test.ts -e spec.tsx -e spec.ts . | rg -i "wallet"

# Search for any tests containing "address" string
rg "test.*address" -t ts -t tsx

Length of output: 189


Script:

#!/bin/bash
# Find all wallet-related files to understand structure
fd . -e ts -e tsx | rg -i "wallet"

# Try different patterns for truncateAddress
ast-grep --pattern 'const truncateAddress = $_'
ast-grep --pattern 'export const truncateAddress = $_'
ast-grep --pattern 'export function truncateAddress($_)'

# Search for address-related tests with correct extension
rg "test.*address" -t ts

Length of output: 2538


Script:

#!/bin/bash
# Check for utility files and inline truncate implementation
rg "truncate.*address" -t ts -t tsx

# Look at the wallet component implementation
cat components/wallet.tsx

Length of output: 10539


Script:

#!/bin/bash
# Check for utils tests
fd . -e test.ts -e test.tsx | rg "utils"

# Look at the utils implementation
cat utils/index.ts

Length of output: 400

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 138-138: components/wallet.tsx#L138
Added line #L138 was not covered by tests

@fmorency fmorency merged commit e7e1380 into main Jan 13, 2025
8 checks passed
@fmorency fmorency deleted the chalabi/safe-truncation branch January 13, 2025 20:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Secure Bech32 truncation
2 participants