Conversation
- Introduced multi-protocol access control features in the CookieJar contract, supporting POAP, Unlock Protocol, Hypercerts, and Hats Protocol. - Updated the client to include new components and hooks for protocol-specific configurations and validations. - Improved testing infrastructure with comprehensive coverage for frontend components and contract functionalities. - Refactored package.json scripts for better organization and added new dependencies to support the enhanced features. These changes significantly expand the functionality of the CookieJar protocol and improve the overall development experience.
- Added a comprehensive NFT Testing Guide for Cookie Jar's local development environment, detailing testing procedures for NFT-gated functionality. - Updated access control terminology from "whitelist" to "allowlist" across various components and contracts to align with new naming conventions. - Introduced new components and hooks for managing allowlist functionalities, improving the user experience and development workflow. - Enhanced package.json scripts and dependencies to support the new features and testing infrastructure. These changes significantly improve the testing capabilities and access control mechanisms within the Cookie Jar protocol.
- Removed unused components such as Features and NetworkSupport from the client. - Updated import paths for hooks and components to follow consistent naming conventions. - Introduced new components for jar management, including ChainDisplay, JarCard, JarControls, and JarGrid, enhancing the user interface and functionality. - Refactored existing components to improve performance and maintainability. These changes streamline the codebase and improve the overall structure of the application.
- Revised the .env.sample file to include new deployment configurations and guidelines for sensitive data management. - Removed outdated commands from the NFT Testing Guide to streamline the testing process. - Updated package.json to reflect the new versioning and added dependencies for improved functionality. - Introduced new hooks and components for jar creation and management, enhancing user experience and operational efficiency. - Improved deployment scripts for better local development setup and optimized performance. These changes significantly enhance the configuration, usability, and overall functionality of the Cookie Jar protocol.
- Deleted the anvil.log and watch-deploy.log files as they are no longer needed for the project. - This cleanup helps streamline the project and reduces unnecessary clutter in the repository.
Feat/ui-revamp
…feat/client-refactor-optimization
- Refactored component imports to follow consistent naming conventions, improving code readability and maintainability. - Introduced new utility functions for formatting addresses and time, enhancing the overall utility library. - Removed obsolete files and utilities, streamlining the codebase and reducing clutter. - Added new components for wallet connection and error handling, improving user experience and functionality. These changes significantly enhance the structure and usability of the Cookie Jar protocol, making it more efficient and user-friendly.
- Deleted the NFT Testing Guide to streamline documentation and reduce redundancy. - Added a new footer component to the client, improving navigation and resource accessibility. - Updated import paths for error boundary components to follow consistent naming conventions. These changes enhance the overall user experience and maintainability of the Cookie Jar protocol.
- Removed outdated dependencies related to cmdk, embla-carousel-react, and various @radix-ui components to streamline the lock file. - This cleanup helps maintain a more efficient and manageable dependency tree, improving overall project maintainability.
…ntation - Implemented lazy loading for heavy components in the CreateCookieJarForm to improve initial load times and overall performance. - Updated README.md to remove the NFT Testing Guide and streamline documentation. - Adjusted TypeScript configuration for better compatibility and performance. - Removed obsolete test files related to the ProtocolAwareWithdrawal component, enhancing code clarity. These changes enhance the user experience and maintainability of the Cookie Jar protocol.
…optimization Feat/client-refactor-optimization
…oof and gas usage warnings - Updated the .env.sample file to include new API keys and configuration options for NFT and metadata services. - Introduced a new event, `HighGasUsageWarning`, to alert users of excessive gas consumption during NFT validation. - Enhanced the `useNftValidation` hook to detect malicious contracts and provide detailed warnings. - Implemented balance proof validation in the `NFTGatedWithdrawalSection` to prevent race conditions for ERC1155 tokens. - Refactored the `ProtocolGateSelector` to support enhanced NFT gates and improved user experience. - Updated deployment configurations and optimized contract size for better performance. These changes significantly improve the security, efficiency, and user experience of the Cookie Jar protocol.
…rations - Added a .cursorignore file to specify files and directories to ignore during indexing. - Updated .env.sample to streamline API key configuration, consolidating Alchemy API keys into a single entry. - Refactored client code to replace instances of "blacklist" with "denylist" for improved terminology consistency. - Enhanced deployment scripts to better manage environment variables and improve local development setup. These changes enhance the clarity, security, and usability of the Cookie Jar protocol.
- Added Playwright configuration for comprehensive E2E testing, including setup and teardown scripts. - Created multiple test specifications covering basic functionality, accessibility, performance, and NFT gating. - Introduced utility functions for wallet interactions and robust selector strategies to enhance test reliability. - Updated package.json to include Playwright dependencies and new test scripts for easier execution. - Added GitHub Actions workflow for automated E2E testing on push and pull request events. These changes significantly improve the testing capabilities and reliability of the Cookie Jar protocol, ensuring a better user experience and code quality.
…ete files - Replaced Jest with Vitest as the testing framework, updating all related configurations and test files accordingly. - Deleted unused test setup files and Jest configuration to streamline the testing environment. - Introduced a new Vitest configuration file to support testing with React and TypeScript. - Updated various test files to utilize Vitest's mocking and assertion capabilities, ensuring compatibility with the new framework. - Removed deprecated utility functions and files to enhance code clarity and maintainability. These changes improve the testing infrastructure and overall code quality of the Cookie Jar protocol.
feat: Enhance NFT validation and withdrawal processes with balance pr…
- Introduced a preinstall script in package.json to automate dependency checks and installations. - Created a new install-deps.sh script to verify the presence of Node.js, Git, and pnpm, and to install Foundry if missing. - Enhanced user experience by providing clear feedback on dependency status and installation steps. These changes streamline the setup process for the Cookie Jar protocol, ensuring all necessary dependencies are in place before project execution.
…iseness - Streamlined the README.md to enhance clarity, focusing on key features and setup instructions. - Updated client README.md to reflect the new structure and features of the Cookie Jar protocol, emphasizing the React frontend and its functionalities. - Consolidated technical stack information and improved the organization of sections for better readability. - Enhanced E2E testing documentation to provide clearer instructions and test structure overview. These changes improve the overall documentation quality, making it easier for users to understand and navigate the Cookie Jar protocol.
- Renamed workflow from "E2E Tests" to "End-to-End Tests" for clarity. - Limited push and pull request triggers to the main branch. - Added a nightly schedule for automated testing. - Consolidated Node.js and pnpm setup into a single step using a custom action. - Enhanced the E2E test script to support CI mode with GitHub Actions reporter. - Improved logging and cleanup processes for background tasks. - Updated deployment and client startup procedures for better reliability. These changes streamline the E2E testing process and improve the overall testing framework for the Cookie Jar protocol.
- Changed the revert message in the `_checkAccessHypercert` function from `InvalidAccessType` to `NotAuthorized` for clearer error reporting. - Updated the corresponding test case to expect the new `NotAuthorized` revert message. - Modified the `NFTGatingEnhancedTest` to correct the withdrawal option naming and added new requirements for access configuration. These changes improve the clarity of access control mechanisms and enhance the robustness of the testing framework in the Cookie Jar protocol.
- Added functions `grantJarDenylistRole` and `revokeJarDenylistRole` to manage user denylist status in the CookieJar contract. - Introduced a `notDenylisted` modifier to restrict access for denylisted users during withdrawal operations. - Updated the ABI to include new denylist functions and errors, enhancing client-side hooks for denylist management. - Refactored role names from "blacklist" to "denylist" for consistency across the codebase. These changes improve access control and user management within the Cookie Jar protocol, aligning with updated terminology and enhancing security.
feat: Introduce denylist functionality and update environment configurations
…enhancement/e2e-test-infra
- Removed obsolete dependencies related to Jest and Babel plugins to streamline the lock file. - Updated package resolutions and integrity checks to reflect the current project requirements. - Enhanced overall maintainability of the pnpm-lock.yaml file by eliminating unnecessary entries.
- Updated CI workflows to trigger on both main and develop branches for better integration. - Modified the pnpm install command in the setup action to handle CI environments more gracefully, allowing fallback to regular install if frozen lockfile fails. - Added informative messages in contract test outputs to guide users on test results. - Improved NFTGatingEnhanced tests by adding balance checks before withdrawals and ensuring jar balance decreases appropriately after transactions. These changes enhance the reliability of CI processes and improve the clarity and robustness of NFT-related tests.
- Updated contract test workflow to skip unnecessary Node.js dependencies during contract builds. - Enhanced output logging for compilation warnings in contract tests, saving logs for review. - Modified NFTGatingEnhanced tests to ensure proper funding of the jar before withdrawals, improving test reliability. - Adjusted install-deps.sh to skip Foundry installation in CI environments, streamlining the setup process. These changes enhance the efficiency of CI processes and improve the robustness of NFT-related tests.
- Updated the code quality workflow to include checks for ESLint configuration and improved logging for linting results. - Enhanced the unit tests workflow to verify the presence of vitest configuration and added fallback mechanisms for running tests. - Added a new script for TypeScript type checking in the client package.json. These changes improve the reliability and clarity of CI processes, ensuring better feedback during code quality checks and testing.
- Updated the code quality workflow to streamline ESLint usage by directly invoking Next.js linting with a non-interactive flag. - Enhanced the integration tests workflow to check for the existence of the integration test script in package.json and improved fallback mechanisms for running tests. - Simplified the unit tests workflow by removing unnecessary NODE_OPTIONS and ensuring clearer error messages for test failures. These changes improve the efficiency and clarity of CI processes, providing better feedback during linting and testing phases.
…t process This commit removes the `vercel.json` configuration file from the root directory, transitioning to a deployment setup managed entirely through the Vercel dashboard. The changes simplify the deployment workflow and enhance maintainability by consolidating configuration settings in one place. Additionally, updates to the `package.json` scripts improve clarity and functionality for building the client application.
… scripts This commit transitions the project from using pnpm to bun for dependency management and script execution. Key changes include updating installation commands, modifying script definitions in package.json, and adjusting documentation to reflect the new setup. The migration aims to streamline the development process and improve performance. Additionally, the removal of pnpm-related files enhances project clarity and maintainability.
… process This commit refines the `package.json` scripts for better organization and clarity, specifically adjusting the client build and type generation commands to ensure they operate within the correct directory context. Additionally, it updates the deployment configuration in `deployments.auto.ts` to reflect the latest factory addresses and timestamps, enhancing the accuracy of deployment tracking. These changes aim to streamline the development workflow and improve maintainability.
- Replace generic NotAuthorized with distinct errors in _checkAccess(): InsufficientNFTBalance, NFTNotOwned, NFTValidationFailed - Use type(uint256).max sentinel in factory to allow explicit 0% fees - Replace require string with custom error TransferFailed in withdrawals - Guard FeeCollected event emission on fee > 0 (reduces noise for 0% jars) - DRY period reset logic via _isNewPeriod/_effectiveWithdrawnInPeriod helpers - Fix emergency withdraw to update pendingTokenBalances accounting - Increase strict purpose minimum from 10 to 27 characters - Add ERC-1155 balanceOf to MockHats for Hats Protocol compatibility - Add proper balanceOf tracking to MockPOAP for ERC-721 validation - Split test access config helpers per protocol (ERC721/ERC1155/Hats) - Fix jarHats to use mockHats with correct testHatId - Fix cooldown test with proper vm.expectRevert assertions - Add hat revocation, wrong hat ID, and multi-user cooldown tests - Add inline remappings and skip rules to foundry.toml Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Update NFT protocol config components (Hats, Hypercert, POAP, Unlock) - Polish NFTGatedWithdrawalSection with improved UX - Update deployment config and supported networks - Fix jar creation hook and token utils - Add doc-links and blockchain constants - Update tests for currency labels, token info, and jar transactions Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…lures - Use FOUNDRY_PROFILE=dev in CI workflows to match local build scripts - Add fetch-depth: 0 for proper submodule resolution - Fix TypeScript error in useJarCreation.ts (widen options array type) - Add vercel.json to specify bun as install command Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
OZ v5 moved ERC777 interfaces from token/ERC777/ to interfaces/. Superfluid protocol-monorepo still imports from the old v4 path. Add oz-compat.sh script that copies the interface files to the expected location, run in CI workflows and postinstall hook. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- docs: remove phantom dev:ethereum/dev:base scripts from root-standards, clarify bun run test vs bun test in testing-patterns - fix(bunfig): remove vitest preload that breaks bun's native test runner, remove hardcoded NODE_ENV=production that prevents dev mode - fix(client): use Unicode code point length for purpose validation to match Solidity, fix negative repeat in deposit placeholder, add safeBigInt for manual NFT token ID input, add htmlFor/id for label accessibility, fix select WCAG contrast using primary-foreground token - fix(contracts): add countUnicodeCodePoints helper for UTF-8 aware purpose validation matching client-side semantics - fix(config): standardize remapping trailing slashes in foundry.toml and contracts/remappings.txt - fix(scripts): use bun run test instead of bun test in package.json for test:client, test:all, and test:ci - docs: fix deploy:base-sepolia description in README Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The safeBigInt IIFE returned bigint[] which isn't assignable to wagmi's expected readonly tuple type. Adding as const narrows the array literal to the correct tuple shape. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…brary CookieJar._validateWithdrawalConstraints had an inline bytes(purpose).length check that duplicated and diverged from CookieJarValidation.validatePurpose. Now delegates to the library which uses countUnicodeCodePoints, matching client-side unicodeCodePointLength semantics for multi-byte characters. Also replace remaining bun test references in README with bun run test. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…ok stability Phase 1: Migrate useJarCreation from manual useState to React Hook Form + Zod - Extract jarCreationSchema.ts with METHOD_TO_ACCESS_TYPE mapping - Replace ~15 useState calls with useForm + zodResolver - Simplify StepContent bridge with lookup instead of 6-case switch Phase 2: Redesign ProtocolSelector UX and consolidate NFTGateInput state - Merge duplicate ConfigurationPanels into one using real protocol components - Add visibleMethods, recommendedMethod props - Replace 11 useState calls in NFTGateInput with typed useReducer - Enhanced useRateLimit with countdown timer and amber UI banner Phase 3: Fix useHats race condition and parallelize ERC detection - Wrap async functions in useCallback with AbortSignal to prevent infinite re-render loops caused by unstable function references in useEffect deps - Add AbortController cleanup to all effects - Remove duplicate cache check in useEnhancedNFTValidation Phase 4: Add ARIA accessibility across all protocol config inputs - ProtocolSelector: role="button", tabIndex, aria-pressed, keyboard handlers - POAPConfig: Convert div onClick to semantic button for search results - ProtocolConfigBase: Add errorId prop + role="alert" on error alerts - All protocol configs: aria-invalid + aria-describedby on inputs - NFTGateInput: aria-label on sliders, remove redundant aria-disabled Phase 5: NFTSelector accessibility and Coming Soon features - NFTCard: role="button", tabIndex, aria-pressed, keyboard handlers - View toggle: aria-label, aria-pressed, role="group" - Skip @tanstack/react-virtual (pagination already bounds DOM nodes) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…ions-1770862588844 Add Claude Code GitHub Workflow
…lection-ux refactor(client): overhaul gating selection UX, accessibility, and hook stability
# Conflicts: # client/__tests__/hooks/jar/createV2CreateArgs.test.ts # contracts/src/CookieJar.sol
…-fixes fix: address review feedback across client and contracts
release: v3.2.0 — NFT gating hardening, Unicode validation, CI fixes
Updated dependencies to fix Next.js and React CVE vulnerabilities. The fix-react2shell-next tool automatically updated the following packages to their secure versions: - next - react-server-dom-webpack - react-server-dom-parcel - react-server-dom-turbopack All package.json files have been scanned and vulnerable versions have been patched to the correct fixed versions based on the official React advisory. Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
…omponents-cve-vu-ys8b07 Fix React Server Components CVE vulnerabilities
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
| } catch { | ||
| // If not JSON, treat as legacy description-only metadata | ||
| return { | ||
| name: metadataString || "Cookie Jar", |
Check warning
Code scanning / CodeQL
Useless conditional Warning test
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 3 days ago
To fix the problem, remove the redundant fallback || "Cookie Jar" from the name field in the catch block, since the earlier if (!metadataString) return guarantees that metadataString is truthy whenever this block executes. We keep the rest of the behavior unchanged: invalid JSON metadata (that is still a non-empty string) will be treated as “legacy description-only metadata” with name equal to the raw string, empty description, and empty image/link.
Concretely, in client/__tests__/MetadataParser.test.tsx, within the parseMetadata function’s catch block (lines 20–25 in the snippet), change name: metadataString || "Cookie Jar", to simply name: metadataString,. No new imports, methods, or other definitions are needed.
| @@ -18,7 +18,7 @@ | ||
| } catch { | ||
| // If not JSON, treat as legacy description-only metadata | ||
| return { | ||
| name: metadataString || "Cookie Jar", | ||
| name: metadataString, | ||
| description: "", | ||
| image: "", | ||
| link: "", |
| * - User-friendly fallback UI | ||
| * - Error reporting capabilities | ||
| */ | ||
| export class ProtocolErrorBoundary extends React.Component< |
Check warning
Code scanning / CodeQL
Unused or undefined state property Warning
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 3 days ago
In general, to fix “state property written but never read” you either (a) remove the unused state property and any writes to it, or (b) start using it meaningfully. Here, the component already passes errorInfo directly into logError and there’s no evidence that the stateful copy is used elsewhere, so the best fix without changing behaviour is to remove errorInfo from the component state entirely.
Concretely in client/components/app/ProtocolErrorBoundary.tsx:
- Update
ProtocolErrorBoundaryStateto remove theerrorInfo?: React.ErrorInfo;field. - In
componentDidCatch, changethis.setState({ error, errorInfo, });to only seterror, sinceerrorInfowill no longer exist on state. - In the
retrymethod’ssetStatecall, removeerrorInfo: undefinedfrom the object, since we no longer track it in state.
No new imports or helper methods are required; we are only simplifying the state shape to match actual usage.
| @@ -9,7 +9,6 @@ | ||
| interface ProtocolErrorBoundaryState { | ||
| hasError: boolean; | ||
| error?: Error; | ||
| errorInfo?: React.ErrorInfo; | ||
| retryCount: number; | ||
| } | ||
|
|
||
| @@ -59,12 +58,12 @@ | ||
| componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { | ||
| this.setState({ | ||
| error, | ||
| errorInfo, | ||
| }); | ||
|
|
||
| // Log error to monitoring service | ||
| this.logError(error, errorInfo); | ||
| } | ||
| } | ||
|
|
||
| componentWillUnmount() { | ||
| if (this.retryTimeoutId) { | ||
| @@ -126,7 +120,6 @@ | ||
| this.setState((prevState) => ({ | ||
| hasError: false, | ||
| error: undefined, | ||
| errorInfo: undefined, | ||
| retryCount: prevState.retryCount + 1, | ||
| })); | ||
| }, delay) as unknown as number; |
| Step {currentStep} of {totalSteps} | ||
| </Badge> | ||
| </div> | ||
| {!isMobile && ( |
Check warning
Code scanning / CodeQL
Useless conditional Warning
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 3 days ago
In general, to fix a useless conditional where a negation or condition is always true within its scope, you should either remove the redundant condition or replace it with the condition that actually varies. Here, the entire <CardHeader> block is already guarded by {!isMobile && (...)}, so any additional {!isMobile && ...} inside that block is redundant.
The best minimal fix without changing behavior is to remove the inner {!isMobile && ( ... )} wrapper around the <Progress> component and render <Progress> directly, since we already know !isMobile is true when that code runs. Concretely, in client/components/create/MobileOptimizedForm.tsx, in the <CardHeader> block starting at line 158, replace:
{!isMobile && (
<Progress value={progressPercentage} className="h-2 mt-2" />
)}with just:
<Progress value={progressPercentage} className="h-2 mt-2" />No new methods, imports, or definitions are needed; this is a local JSX cleanup only.
| @@ -166,9 +166,7 @@ | ||
| Step {currentStep} of {totalSteps} | ||
| </Badge> | ||
| </div> | ||
| {!isMobile && ( | ||
| <Progress value={progressPercentage} className="h-2 mt-2" /> | ||
| )} | ||
| <Progress value={progressPercentage} className="h-2 mt-2" /> | ||
| </CardHeader> | ||
| )} | ||
|
|
| disabled={isLoading} | ||
| > | ||
| <RefreshCw | ||
| className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} |
Check warning
Code scanning / CodeQL
Useless conditional Warning
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 3 days ago
In general, to fix a useless conditional you either (a) wire the condition to a real changing state so it sometimes evaluates differently, or (b) remove the conditional and simplify the expression to its always-taken branch. Since we cannot safely modify the missing surrounding logic (where isLoading is defined) and CodeQL states that isLoading is always false at this use-site, the minimal, behavior-preserving fix is to remove the ternary and use a constant classname.
Concretely, in client/components/nft/UnlockMembershipStatus.tsx, at line 183, replace:
className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`}with a static class name string:
className="h-4 w-4"This keeps rendering the same visual result as before (because "animate-spin" was never actually applied) and removes the useless conditional. No new imports, methods, or additional definitions are required.
| @@ -180,7 +180,7 @@ | ||
| disabled={isLoading} | ||
| > | ||
| <RefreshCw | ||
| className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} | ||
| className="h-4 w-4" | ||
| /> | ||
| </Button> | ||
| </div> |
| [optimismSepolia.id]: createFallbackTransport( | ||
| [ | ||
| "https://op-sepolia-pokt.nodies.app", | ||
| "https://opt-sepolia.g.alchemy.com/v2/${alchemyId}", |
Check warning
Code scanning / CodeQL
Template syntax in string literal Warning
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 3 days ago
In general, to fix this category of issue, you should convert ordinary quoted strings that are intended to interpolate variables into template literals by wrapping them in backticks instead of single or double quotes. This allows ${variableName} placeholders to be evaluated at runtime.
For this specific case in client/config/supported-networks.ts, change the Optimism Sepolia Alchemy URL at line 335 from a double-quoted string to a template literal, matching how the mainnet Alchemy URL on line 323 is handled. Concretely, replace "https://opt-sepolia.g.alchemy.com/v2/${alchemyId}" with `https://opt-sepolia.g.alchemy.com/v2/${alchemyId}`. No new imports or helper functions are required; alchemyId is already defined at line 192, and template literals are standard TypeScript/JavaScript syntax. This preserves existing behavior everywhere else and simply ensures the correct API key is interpolated into the Optimism Sepolia RPC URL.
| @@ -332,7 +332,7 @@ | ||
| [optimismSepolia.id]: createFallbackTransport( | ||
| [ | ||
| "https://op-sepolia-pokt.nodies.app", | ||
| "https://opt-sepolia.g.alchemy.com/v2/${alchemyId}", | ||
| `https://opt-sepolia.g.alchemy.com/v2/${alchemyId}`, | ||
| ], | ||
| [ | ||
| "https://optimism-sepolia.blockpi.network/v1/rpc/public", |
| return `${Number(formatted).toFixed(maxDecimals)} ${symbol}`; | ||
| } catch (error) { | ||
| console.error("Error formatting amount:", error); | ||
| return `${amount || 0} ${symbol}`; |
Check warning
Code scanning / CodeQL
Useless conditional Warning
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 3 days ago
In general, to fix a useless conditional where a variable is guaranteed to be truthy or falsy at a given point, remove the redundant conditional logic and use the variable directly (or adjust the control flow so that the intended check happens where it still has meaning). This avoids dead code and makes the behavior clearer.
For this specific case in client/lib/blockchain/token-utils.ts, inside formatTokenAmount, the catch block currently returns `${amount || 0} ${symbol}`. Because if (!amount) return ... has already run, amount cannot be undefined there. Using amount || 0 is therefore useless: it will always evaluate to amount, and the 0 fallback is never used. The best fix that preserves existing behavior is to change the return line in the catch block to `${amount} ${symbol}`. No imports or additional helpers are required, and no behavior change occurs for any possible input because the || 0 branch was unreachable.
The only change needed is in this file, in the catch block of formatTokenAmount, around line 100. Replace the expression amount || 0 with just amount.
| @@ -97,7 +97,7 @@ | ||
| return `${Number(formatted).toFixed(maxDecimals)} ${symbol}`; | ||
| } catch (error) { | ||
| console.error("Error formatting amount:", error); | ||
| return `${amount || 0} ${symbol}`; | ||
| return `${amount} ${symbol}`; | ||
| } | ||
| } | ||
|
|
No description provided.