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

Rc 1 #1851

Open
wants to merge 61 commits into
base: main
Choose a base branch
from
Open

Rc 1 #1851

wants to merge 61 commits into from

Conversation

ponderingdemocritus
Copy link
Contributor

@ponderingdemocritus ponderingdemocritus commented Oct 15, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a new status DefenderPresent to improve claimability logic in battle management.
    • Introduced a new utility function divideByPrecision for enhanced resource management in the building entity details.
    • Added a new method timeUntilFinishTick in the ProductionManager for better production timing calculations.
  • Bug Fixes

    • Streamlined claimability checks and fixed related logic in the BattleManager.
    • Improved error handling in the BattleActions component to prevent unhandled promise rejections.
  • UI Improvements

    • Enhanced resource handling in the ResourceChip component for more dynamic balance calculations.
    • Minor adjustments to UI elements for better presentation, including updates to the BattleActions component.
  • Chores

    • Removed unused imports and streamlined hooks for better performance.
    • Updated the version of the Dojo dependency in configuration files.

Copy link

vercel bot commented Oct 15, 2024

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

Name Status Preview Comments Updated (UTC)
eternum ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 18, 2024 10:19am

Copy link
Contributor

mentatbot bot commented Oct 15, 2024

You are out of MentatBot reviews. Your usage will refresh October 21 at 07:00 AM.

Copy link
Contributor

coderabbitai bot commented Oct 15, 2024

Walkthrough

This pull request introduces several changes across multiple files, primarily enhancing the claimability logic in the BattleManager class by adding a new status, DefenderPresent, and simplifying the isClaimable method. Additionally, modifications to the BattleManager test suite improve the accuracy of claimability and attackability checks. Changes to the ProductionManager and BuildingEntityDetails enhance resource management capabilities, while updates across various components streamline logic and improve maintainability. The overall structure and functionality of various components remain intact while improving clarity and usability.

Changes

File Path Change Summary
client/src/dojo/modelManager/BattleManager.ts Added DefenderPresent to ClaimStatus enum; removed battleIsClaimable property; streamlined isClaimable method logic.
client/src/dojo/modelManager/__tests__/BattleManager.test.ts Updated test cases for isClaimable and isAttackable methods to reflect new claimability logic, including checks for defender presence.
client/src/dojo/modelManager/ProductionManager.ts Introduced multiplyByPrecision utility; refactored getStoreCapacity method; updated resource input handling; added timeUntilFinishTick method.
client/src/ui/modules/entity-details/BuildingEntityDetails.tsx Added divideByPrecision utility; replaced REALM_UPGRADE_COSTS with configManager.realmUpgradeCosts; updated CastleDetails component logic.
client/src/ui/modules/military/battle-view/BattleActions.tsx Updated state initialization, effect dependencies, and error handling in asynchronous functions; streamlined loading state management.
client/src/ui/components/resources/ResourceChip.tsx Updated imports and balance calculations; introduced useEffect for dynamic balance updates; simplified netRate calculation.

Possibly related PRs

  • fix: claim on structures + selected army #1847: This PR directly modifies the BattleManager class, adding the DefenderPresent status to the ClaimStatus enum and updating the isClaimable method, which aligns closely with the changes made in the main PR regarding claimability logic.
  • feat: randomize mercenaries number #1861: This PR is related as it also modifies the BattleManager class, adding the DefenderPresent status to the ClaimStatus enum and updating the isClaimable method, which is consistent with the changes in the main PR.

Suggested reviewers

  • bob0005

🐰 In the meadow where battles unfold,
A new status emerges, brave and bold.
With guilds now chatting, colors so bright,
Our claims are more clear, in day and in night.
Hopping through changes, we dance with delight,
For the game grows richer, oh what a sight! 🌼


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.

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.

fix: claim on structures + selected army
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 (6)
client/src/ui/modules/entity-details/Entities.tsx (2)

10-10: LGTM: Simplified player structures retrieval

The use of the useEntities hook to directly access playerStructures is a clean and efficient approach. This change is consistent with the updated import and simplifies the component's logic.

Consider adding a comment explaining what playerStructures represents, especially if it's used in multiple places within the component. This can enhance code readability and maintainability.


Line range hint 1-24: Overall assessment: Improved code structure and maintainability

The changes in this file represent a positive refactoring effort:

  1. Introduction of the useEntities custom hook improves state management.
  2. Simplification of player structures retrieval enhances code readability.
  3. Consistent application of the new approach throughout the component.

These modifications align well with React best practices and should lead to more maintainable and potentially more performant code. The removal of explicit address handling suggests that this logic has been encapsulated within the useEntities hook, which is a good separation of concerns.

As the codebase evolves, consider documenting the responsibilities and usage of custom hooks like useEntities in a central location or in comments above the hook definition. This will help maintain consistency across the application and ease onboarding for new developers.

client/src/ui/modules/entity-details/CombatEntityDetails.tsx (2)

22-22: LGTM: Improved player structures access with a minor suggestion

The changes effectively implement the new useEntities hook:

  1. Direct destructuring of playerStructures simplifies the code.
  2. Usage in useOwnArmiesByPosition is correct.

Consider memoizing the result of playerStructures() if it's called frequently:

const memoizedPlayerStructures = useMemo(() => playerStructures(), [playerStructures]);

Then use memoizedPlayerStructures in the useOwnArmiesByPosition hook to potentially improve performance.

Also applies to: 28-28


Line range hint 19-165: LGTM: Component structure maintained with improved data access

The refactoring has been implemented smoothly:

  1. Overall component logic and structure remain intact.
  2. Changes are localized to data fetching, improving maintainability.
  3. The component continues to handle army selection, tab management, and sub-component rendering effectively.

Consider enhancing type safety by explicitly typing the useEntities hook return value:

const { playerStructures }: { playerStructures: () => PlayerStructure[] } = useEntities();

This would provide better IDE support and catch potential type mismatches early.

client/src/hooks/helpers/useEntities.tsx (2)

Line range hint 154-158: Fix incorrect dependencies in useMemo for getPlayerStructures

In the getPlayerStructures function, the dependency array for useMemo incorrectly includes otherRealms instead of playerStructures. This may cause the memoized value to not update correctly when playerStructures changes.

Apply this diff to correct the dependency array:

-    }, [otherRealms, filterFn]);
+    }, [playerStructures, filterFn]);

Line range hint 160-164: Fix incorrect dependencies in useMemo for getOtherStructures

Similarly, in the getOtherStructures function, the dependency array for useMemo incorrectly includes otherRealms instead of otherStructures. This could lead to stale data being returned.

Apply this diff to correct the dependency array:

-    }, [otherRealms, filterFn]);
+    }, [otherStructures, filterFn]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cbc538d and 44c2368.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • client/src/hooks/helpers/useEntities.tsx (1 hunks)
  • client/src/hooks/store/useMarketStore.tsx (0 hunks)
  • client/src/ui/modules/entity-details/CombatEntityDetails.tsx (2 hunks)
  • client/src/ui/modules/entity-details/Entities.tsx (1 hunks)
  • client/src/ui/modules/military/Military.tsx (1 hunks)
  • contracts/manifests/dev/deployment/manifest.json (1 hunks)
  • contracts/manifests/dev/deployment/manifest.toml (1 hunks)
💤 Files with no reviewable changes (1)
  • client/src/hooks/store/useMarketStore.tsx
✅ Files skipped from review due to trivial changes (1)
  • contracts/manifests/dev/deployment/manifest.json
🧰 Additional context used
🔇 Additional comments (8)
client/src/ui/modules/military/Military.tsx (3)

15-15: LGTM! Correct update of useMemo dependencies.

The update of the useMemo dependencies to include playerStructures is correct and consistent with the changes made to the data source. This ensures that the memoized value is recalculated appropriately when the player structures or entityId changes.


11-11: LGTM! Verify consistency of the new entity management approach.

The switch to using useEntities for retrieving player structures is a good improvement. It centralizes entity management and potentially simplifies the component's logic.

To ensure this new approach is consistently applied across the codebase, please run the following script:

#!/bin/bash
# Description: Check for consistency in entity management approach

# Test 1: Check for other usages of useEntities in the codebase
echo "Checking for useEntities usage across the codebase:"
rg "useEntities" --type typescript --type tsx

# Test 2: Check for any remaining usages of the old getPlayerStructures approach
echo "Checking for remaining usages of getPlayerStructures:"
rg "getPlayerStructures" --type typescript --type tsx

# Test 3: Verify the implementation of playerStructures in useEntities
echo "Verifying playerStructures implementation in useEntities:"
rg "playerStructures.*=" hooks/helpers/useEntities.ts

Also applies to: 14-14


1-1: LGTM! Consider verifying the impact of import changes.

The shift from useDojo to useEntities suggests an improvement in code organization and separation of concerns. This change looks good and aligns with best practices for custom hook usage in React.

To ensure this change doesn't negatively impact other parts of the codebase, please run the following script:

✅ Verification successful

Previous verification scripts encountered issues. Generating updated scripts to ensure accurate verification:


Previous verification encountered issues. Generating updated scripts to ensure accurate verification:


Import changes verified successfully.

  • Removed imports useDojo and getPlayerStructures are no longer used in Military.tsx.
  • useEntities is correctly exported from client/src/hooks/helpers/useEntities.tsx and properly utilized in the component.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining usages of removed imports

# Test 1: Check for any remaining usages of useDojo in this file
echo "Checking for useDojo usage in Military.tsx:"
rg "useDojo" client/src/ui/modules/military/Military.tsx

# Test 2: Check for any remaining usages of getPlayerStructures in this file
echo "Checking for getPlayerStructures usage in Military.tsx:"
rg "getPlayerStructures" client/src/ui/modules/military/Military.tsx

# Test 3: Check if useEntities is properly exported from the specified path
echo "Verifying useEntities export:"
rg "export.*useEntities" hooks/helpers/useEntities.ts

Length of output: 649


Script:

#!/bin/bash
# Description: Updated scripts to verify import changes in Military.tsx

# Test 1: Check for any remaining usages of useDojo in Military.tsx
echo "Checking for useDojo usage in Military.tsx:"
rg "useDojo" client/src/ui/modules/military/Military.tsx

# Test 2: Check for any remaining usages of getPlayerStructures in Military.tsx
echo "Checking for getPlayerStructures usage in Military.tsx:"
rg "getPlayerStructures" client/src/ui/modules/military/Military.tsx

# Test 3: Locate the useEntities hook to verify its export
echo "Locating useEntities hook in the codebase:"
FOUND_PATH=$(fd "useEntities\.tsx" hooks/)
if [ -z "$FOUND_PATH" ]; then
  echo "useEntities.tsx not found in hooks/ directory."
else
  echo "useEntities.tsx found at: $FOUND_PATH"
  echo "Verifying useEntities export:"
  rg "export .*useEntities" "$FOUND_PATH"
fi

Length of output: 697


Script:

#!/bin/bash
# Description: Updated scripts to verify import changes in Military.tsx

# Test 1: Check for any remaining usages of useDojo in Military.tsx
echo "Checking for useDojo usage in Military.tsx:"
rg "useDojo" client/src/ui/modules/military/Military.tsx

# Test 2: Check for any remaining usages of getPlayerStructures in Military.tsx
echo "Checking for getPlayerStructures usage in Military.tsx:"
rg "getPlayerStructures" client/src/ui/modules/military/Military.tsx

# Test 3: Locate the useEntities hook in the entire codebase
echo "Locating useEntities hook in the codebase:"
FOUND_PATH=$(rg -g "useEntities.tsx" --files)
if [ -z "$FOUND_PATH" ]; then
  echo "useEntities.tsx not found in the codebase."
else
  echo "useEntities.tsx found at: $FOUND_PATH"
  echo "Verifying useEntities export:"
  rg "export .*useEntities" "$FOUND_PATH"
fi

Length of output: 935

client/src/ui/modules/entity-details/Entities.tsx (2)

3-3: LGTM: Improved state management with custom hook

The change from importing getPlayerStructures to useEntities is a good refactoring step. Using a custom hook can provide better state management, reusability, and potentially easier testing. This change aligns well with React best practices.


14-14: Verify the behavior of playerStructures function

The change to use playerStructures() is consistent with the earlier modifications and simplifies the code. However, it's important to ensure that this function behaves as expected.

Please confirm that playerStructures() correctly returns the structures for the current player without needing an explicit address parameter. You may want to check the implementation of the useEntities hook to verify this behavior.

To help with verification, you can run the following script to examine the useEntities hook implementation:

client/src/ui/modules/entity-details/CombatEntityDetails.tsx (1)

3-3: LGTM: Import changes reflect refactoring of data access

The changes to the import statements are consistent with the described refactoring:

  1. Adding useEntities suggests a more centralized approach to accessing entity data.
  2. Importing ID from "@bibliothecadao/eternum" indicates more explicit type usage.

These changes should lead to improved code organization and type safety.

Also applies to: 13-13

contracts/manifests/dev/deployment/manifest.toml (2)

Line range hint 1-1016: LGTM for the rest of the file.

The change to the block_number is the only modification in this file. All other configurations, including world settings, contracts, and models, remain unchanged. This consistency is good for maintaining the overall structure and functionality of the deployment.


8-8: Block number has been decreased. Please clarify the reason for this change.

The block_number in the [world] section has been updated from 65 to 50. This change could potentially affect the deployment process or the initial state of the world contract.

Could you please provide more context on why this change was made? Are there any specific implications or benefits we should be aware of? Additionally, please confirm if this change is intentional and if it has been tested in a development environment.

✅ Verification successful

Block number update is isolated and does not affect other configurations.

The block_number in the [world] section has been updated from 65 to 50. Our search across configuration and deployment files shows no other references to these block numbers, indicating that this change is isolated.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any references to the old or new block number in other configuration files or deployment scripts.

echo "Searching for references to block numbers 65 and 50 in configuration and deployment files:"
rg --type toml --type yaml --type json -n '(block_number|block)\s*[=:]\s*(50|65)' ./contracts

Length of output: 357

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

🧹 Outside diff range and nitpick comments (33)
client/src/ui/modules/military/battle-view/TopScreenView.tsx (3)

19-19: LGTM! Consider using a design system variable for consistency.

The changes to the outer div's className improve the component's layout and styling. The shift from a semi-transparent black to a solid brown background color is noted.

Consider using a design system variable for the background color (e.g., bg-primary) instead of a specific color like bg-brown. This would improve consistency and make future theme changes easier.


20-20: LGTM! Consider adding an aria-label for improved accessibility.

The change from a <div> to an <h1> element improves the semantic structure of the component. The added mb-4 class enhances the spacing.

For better accessibility, consider adding an aria-label to the parent <div> to provide more context about the battle view. For example:

<div className="mx-auto bg-brown text-2xl p-4 flex flex-col w-72 text-center rounded-b-2xl" aria-label="Battle view controls">

21-23: LGTM! Consider capitalizing the button text for consistency.

The change from inline classes to a variant prop is a good move towards using a standardized button component. This improves consistency and makes global style updates easier.

For consistency with typical UI conventions, consider capitalizing the first letter of each word in the button text:

<Button variant="primary" onClick={() => setBattleView(null)}>
  Exit Battle View
</Button>
client/src/ui/modules/military/battle-view/EntityAvatar.tsx (1)

16-19: Improved category checks and mercenary detection

The refactored category checks using the isCategory helper function have improved code readability and consistency. The simplified mercenary check with optional chaining is also a safer approach.

For even better consistency, consider refactoring the mercenary check to use a similar pattern:

const isMercenary = isCategory("Mercenary", structure);

This would require adding a category for mercenaries in the Structure type, but it would make all structure type checks uniform.

client/src/ui/modules/military/battle-view/Troops.tsx (1)

51-55: LGTM! Consider using a relative unit for image width.

The changes to the TroopCard component look good overall:

  1. The transformation logic for the image has been simplified, which improves maintainability.
  2. Using an h4 for the troop name enhances the semantic HTML structure.

However, regarding the image width change:

Consider using a relative unit like rem instead of vw for the image width. This would maintain consistency across different viewport sizes while still allowing for responsiveness. For example:

- className={`w-[6vw] object-cover transform mx-auto p-2  ${!defending ? "scale-x-[-1]" : ""}`}
+ className={`w-24 object-cover transform mx-auto p-2  ${!defending ? "scale-x-[-1]" : ""}`}

This change sets the width to 24rem (384px at default font size), which is close to 6vw on a 1920px wide screen but will maintain a more consistent size across different screen widths.

client/src/ui/modules/LoadingScreen.tsx (2)

40-40: LGTM: Inner container background color updated correctly.

The background color of the inner content container has been successfully changed from semi-transparent black to semi-transparent brown. This change is consistent with the main container's color update and maintains the semi-transparency for better readability.

For consistency, consider extracting the color values into CSS variables or a theme configuration. This would make it easier to manage and update the color scheme across the application in the future.


Line range hint 1-54: Overall: Changes improve visual consistency.

The modifications to the LoadingScreen component successfully update the background colors from black to brown, enhancing the visual consistency of the loading screen. The changes are well-implemented and align with the provided summary.

To further improve the component:

  1. Consider extracting color values into a centralized theme configuration for easier management and consistency across the application.
  2. Evaluate the accessibility of the new color scheme, ensuring sufficient contrast for readability.
  3. If not already in place, implement a theming system to allow for easy switching between different color schemes or modes (e.g., light/dark mode).
client/src/ui/elements/BaseThreeTooltip.tsx (2)

Line range hint 30-33: Consider addressing the TODO comment

There's a TODO comment indicating a need for refactoring when the initial mouse position is available. It might be beneficial to create a task to address this in the future.

Would you like me to create a GitHub issue to track this TODO item?


Line range hint 25-29: Consider using CSS classes for positioning instead of inline styles

The component currently uses inline styles for positioning the tooltip. While this works, it might be worth considering the use of CSS classes for positioning. This could potentially improve maintainability and make it easier to apply consistent styling across the application.

Here's a potential approach:

  1. Define CSS classes for positioning in your stylesheet:
.tooltip-position {
  position: absolute;
  transition: left 0.1s, top 0.1s;
}
  1. Update the component to use this class and data attributes:
 <div
   ref={ref}
+  className={clsx("tooltip-position", "min-w-[215px] ml-3 mt-3 rounded-xl relative p-2 bg-brown/90 text-gold", position, className, {
     hidden: !visible,
   })}
 >
  1. Update the setTooltipPosition function:
const setTooltipPosition = (e: MouseEvent) => {
  if (ref.current) {
    ref.current.style.setProperty('--x', `${e.clientX}px`);
    ref.current.style.setProperty('--y', `${e.clientY}px`);
  }
};
  1. Update your CSS:
.tooltip-position {
  left: var(--x);
  top: var(--y);
}

This approach separates the positioning logic from the inline styles, potentially making the code more maintainable.

client/src/ui/components/trading/MarketResourceSideBar.tsx (2)

35-36: LGTM: Enhanced grid header with improved spacing and clarity

The changes improve the grid header's appearance and clarity:

  1. Adding py-2 to the grid container provides better vertical spacing.
  2. Including "Resource" text in the first column header clarifies its purpose.
  3. The px-2 class on the "Resource" text ensures proper alignment.

These modifications enhance the overall readability and user experience of the component.

Consider adding similar px-2 padding to the other column headers for consistent alignment across all columns.


Line range hint 1-78: Consider extracting price calculation logic for improved readability

The component's logic for calculating ask, bid, and AMM prices is sound, but it might benefit from some refactoring for improved readability and maintainability.

Consider extracting the price calculation logic into a separate function. This would make the render function cleaner and easier to understand. Here's a suggested refactoring:

const calculatePrices = (resource: Resource, resourceAskOffers: MarketInterface[], resourceBidOffers: MarketInterface[], marketManager?: MarketManager) => {
  const askPrice = resourceBidOffers
    .filter((offer) => (resource.id ? offer.makerGets[0]?.resourceId === resource.id : true))
    .reduce((acc, offer) => (offer.perLords > acc ? offer.perLords : acc), 0);

  const bidPrice = resourceAskOffers
    .filter((offer) => offer.takerGets[0].resourceId === resource.id)
    .reduce((acc, offer) => (offer.perLords < acc ? offer.perLords : acc), Infinity);

  const ammPrice = marketManager?.getMarketPrice() || 0;

  return {
    askPrice: askPrice === Infinity ? "0" : askPrice.toFixed(2),
    bidPrice: bidPrice === Infinity ? "0" : bidPrice.toFixed(2),
    ammPrice
  };
};

Then, in your render function:

const { askPrice, bidPrice, ammPrice } = calculatePrices(resource, resourceAskOffers, resourceBidOffers, marketManager);

This refactoring would make the component more modular and easier to maintain.

client/src/ui/elements/CircleButton.tsx (1)

Color scheme is mostly consistent across the application. However, the following instances use black color classes and should be reviewed for consistency:

  • client/src/ui/modules/stream/EventStream.tsx: Uses border-black/10
  • client/src/ui/elements/Button.tsx: Uses hover:text-black/90
🔗 Analysis chain

Line range hint 77-91: Verify color scheme consistency across the application.

The changes to the CircleButton component involve updating the color scheme from black to brown. While these changes appear intentional and consistent within this component, it would be beneficial to verify that this color scheme update is applied consistently across other components in the application.

To check for consistency, you can run the following script:

This script will help identify other components that might need similar color updates to maintain visual consistency throughout the application.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of black and brown color classes across the application

echo "Checking for black color classes:"
rg --type tsx --type jsx 'bg-black|border-black|text-black'

echo "\nChecking for brown color classes:"
rg --type tsx --type jsx 'bg-brown|border-brown|text-brown'

Length of output: 337


Script:

#!/bin/bash
# Description: Check for usage of black and brown color classes across the application by searching .tsx and .jsx files

echo "Checking for black color classes:"
rg --glob '*.tsx' --glob '*.jsx' 'bg-black|border-black|text-black'

echo "\nChecking for brown color classes:"
rg --glob '*.tsx' --glob '*.jsx' 'bg-brown|border-brown|text-brown'

Length of output: 11470

client/src/ui/elements/Button.tsx (2)

20-20: LGTM! Consider minor adjustment for consistency.

The updated primary style aligns well with what appears to be a new brown and gold color scheme. This change enhances the visual consistency of the UI.

For even better consistency, consider changing from-yellow-600 to-yellow-700 and hover:from-yellow-700 hover:to-yellow-800 to use brown tones instead of yellow, if that matches the intended design.


20-31: Overall, the button styles have been successfully updated to a new color scheme.

The changes to the Button component styles reflect a shift from a black-based theme to a brown and gold theme. This update appears to be part of a broader effort to refine the UI's visual identity. The changes are largely consistent across different button variants, which should lead to a more cohesive user interface.

Key points:

  1. Background colors have been changed from black to brown.
  2. Hover states have been adjusted to use gold or lighter brown shades.
  3. The overall structure and functionality of the component remain intact.

These updates should enhance the visual consistency of the UI while maintaining the existing button behavior.

To further improve maintainability, consider extracting the color values (e.g., brown, gold) into CSS variables or a theme configuration file. This would make it easier to manage and update the color scheme across the entire application in the future.

client/src/index.css (1)

2-2: Ensure comprehensive testing of the new typography

The introduction of the "Bokor" font and its application to all heading elements represents a significant change to the application's visual design. To ensure a smooth transition and maintain design integrity, please:

  1. Conduct a thorough visual review of all pages and components that use headings.
  2. Test the new font across different browsers, devices, and screen sizes to ensure consistent rendering and readability.
  3. Consider creating before/after screenshots for the design team to review and approve.
  4. Update any design documentation or style guides to reflect this change.
  5. If this is part of a larger design overhaul, consider implementing the changes incrementally and documenting the process for the team.

Given the scope of this change, it might be beneficial to implement a theming system (if not already in place) that allows for easier global typography updates in the future. This could involve creating CSS custom properties (variables) for font families, which would make it easier to manage and update typography across the application.

Also applies to: 24-24, 33-33

client/src/ui/modules/navigation/SecondaryMenuItems.tsx (2)

64-64: Color change enhances UI consistency

The background color of the notification div has been changed from bg-black/90 to bg-brown/90. This modification likely improves the visual consistency with the game's overall color scheme.

Consider adding a comment explaining the reason for this specific color choice to help future developers understand the design decision.


Line range hint 1-124: Consider refactoring for improved maintainability

While the color change looks good, here are some suggestions to improve the overall component:

  1. The component has multiple responsibilities. Consider breaking it down into smaller, more focused components for better maintainability.

  2. Extract hardcoded values as constants. For example:

    const QUESTS_THRESHOLD = 8;

    Then use QUESTS_THRESHOLD instead of 8 in the condition.

  3. Improve type safety by replacing any with a proper type for quests:

    const completedQuests = quests?.filter((quest: Quest) => quest.status === QuestStatus.Claimed);
  4. The secondaryNavigation array could be defined outside the component to prevent unnecessary re-creation on each render.

Would you like me to provide more detailed refactoring suggestions for any of these points?

client/src/ui/modules/military/battle-view/BattleSideView.tsx (3)

86-89: LGTM! Consider extracting common classes.

The changes to the background and margin classes improve the component's styling and layout. The use of predefined color classes (bg-brown) is good for maintaining consistency.

Consider extracting the common classes into a separate variable or constant to improve readability and maintainability, especially if these classes are used in multiple components:

const commonClasses = "flex col-span-5 bg-brown mx-4 bg-hex-bg -mt-16";

// Usage
<div className={`${commonClasses} ${
  battleSide === BattleSide.Attack ? "flex-row" : "flex-row-reverse"
}`}>

Line range hint 91-94: LGTM! Consider adding a fallback for undefined values.

The conditional logic for the address prop is a good improvement, allowing different handling based on the battle side.

Consider adding a fallback value in case both account.address and battleEntityId are undefined:

address={battleSide === BattleSide.Attack 
  ? account.address 
  : battleEntityId?.toString() ?? 'unknown'}

This ensures that the EntityAvatar always receives a valid string value for its address prop.


Line range hint 102-111: Add a key prop to mapped elements.

The static analysis tool has identified a missing key property for elements in the iterable. This can lead to performance issues and unexpected behavior in React.

To resolve this, add a unique key to each mapped element. Since army.entity_id seems to be a unique identifier, you can use it as the key:

 {React.Children.toArray(
   ownSideArmies.map((army) => {
     if (!army) return;
     const addressName = getAddressNameFromEntity(army.entity_id);
     return (
-      <div className="flex justify-around px-2 py-1 rounded bg-brown/70 text-xs gap-2 border-gold/10 border">
+      <div key={army.entity_id} className="flex justify-around px-2 py-1 rounded bg-brown/70 text-xs gap-2 border-gold/10 border">
         <span className="self-center align-middle">{addressName}</span>
         <span className="self-center align-middle">{army?.name}</span>
         {army?.isMine && (
           <div className="h-6 border px-1 rounded self-center">

This change will resolve the warning and improve the component's performance and predictability.

🧰 Tools
🪛 Biome

[error] 102-102: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

client/src/ui/elements/ResourceIcon.tsx (1)

100-104: LGTM: Tooltip styling and text rendering improved.

The changes to the tooltip styling and text rendering logic are well-implemented:

  • The background color change to bg-brown likely improves consistency with the overall UI design.
  • The use of the tooltipText prop with a fallback to the resource name is a good implementation of the new feature.

Minor suggestion for consistency:

Consider updating the text color class for better contrast with the new brown background. For example:

- <span className="relative z-10 p-2 text-xs leading-none  whitespace-no-wrap rounded shadow-lg bg-gray-1000">
+ <span className="relative z-10 p-2 text-xs leading-none text-white whitespace-no-wrap rounded shadow-lg">

This removes the potentially conflicting bg-gray-1000 class and adds text-white for better readability against the brown background.

client/src/ui/modules/military/battle-view/BattleProgressBar.tsx (2)

146-146: LGTM: Enhanced progress bar styling

The addition of "relative h-6 mx-auto bg-opacity-40" classes improves the positioning and styling of the progress bar. This change enhances the visual presentation and layout of the component.

Consider adding a rounded class to give the progress bar rounded corners, which might improve its aesthetic appeal:

- <div className="relative h-6  mx-auto bg-opacity-40" style={{ background: gradient }}>
+ <div className="relative h-6 mx-auto bg-opacity-40 rounded" style={{ background: gradient }}>

161-161: LGTM: Improved battle information grid layout

The changes to the grid's className enhance the layout and styling of the battle information. The new classes ensure consistent width with the progress bar, create a clear 3-column layout, and improve readability with increased font size and padding.

For consistency with the progress bar, consider adding the rounded class to this div as well:

- <div className="mx-auto w-2/3 grid grid-cols-3 text-2xl bg-hex-bg px-4 py-2">
+ <div className="mx-auto w-2/3 grid grid-cols-3 text-2xl bg-hex-bg px-4 py-2 rounded">
client/tailwind.config.js (1)

48-48: Consider removing commented-out code.

The 'hex-bg' background image is commented out. If this image is no longer needed, consider removing the line entirely to keep the codebase clean. If it's intended for future use, please add a comment explaining why it's being kept.

client/src/ui/components/trading/MarketModal.tsx (1)

80-82: Improved tab labels with icons

The addition of icons to the tab labels enhances the UI and improves user experience. The consistent structure across all tabs is commendable.

Consider extracting this repeated structure into a separate component for better maintainability:

const TabLabel = ({ icon: Icon, text }: { icon: React.ComponentType, text: string }) => (
  <div className="flex relative group items-center gap-2">
    <Icon className="w-6 fill-current" />
    <div className="self-center">{text}</div>
  </div>
);

Then use it like:

label: <TabLabel icon={Scroll} text="Order Book" />

This would reduce repetition and make future changes easier.

Also applies to: 99-101, 117-119, 131-133, 145-147

client/src/ui/components/military/ArmyChip.tsx (1)

263-263: LGTM! Consider adding a focus state for keyboard navigation.

The change from bg-black to bg-brown for the selected army background looks good and likely improves the visual consistency with the rest of the application.

To enhance accessibility, consider adding a focus state for keyboard navigation. This can be achieved by adding a focus:ring-2 focus:ring-gold focus:outline-none class to the clickable div. For example:

-          className={`rounded cursor-pointer transition-all duration-300 ${
-            selectedArmy?.entity_id === army.entity_id ? "bg-gray-300" : "bg-brown"
-          }`}
+          className={`rounded cursor-pointer transition-all duration-300 focus:ring-2 focus:ring-gold focus:outline-none ${
+            selectedArmy?.entity_id === army.entity_id ? "bg-gray-300" : "bg-brown"
+          }`}

This will add a gold ring around the focused item when navigating with a keyboard, improving accessibility without affecting the visual design for mouse users.

client/src/ui/modules/chat/Chat.tsx (3)

30-32: LGTM: Enhanced Chat component with guild functionality

The changes to the Chat component successfully integrate guild functionality and improve the overall structure. The new useEffect hooks for scrolling and salt management are well-implemented. The updated changeTabs function now correctly handles guild tabs, and the rendering of tabs has been appropriately modified.

Consider adding comments to explain the purpose of the new useEffect hooks and the logic in the changeTabs function for better maintainability.

Also applies to: 51-64, 66-101, 103-111


310-409: LGTM: New ChatSelect component

The new ChatSelect component is a well-implemented addition to the Chat functionality. It provides:

  1. Efficient channel selection, including support for guild channels
  2. A search feature for filtering channels, enhancing user experience
  3. Proper handling of different channel types (global, guild, private)

Consider extracting the filtering logic (lines 341-344) into a separate function for better readability and potential reuse. For example:

const filterPlayers = (players: Player[], searchInput: string, selectedChannel: string) => {
  return players.filter(
    (player) =>
      player.addressName.toLowerCase().startsWith(searchInput.toLowerCase()) || player.addressName === selectedChannel
  );
};

Then use it in the component:

const filteredPlayers = filterPlayers(players, searchInput, selectedChannel);

Line range hint 1-409: Consider improving code organization and reusability

While the changes and additions to this file are generally well-implemented, there are a few areas where we could improve code organization and reusability:

  1. File size: The file has grown quite large. Consider splitting it into separate files for each main component (Chat, Messages, ChatSelect) to improve maintainability.

  2. Color styling: There's repetition in color styling logic (e.g., lines 147-151 and 275-279). Consider extracting this into a utility function:

const getChannelColor = (channelName: string, guildName: string | undefined) => {
  if (channelName === GLOBAL_CHANNEL_KEY) return CHAT_COLORS.GLOBAL;
  if (channelName === guildName) return CHAT_COLORS.GUILD;
  return CHAT_COLORS.PRIVATE;
};
  1. Type definitions: Consider moving type definitions (like the props for Messages and ChatSelect components) to a separate types file for better organization and potential reuse.

These changes would enhance the overall structure and maintainability of the code.

client/src/ui/components/trading/MarketOrderPanel.tsx (4)

163-174: Enhanced market price display and layout

The changes to the market price container improve the visual appearance and layout:

  1. Added rounded-xl class for consistency with other components.
  2. Adjusted padding and used flex layout for better organization of information.
  3. Included more details like the resource icon and number of bids/asks.

The background color change for the locked resources message from black to brown aligns better with the overall theme.

Consider adding a transition effect to the hover state of the market price container for a smoother user experience. For example:

- className={`text-2xl flex  font-bold  justify-between py-4 px-8 border-gold/10 border rounded-xl ${
+ className={`text-2xl flex font-bold justify-between py-4 px-8 border-gold/10 border rounded-xl transition-colors duration-200 ${
    !isBuy ? "bg-green/20 text-green" : "bg-red/20 text-red"
  }`}

Also applies to: 181-181, 200-202


378-380: Improved OrderRow layout and visual representation

The changes to the OrderRow component enhance its appearance and readability:

  1. Added rounded class for consistency with other components.
  2. Implemented a grid system for better organization of order details.
  3. Included ResourceIcon components to improve visual representation of resources.

These updates make the order information more accessible and visually appealing.

For consistency with other components, consider changing the rounded class to rounded-xl:

- className={`flex flex-col p-1  px-2  hover:bg-white/15 duration-150 border-gold/10 border relative rounded text-sm ${
+ className={`flex flex-col p-1 px-2 hover:bg-white/15 duration-150 border-gold/10 border relative rounded-xl text-sm ${
    isSelf ? "bg-blueish/10" : "bg-white/10"
  } ${isMakerResourcesLocked ? "opacity-50" : ""}`}

Also applies to: 389-390


601-603: Enhanced OrderCreation component layout and interaction

The changes to the OrderCreation component improve its usability and visual consistency:

  1. Added rounded-xl class to the main container for consistency with other components.
  2. Implemented flex layout with gap for better spacing and organization.
  3. Adjusted NumberInput components to allow for more intuitive user interaction, including setting maximum values based on available resources.

These updates enhance the user experience when creating new orders.

To improve code readability, consider extracting the repeated NumberInput setup into a separate component or custom hook. This would reduce duplication and make the code more maintainable. For example:

const ResourceInput = ({ label, value, onChange, max, resource }) => (
  <div className="w-1/3 gap-1 flex flex-col">
    <div className="uppercase text-sm flex gap-2 font-bold">
      <ResourceIcon withTooltip={false} size="xs" resource={resource} />
      {label}
    </div>
    <NumberInput
      value={value}
      className="w-full col-span-3"
      onChange={onChange}
      max={max}
    />
    <div className="text-sm font-bold text-gold/70">
      {currencyFormat(max * EternumGlobalConfig.resources.resourcePrecision, 0)} avail.
    </div>
  </div>
);

// Usage in OrderCreation
<ResourceInput
  label={isBuy ? "Buy" : "Sell"}
  value={resource}
  onChange={(value) => setResource(Number(value))}
  max={!isBuy ? resourceBalance / EternumGlobalConfig.resources.resourcePrecision : Infinity}
  resource={findResourceById(resourceId)?.trait || ""}
/>

This would make the OrderCreation component more concise and easier to maintain.

Also applies to: 609-615, 647-653


Line range hint 1-686: Overall UI enhancements and improved user interaction

The changes in this file significantly improve the visual consistency and user experience of the trading interface:

  1. Consistent use of rounded corners (rounded-xl) across components.
  2. Improved layout and spacing using flex and grid systems.
  3. Enhanced visual representation of resources using ResourceIcon components.
  4. Better user interaction with NumberInput components, including max value constraints.

These updates contribute to a more polished and user-friendly trading interface.

Consider implementing a theming system or design tokens to manage consistent styling across components. This would make it easier to maintain and update the UI in the future, especially if the application grows or requires different themes. For example, you could define a set of design tokens for colors, border radii, and spacing, and use them throughout the components instead of hardcoding values.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 44c2368 and d3bd7cb.

⛔ Files ignored due to path filters (5)
  • client/src/assets/icons/Coins.svg is excluded by !**/*.svg
  • client/src/assets/icons/Crown.svg is excluded by !**/*.svg
  • client/src/assets/icons/Scroll.svg is excluded by !**/*.svg
  • client/src/assets/icons/Sparkles.svg is excluded by !**/*.svg
  • client/src/assets/icons/Swap.svg is excluded by !**/*.svg
📒 Files selected for processing (49)
  • balancing/src/App.tsx (1 hunks)
  • client/src/index.css (3 hunks)
  • client/src/three/helpers/utils.ts (1 hunks)
  • client/src/ui/components/ModalContainer.tsx (1 hunks)
  • client/src/ui/components/bank/AddLiquidity.tsx (5 hunks)
  • client/src/ui/components/bank/ConfirmationPopup.tsx (1 hunks)
  • client/src/ui/components/bank/LiquidityResourceRow.tsx (1 hunks)
  • client/src/ui/components/bank/ResourceBar.tsx (4 hunks)
  • client/src/ui/components/bank/Swap.tsx (3 hunks)
  • client/src/ui/components/construction/SelectPreviewBuilding.tsx (3 hunks)
  • client/src/ui/components/entities/Entity.tsx (2 hunks)
  • client/src/ui/components/hints/Buildings.tsx (1 hunks)
  • client/src/ui/components/hints/HintModal.tsx (1 hunks)
  • client/src/ui/components/military/ArmyChip.tsx (1 hunks)
  • client/src/ui/components/military/ArmyManagementCard.tsx (1 hunks)
  • client/src/ui/components/structures/construction/StructureCard.tsx (3 hunks)
  • client/src/ui/components/trading/MarketModal.tsx (10 hunks)
  • client/src/ui/components/trading/MarketOrderPanel.tsx (5 hunks)
  • client/src/ui/components/trading/MarketResourceSideBar.tsx (1 hunks)
  • client/src/ui/containers/BaseContainer.tsx (1 hunks)
  • client/src/ui/elements/BaseThreeTooltip.tsx (1 hunks)
  • client/src/ui/elements/Button.tsx (1 hunks)
  • client/src/ui/elements/CircleButton.tsx (2 hunks)
  • client/src/ui/elements/ListSelect.tsx (1 hunks)
  • client/src/ui/elements/NumberInput.tsx (2 hunks)
  • client/src/ui/elements/ResourceIcon.tsx (1 hunks)
  • client/src/ui/elements/SecondaryPopup.tsx (2 hunks)
  • client/src/ui/elements/Select.tsx (2 hunks)
  • client/src/ui/elements/Tooltip.tsx (1 hunks)
  • client/src/ui/layouts/World.tsx (1 hunks)
  • client/src/ui/modules/LoadingScreen.tsx (1 hunks)
  • client/src/ui/modules/chat/Chat.tsx (7 hunks)
  • client/src/ui/modules/chat/ChatTab.tsx (1 hunks)
  • client/src/ui/modules/military/battle-view/Battle.tsx (1 hunks)
  • client/src/ui/modules/military/battle-view/BattleHistory.tsx (1 hunks)
  • client/src/ui/modules/military/battle-view/BattleProgressBar.tsx (2 hunks)
  • client/src/ui/modules/military/battle-view/BattleSideView.tsx (3 hunks)
  • client/src/ui/modules/military/battle-view/EntityAvatar.tsx (2 hunks)
  • client/src/ui/modules/military/battle-view/LockedResources.tsx (1 hunks)
  • client/src/ui/modules/military/battle-view/TopScreenView.tsx (1 hunks)
  • client/src/ui/modules/military/battle-view/Troops.tsx (2 hunks)
  • client/src/ui/modules/navigation/SecondaryMenuItems.tsx (1 hunks)
  • client/src/ui/modules/navigation/TopMiddleNavigation.tsx (5 hunks)
  • client/src/ui/modules/onboarding/Steps.tsx (1 hunks)
  • client/src/ui/modules/social/PlayerId.tsx (4 hunks)
  • client/src/ui/modules/stream/EventStream.tsx (2 hunks)
  • client/tailwind.config.js (2 hunks)
  • contracts/manifests/dev/deployment/manifest.json (1 hunks)
  • contracts/manifests/dev/deployment/manifest.toml (1 hunks)
✅ Files skipped from review due to trivial changes (9)
  • balancing/src/App.tsx
  • client/src/three/helpers/utils.ts
  • client/src/ui/components/ModalContainer.tsx
  • client/src/ui/components/bank/ConfirmationPopup.tsx
  • client/src/ui/components/hints/Buildings.tsx
  • client/src/ui/components/hints/HintModal.tsx
  • client/src/ui/components/military/ArmyManagementCard.tsx
  • client/src/ui/elements/SecondaryPopup.tsx
  • client/src/ui/modules/navigation/TopMiddleNavigation.tsx
🚧 Files skipped from review as they are similar to previous changes (7)
  • client/src/ui/components/bank/AddLiquidity.tsx
  • client/src/ui/components/bank/ResourceBar.tsx
  • client/src/ui/components/entities/Entity.tsx
  • client/src/ui/elements/NumberInput.tsx
  • client/src/ui/modules/chat/ChatTab.tsx
  • contracts/manifests/dev/deployment/manifest.json
  • contracts/manifests/dev/deployment/manifest.toml
🧰 Additional context used
🪛 Biome
client/src/ui/modules/military/battle-view/BattleProgressBar.tsx

[error] 145-145: 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)


[error] 145-145: 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)

client/src/ui/modules/military/battle-view/BattleSideView.tsx

[error] 102-102: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

🔇 Additional comments (67)
client/src/ui/modules/military/battle-view/LockedResources.tsx (1)

12-12: Verify the intentional removal of background and border styles.

The background color (bg-[#1b1a1a], bg-hex-bg) and border (border-l-4 border-r-4 border-gold/20) classes have been removed from the outer div. While this simplifies the component's styling, it may affect its visual appearance.

Please confirm if this change is intentional and that the styling is being handled elsewhere (e.g., in a parent component or global stylesheet) to maintain visual consistency.

To verify the impact of this change, you can run the following command:

This will help ensure that the styling for LockedResources is properly managed elsewhere in the codebase.

client/src/ui/containers/BaseContainer.tsx (1)

20-20: Consider the impact of changing the background color

The background color class has been changed from "bg-black/90" to "bg-brown/90". While this change may align with updated design requirements, please consider the following points:

  1. Ensure this change is consistent with the overall design system and color palette of the application.
  2. Verify that the new brown background provides sufficient contrast with the text and other elements within the container for accessibility purposes.
  3. Check if this change affects the visibility of the border gradient, as it might be less noticeable on a brown background compared to a black one.
  4. Confirm that this change has been approved by the design team and is intentional.

To ensure consistency across the codebase, let's check for other occurrences of the previous background color:

This will help identify if similar changes need to be made elsewhere for consistency.

client/src/ui/modules/military/battle-view/EntityAvatar.tsx (3)

13-14: Great addition of helper functions!

The introduction of getStructureCategory and isCategory functions is a good refactoring decision. These helper functions improve code readability and maintainability by abstracting the category checking logic. The use of optional chaining in getStructureCategory is also a good practice for handling potential undefined values.


35-35: Good code organization

The addition of a blank line before the return statement improves code readability by clearly separating the logic section from the JSX.


37-46: Verify layout changes and consider animation reusability

The changes to the motion.img component look good overall. Here are some points to consider:

  1. The image size has increased from 44 to 56 units. Please verify that this change doesn't negatively impact the layout.
  2. Moving animation variants inline improves code locality, which is good. However, if these animations are used elsewhere, consider keeping them in a separate constant for reusability.
  3. The -mt-12 class applies a negative top margin. While this might be intentional for layout purposes, please ensure it doesn't cause any unexpected layout issues.

To verify the layout changes, please review the component in various screen sizes and contexts where it's used.

client/src/ui/modules/military/battle-view/Troops.tsx (2)

49-49: LGTM! Improved visual design.

The updates to the TroopCard component's main div enhance its visual appearance and interactivity. The addition of background color, text color, rounded corners, padding, hover effect, and transition duration contribute to a more polished and consistent design.


17-31: LGTM! Verify troop type changes.

The changes to the TroopRow component look good. The simplification of the className prop and the updates to the count prop are appropriate. However, please confirm that the troop type changes (Knight instead of Crossbowman, and Crossbowman instead of Paladin) align with the intended game design.

To ensure consistency across the codebase, please run the following script:

✅ Verification successful

Verified: Troop type changes are consistent.

No remaining references to the old troop order were found in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to the old troop order

# Test: Search for Crossbowman as the first troop or Paladin as the second troop
rg --type typescript 'TroopCard.*Crossbowman.*TroopCard.*Paladin'

Length of output: 102


Script:

#!/bin/bash
# Description: Check for any remaining references to the old troop order

# Test: Search for Crossbowman as the first troop or Paladin as the second troop in .tsx files
rg --type tsx 'TroopCard.*Crossbowman.*TroopCard.*Paladin'

Length of output: 88


Script:

#!/bin/bash
# Description: Check for any remaining references to the old troop order

# Test: Search for Crossbowman as the first troop or Paladin as the second troop in .ts and .tsx files
rg 'TroopCard.*Crossbowman.*TroopCard.*Paladin' -g '*.ts' -g '*.tsx'

Length of output: 70

client/src/ui/modules/LoadingScreen.tsx (1)

38-38: LGTM: Background color change implemented correctly.

The background color of the main container has been updated from black to brown as intended. This change aligns with the summary and improves the visual consistency of the loading screen.

client/src/ui/elements/BaseThreeTooltip.tsx (1)

56-56: Background color change from black to brown

The background color of the tooltip has been changed from bg-black/90 to bg-brown/90. This modification alters the visual appearance of the tooltip from a semi-transparent black to a semi-transparent brown.

To ensure consistency across the application, let's verify if this color change is part of a broader design update:

This will help us understand if this is an isolated change or part of a larger design update.

✅ Verification successful

Background color change is consistently applied across multiple components

The change from bg-black/90 to bg-brown/90 has been implemented in several files, indicating it is part of a broader design update.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other occurrences of bg-brown/90 and bg-black/90 in the codebase

echo "Occurrences of bg-brown/90:"
rg --type tsx --type jsx "bg-brown/90" -c

echo "Occurrences of bg-black/90:"
rg --type tsx --type jsx "bg-black/90" -c

Length of output: 269


Script:

#!/bin/bash
# Description: Check for other occurrences of bg-brown/90 and bg-black/90 in tsx and jsx files

echo "Occurrences of bg-brown/90:"
rg "bg-brown/90" --glob "*.tsx" --glob "*.jsx" -c

echo "Occurrences of bg-black/90:"
rg "bg-black/90" --glob "*.tsx" --glob "*.jsx" -c

Length of output: 1015

client/src/ui/components/structures/construction/StructureCard.tsx (4)

31-31: LGTM: Background color change enhances visual consistency.

The change from bg-black/30 to bg-brown/30 for the main container's background color appears to be a deliberate design decision. This modification likely improves the visual consistency with the overall color scheme of the application.

To ensure this change aligns with the intended design, please verify the visual appearance in the context of the entire application. You may want to check if similar color updates are needed in other components for consistency.


44-44: LGTM: Overlay color change maintains design consistency.

The modification from bg-black/70 to bg-brown/70 for the overlay's background color is consistent with the previous change, maintaining the new color scheme throughout the component.

Please ensure that the content within this overlay (specifically the "Need More Resources" message and the Silo icon) remains clearly visible and readable against the new brown background. You may want to test this with various screen settings to confirm optimal contrast and legibility.


66-66: LGTM: ResourceIcon background color change completes the design update.

The change from bg-black/10 to bg-brown/10 for the ResourceIcon's background completes the consistent application of the new color scheme throughout the component.

To ensure optimal user experience, please verify that the ResourceIcon remains clearly visible against this new brown background, especially given the low opacity (10%). Test with various icons and screen settings to confirm that the subtle background effect enhances rather than hinders the icon's visibility.


Line range hint 31-66: Summary: Consistent color scheme update enhances visual design.

The changes in this file consistently update the color scheme from black to brown across various elements of the StructureCard component. This modification appears to be part of a broader design update to enhance visual consistency throughout the application.

While these changes improve the aesthetic coherence, it's crucial to ensure that:

  1. The new color scheme maintains or improves readability and contrast for all content.
  2. The changes align with the overall design system and accessibility guidelines of the application.
  3. Similar updates are applied consistently across other components if necessary.

To fully validate these changes:

  1. Test the component with various content and screen settings to ensure optimal visibility and readability.
  2. Review the component in the context of the entire application to confirm design consistency.
  3. Consider conducting a brief accessibility audit to ensure the new color scheme meets all necessary contrast requirements.
client/src/ui/components/trading/MarketResourceSideBar.tsx (1)

33-33: LGTM: Improved styling for better visual appeal

The addition of bg-brown, rounded-2xl, and p-1 classes enhances the component's appearance, providing a distinct background color, rounded corners, and appropriate padding. These changes align well with modern UI practices and likely improve the overall user experience.

client/src/ui/elements/Tooltip.tsx (1)

37-37: Verify the design consistency of the new tooltip background color.

The background color of the tooltip has been changed from black to brown (bg-black/90 to bg-brown/90). While this change doesn't affect the functionality, it's important to ensure it aligns with the overall design system and maintains sufficient contrast for accessibility.

To verify the consistency and impact of this change:

  1. Check if this color change is part of a broader design update.
  2. Ensure the new brown background provides sufficient contrast with the text color for readability.
  3. Verify if this change is applied consistently across all instances of tooltips in the application.

Please review the results of this script to ensure the color change is consistent with the overall design and doesn't introduce any inconsistencies.

client/src/ui/elements/CircleButton.tsx (2)

77-77: Styling update for non-active button state.

The background and border colors for the non-active button state have been updated. This change appears to be a deliberate styling decision, likely to better align with the overall design theme of the application.


91-91: Consistent styling update for disabled button state.

The overlay color for the disabled button state has been changed from black to brown, maintaining consistency with the previous styling update. This change enhances the overall visual coherence of the button component across its various states.

client/src/ui/elements/Button.tsx (2)

21-21: LGTM! Consistent with the new color scheme.

The change from bg-black to bg-brown in the default style is consistent with the updates made to the primary style, reinforcing the new color scheme.


22-22: LGTM! Consistent opacity levels maintained.

The enabledStyle changes from black to brown while maintaining the same opacity levels (10% for normal state, 30% for hover state). This update is consistent with the overall shift in color scheme and preserves the original design intent.

client/src/index.css (2)

24-24: Consider the design implications of changing heading fonts

The font for all heading elements (h1-h6) and their corresponding classes (.h1-.h6) has been changed from "Sedan" to "Bokor". While this change may be intentional, please consider the following:

  1. Does this change align with the overall design system of the application?
  2. Have you tested the readability and appearance of "Bokor" across different screen sizes and devices?
  3. Are there any specific headings that should retain the previous font for design purposes?
  4. Has the design team approved this global change to heading typography?

To ensure consistency, check if there are any other places in the codebase where "Sedan" is still being used for headings:

#!/bin/bash
# Search for "Sedan" font usage in heading-related styles
rg --type css --type typescript 'font-family:.*Sedan.*h[1-6]'

This will help identify any inconsistencies in heading styles across the application.

Also applies to: 33-33


2-2: Verify the necessity of the new "Bokor" font import

The addition of a new font import can impact the application's load time. Please confirm that the "Bokor" font is essential for the design and consider the following:

  1. Is this font being used extensively throughout the application to justify the additional resource load?
  2. Have you considered using font subsetting to reduce the file size if only specific characters are needed?
  3. Is there a fallback strategy in place for users with slow internet connections?

To check the usage of the "Bokor" font across the project, run the following command:

This will help determine if the font is used beyond the changes in this file.

✅ Verification successful

"Bokor" font usage verified

The "Bokor" font is only used in client/src/index.css, as per the changes. No additional usage found across the project.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for "Bokor" font usage in CSS and TSX files
rg --type css --type typescript "font-family:.*Bokor" -g '!index.css'

Length of output: 192


Script:

#!/bin/bash
# Search for "Bokor" font usage in CSS, TS, and TSX files excluding index.css
rg "font-family:.*Bokor" -g "*.css" -g "*.ts" -g "*.tsx" --ignore-file index.css

Length of output: 244


Script:

#!/bin/bash
# Search for "Bokor" font usage in CSS, TS, and TSX files excluding client/src/index.css
rg "font-family:.*Bokor" -g "*.css" -g "*.ts" -g "*.tsx" -g "!client/src/index.css"

Length of output: 85

client/src/ui/elements/ListSelect.tsx (1)

63-63: Verify the intentionality of background color change

The background color for the Listbox.Options component is now always set to "bg-brown", regardless of the props.style value. This change removes the ability to have a black background when props.style === "black".

  1. If this change is intentional to standardize the appearance:

    • Consider removing the conditional statement entirely, as it no longer affects the outcome.
  2. If this change is unintentional:

    • Revert to the previous implementation to maintain the ability to have different background colors based on props.style.

Please confirm if this change aligns with the intended design and functionality of the ListSelect component.

client/src/ui/modules/military/battle-view/BattleHistory.tsx (1)

79-79: Approve CSS class change with a suggestion for visual verification.

The change from mb-4 to my-4 for the event wrapper div is a reasonable adjustment. It will provide equal vertical spacing above and below each event entry, potentially improving readability and visual separation.

To ensure this change aligns with the overall design and doesn't negatively impact the layout, please verify the following:

  1. Check that the added top margin doesn't create unintended spacing at the beginning of the list.
  2. Confirm that the change doesn't cause any overflow issues in the parent container.
  3. Ensure the new spacing is consistent with the design system and other similar components.

Consider reviewing this change with the design team if it significantly alters the visual appearance of the battle history.

client/src/ui/modules/military/battle-view/Battle.tsx (2)

70-80: Summary: Design updates enhance battle view aesthetics and responsiveness.

The changes in this file focus on improving the visual design and layout flexibility of the Battle component. The new styling with bg-brown and bg-hex-bg classes, along with the shift to a minimum height, should result in a more thematically consistent and responsive battle view. The repositioning of the BattleProgressBar component might affect its relation to other elements, so it's worth testing the layout across different screen sizes to ensure a good user experience.

These modifications don't alter the component's core functionality but do enhance its visual presentation. Consider updating related components or views to maintain consistency across the application.


70-80: Styling and structure changes improve flexibility and theme consistency.

The modifications to the battle view container enhance the component's flexibility and visual consistency:

  1. Changing from bg-[#1b1a1a] to bg-brown aligns the color scheme with what seems to be an updated design system.
  2. Adding bg-hex-bg introduces a hexagonal background pattern, which is thematically appropriate for a battle view.
  3. Switching from h-[35vh] to min-h-[40vh] allows for more responsive behavior, accommodating varying content sizes.
  4. Relocating the BattleProgressBar component inside this container might affect its positioning. Ensure this doesn't negatively impact the overall layout or user experience.

To ensure consistency across the codebase, let's check for other occurrences of the old background color:

Also, let's verify the usage of the new bg-brown and bg-hex-bg classes:

✅ Verification successful

Background color updates are consistent and isolated.

The old background color class bg-[#1b1a1a] is no longer present in the codebase, confirming that the change in Battle.tsx is isolated. The new classes bg-brown and bg-hex-bg are consistently used across multiple components, ensuring visual consistency and adherence to the updated design system.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other occurrences of the old background color
rg --type tsx --type jsx 'bg-\[#1b1a1a\]'

Length of output: 71


Script:

#!/bin/bash
# Check for other usages of the new background classes
rg --type tsx --type jsx 'bg-brown'
rg --type tsx --type jsx 'bg-hex-bg'

Length of output: 128


Script:

#!/bin/bash
# Search for other occurrences of the old background color
rg 'bg-\[#1b1a1a\]' -g '*.tsx' -g '*.jsx'

Length of output: 43


Script:

#!/bin/bash
# Check for other usages of the new background classes
rg 'bg-brown' -g '*.tsx' -g '*.jsx'
rg 'bg-hex-bg' -g '*.tsx' -g '*.jsx'

Length of output: 13607

client/src/ui/elements/Select.tsx (3)

69-69: LGTM: Background color update for SelectContent

The change from bg-black/90 to bg-brown/90 for the SelectContent background looks good. This update likely improves the visual consistency with the overall design theme.

To ensure visual consistency, please verify this change in the context of the entire UI. Consider checking:

  1. If the new brown background contrasts well with the text color.
  2. If it aligns with other dropdown menus or similar UI elements in the application.

107-107: LGTM: Layout improvement for SelectItem

The addition of justify-between to the SelectItem's className is a good improvement. This change will create better spacing between the item text and the check icon, enhancing the overall layout of the dropdown items.

To ensure the layout improvement is effective:

  1. Please verify that the text and check icon are properly aligned at the edges of the dropdown.
  2. Check if this change maintains consistency with other similar UI elements in the application.
  3. Ensure that the layout works well with various text lengths in the dropdown items.

You may want to test this with different screen sizes to confirm the responsiveness of the new layout.


Line range hint 1-132: Summary: Minor style improvements to Select component

The changes made to the Select component are purely cosmetic and should enhance its visual appeal:

  1. The background color of SelectContent has been updated to a brown shade, potentially improving theme consistency.
  2. The layout of SelectItem has been adjusted to better space out its contents.

These changes don't introduce any new functionality or potential bugs. However, it's crucial to verify that these updates maintain visual consistency with the rest of the application and work well across different screen sizes and content lengths.

To ensure these changes integrate well with the overall UI:

  1. Test the Select component with various content types and lengths.
  2. Verify the appearance on different screen sizes and devices.
  3. Check for consistency with other UI elements and the overall design language of the application.
client/src/ui/layouts/World.tsx (1)

87-87: LGTM! Verify design consistency.

The change from "bg-black" to "bg-brown" for the loading overlay background looks good. This modification only affects the visual appearance and doesn't introduce any functional changes.

Please confirm that this color change aligns with the overall design system and color scheme of the application. If it's part of a broader design update, consider updating other relevant components for consistency.

client/src/ui/elements/ResourceIcon.tsx (3)

Line range hint 27-27: LGTM: Addition of tooltipText property enhances component flexibility.

The new optional tooltipText property in the Props type is a good addition. It allows for custom tooltip text, improving the component's reusability and flexibility.


Line range hint 89-89: LGTM: Function signature updated correctly.

The ResourceIcon component function signature has been properly updated to include the new tooltipText property. This change is consistent with the Props type modification and maintains the existing default behavior for withTooltip.


Line range hint 1-110: Overall assessment: Changes improve component flexibility and UI consistency.

The modifications to the ResourceIcon component are well-implemented and enhance its functionality:

  1. The addition of the tooltipText property improves reusability.
  2. The tooltip styling changes likely contribute to better UI consistency.
  3. The implementation maintains the existing structure while adding new features.

These changes are approved, with a minor suggestion for text color adjustment in the tooltip for optimal readability.

client/src/ui/modules/military/battle-view/BattleProgressBar.tsx (1)

139-139: LGTM: Improved component layout

The change to set the width to 2/3 and center the component horizontally improves the overall layout and positioning. This adjustment enhances the visual presentation of the battle progress bar.

client/src/ui/modules/stream/EventStream.tsx (5)

11-11: LGTM: Import statements reorganized.

The changes in the import statements are minor reorganizations that don't affect the functionality of the code. The Minimize icon import and the @dojoengine/recs imports have been moved to different lines. This change is acceptable and doesn't introduce any issues.

Also applies to: 18-18


172-174: Styling change: Minimize button background updated.

The background color of the minimize button has been changed from a black shade to a brown shade. This change is part of a broader shift in the color scheme of the component. While it doesn't affect functionality, it does alter the visual appearance of the EventStream component.


177-179: Styling change: Hidden event stream container background updated.

The background color of the event stream container when hidden has been changed from a light black shade to a light brown shade. This change is consistent with the overall color scheme update and only affects the appearance when the event stream is minimized. The functionality remains unchanged.


181-181: Styling changes: Event stream container and items updated.

The background colors of the event stream container and individual event items have been updated:

  1. Main container background changed from bg-black/40 to bg-brown/40 and added bg-hex-bg.
  2. Hover effect on event items changed from hover:bg-black/20 to hover:bg-brown/20.

These changes are part of the overall shift from black to brown in the color scheme and may significantly alter the visual appearance of the component. The addition of bg-hex-bg might introduce a new visual pattern to the background.

While these changes don't affect functionality, it's recommended to verify the new look in a staging environment to ensure it meets the desired design requirements.

To verify the visual changes, please review the component in a staging environment and confirm that the new color scheme aligns with the intended design. You may want to check:

  1. The overall appearance of the event stream container
  2. The visibility and readability of event items
  3. The effectiveness of the hover effect on event items
  4. The impact of the bg-hex-bg class on the background appearance

Also applies to: 188-188


Line range hint 1-203: Summary of changes and suggestions for next steps.

The changes in this file are primarily visual, shifting the color scheme of the EventStream component from black to brown. This includes updates to the background colors of the main container, the minimize button, and the hover effects on event items. The functionality of the component remains unchanged.

Suggestions for next steps:

  1. Provide context: It would be helpful to understand the reasoning behind these color changes. Consider adding a comment in the code or updating the PR description to explain the design decision.
  2. Verify design: Ensure that these changes have been reviewed and approved by the design team.
  3. Cross-browser testing: Verify that the new colors render consistently across different browsers and devices.
  4. Accessibility check: Confirm that the new color scheme maintains sufficient contrast ratios for readability and meets accessibility standards.
  5. Performance impact: Although unlikely, verify that the addition of the bg-hex-bg class doesn't introduce any performance issues, especially on lower-end devices.

Overall, the changes appear to be a consistent update to the component's visual style. Once the above points are addressed, this update should be ready for merging.

To address these suggestions, please:

  1. Update the PR description with the context for these changes.
  2. Confirm that the design team has approved these changes.
  3. Perform cross-browser testing and report the results.
  4. Run an accessibility check on the new color scheme and report the results.
  5. Monitor performance metrics, particularly on lower-end devices, to ensure no significant impact from the bg-hex-bg class.
client/tailwind.config.js (4)

65-65: LGTM! Verify UI appearance with updated colors.

The color updates for gold, red, brown, dark, and green look good. These changes will likely impact the overall appearance of the UI.

Please ensure that these color changes have been tested across different components and pages to maintain visual consistency and meet design requirements.

Also applies to: 70-70, 76-76, 78-78, 83-83


Line range hint 239-252: LGTM! Use the 'no-scrollbar' utility judiciously.

The new 'no-scrollbar' utility class is a good addition for hiding scrollbars across different browsers. This can enhance the UI aesthetics in certain scenarios.

While this utility is useful, please ensure it's used judiciously. Hiding scrollbars can impact user experience and accessibility, especially for users who rely on scrollbars for navigation. Consider the following:

  1. Use this utility only when necessary and when alternative navigation methods are available.
  2. Ensure that the content is still accessible and navigable, especially for keyboard users.
  3. Test the implementation across different devices and screen sizes to prevent content from becoming inaccessible.

To verify proper usage, you can search for applications of this new utility:

#!/bin/bash
# Search for usage of the 'no-scrollbar' utility
rg --type tsx --type ts 'no-scrollbar' src/

Line range hint 1-261: Overall, the changes look good but require careful testing.

The updates to the Tailwind configuration file include several color changes, the addition of a new 'enemy' color, and a new utility class for hiding scrollbars. These changes can significantly impact the UI appearance and functionality.

To ensure these changes are implemented correctly and don't introduce any unintended side effects:

  1. Conduct a thorough visual review of all affected components and pages.
  2. Test the application across different browsers and devices to verify cross-browser compatibility.
  3. Perform accessibility testing, especially for areas where the 'no-scrollbar' utility is applied.
  4. Update any relevant documentation or style guides to reflect these new color values and utilities.

Consider running a comprehensive UI test suite if available:

#!/bin/bash
# Run UI tests (replace with your actual test command)
npm run test:ui

86-86: LGTM! Ensure consistent usage of the new 'enemy' color.

The addition of the 'enemy' color is a good improvement for better visual distinction. The comment explaining its purpose is helpful.

To maintain consistency, please ensure that this new color is used appropriately across all relevant components where enemy entities are displayed. Consider running a search to find potential places where this color should be applied:

✅ Verification successful

The previous shell script encountered errors. Here is a corrected version to search for potential usages of the new 'enemy' color:


The previous shell script encountered issues with unrecognized file types. Here is a corrected version to search for potential usages of the new 'enemy' color:


The previous search targeted a non-existent directory. Here is a corrected script to search within the client/ directory for potential usages of the new 'enemy' color:


Consistent usage of the new 'enemy' color confirmed.

The new 'enemy' color #46201D is appropriately used in ArmyInfoLabel.tsx, enhancing visual distinction without introducing inconsistencies.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential places to apply the new 'enemy' color
rg --type tsx --type ts 'enemy|opponent|foe' src/

Length of output: 273


Script:

#!/bin/bash
# Search for potential places to apply the new 'enemy' color
rg --type tsx --type ts 'enemy|opponent|foe' src/

Length of output: 79


Script:

#!/bin/bash
# Search for potential places to apply the new 'enemy' color
rg 'enemy|opponent|foe' --glob '*.ts' --glob '*.tsx' src/

Length of output: 104


Script:

#!/bin/bash
# Search for potential places to apply the new 'enemy' color within the client directory
rg 'enemy|opponent|foe' --glob '*.ts' --glob '*.tsx' client/

Length of output: 3126

client/src/ui/components/bank/LiquidityResourceRow.tsx (1)

228-228: LGTM! Consider verifying visual consistency.

The change from bg-black/70 to bg-brown/70 for the background color is approved. This modification enhances the visual appearance of the InputResourcesPrice component.

To ensure visual consistency across the application, please verify that this color change aligns with the overall design system. You may want to check if similar components use the same background color for consistency.

client/src/ui/components/trading/MarketModal.tsx (6)

1-5: LGTM: New icon imports enhance UI elements

The addition of these SVG icons (Coins, Crown, Scroll, Sparkles, and Swap) is a good improvement. They will likely enhance the visual representation of tab labels, making the UI more intuitive and visually appealing.


162-163: LGTM: Enhanced modal container styling

The updates to the modal container improve its visual appeal and structure. The addition of a border, rounded corners, and a dark background creates a more defined and aesthetically pleasing container. The use of a grid layout provides a flexible and responsive structure for the modal content.


Line range hint 175-183: Simplified Select component styling

The removal of specific background styling from the SelectContent component is a good step towards more consistent theming. This change allows the component to inherit default styles, which can lead to better overall design coherence.

However, it's important to verify that the inherited styles still provide sufficient contrast and visibility for the select options.

Please check that the select dropdown is still clearly visible and usable with the inherited styles in various color schemes (e.g., light and dark modes if applicable).


202-216: LGTM: Improved header layout and structure

The changes to the header section enhance both the visual appeal and the semantic structure of the component:

  1. Centering the title and using an h1 element improves the visual hierarchy and semantic meaning.
  2. The repositioning of the hint modal toggle button likely creates a better balance in the layout.

These changes contribute to a more polished and user-friendly interface.


223-227: LGTM: Improved tab list layout

The use of a flex layout for the tab list is a good improvement. This change ensures consistent spacing and alignment of tabs, likely enhancing the responsiveness of the layout. It contributes to a more polished and flexible user interface.


Line range hint 1-240: Overall assessment: Significant UI improvements with no major issues

The changes to the MarketModal component focus on enhancing the user interface and improving the overall layout. Key improvements include:

  1. Addition of intuitive icons to tab labels
  2. Improved modal container styling
  3. Simplified Select component styling
  4. Enhanced header layout and structure
  5. Improved tab list layout using flex

These changes contribute to a more visually appealing and user-friendly interface without introducing any significant logic changes or potential bugs. The component's core functionality remains intact while its presentation has been notably improved.

Consider implementing the suggested TabLabel component to further improve code maintainability. Also, ensure that the Select component's inherited styles provide sufficient contrast and visibility in all relevant color schemes.

client/src/ui/components/bank/Swap.tsx (4)

65-66: LGTM: Efficient balance calculation with memoization

The addition of memoized lordsBalance and resourceBalance variables is a good optimization. It prevents unnecessary recalculations and simplifies balance retrieval throughout the component.


70-71: LGTM: Simplified and consistent balance check

The updated hasEnough calculation correctly utilizes the new memoized balance variables. This change improves code consistency and readability while maintaining the correct logic for checking if the user has sufficient balance for the swap.


275-276: LGTM: Robust slippage calculation

The addition of Math.abs() in the slippage calculation is a good defensive programming practice. It ensures that the calculation works correctly regardless of the sign of the input values, making the component more robust against potential edge cases.


165-165: 🛠️ Refactor suggestion

Consider consistent max value handling for all resources

While adding a max prop to the ResourceBar is a good idea to prevent overspending, the current implementation is inconsistent. It limits the input for Lords but not for other resources.

Consider updating the max prop to use resourceBalance for non-Lords resources:

-max={isLords ? divideByPrecision(lordsBalance) : Infinity}
+max={isLords ? divideByPrecision(lordsBalance) : divideByPrecision(resourceBalance)}

This change would ensure consistent behavior across all resource types and prevent users from inputting amounts greater than their available balance for any resource.

client/src/ui/modules/onboarding/Steps.tsx (7)

35-37: LGTM! Verify visual appearance of updated StepContainer.

The changes to the StepContainer's styling look good. The background color has been updated from black to brown, and new visual effects have been added (border-gradient, animatedBackground).

Please ensure that these visual changes align with the overall design system and provide a cohesive user experience across the onboarding process.


Line range hint 65-219: LGTM! Naming component remains unchanged.

The Naming component's functionality appears to be unchanged. It continues to handle address naming, account management, and related UI interactions effectively.


Line range hint 221-229: Significant change in StepTwo: Verify SettleRealmComponent functionality.

The StepTwo component has been completely replaced with a new SettleRealmComponent. This change likely introduces new functionality related to realm selection or settlement.

Could you provide more information about the SettleRealmComponent? It's important to ensure that this change aligns with the overall onboarding flow and user experience objectives.


Line range hint 231-296: LGTM! Consistent layout and informative content in Steps Three, Four, and Five.

The changes to StepThree, StepFour, and StepFive components look good. They now use a consistent ContainerWithSquire layout and provide important game information to new players.

Please review the content of each step to ensure it provides complete and clear information about the game world and mechanics. Consider having a game designer or content writer review these sections to optimize the onboarding experience.


Line range hint 307-319: LGTM! Engaging final step with clear call-to-action.

The changes to the StepSix component look good. The addition of the ResourceIcon and the message about quests provide a visually engaging and informative final step in the onboarding process.

Please ensure that the NavigateToRealm component functions correctly and provides a smooth transition from the onboarding process to the actual gameplay. Test this transition thoroughly to avoid any potential issues that could disrupt the user experience.


Line range hint 321-348: LGTM! Smooth transition to gameplay implemented.

The NavigateToRealm component effectively handles the transition from onboarding to the game world. The use of state management and custom event dispatch suggests a well-thought-out approach to managing this transition.

Please ensure that:

  1. The 'ACCOUNT_CHANGE_EVENT' is properly handled across the application.
  2. The 250ms timeout before navigation is necessary and doesn't cause any noticeable delay for users.
  3. Error handling is in place in case the navigation or state updates fail.

Line range hint 1-348: Overall improvements to onboarding process and user experience.

The changes to the Steps.tsx file significantly enhance the onboarding process. Key improvements include:

  1. Consistent styling and layout across steps.
  2. Introduction of new components like SettleRealmComponent and ContainerWithSquire.
  3. Clear progression through the onboarding steps with informative content.
  4. Smooth transition from onboarding to gameplay.

These changes should result in a more engaging and informative onboarding experience for new players.

To ensure the best possible user experience:

  1. Conduct thorough end-to-end testing of the entire onboarding flow.
  2. Verify that all new components (e.g., SettleRealmComponent) function as intended.
  3. Review the content of each step for clarity and completeness.
  4. Test the final transition to gameplay across different devices and network conditions.
client/src/ui/modules/chat/Chat.tsx (2)

7-7: LGTM: New imports and hook usage

The new imports and the use of the useCallback hook are appropriate for the changes made to the component. The addition of useGuilds and CHAT_COLORS aligns well with the new guild functionality and chat color management.

Also applies to: 10-10, 14-14, 17-17


205-208: LGTM: Improved Messages component with guild support

The Messages component has been successfully updated to handle guild messages. The changes include:

  1. Proper identification of guild messages
  2. Updated message key generation to include guild messages
  3. Appropriate color styling based on the channel type (global, guild, or private)

These modifications enhance the component's functionality and visual representation of different message types.

Also applies to: 219-222, 273-279

client/src/ui/components/trading/MarketOrderPanel.tsx (1)

59-61: Improved UI with rounded corners

The addition of the rounded-xl class to the main container enhances the visual consistency with other components in the UI.

client/src/ui/components/construction/SelectPreviewBuilding.tsx (1)

350-350: Consistent color scheme update applied.

The background color classes have been updated from black to brown (e.g., bg-black/30 to bg-brown/30) for both the main container and the overlay. This change is consistently applied and likely improves the visual design without affecting functionality.

Also applies to: 367-367, 390-390

client/src/ui/modules/social/PlayerId.tsx (3)

15-15: Import 'getMessageKey' for chat tab key generation

The getMessageKey function is properly imported from "../chat/utils" to generate unique keys for chat tabs.


27-27: Retrieve 'addTab' from chat store

The addTab function is correctly retrieved from the chat store using useChatStore, ensuring proper tab management.


127-127: Update background color for player name display

The background color class is updated to bg-brown/20, enhancing the visual consistency of the player name display.

Comment on lines +30 to 31
"px-6 py-2 bg-brown font-semibold text-lg uppercase tracking-wider shadow-md hover:from-yellow-700 hover:to-yellow-800 focus:outline-none border-2 outline-gold hover:bg-gold border-y hover:border-gold hover:bg-brown/90 bg-brown/40 hover:text-black/90",
loadingStyle: "relative",
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

LGTM, but hover text color inconsistency noted.

The opaque style changes align well with the new color scheme, switching from black to brown. However, there's an inconsistency in the hover text color:

  • The primary style uses hover:text-brown
  • The opaque style uses hover:text-black/90

Consider changing hover:text-black/90 to hover:text-brown in the opaque style for consistency with the primary style, unless this difference is intentional.

@@ -139,7 +139,7 @@ export const BattleSideView = ({
{showBattleDetails && battleEntityId ? (
<BattleHistory battleSide={battleSide} battleId={battleEntityId} />
) : (
<TroopRow troops={ownSideTroopsUpdated} />
<TroopRow defending={battleSide === BattleSide.Defence} troops={ownSideTroopsUpdated} />
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

Potential Issue: defending prop is used but not defined in TroopRow component.

It appears that the defending prop is being passed to the TroopRow component in BattleSideView.tsx, but this prop is not defined in the component's props within Troops.tsx or Combat.tsx. This might lead to TypeScript errors or unintended behavior during runtime.

  • Ensure that the defending prop is properly defined in the TroopRow component's prop types in Troops.tsx and Combat.tsx.
  • Verify that the TroopRow component utilizes the defending prop as intended.
🔗 Analysis chain

LGTM! Please provide context on the defending prop usage.

The addition of the defending prop to TroopRow is a good way to pass contextual information about the battle side.

Could you please provide more context on how the defending prop is used within the TroopRow component? This information would help ensure that the prop is being utilized effectively and that the component's behavior aligns with the intended design.

To assist in verifying the usage, you can run the following script:

This will help us understand how the defending prop is defined and used within the TroopRow component.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the TroopRow component definition and its usage of the 'defending' prop
ast-grep --lang typescript --pattern 'const TroopRow = ({ defending, $_ }: { defending: boolean, $_ }) => { $$$ }'

Length of output: 116


Script:

#!/bin/bash
# Search for the TroopRow component defined as a class-based component
ast-grep --lang typescript --pattern 'class TroopRow extends React.Component<$$_, $$_> { $$$ }'

Length of output: 97


Script:

#!/bin/bash
# Search for all occurrences of 'TroopRow' in TypeScript files
rg 'TroopRow' --glob '*.tsx'

Length of output: 609


Script:

#!/bin/bash
# Verify if the 'TroopRow' component definitions include the 'defending' prop
rg 'TroopRow\s*=\s*\(\{[^}]*defending[^}]*\}' --glob '*.tsx' client/src/ui/modules/military/battle-view/Troops.tsx client/src/ui/components/hints/Combat.tsx

Length of output: 158

@@ -136,14 +136,14 @@ export const BattleProgressBar = ({
<motion.div
initial="hidden"
animate="visible"
className=""
className="w-2/3 mx-auto"
variants={{
hidden: { y: "100%" },
visible: { y: "0%", transition: { duration: 0.5 } },
}}
>
{!isNaN(Number(attackingHealthPercentage)) && !isNaN(Number(defendingHealthPercentage)) && (
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace isNaN with Number.isNaN for improved type safety

The static analysis tool has flagged the use of the global isNaN function. This function attempts type coercion, which can lead to unexpected results. It's recommended to use Number.isNaN instead for improved type safety and more predictable behavior.

Please apply the following change:

- {!isNaN(Number(attackingHealthPercentage)) && !isNaN(Number(defendingHealthPercentage)) && (
+ {!Number.isNaN(Number(attackingHealthPercentage)) && !Number.isNaN(Number(defendingHealthPercentage)) && (

This change will ensure more reliable NaN checks and improve the overall robustness of the code.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{!isNaN(Number(attackingHealthPercentage)) && !isNaN(Number(defendingHealthPercentage)) && (
{!Number.isNaN(Number(attackingHealthPercentage)) && !Number.isNaN(Number(defendingHealthPercentage)) && (
🧰 Tools
🪛 Biome

[error] 145-145: 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)


[error] 145-145: 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)

Comment on lines +31 to +37
addTab({
name: playerName,
key: getMessageKey(account.address, selectedPlayer),
address: toHexString(selectedPlayer),
displayed: true,
lastSeen: new Date(),
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure 'account.address' is defined before using in 'getMessageKey'

In the handleClick function, getMessageKey is called with account.address and selectedPlayer without verifying if account.address is defined. To prevent potential runtime errors, consider adding a check to ensure account.address is defined before using it.

* feat: implement randomness for number of mercenaries

* fix tests + address PR comments
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: 6

🧹 Outside diff range and nitpick comments (5)
sdk/packages/eternum/src/constants/global.ts (2)

98-103: LGTM! Consider using an enum for mercenary types.

The new constants for mercenaries provide more flexibility by defining lower and upper bounds. The naming convention is consistent and clear, and the use of underscores for large numbers improves readability.

Consider using an enum for mercenary types to improve type safety and reduce the likelihood of typos:

enum MercenaryType {
  Knights = 'knights',
  Paladins = 'paladins',
  Crossbowmen = 'crossbowmen',
}

export const MERCENARIES_BOUNDS = {
  [MercenaryType.Knights]: { lower: 1_000, upper: 10_000 },
  [MercenaryType.Paladins]: { lower: 1_000, upper: 10_000 },
  [MercenaryType.Crossbowmen]: { lower: 1_000, upper: 10_000 },
};

This approach would centralize the mercenary types and their bounds, making it easier to maintain and extend in the future.


191-196: LGTM! Consider using camelCase for consistency.

The updated mercenaries section in the EternumGlobalConfig object aligns well with the new constants defined earlier. The structure is more flexible, allowing for different ranges for each mercenary type.

For consistency with TypeScript conventions, consider using camelCase for the property names:

mercenaries: {
  knightsLowerBound: MERCENARIES_KNIGHTS_LOWER_BOUND,
  knightsUpperBound: MERCENARIES_KNIGHTS_UPPER_BOUND,
  paladinsLowerBound: MERCENARIES_PALADINS_LOWER_BOUND,
  paladinsUpperBound: MERCENARIES_PALADINS_UPPER_BOUND,
  crossbowmenLowerBound: MERCENARIES_CROSSBOWMEN_LOWER_BOUND,
  crossbowmenUpperBound: MERCENARIES_CROSSBOWMEN_UPPER_BOUND,
  // ... rest of the mercenaries config
},

This would maintain consistency with the rest of the TypeScript codebase.

contracts/src/utils/testing/config.cairo (2)

184-202: LGTM! Consider using a struct for improved readability.

The changes to set_mercenaries_config provide more granular control over troop counts by specifying lower and upper bounds for each troop type. This implementation allows for dynamic configuration of mercenary troops, which can be beneficial for gameplay balancing.

To improve code readability and maintainability, consider creating a struct to encapsulate the troop bounds:

struct TroopBounds {
    lower: u32,
    upper: u32,
}

struct MercenariesConfig {
    knights: TroopBounds,
    paladins: TroopBounds,
    crossbowmen: TroopBounds,
}

// Usage:
let config = MercenariesConfig {
    knights: TroopBounds { lower: 0, upper: 4_000_000 },
    paladins: TroopBounds { lower: 0, upper: 4_000_000 },
    crossbowmen: TroopBounds { lower: 0, upper: 4_000_000 },
};

IMercenariesConfigDispatcher { contract_address: config_systems_address }
    .set_mercenaries_config(config, mercenaries_rewards);

This approach would make the function call cleaner and easier to maintain as the number of parameters grows.


Line range hint 206-215: LGTM! Consider using a struct for consistency.

The use of named parameters in set_settlement_config significantly improves code readability by clearly indicating what each value represents. This change enhances the maintainability of the code without altering its functionality.

For consistency with the previous suggestion and to further improve code organization, consider creating a struct for the settlement configuration:

struct SettlementConfig {
    radius: u32,
    angle_scaled: u32,
    center: u32,
    min_distance: u32,
    max_distance: u32,
    min_scaling_factor_scaled: u64,
    min_angle_increase: u32,
    max_angle_increase: u32,
}

// Usage:
let config = SettlementConfig {
    radius: 50,
    angle_scaled: 0,
    center: 2147483646,
    min_distance: 1,
    max_distance: 5,
    min_scaling_factor_scaled: 1844674407370955161,
    min_angle_increase: 30,
    max_angle_increase: 100,
};

ISettlementConfigDispatcher { contract_address: config_systems_address }
    .set_settlement_config(config);

This approach would maintain consistency with other configuration structures and make it easier to add or modify settlement parameters in the future.

sdk/packages/eternum/src/config/index.ts (1)

486-489: Ensure consistent formatting for 'crossbowmen' parameters

The key-value pairs for crossbowmen_lower_bound and crossbowmen_upper_bound are split across multiple lines, whereas the previous entries for knights and paladins are on single lines. For consistency and improved readability, consider formatting the 'crossbowmen' parameters similarly.

Apply this diff to adjust the formatting:

-        crossbowmen_lower_bound:
-          config.config.mercenaries.crossbowmen_lower_bound * config.config.resources.resourcePrecision,
-        crossbowmen_upper_bound:
-          config.config.mercenaries.crossbowmen_upper_bound * config.config.resources.resourcePrecision,
+        crossbowmen_lower_bound: config.config.mercenaries.crossbowmen_lower_bound * config.config.resources.resourcePrecision,
+        crossbowmen_upper_bound: config.config.mercenaries.crossbowmen_upper_bound * config.config.resources.resourcePrecision,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d3bd7cb and 43456ea.

📒 Files selected for processing (10)
  • contracts/src/models/config.cairo (1 hunks)
  • contracts/src/systems/config/contracts.cairo (2 hunks)
  • contracts/src/systems/dev/contracts/bank.cairo (1 hunks)
  • contracts/src/systems/map/contracts.cairo (2 hunks)
  • contracts/src/utils/testing/config.cairo (1 hunks)
  • sdk/packages/eternum/src/config/index.ts (1 hunks)
  • sdk/packages/eternum/src/constants/global.ts (2 hunks)
  • sdk/packages/eternum/src/provider/index.ts (1 hunks)
  • sdk/packages/eternum/src/types/common.ts (2 hunks)
  • sdk/packages/eternum/src/types/provider.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • sdk/packages/eternum/src/types/common.ts
🧰 Additional context used
🔇 Additional comments (5)
sdk/packages/eternum/src/types/provider.ts (1)

545-550: Approve changes to SetMercenariesConfigProps interface with considerations

The modifications to the SetMercenariesConfigProps interface provide more granular control over mercenary configurations by introducing separate lower and upper bounds for each troop type. This change enhances flexibility in setting mercenary parameters.

Please ensure that all usages of SetMercenariesConfigProps in the codebase have been updated to reflect these changes. Additionally, verify if the removal of the Troops type from this interface affects any other parts of the codebase.

sdk/packages/eternum/src/provider/index.ts (2)

1084-1105: Improved granularity in mercenary configuration

The changes to the set_mercenaries_config function enhance the flexibility of mercenary configuration by allowing specific bounds for different troop types (knights, paladins, crossbowmen). This granular control is a positive improvement over the previous generic 'troops' parameter.

The implementation correctly includes all new parameters in the function signature and the calldata construction. This change aligns well with the provided AI-generated summary.


1084-1105: Verify impact on related components

While the changes to set_mercenaries_config are well-implemented, it's important to ensure that all components interacting with this function are updated to accommodate the new parameter structure.

Please run the following script to identify potential areas that may need updates:

✅ Verification successful

Impact on related components verified

All calls to set_mercenaries_config have been updated to accommodate the new parameter structure, and no references to the old troops parameter were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find usages of set_mercenaries_config to ensure they're updated

# Search for calls to set_mercenaries_config
echo "Searching for calls to set_mercenaries_config:"
rg "set_mercenaries_config" --type typescript --type javascript

# Search for references to the old 'troops' parameter
echo "Searching for references to the old 'troops' parameter:"
rg "troops.*set_mercenaries_config" --type typescript --type javascript

Length of output: 437


Script:

#!/bin/bash
# Description: Find usages of set_mercenaries_config to ensure they're updated

# Search for calls to set_mercenaries_config in TypeScript and JavaScript files
echo "Searching for calls to set_mercenaries_config:"
rg "set_mercenaries_config" -g "*.ts" -g "*.tsx" -g "*.js" -g "*.jsx"

# Search for references to the old 'troops' parameter in TypeScript and JavaScript files
echo "Searching for references to the old 'troops' parameter:"
rg "troops\s*,\s*set_mercenaries_config" -g "*.ts" -g "*.tsx" -g "*.js" -g "*.jsx"

Length of output: 701

contracts/src/systems/dev/contracts/bank.cairo (1)

82-82: LGTM! Simplified mercenary addition improves maintainability

Replacing the previous logic with a single call to InternalMapSystemsImpl::add_mercenaries_to_structure enhances code readability and maintainability by abstracting the mercenary addition process.

contracts/src/systems/map/contracts.cairo (1)

172-176: Implementation Enhancement Looks Good

The addition of transferring rewards to the mine structure enhances the functionality by ensuring the mine entity receives the appropriate rewards upon discovery.

Comment on lines +254 to +257
let tx_info = starknet::get_tx_info();
let salt_one: u256 = tx_info.transaction_hash.into();
let salt_two: u256 = starknet::get_block_timestamp().into();
let salt_three: u256 = tx_info.nonce.into();
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential Security Issue: Use of Predictable Salts for Randomness

Using tx_info.transaction_hash, starknet::get_block_timestamp(), and tx_info.nonce as salts for random number generation can lead to predictable outputs. Transaction hashes, timestamps, and nonces can be influenced or predicted by malicious actors, potentially allowing them to manipulate the random troop counts.

Consider using a more secure and unpredictable source of randomness. For example, you might use a verifiable random function (VRF) or another blockchain-provided randomness beacon that is resistant to manipulation.

Comment on lines +259 to +279
let random_knights_amount: u64 = random::random(
salt_one.low,
mercenaries_config.knights_upper_bound.into() - mercenaries_config.knights_lower_bound.into()
)
.try_into()
.unwrap()
+ mercenaries_config.knights_lower_bound;
let random_paladins_amount: u64 = random::random(
salt_two.low,
mercenaries_config.paladins_upper_bound.into() - mercenaries_config.paladins_lower_bound.into()
)
.try_into()
.unwrap()
+ mercenaries_config.paladins_lower_bound;
let random_crossbowmen_amount: u64 = random::random(
salt_three.low,
mercenaries_config.crossbowmen_upper_bound.into() - mercenaries_config.crossbowmen_lower_bound.into()
)
.try_into()
.unwrap()
+ mercenaries_config.crossbowmen_lower_bound;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Random Troop Counts May Be Predictable and Manipulable

The random troop counts for knights, paladins, and crossbowmen are generated using salts derived from transaction and block data:

  • salt_one.low from transaction_hash
  • salt_two.low from block_timestamp
  • salt_three.low from nonce

Since these values can be predicted or manipulated, the resulting troop counts may not be truly random, potentially impacting game balance and fairness.

Recommend updating the random number generation process to use a secure and unbiased source of randomness. For instance, consider:

  • Utilizing on-chain randomness provided by the blockchain protocol that is designed to be unpredictable and tamper-resistant.
  • Implementing a commit-reveal scheme where randomness is derived from player commitments.
  • Using randomness provided by an oracle service if available and appropriate for your application's trust model.

Comment on lines +482 to +489
knights_lower_bound: config.config.mercenaries.knights_lower_bound * config.config.resources.resourcePrecision,
knights_upper_bound: config.config.mercenaries.knights_upper_bound * config.config.resources.resourcePrecision,
paladins_lower_bound: config.config.mercenaries.paladins_lower_bound * config.config.resources.resourcePrecision,
paladins_upper_bound: config.config.mercenaries.paladins_upper_bound * config.config.resources.resourcePrecision,
crossbowmen_lower_bound:
config.config.mercenaries.crossbowmen_lower_bound * config.config.resources.resourcePrecision,
crossbowmen_upper_bound:
config.config.mercenaries.crossbowmen_upper_bound * config.config.resources.resourcePrecision,
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider refactoring to reduce code duplication

The assignments for the troop bounds (knights_lower_bound, paladins_lower_bound, crossbowmen_lower_bound, etc.) are repetitive. Refactoring the code to iterate over the troop types can reduce duplication and enhance maintainability.

For example:

const troopTypes = ['knights', 'paladins', 'crossbowmen'];
troopTypes.forEach((troop) => {
  tx[`${troop}_lower_bound`] =
    config.config.mercenaries[`${troop}_${'lower_bound'}`] * config.config.resources.resourcePrecision;
  tx[`${troop}_upper_bound`] =
    config.config.mercenaries[`${troop}_${'upper_bound'}`] * config.config.resources.resourcePrecision;
});

Ensure that tx is appropriately defined and adjust the context as needed.

Comment on lines +394 to +399
knights_lower_bound: u64,
knights_upper_bound: u64,
paladins_lower_bound: u64,
paladins_upper_bound: u64,
crossbowmen_lower_bound: u64,
crossbowmen_upper_bound: u64,
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider encapsulating troop bounds into a nested structure for better organization

The addition of individual lower and upper bounds for each troop type enhances configuration granularity. However, grouping these bounds into a nested structure can improve maintainability and scalability, especially if more troop types are added in the future.

Apply this refactor:

 pub struct MercenariesConfig {
     #[key]
     config_id: ID,
-    knights_lower_bound: u64,
-    knights_upper_bound: u64,
-    paladins_lower_bound: u64,
-    paladins_upper_bound: u64,
-    crossbowmen_lower_bound: u64,
-    crossbowmen_upper_bound: u64,
+    knights_bounds: TroopBounds,
+    paladins_bounds: TroopBounds,
+    crossbowmen_bounds: TroopBounds,
     rewards: Span<(u8, u128)>
 }
 
+pub struct TroopBounds {
+    lower_bound: u64,
+    upper_bound: u64,
+}

Committable suggestion was skipped due to low confidence.

Comment on lines +153 to +162
fn set_mercenaries_config(
ref world: IWorldDispatcher,
knights_lower_bound: u64,
knights_upper_bound: u64,
paladins_lower_bound: u64,
paladins_upper_bound: u64,
crossbowmen_lower_bound: u64,
crossbowmen_upper_bound: u64,
rewards: Span<(u8, u128)>
);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider encapsulating troop bounds into a struct for clarity

The function set_mercenaries_config has multiple parameters for troop bounds, which can make the signature lengthy and harder to maintain. Consider encapsulating the troop bounds into a dedicated struct to enhance readability and maintainability.

Apply this diff to refactor the function signature:

 fn set_mercenaries_config(
     ref world: IWorldDispatcher,
-    knights_lower_bound: u64,
-    knights_upper_bound: u64,
-    paladins_lower_bound: u64,
-    paladins_upper_bound: u64,
-    crossbowmen_lower_bound: u64,
-    crossbowmen_upper_bound: u64,
+    troop_bounds: TroopBounds,
     rewards: Span<(u8, u128)>
 );

Define the TroopBounds struct as:

struct TroopBounds {
    knights_lower_bound: u64,
    knights_upper_bound: u64,
    paladins_lower_bound: u64,
    paladins_upper_bound: u64,
    crossbowmen_lower_bound: u64,
    crossbowmen_upper_bound: u64,
}

Comment on lines +657 to +693
fn set_mercenaries_config(
ref world: IWorldDispatcher,
knights_lower_bound: u64,
knights_upper_bound: u64,
paladins_lower_bound: u64,
paladins_upper_bound: u64,
crossbowmen_lower_bound: u64,
crossbowmen_upper_bound: u64,
rewards: Span<(u8, u128)>
) {
assert_caller_is_admin(world);

set!(world, (MercenariesConfig { config_id: WORLD_CONFIG_ID, troops, rewards }));
assert!(
knights_lower_bound < knights_upper_bound, "knights_lower_bound must be lower than knights_upper_bound"
);
assert!(
paladins_lower_bound < paladins_upper_bound,
"paladins_lower_bound must be lower than paladins_upper_bound"
);
assert!(
crossbowmen_lower_bound < crossbowmen_upper_bound,
"crossbowmen_lower_bound must be lower than crossbowmen_upper_bound"
);

set!(
world,
(MercenariesConfig {
config_id: WORLD_CONFIG_ID,
knights_lower_bound,
knights_upper_bound,
paladins_lower_bound,
paladins_upper_bound,
crossbowmen_lower_bound,
crossbowmen_upper_bound,
rewards
})
);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor repetitive assertions to improve maintainability

The assertions checking the lower and upper bounds for each troop type are repetitive. Consider refactoring them into a loop to reduce code duplication and enhance readability.

Apply this diff to refactor the assertions:

+            let troop_bounds = [
+                ("knights", knights_lower_bound, knights_upper_bound),
+                ("paladins", paladins_lower_bound, paladins_upper_bound),
+                ("crossbowmen", crossbowmen_lower_bound, crossbowmen_upper_bound),
+            ];
+            for (name, lower_bound, upper_bound) in troop_bounds {
+                assert!(
+                    lower_bound < upper_bound,
+                    "{}_lower_bound must be lower than {}_upper_bound",
+                    name, name
+                );
+            }
-
             assert!(
                 knights_lower_bound < knights_upper_bound, "knights_lower_bound must be lower than knights_upper_bound"
             );
             assert!(
                 paladins_lower_bound < paladins_upper_bound,
                 "paladins_lower_bound must be lower than paladins_upper_bound"
             );
             assert!(
                 crossbowmen_lower_bound < crossbowmen_upper_bound,
                 "crossbowmen_lower_bound must be lower than crossbowmen_upper_bound"
             );

Committable suggestion was skipped due to low confidence.

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

🧹 Outside diff range and nitpick comments (51)
client/src/ui/elements/StaminaResourceCost.tsx (1)

Line range hint 1-48: Overall changes improve maintainability while preserving functionality

The modifications to the StaminaResourceCost component enhance its maintainability and align it with what appears to be a broader architectural shift towards centralized configuration management. The core functionality and interface of the component remain intact, which is commendable.

However, there's room for improvement in error handling:

Consider adding error handling for cases where configManager.getTravelStaminaCost() or configManager.getExploreStaminaCost() might return undefined or unexpected values. This could prevent potential runtime errors and improve the component's robustness.

Example:

const travelCost = configManager.getTravelStaminaCost() ?? 0;
const exploreCost = configManager.getExploreStaminaCost() ?? 0;
const costs = travelLength * (isExplored ? -travelCost : -exploreCost);
client/src/ui/components/resources/RealmResourcesIO.tsx (2)

21-21: LGTM: Centralized resource input management

The use of configManager.resourceInputs aligns well with the move towards centralized configuration management. This change improves maintainability and flexibility of the resource input data.

Consider using object destructuring for a more concise syntax:

const { resourceInputs } = configManager;

26-28: LGTM: Updated resource consumption calculation

The changes correctly implement the new resource input data source while maintaining the existing filtering logic. This aligns well with the centralized configuration approach.

Consider memoizing the resourcesConsumed calculation to optimize performance, especially if realm or resourcesInputs don't change frequently:

import { useMemo } from 'react';

// ...

const resourcesConsumed = useMemo(() => {
  if (!realm) return [];
  return [...new Set(
    resourcesProduced.flatMap((resourceId) => 
      resourcesInputs[resourceId]
        .filter((input) => input.resource !== ResourcesIds["Wheat"] && input.resource !== ResourcesIds["Fish"])
        .map((input) => input.resource)
    )
  )];
}, [realm, resourcesInputs, resourcesProduced]);

This optimization would prevent unnecessary recalculations on each render.

client/src/ui/components/hints/GettingStarted.tsx (3)

1-1: Improved configuration management approach

The changes in the import statements reflect a shift towards a more centralized and flexible configuration management system. By using configManager and TickIds, the code becomes more maintainable and easier to update across the application.

Consider documenting this new approach in the project's README or developer documentation to ensure consistent usage across the codebase.

Also applies to: 3-3


11-11: Improved flexibility in time cycle calculation

The updated calculation for the Eternum Day duration uses the new configuration management system, which provides better flexibility and maintainability. This change aligns well with the updated import statements.

Consider extracting the calculation into a separate constant or function for improved readability:

const SECONDS_IN_MINUTE = 60;
const eternumDayInMinutes = configManager.getTick(TickIds.Armies) / SECONDS_IN_MINUTE;

Then use eternumDayInMinutes in the template string. This would make the code more self-documenting and easier to maintain.


Line range hint 1-58: Overall improvement in configuration management and maintainability

The changes in this file represent a positive step towards more flexible and maintainable code. By centralizing configuration management and using dynamic retrieval of tick intervals, the code becomes more adaptable to future changes. The core functionality of the GettingStarted component remains intact, ensuring that the user experience is preserved while improving the underlying implementation.

As the project continues to evolve, consider applying similar refactoring techniques to other components that may still be using global constants or hard-coded configuration values. This will ensure consistency across the codebase and make future updates easier to manage.

config/index.ts (4)

Line range hint 8-14: Approve environment variable checks with a suggestion for improvement.

The addition of environment variable checks improves the robustness of the configuration setup. However, the error message could be more informative.

Consider updating the error message to include all checked variables:

- throw new Error("VITE_PUBLIC_MASTER_ADDRESS is required");
+ throw new Error("VITE_PUBLIC_MASTER_ADDRESS, VITE_PUBLIC_MASTER_PRIVATE_KEY, and VITE_PUBLIC_NODE_URL are required");

Line range hint 19-23: Approve manifest and node URL selection with a suggestion.

The conditional selection of manifest and node URL based on the VITE_PUBLIC_DEV environment variable improves flexibility between development and production environments.

Consider making the development node URL configurable:

- const nodeUrl = VITE_PUBLIC_DEV === "true" ? "http://127.0.0.1:5050/" : VITE_PUBLIC_NODE_URL;
+ const nodeUrl = VITE_PUBLIC_DEV === "true" ? (process.env.VITE_PUBLIC_DEV_NODE_URL || "http://127.0.0.1:5050/") : VITE_PUBLIC_NODE_URL;

This change would allow developers to override the default development URL if needed.


Line range hint 25-34: Approve user confirmation for non-dev environments with a suggestion.

The addition of a user confirmation prompt for non-development environments is a good safety measure to prevent accidental configuration of production environments.

Consider using an asynchronous input method or environment variable for confirmation in environments where prompt might not be available or suitable:

import readline from 'readline';

// ... (existing code)

if (!VITE_PUBLIC_DEV) {
  if (process.env.VITE_CONFIRM_PRODUCTION !== 'true') {
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });

    await new Promise<void>((resolve, reject) => {
      rl.question(
        "You are about to set the configuration for a non-development environment. Are you sure you want to proceed? (yes/no) ",
        (answer) => {
          rl.close();
          if (answer.toLowerCase() !== "yes") {
            console.log("Configuration setup cancelled.");
            process.exit(0);
          }
          resolve();
        }
      );
    });
  }
}

This approach provides more flexibility and can work in various environments.


Line range hint 43-56: Approve configuration setup with suggestions for improvement.

The conditional modification of the setupConfig object based on the VITE_PUBLIC_DEV environment variable allows for different configurations in development and production environments, which is a good practice.

Consider the following improvements for more flexibility:

  1. Use environment variables for development-specific values:
const setupConfig: Config =
  VITE_PUBLIC_DEV === "true"
    ? {
        ...EternumGlobalConfig,
        stamina: {
          ...EternumGlobalConfig.stamina,
          travelCost: Number(process.env.VITE_DEV_TRAVEL_COST) || 0,
          exploreCost: Number(process.env.VITE_DEV_EXPLORE_COST) || 0,
        },
        battle: {
          graceTickCount: Number(process.env.VITE_DEV_GRACE_TICK_COUNT) || 0,
          delaySeconds: Number(process.env.VITE_DEV_DELAY_SECONDS) || 0,
        },
      }
    : EternumGlobalConfig;
  1. Create a separate development config file to manage these values:
import devConfig from './devConfig';

const setupConfig: Config =
  VITE_PUBLIC_DEV === "true"
    ? {
        ...EternumGlobalConfig,
        ...devConfig,
      }
    : EternumGlobalConfig;

These changes would make the development configuration more maintainable and flexible.

client/src/ui/elements/StaminaResource.tsx (1)

31-31: Updated stamina cost retrieval method

The change from EternumGlobalConfig.stamina.travelCost to configManager.getTravelStaminaCost() is consistent with the new configuration management approach. This modification:

  1. Aligns with the centralized configuration management introduced earlier.
  2. Potentially allows for more dynamic or context-dependent stamina cost calculations.

Consider extracting the travel stamina cost into a variable for improved readability:

const travelStaminaCost = configManager.getTravelStaminaCost();
const staminaColor = staminaAmount < travelStaminaCost ? "bg-red" : "bg-yellow";

This change would make the code more self-documenting and easier to understand at a glance.

client/src/ui/components/hints/Realm.tsx (1)

Line range hint 1-33: Summary: Good refactoring, but verify precision handling.

The changes in this file are part of a larger refactoring effort to use configManager for realm upgrade costs, which improves flexibility and maintainability. However, the removal of precision handling (via multiplyByPrecision) needs careful consideration.

To ensure the refactoring is complete and consistent:

  1. Verify that configManager.realmUpgradeCosts provides correctly scaled values that don't require additional precision handling.
  2. Check if precision handling is needed in the ResourceCost component or anywhere else where these costs are displayed or used in calculations.
  3. Consider adding a comment explaining why precision handling is no longer needed at this level, if that's indeed the case.

These steps will help maintain accuracy in cost representations and calculations throughout the application.

client/src/ui/elements/ArmyCapacity.tsx (2)

22-22: Approved: Consistent use of configManager

The update to use configManager.getExploreReward() is consistent with the new import and represents an improvement in configuration management. This change maintains the existing logic while potentially allowing for more dynamic configuration of the explore reward.

For improved readability, consider extracting the explore reward into a constant at the beginning of the component:

const exploreReward = BigInt(configManager.getExploreReward());

Then use this constant in the comparison:

if (remainingCapacity < exploreReward) return CapacityColor.MEDIUM;

This would make the code more self-documenting and easier to maintain.


Incomplete Migration from EternumGlobalConfig to configManager Detected

The verification revealed that EternumGlobalConfig is still used extensively across multiple files in the codebase. This indicates that the refactoring to configManager is not yet fully implemented.

Actions Required:

  • Complete Refactoring: Ensure that all instances of EternumGlobalConfig are replaced with configManager to maintain consistency.
  • Automated Search and Replace: Utilize automated tools or scripts to identify and update remaining usages systematically.
  • Update Documentation: Reflect the changes in the project documentation to guide future development and onboarding.
  • Review Dependencies: Verify that replacing EternumGlobalConfig does not adversely affect other parts of the application.
🔗 Analysis chain

Line range hint 2-22: Overall: Positive change with potential for broader impact

The changes in this file represent a positive step towards more flexible and maintainable configuration management. The shift from EternumGlobalConfig to configManager is well-implemented and consistent within this component.

To ensure consistency across the entire application:

  1. Verify that similar changes have been made in other components that previously used EternumGlobalConfig.
  2. Consider updating the project documentation to reflect this new approach to configuration management.
  3. If not already done, consider adding unit tests to verify the correct usage of configManager throughout the application.

To help verify the consistent usage of configManager across the project, you can run the following script:

This will help identify any places where the old EternumGlobalConfig might still be in use, and confirm the adoption of configManager across the project.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for remaining usage of EternumGlobalConfig and new usage of configManager

echo "Checking for remaining usage of EternumGlobalConfig:"
rg --type typescript --type tsx "EternumGlobalConfig"

echo "\nChecking for new usage of configManager:"
rg --type typescript --type tsx "configManager"

Length of output: 381


Script:

#!/bin/bash
# Description: Check for remaining usage of EternumGlobalConfig and new usage of configManager in .ts and .tsx files

echo "Checking for remaining usage of EternumGlobalConfig in .ts and .tsx files:"
rg "EternumGlobalConfig" --glob "*.ts" --glob "*.tsx"

echo "\nChecking for new usage of configManager in .ts and .tsx files:"
rg "configManager" --glob "*.ts" --glob "*.tsx"

Length of output: 36272

client/src/ui/components/worldmap/structures/StructureLabel.tsx (2)

42-42: Approve calculation change and suggest documentation

The modification in the immunityEndTimestamp calculation is a good improvement. It uses the new tick management system, which appears to offer more flexibility and specificity in handling game timings.

Consider adding a brief comment explaining the calculation, especially the significance of getBattleGraceTickCount(). This would enhance code readability and maintainability. For example:

// Calculate immunity end timestamp based on battle grace period and army tick interval
const immunityEndTimestamp = (
  Number(structure?.created_at || 0) +
  configManager.getBattleGraceTickCount() * configManager.getTick(TickIds.Armies)
);

Line range hint 12-22: Consider safeguarding against negative timer values

While the current implementation aligns with the previous learning that negative timer values don't need special handling, it might be beneficial to add a small safeguard to ensure only non-negative values are displayed.

Consider modifying the formatTime call in the ImmunityTimer component:

- <div className="text-lg font-bold text-white animate-pulse">{formatTime(timer)}</div>
+ <div className="text-lg font-bold text-white animate-pulse">{formatTime(Math.max(0, timer))}</div>

This change ensures that even if a negative value somehow occurs, the displayed time will always be non-negative, improving robustness without significantly altering the existing behavior.

client/src/ui/components/hints/Transfers.tsx (2)

25-25: Improved donkey capacity retrieval

The use of configManager.getCapacityConfig(CapacityConfigCategory.Donkey) is a good improvement:

  1. It centralizes configuration management.
  2. It allows for easier updates to capacity values.
  3. The use of CapacityConfigCategory.Donkey enhances code readability and type safety.

Consider extracting the capacity calculation to a constant for improved readability:

const donkeyCapacityKg = configManager.getCapacityConfig(CapacityConfigCategory.Donkey) / GRAMS_PER_KG;

Then use it in the JSX:

<strong>{donkeyCapacityKg} kg</strong>

28-34: Improved resource weight retrieval and display

The use of configManager.getResourceWeight(ResourcesIds.<Resource>) is a good improvement:

  1. It centralizes configuration management for resource weights.
  2. It allows for easier updates to weight values.
  3. The use of ResourcesIds enum enhances code readability and type safety.

The layout changes with additional div wrappers improve the structure of the resource weight display.

For consistency, consider applying the same structure to all resource weight displays:

<div className="flex mt-4 justify-center w-full gap-8 font-bold border p-2">
  <div>Lords: {`${configManager.getResourceWeight(ResourcesIds.Lords) / GRAMS_PER_KG} kg/unit`}</div>
  <div>Food: {`${configManager.getResourceWeight(ResourcesIds.Wheat) / GRAMS_PER_KG} kg/unit`}</div>
  <div>Resource: {`${configManager.getResourceWeight(ResourcesIds.Wood) / GRAMS_PER_KG} kg/unit`}</div>
</div>

This removes the ml-2 classes and makes the structure more uniform.

client/src/ui/components/trading/RealmProduction.tsx (2)

Line range hint 44-48: LGTM with a minor suggestion: Improved resource consumption logic.

The updated logic for calculating consumed resources is more specific and potentially more efficient. It correctly uses the new resourcesInputs structure and explicitly filters out "Wheat" and "Fish".

Consider extracting the filter condition into a separate constant or function for improved readability:

const isConsumedResource = (input) => 
  input.resource !== ResourcesIds["Wheat"] && 
  input.resource !== ResourcesIds["Fish"];

return resourcesInputs[resourceId]
  .filter(isConsumedResource)
  .map((input) => input.resource);

This change would make the logic more self-documenting and easier to maintain.

🧰 Tools
🪛 Biome

[error] 32-69: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


Line range hint 1-48: Overall assessment: Improved configuration and resource management.

The changes in this file significantly enhance the RealmProduction component by:

  1. Introducing centralized configuration management through configManager.
  2. Improving resource input handling with a more flexible approach.
  3. Refining the logic for calculating consumed resources.

These modifications contribute to better maintainability, flexibility, and potentially improved performance. The component's core functionality remains intact while adopting a more robust approach to resource management.

To further improve the component:

  1. Consider extracting the resource filtering logic into a separate utility function for reusability.
  2. If the configManager is used extensively, consider creating a custom hook for accessing configuration, which could simplify testing and provide a consistent interface across components.
🧰 Tools
🪛 Biome

[error] 32-69: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

client/src/ui/components/trading/TradeHistoryEvent.tsx (2)

3-4: Approved: Import changes enhance modularity and flexibility.

The updated import statement now includes the divideByPrecision function alongside currencyIntlFormat. This change, combined with the removal of the EternumGlobalConfig import (not visible in the provided code), suggests an improvement in how resource amounts are processed. This approach enhances modularity and flexibility by moving the precision handling logic to a utility function.

Consider documenting the divideByPrecision function to ensure its purpose and usage are clear to other developers working on the project.


45-48: Approved: Improved resource amount formatting.

The changes in the TradeHistoryEvent component enhance the way resource amounts are formatted and displayed. Using the divideByPrecision function instead of directly accessing EternumGlobalConfig.resources.resourcePrecision improves modularity and maintainability.

To further improve readability, consider extracting the formatted amounts into variables before using them in the JSX. For example:

const formattedTakenAmount = currencyIntlFormat(divideByPrecision(trade.event.resourceTaken.amount), 2);
const formattedGivenAmount = currencyIntlFormat(divideByPrecision(trade.event.resourceGiven.amount), 2);

// Then in JSX
<div>{`${formattedTakenAmount} for ${formattedGivenAmount}`}</div>

This approach would make the JSX more concise and easier to read.

client/src/ui/components/hints/Buildings.tsx (2)

12-13: Improved building data retrieval logic

The changes enhance the robustness and maintainability of the building data retrieval logic. However, there are a couple of suggestions for further improvement:

  1. Replace isNaN with Number.isNaN for safer number checking:
if (Number.isNaN(Number(buildingId))) continue;
  1. Consider using a type guard instead of type assertion for better type safety:
if (typeof buildingId === 'number' && BuildingType[buildingId as keyof typeof BuildingType]) {
  // Rest of the logic
}

The use of configManager methods for retrieving building costs and configurations is a good practice for centralized management.

Also applies to: 15-20

🧰 Tools
🪛 Biome

[error] 13-13: 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)


Line range hint 27-32: Simplified building cost mapping

The updated cost mapping logic is more straightforward and aligns with the use of configManager for retrieving building costs. This change improves code readability and maintainability.

Consider a minor optimization:

building_resource_type: configManager.getResourceBuildingProduced(buildingId),
cost_of_building: buildingCosts.map(({ amount, ...rest }) => ({ ...rest, amount })),

This approach uses object destructuring and spread operators to create a new object for each cost item, potentially improving performance for larger datasets.

🧰 Tools
🪛 Biome

[error] 13-13: 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)

client/src/ui/components/worldmap/armies/ActionInfo.tsx (1)

100-100: Approve change with suggestions for optimization and error handling

The change from a static config value to configManager.getExploreReward() improves flexibility and centralization of configuration management. However, consider the following suggestions:

  1. Optimize performance by memoizing the result of getExploreReward() using useMemo to prevent unnecessary recalculations on each render.
  2. Add error handling in case configManager is undefined or getExploreReward() fails.

Here's an example of how you could implement these suggestions:

const exploreReward = useMemo(() => {
  try {
    return configManager.getExploreReward();
  } catch (error) {
    console.error('Failed to get explore reward:', error);
    return 0; // or some default value
  }
}, []);

// Then in your JSX:
<div>+{exploreReward} Random resource</div>

This approach ensures the reward is only calculated when necessary and provides a fallback in case of errors.

client/src/ui/components/worldmap/leaderboard/LeaderboardPanel.tsx (1)

35-35: Approved: Calculation updated to use dynamic configuration.

The change from a hardcoded constant to configManager.getHyperstructureConfig().pointsForWin improves flexibility and maintainability. This modification allows for easier updates to the points required for a win without changing this specific file.

Consider extracting the configuration value to a local constant for improved readability:

-    return Math.min((playerPoints / configManager.getHyperstructureConfig().pointsForWin) * 100, 100);
+    const pointsForWin = configManager.getHyperstructureConfig().pointsForWin;
+    return Math.min((playerPoints / pointsForWin) * 100, 100);

This change would make the calculation more readable and potentially more performant if the function is called multiple times.

client/src/ui/components/structures/construction/StructureConstructionMenu.tsx (2)

41-41: Improved precision handling in balance check

The use of multiplyByPrecision standardizes precision handling, aligning with the overall shift towards using configManager. This change improves consistency across the application.

Consider extracting the balance check logic into a separate utility function for better reusability and testability.


88-93: Improved configuration management in StructureInfo

The changes to cost retrieval and perTick calculation align with the centralized configuration management approach. The use of configManager.getHyperstructureConfig() provides a more flexible way to access hyperstructure-specific configurations.

Consider creating a custom hook for hyperstructure-related calculations to further improve code organization and reusability.

client/src/dojo/modelManager/__tests__/__BattleManagerMock__.ts (1)

153-170: Approve the addition of generateMockTroopConfig with suggestions for improvement.

The new generateMockTroopConfig function is a valuable addition for creating consistent mock troop configurations in tests. However, consider the following improvements:

  1. Use more realistic values for some parameters to better represent actual game scenarios.
  2. Add JSDoc comments to explain the purpose and usage of the function.
  3. Consider making some values configurable through function parameters for more flexible testing.

Here's an example of how you could implement these suggestions:

/**
 * Generates a mock troop configuration for testing purposes.
 * @param {Object} overrides - Optional. Override specific configuration values.
 * @returns {Object} A mock troop configuration object.
 */
export const generateMockTroopConfig = (overrides = {}) => {
  const defaultConfig = {
    health: 100,
    knightStrength: 10,
    paladinStrength: 15,
    crossbowmanStrength: 8,
    advantagePercent: 1200, // 20% advantage
    disadvantagePercent: 800, // 20% disadvantage
    maxTroopCount: 500000,
    pillageHealthDivisor: 8,
    baseArmyNumberForStructure: 3,
    armyExtraPerMilitaryBuilding: 1,
    maxArmiesPerStructure: 7,
    battleLeaveSlashNum: 25,
    battleLeaveSlashDenom: 100,
    battleTimeScale: 1000,
  };

  return { ...defaultConfig, ...overrides };
};

This implementation allows for more realistic default values and the flexibility to override specific values in tests when needed.

client/src/ui/components/worldmap/structures/StructureListItem.tsx (1)

64-65: Improved immunityEndTimestamp calculation.

The updated calculation of immunityEndTimestamp using configManager methods enhances flexibility and maintainability. It also introduces a more type-safe approach with TickIds.Armies.

Consider adding a brief comment explaining the calculation for improved readability:

// Calculate immunity end timestamp based on creation time, grace period, and army tick interval
const immunityEndTimestamp =
  Number(structure?.created_at) + configManager.getBattleGraceTickCount() * configManager.getTick(TickIds.Armies);
sdk/packages/eternum/src/types/common.ts (1)

369-373: New Player interface looks good, minor suggestion for consistency

The addition of the Player interface is a good improvement, providing a clear structure for player data. It includes essential properties like entity_id, address (using ContractAddress type, which is good for blockchain integration), and addressName for human-readable identification.

For consistency with other parts of the codebase, consider using the ID type alias for the entity_id property:

export interface Player {
  entity_id: ID;
  address: ContractAddress;
  addressName: string;
}

This change would align the Player interface with the usage of ID type throughout the rest of the file.

client/src/hooks/helpers/useRealm.tsx (2)

227-228: LGTM: Improved hasCapacity calculation

The use of configManager.getBasePopulationCapacity() instead of a hardcoded value improves the flexibility and maintainability of the code. This change allows for easier updates to the base population capacity without modifying the component logic.

Consider extracting the capacity calculation into a separate variable for improved readability:

const totalCapacity = population.capacity + configManager.getBasePopulationCapacity();
hasCapacity: !population || totalCapacity > population.population,

292-293: LGTM: Consistent hasCapacity calculation in getRealms

The modification to use configManager.getBasePopulationCapacity() in the getRealms function maintains consistency with the useGetRealm function. This change ensures that the base population capacity is sourced from a centralized configuration across the application.

For consistency and improved readability, consider applying the same extraction of the capacity calculation as suggested for the useGetRealm function:

const totalCapacity = population.capacity + configManager.getBasePopulationCapacity();
hasCapacity: !population || totalCapacity > population.population,
client/src/hooks/helpers/useStructures.tsx (1)

234-236: LGTM: Improved speed configuration retrieval

The modification to use configManager.getSpeedConfig(DONKEY_ENTITY_TYPE) instead of EternumGlobalConfig.speed.donkey is a good improvement. It centralizes configuration management and enhances maintainability.

Consider adding a comment explaining the calculation for better readability:

// Calculate travel time in hours, rounded down
const timeToTravel = Math.floor(
  ((distanceFromPosition / configManager.getSpeedConfig(DONKEY_ENTITY_TYPE)) * 3600) / 60 / 60
);
client/src/ui/components/trading/TransferBetweenEntities.tsx (3)

1-1: Improved configuration management and type safety.

The changes to the import statements are good improvements:

  1. Using configManager instead of a global config enhances modularity and flexibility.
  2. Importing DONKEY_ENTITY_TYPE increases type safety and code readability.

Consider grouping related imports together. For example, you could move the configManager import next to other project-specific imports for better organization.

Also applies to: 10-10


84-85: Enhanced flexibility in speed configuration.

The use of configManager.getSpeedConfig(DONKEY_ENTITY_TYPE) is a good improvement:

  1. It allows for dynamic configuration of speed values.
  2. The use of DONKEY_ENTITY_TYPE improves code clarity and type safety.

Consider adding error handling in case the speed configuration is not found for the given entity type. For example:

const speed = configManager.getSpeedConfig(DONKEY_ENTITY_TYPE) ?? defaultSpeed;

This ensures the component doesn't break if the configuration is missing.


Line range hint 1-285: Overall improvement in code quality and maintainability.

The changes in this file represent a positive step towards better code organization and flexibility:

  1. The shift to using configManager allows for more dynamic and centralized configuration management.
  2. The introduction of DONKEY_ENTITY_TYPE improves type safety and code readability.
  3. These changes enhance the maintainability of the code without altering the core functionality of the component.

As the project evolves, consider further modularizing the configuration management. You might want to create a dedicated configuration service that encapsulates all config-related logic, making it easier to manage and test configuration changes across the application.

client/src/ui/components/hyperstructures/StructureCard.tsx (1)

Line range hint 1-250: Overall: Good refactoring to use configurable maximum troop count.

The changes in this file consistently replace the hardcoded MAX_TROOPS_PER_ARMY constant with a dynamic maxTroopCountPerArmy value obtained from the configManager. This refactoring improves the flexibility and maintainability of the codebase by allowing for configuration changes without modifying the component code.

The modifications are well-implemented and don't introduce any apparent issues. They maintain consistency with the existing codebase while enhancing its adaptability.

Consider extracting the maxTroopCountPerArmy calculation to a higher-level component or a custom hook if it's used in multiple components. This could further reduce redundancy and improve maintainability. For example:

// In a new file, e.g., hooks/useTroopConfig.ts
import { configManager } from "@/dojo/setup";

export const useTroopConfig = () => {
  const maxTroopCountPerArmy = configManager.getTroopConfig().maxTroopCount;
  return { maxTroopCountPerArmy };
};

// In your component
import { useTroopConfig } from '@/hooks/useTroopConfig';

const { maxTroopCountPerArmy } = useTroopConfig();

This approach would centralize the configuration retrieval and make it easier to manage and update across multiple components if needed.

sdk/packages/eternum/src/config/index.ts (1)

482-489: Approve changes and suggest refactoring to reduce duplication

The changes to use lower and upper bounds for troop counts add more flexibility to the mercenary configuration, which is good. However, the code is still repetitive and could benefit from refactoring to improve maintainability.

Consider refactoring the code to reduce duplication, as suggested in the past review. Here's an example of how you could do this:

const troopTypes = ['knights', 'paladins', 'crossbowmen'];
const bounds = ['lower_bound', 'upper_bound'];

const troopBounds = Object.fromEntries(
  troopTypes.flatMap(troop => 
    bounds.map(bound => [
      `${troop}_${bound}`,
      config.config.mercenaries[`${troop}_${bound}`] * config.config.resources.resourcePrecision
    ])
  )
);

const tx = await config.provider.set_mercenaries_config({
  signer: config.account,
  ...troopBounds,
  rewards: config.config.mercenaries.rewards.map((reward) => ({
    resource: reward.resource,
    amount: reward.amount * config.config.resources.resourcePrecision * config.config.resources.resourceMultiplier,
  })),
});

This refactored version reduces duplication and makes it easier to add new troop types in the future if needed.

client/src/ui/components/trading/MarketOrderPanel.tsx (3)

263-263: Improved OrderRow component

The changes to the OrderRow component bring several improvements:

  1. Updated styling with rounded corners for better visual consistency.
  2. Improved travel time calculation using configManager, enhancing maintainability.
  3. Updated display logic for resource amounts, likely improving clarity.

These changes contribute to a more consistent and maintainable codebase.

However, consider extracting the complex ternary operations (e.g., lines 305-306, 312-313) into separate variables or functions for improved readability.

Consider refactoring complex ternary operations for better readability:

const getInputValue = () => {
  const baseAmount = isBuy ? offer.makerGets[0].amount : offer.takerGets[0].amount;
  const ratio = isBuy ? resourceBalanceRatio : lordsBalanceRatio;
  return divideByPrecision(baseAmount) * ratio;
};

const inputValue = getInputValue();

Also applies to: 305-306, 312-313, 318-318, 377-379, 382-384, 388-389


452-452: Enhanced OrderCreation component and improved donkey calculation

The changes to the OrderCreation component and the addition of the calculateDonkeysNeeded function bring several improvements:

  1. Updated styling with rounded corners for better visual consistency.
  2. Improved accuracy in calculating maximum values for NumberInput components using divideByPrecision.
  3. Introduction of calculateDonkeysNeeded function, which improves code organization and reusability.

These changes contribute to a more consistent, accurate, and maintainable codebase.

Consider adding a comment to explain the logic behind the calculateDonkeysNeeded function, especially the use of CapacityConfigCategory.Donkey.

Add a comment to explain the calculateDonkeysNeeded function:

// Calculate the number of donkeys needed based on the order weight
// and the capacity config for donkeys
const calculateDonkeysNeeded = (orderWeight: number): number => {
  return Math.ceil(divideByPrecision(orderWeight) / configManager.getCapacityConfig(CapacityConfigCategory.Donkey));
};

Also applies to: 457-457, 550-550, 594-594, 607-607, 639-639, 682-684


Line range hint 1-684: Overall improvements to MarketOrderPanel component

The changes made to the MarketOrderPanel component and its sub-components bring significant improvements:

  1. Enhanced configuration management with the introduction of configManager.
  2. Improved visual consistency across all components with the addition of rounded corners and better layout structures.
  3. More accurate calculations and display logic for resource amounts and prices.
  4. Better code organization with the introduction of the calculateDonkeysNeeded function.
  5. Updated styling for locked resources and market price displays, improving user experience.

These changes collectively contribute to a more maintainable, consistent, and user-friendly interface for market orders.

To further enhance the code:

  1. Consider adding more comments to explain complex logic, especially in areas dealing with resource calculations and conversions.
  2. Look for opportunities to extract repeated logic into reusable functions, particularly for price and resource amount calculations.
  3. Ensure that all error cases are properly handled, especially when dealing with user inputs and API calls.

To improve the overall architecture:

  1. Consider creating a separate utility file for common functions like calculateDonkeysNeeded and other resource-related calculations.
  2. Evaluate the possibility of using React Context or a state management library to handle shared state, which could simplify prop drilling in nested components.
  3. Implement proper error boundaries to gracefully handle and display any runtime errors that may occur during rendering or data fetching.
client/src/ui/components/resources/ResourceWeight.tsx (3)

Line range hint 14-25: Fix potential infinite loop due to useEffect dependencies

Including resourceWeight and donkeyBalance in the dependency array of the useEffect hook may cause an infinite loop. These state variables are updated within the useEffect, which triggers a re-render and re-runs the useEffect again. To prevent this, remove resourceWeight and donkeyBalance from the dependency array.

Apply this diff to fix the dependency array:

 useEffect(() => {
   // existing code
-}, [resources, entityId, resourceWeight, donkeyBalance, setCanCarry]);
+}, [resources, entityId, setCanCarry]);

87-87: Consistent labeling: Rename 'Food' to 'Wheat'

Since you're using ResourcesIds.Wheat to fetch the resource weight, consider renaming the label from 'Food' to 'Wheat' for consistency and clarity.

Apply this diff to update the label:

-<div>Food: {`${configManager.getResourceWeight(ResourcesIds.Wheat) / GRAMS_PER_KG} kg/unit`}</div>
+<div>Wheat: {`${configManager.getResourceWeight(ResourcesIds.Wheat) / GRAMS_PER_KG} kg/unit`}</div>

89-90: Clarify label from 'Resource' to 'Wood'

The label 'Resource' is generic and may cause confusion. Since the resource is specifically 'Wood', update the label to reflect this for better clarity.

Apply this diff to change the label:

-<div className="ml-2">
-  Resource: {`${configManager.getResourceWeight(ResourcesIds.Wood) / GRAMS_PER_KG} kg/unit`}
+</div>
+<div className="ml-2">
+  Wood: {`${configManager.getResourceWeight(ResourcesIds.Wood) / GRAMS_PER_KG} kg/unit`}
</div>
client/src/ui/components/hints/Resources.tsx (1)

73-75: Avoid using 'any'; specify a proper type for 'cost'.

Using (cost: any) reduces type safety. Defining a specific type for cost enhances code reliability and maintainability.

If there's an existing type for cost, apply it:

-        cost: configManager.resourceInputs[resourceId].map((cost: any) => ({
+        cost: configManager.resourceInputs[resourceId].map((cost: CostType) => ({

Alternatively, define an appropriate interface for CostType that matches the structure of the cost objects.

client/src/ui/components/hints/TheMap.tsx (1)

5-5: Remove unnecessary empty import statement

The import statement at line 5 is empty and doesn't import anything:

import {} from "@/ui/utils/utils";

This is unnecessary and can be safely removed to clean up the code.

Apply this diff to remove the unused import:

-import {} from "@/ui/utils/utils";
client/src/hooks/helpers/useQuests.tsx (1)

Line range hint 114-212: Incomplete Dependencies in useMemo Hook

In the useMemo starting at line 114, several variables used within the memoization function (buildingQuantities, hasAnyPausedBuilding, hasDefensiveArmy, hasAttackingArmy, hasTraveled, fragmentMines, hyperstructureContributions, hyperstructures, playerPillages) are not included in the dependencies array. This might lead to stale or incorrect quest statuses if any of these variables change.

Consider updating the dependencies array to include all relevant variables:

 return useMemo(
   () => ({
     // ... quest statuses
   }),
   [
     structureEntityId,
     questClaimStatus,
     unclaimedQuestsCount > 0 ? entityUpdate : null,
     unclaimedQuestsCount > 0 ? orders : null,
+    buildingQuantities,
+    hasAnyPausedBuilding,
+    hasDefensiveArmy,
+    hasAttackingArmy,
+    hasTraveled,
+    fragmentMines,
+    hyperstructureContributions,
+    hyperstructures,
+    playerPillages,
   ],
 );
client/src/ui/utils/utils.tsx (1)

292-293: Ensure tickIntervalInSeconds is valid to prevent division by zero

While the default value of tickIntervalInSeconds is set to 1 using the || 1 fallback, consider explicitly handling cases where configManager.getTick(TickIds.Armies) might return 0 to prevent potential division by zero errors.

You might want to ensure that tickIntervalInSeconds is always greater than zero before performing the division:

const tickIntervalInSeconds = configManager.getTick(TickIds.Armies);
const validTickInterval = tickIntervalInSeconds && tickIntervalInSeconds > 0 ? tickIntervalInSeconds : 1;
return Number(time / validTickInterval);
client/src/dojo/modelManager/BattleManager.ts (1)

61-61: Rephrase enum value for clarity

The message "An army's defending the structure" could be clearer. Consider rephrasing to "An army is defending the structure" for better readability and to avoid the contraction in a user-facing string.

Apply this diff to update the message:

-      DefenderPresent = "An army's defending the structure",
+      DefenderPresent = "An army is defending the structure",
client/src/ui/components/hints/WorldStructures.tsx (1)

98-98: Correct typo: 'shareholers' should be 'shareholders'

There's a typo in the text. 'shareholers' should be corrected to 'shareholders' to maintain professionalism and clarity.

Apply this diff to fix the typo:

-                  <br />A new set of shareholers can be set every{" "}
+                  <br />A new set of shareholders can be set every{" "}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 43456ea and 0e25f47.

📒 Files selected for processing (59)
  • client/src/dojo/contractComponents.ts (5 hunks)
  • client/src/dojo/modelManager/ArmyMovementManager.ts (6 hunks)
  • client/src/dojo/modelManager/BattleManager.ts (8 hunks)
  • client/src/dojo/modelManager/ConfigManager.ts (1 hunks)
  • client/src/dojo/modelManager/LeaderboardManager.ts (5 hunks)
  • client/src/dojo/modelManager/MarketManager.ts (5 hunks)
  • client/src/dojo/modelManager/ProductionManager.ts (4 hunks)
  • client/src/dojo/modelManager/tests/BattleManager.test.ts (4 hunks)
  • client/src/dojo/modelManager/tests/BattleManagerMock.ts (1 hunks)
  • client/src/dojo/modelManager/utils/LeaderboardUtils.test.ts (0 hunks)
  • client/src/dojo/modelManager/utils/LeaderboardUtils.ts (2 hunks)
  • client/src/hooks/helpers/useHyperstructures.tsx (2 hunks)
  • client/src/hooks/helpers/useQuests.tsx (3 hunks)
  • client/src/hooks/helpers/useRealm.tsx (3 hunks)
  • client/src/hooks/helpers/useStructures.tsx (2 hunks)
  • client/src/three/systems/SystemManager.ts (4 hunks)
  • client/src/ui/components/bank/LiquidityResourceRow.tsx (4 hunks)
  • client/src/ui/components/bank/Swap.tsx (9 hunks)
  • client/src/ui/components/construction/SelectPreviewBuilding.tsx (12 hunks)
  • client/src/ui/components/hints/Buildings.tsx (2 hunks)
  • client/src/ui/components/hints/Combat.tsx (6 hunks)
  • client/src/ui/components/hints/GettingStarted.tsx (1 hunks)
  • client/src/ui/components/hints/Realm.tsx (2 hunks)
  • client/src/ui/components/hints/Resources.tsx (3 hunks)
  • client/src/ui/components/hints/TheMap.tsx (6 hunks)
  • client/src/ui/components/hints/Transfers.tsx (2 hunks)
  • client/src/ui/components/hints/WorldStructures.tsx (4 hunks)
  • client/src/ui/components/hyperstructures/HyperstructurePanel.tsx (5 hunks)
  • client/src/ui/components/hyperstructures/StructureCard.tsx (4 hunks)
  • client/src/ui/components/military/ArmyList.tsx (4 hunks)
  • client/src/ui/components/military/ArmyManagementCard.tsx (6 hunks)
  • client/src/ui/components/quest/questDetails.tsx (7 hunks)
  • client/src/ui/components/resources/EntityResourceTable.tsx (2 hunks)
  • client/src/ui/components/resources/RealmResourcesIO.tsx (2 hunks)
  • client/src/ui/components/resources/ResourceChip.tsx (2 hunks)
  • client/src/ui/components/resources/ResourceWeight.tsx (3 hunks)
  • client/src/ui/components/structures/construction/StructureConstructionMenu.tsx (3 hunks)
  • client/src/ui/components/trading/MarketOrderPanel.tsx (15 hunks)
  • client/src/ui/components/trading/RealmProduction.tsx (2 hunks)
  • client/src/ui/components/trading/TradeHistoryEvent.tsx (2 hunks)
  • client/src/ui/components/trading/TransferBetweenEntities.tsx (3 hunks)
  • client/src/ui/components/worldmap/armies/ActionInfo.tsx (3 hunks)
  • client/src/ui/components/worldmap/armies/ArmyInfoLabel.tsx (3 hunks)
  • client/src/ui/components/worldmap/leaderboard/LeaderboardPanel.tsx (2 hunks)
  • client/src/ui/components/worldmap/structures/StructureLabel.tsx (2 hunks)
  • client/src/ui/components/worldmap/structures/StructureListItem.tsx (2 hunks)
  • client/src/ui/elements/ArmyCapacity.tsx (2 hunks)
  • client/src/ui/elements/StaminaResource.tsx (2 hunks)
  • client/src/ui/elements/StaminaResourceCost.tsx (2 hunks)
  • client/src/ui/modules/entity-details/BuildingEntityDetails.tsx (5 hunks)
  • client/src/ui/modules/navigation/TopMiddleNavigation.tsx (10 hunks)
  • client/src/ui/modules/onboarding/Steps.tsx (4 hunks)
  • client/src/ui/utils/realms.tsx (2 hunks)
  • client/src/ui/utils/utils.tsx (6 hunks)
  • config/index.ts (1 hunks)
  • sdk/packages/eternum/src/config/index.ts (2 hunks)
  • sdk/packages/eternum/src/constants/global.ts (5 hunks)
  • sdk/packages/eternum/src/constants/hyperstructure.ts (0 hunks)
  • sdk/packages/eternum/src/types/common.ts (3 hunks)
💤 Files with no reviewable changes (2)
  • client/src/dojo/modelManager/utils/LeaderboardUtils.test.ts
  • sdk/packages/eternum/src/constants/hyperstructure.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • client/src/dojo/modelManager/tests/BattleManager.test.ts
  • client/src/ui/components/bank/LiquidityResourceRow.tsx
  • client/src/ui/components/bank/Swap.tsx
  • client/src/ui/components/construction/SelectPreviewBuilding.tsx
  • client/src/ui/components/military/ArmyManagementCard.tsx
  • client/src/ui/modules/navigation/TopMiddleNavigation.tsx
🧰 Additional context used
📓 Learnings (1)
client/src/ui/components/worldmap/structures/StructureLabel.tsx (1)
Learnt from: aymericdelab
PR: BibliothecaDAO/eternum#1818
File: client/src/ui/components/worldmap/structures/StructureLabel.tsx:47-0
Timestamp: 2024-10-11T20:13:27.277Z
Learning: In `StructureLabel.tsx`, when `timer` is negative, the immunity message is not shown, so handling negative `timer` values isn't necessary.
🪛 Biome
client/src/ui/components/hints/Buildings.tsx

[error] 13-13: 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 (107)
client/src/ui/elements/StaminaResourceCost.tsx (2)

1-1: Approved: Import changes reflect shift in configuration management

The changes in the import statements, specifically the addition of configManager and the removal of EternumGlobalConfig, indicate a transition to a more centralized configuration management approach. This change aligns well with the modifications in the stamina cost calculation logic.

Also applies to: 4-4


26-26: Approved: Enhanced flexibility in stamina cost calculation

The modification in stamina cost calculation logic, utilizing configManager.getTravelStaminaCost() and configManager.getExploreStaminaCost(), introduces greater flexibility in configuration management. This approach allows for potential dynamic adjustments to costs while maintaining the existing logic for differentiating between travel and explore scenarios.

client/src/ui/components/resources/EntityResourceTable.tsx (4)

1-1: LGTM: Import changes enhance configuration management and precision.

The addition of configManager and multiplyByPrecision imports aligns with the goal of improving the calculation of maximum storehouse capacity. These changes suggest a move towards centralized configuration management and more precise calculations.

Also applies to: 3-3


19-20: LGTM: Improved calculation of maxStorehouseCapacityKg.

The refactored calculation of maxStorehouseCapacityKg offers several improvements:

  1. It uses configManager.getCapacityConfig, allowing for more flexible and centralized configuration management.
  2. The addition of multiplyByPrecision ensures accurate calculations, mitigating potential floating-point precision issues.
  3. The new implementation is more maintainable and aligns with best practices for configuration management.

These changes enhance the overall reliability and flexibility of the storehouse capacity calculation.


Line range hint 1-48: LGTM: Changes integrate well with existing component structure.

The modifications to the EntityResourceTable component have been seamlessly integrated:

  1. The overall structure and logic flow of the component remain intact.
  2. Performance optimizations using useMemo are preserved.
  3. The rendering logic for resource elements continues to work harmoniously with the updated calculations.

This integration demonstrates a good balance between introducing improvements and maintaining the existing, well-functioning parts of the component.


Line range hint 1-48: Summary: Enhancements to EntityResourceTable improve precision and maintainability.

The changes to EntityResourceTable.tsx successfully achieve the following:

  1. Introduce centralized configuration management through configManager.
  2. Enhance precision in storehouse capacity calculations using multiplyByPrecision.
  3. Improve code maintainability and flexibility.

These modifications align well with the PR objectives and the AI-generated summary. They enhance the component's functionality without introducing breaking changes or disrupting its overall structure. The continued use of performance optimizations like useMemo ensures that the component remains efficient.

Great job on these improvements!

client/src/ui/components/resources/RealmResourcesIO.tsx (2)

1-1: LGTM: Import changes improve modularity

The addition of configManager import and removal of RESOURCE_INPUTS_SCALED suggest a move towards centralized configuration management. This change enhances modularity and maintainability of the codebase.


Line range hint 1-53: Overall: Positive changes improving modularity and maintainability

The modifications to this component demonstrate a shift towards more centralized configuration management, which is a positive change for maintainability and flexibility. The core functionality of the component remains intact, with improvements in how resource data is accessed and processed.

The suggestions provided (destructuring syntax and memoization) are optional optimizations that could further enhance the code's readability and performance.

Great job on these improvements!

config/index.ts (1)

62-62: Approve the increased delay with a request for clarification.

The delay before setting up the bank has been increased from 15 to 20 seconds, which is reflected in both the console log message and the timeout duration.

Could you provide more context on why this delay is necessary and why it was increased? This information would be valuable as a comment in the code for future maintenance.

Consider adding a comment explaining the reason for the delay:

// Add a 20-second delay before setting up the bank
// This delay is necessary because [reason for the delay]
console.log("Waiting for 20 seconds before setting up the bank...");
await new Promise((resolve) => setTimeout(resolve, 20000));
client/src/ui/utils/realms.tsx (1)

1-1: Approve import changes: Improved modularity with centralized configuration

The introduction of configManager import and removal of constant imports (BASE_POPULATION_CAPACITY and BUILDING_POPULATION) indicate a positive shift towards centralized configuration management. This change enhances modularity and maintainability by allowing easier updates to configuration values without modifying multiple files.

client/src/ui/elements/StaminaResource.tsx (2)

2-2: Improved configuration management

The addition of configManager import is a positive change. It replaces the use of a global configuration object with a centralized configuration manager, which is a better practice in software development.

This change:

  1. Enhances modularity and flexibility in managing configurations.
  2. Makes the code more testable by allowing easier mocking of configuration values.
  3. Centralizes configuration management, reducing the risk of inconsistencies across the application.

Line range hint 1-62: Overall impact: Improved configuration management without functional changes

The changes in this file represent a positive step towards better configuration management:

  1. The core functionality of the StaminaResource component remains intact.
  2. The transition from a global config object to a centralized config manager improves modularity and maintainability.
  3. The changes are consistent throughout the file.

These modifications enhance the code quality without altering the component's behavior.

To ensure that these changes haven't inadvertently affected other parts of the codebase, please run the following verification script:

This script will help ensure that the migration to configManager.getTravelStaminaCost() is complete and consistent across the entire codebase.

✅ Verification successful

Verification Successful: Configuration Migration Complete

All references to EternumGlobalConfig.stamina.travelCost have been successfully migrated to configManager.getTravelStaminaCost(). The usage of configManager.getTravelStaminaCost() is consistent across the codebase, ensuring improved maintainability and configuration management without affecting the component's functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to EternumGlobalConfig.stamina.travelCost

# Test: Search for any remaining references to EternumGlobalConfig.stamina.travelCost
# Expect: No results, indicating complete migration to configManager.getTravelStaminaCost()
rg --type typescript "EternumGlobalConfig\.stamina\.travelCost"

# Test: Verify consistent usage of configManager.getTravelStaminaCost()
# Expect: Results showing consistent usage across the codebase
rg --type typescript "configManager\.getTravelStaminaCost\(\)"

Length of output: 200


Script:

#!/bin/bash
# Description: Check for any remaining references to EternumGlobalConfig.stamina.travelCost and verify consistent usage of configManager.getTravelStaminaCost()

# Test: Search for any remaining references to EternumGlobalConfig.stamina.travelCost
# Expect: No results, indicating complete migration to configManager.getTravelStaminaCost()
rg --type ts --type tsx "EternumGlobalConfig\.stamina\.travelCost"

# Test: Verify consistent usage of configManager.getTravelStaminaCost()
# Expect: Results showing consistent usage across the codebase
rg --type ts --type tsx "configManager\.getTravelStaminaCost\(\)"

Length of output: 192


Script:

#!/bin/bash
# Description: Check for any remaining references to EternumGlobalConfig.stamina.travelCost 
# and verify consistent usage of configManager.getTravelStaminaCost()

# Test: Search for any remaining references to EternumGlobalConfig.stamina.travelCost
# Expect: No results, indicating complete migration to configManager.getTravelStaminaCost()
rg -g "*.ts" -g "*.tsx" "EternumGlobalConfig\.stamina\.travelCost"

# Test: Verify consistent usage of configManager.getTravelStaminaCost()
# Expect: Results showing consistent usage across the codebase
rg -g "*.ts" -g "*.tsx" "configManager\.getTravelStaminaCost\(\)"

Length of output: 1099

client/src/ui/components/hints/Realm.tsx (2)

29-33: Approved, but consider precision handling.

The changes align well with the new import structure, using configManager.realmUpgradeCosts instead of the hardcoded REALM_UPGRADE_COSTS. This approach is more flexible and maintainable.

However, the removal of multiplyByPrecision raises a concern about precision handling. Let's verify if precision is handled elsewhere:

#!/bin/bash
# Description: Check for precision handling in related files.

# Test 1: Search for precision-related functions in utility files
rg --type typescript '(multiplyByPrecision|divideByPrecision|formatPrecision)' client/src/ui/utils/

# Test 2: Check if ResourceCost component handles precision
ast-grep --lang typescript --pattern 'const ResourceCost = ({ resourceId, amount, size }: ResourceCostProps) => {
  $$$
}'

If precision is not handled elsewhere, consider adding a comment or TODO to address this in the future to ensure accurate cost representation.


1-4: LGTM! Verify usage of new import.

The changes to the imports look good. The shift from hardcoded REALM_UPGRADE_COSTS to configManager suggests a more flexible approach to managing realm upgrade costs.

Let's verify the usage of configManager in the file:

✅ Verification successful

Verified usage of configManager.

The configManager.realmUpgradeCosts is properly utilized within the Realm.tsx component.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of configManager in the file.

# Test: Search for configManager usage
rg --type typescript 'configManager\.realmUpgradeCosts' client/src/ui/components/hints/Realm.tsx

Length of output: 261


Script:

#!/bin/bash
# Description: Search for all usages of configManager in Realm.tsx using ripgrep and ast-grep.

# Using ripgrep to find any occurrence of configManager in Realm.tsx
rg 'configManager' client/src/ui/components/hints/Realm.tsx

# Using ast-grep to find import statements and usages of configManager
ast-grep --lang typescript --pattern 'import { configManager } from $_;' client/src/ui/components/hints/Realm.tsx

ast-grep --lang typescript --pattern '$_configManager$_' client/src/ui/components/hints/Realm.tsx

Length of output: 863

client/src/ui/elements/ArmyCapacity.tsx (1)

2-2: Approved: Improved configuration management

The introduction of configManager from "@/dojo/setup" is a positive change. This shift from a static configuration (previously EternumGlobalConfig) to a dynamic configuration manager can provide more flexibility in managing application settings. It potentially allows for runtime configuration changes or environment-specific configurations, which can be beneficial for maintainability and adaptability of the application.

client/src/ui/components/worldmap/structures/StructureLabel.tsx (1)

Line range hint 1-70: Summary of changes and overall assessment

The modifications to StructureLabel.tsx represent a positive step towards improved modularity and configuration management. The shift from EternumGlobalConfig to a more specific tick management system using TickIds and configManager methods suggests a more flexible approach to handling game timings.

Key points:

  1. The import changes and calculation modifications are consistent and well-implemented.
  2. The core functionality of the component remains intact.
  3. The new approach potentially allows for more granular control over different aspects of the game timing.

These changes should enhance the maintainability and flexibility of the code. Good job on the refactoring effort!

client/src/ui/components/hints/Transfers.tsx (2)

1-1: Improved import management and configuration centralization

The changes to the import statements are well-considered:

  1. Adding configManager import centralizes configuration management.
  2. Including CapacityConfigCategory and ResourcesIds in the existing import improves type safety.
  3. Removing direct imports from global config enhances maintainability.

These modifications align with best practices for React component development.

Also applies to: 5-5


Line range hint 1-34: Consistent and improved Transfers component

The changes to the Transfers component are well-implemented:

  1. The overall structure and functionality of the component remain intact.
  2. Configuration retrieval is improved without affecting the component's core logic.
  3. The modifications enhance maintainability and align with best practices.

These changes are consistent with the component's purpose and the AI-generated summary.

To ensure no unintended changes were introduced, run the following verification:

These checks will help confirm that all intended changes have been properly implemented and no unintended references or hardcoded values remain.

✅ Verification successful

To address the issues with the previous verification scripts, please run the following updated shell scripts:

These updated commands omit the --type flag and directly search within the specified file using its path and standard TypeScript file extensions. This should provide the necessary verification without encountering the previous file type recognition issues.


Transfers Component Verified Successfully

The verification confirms that:

  1. No references to EternumGlobalConfig or WEIGHTS_GRAM remain.
  2. All resource weight retrievals utilize configManager.
  3. No hardcoded weight or capacity values are present.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify that no unexpected changes were made to the Transfers component

# Check for any remaining references to EternumGlobalConfig or WEIGHTS_GRAM
rg --type typescript 'EternumGlobalConfig|WEIGHTS_GRAM' client/src/ui/components/hints/Transfers.tsx

# Verify that all resource weight retrievals use configManager
rg --type typescript 'configManager\.getResourceWeight\(ResourcesIds\.' client/src/ui/components/hints/Transfers.tsx

# Check for any remaining hardcoded weight or capacity values
rg --type typescript '\d+(\.\d+)?\s*(kg|g)' client/src/ui/components/hints/Transfers.tsx

Length of output: 417


Script:

#!/bin/bash
# Verify that no unexpected changes were made to the Transfers component

# Check for any remaining references to EternumGlobalConfig or WEIGHTS_GRAM
rg 'EternumGlobalConfig|WEIGHTS_GRAM' client/src/ui/components/hints/Transfers.tsx

# Verify that all resource weight retrievals use configManager
rg 'configManager\.getResourceWeight\(ResourcesIds\.' client/src/ui/components/hints/Transfers.tsx

# Check for any remaining hardcoded weight or capacity values
rg '\d+(\.\d+)?\s*(kg|g)' client/src/ui/components/hints/Transfers.tsx

Length of output: 577

client/src/ui/components/trading/RealmProduction.tsx (2)

1-1: LGTM: Import changes enhance configuration management.

The addition of configManager import and removal of RESOURCE_INPUTS_SCALED suggest a move towards more centralized and flexible configuration management. This change is likely to improve maintainability and consistency across the application.


39-40: LGTM: Improved resource input management.

The use of configManager.resourceInputs for declaring resourcesInputs aligns well with the centralized configuration approach. This change enhances flexibility in managing resource inputs and promotes consistency across the application.

client/src/ui/components/hints/Buildings.tsx (3)

1-1: Improved configuration management

The changes to the import statements reflect a shift towards centralized configuration management using configManager. This approach enhances maintainability and flexibility by centralizing building-related configurations.

Also applies to: 5-5


26-26: Consistent use of configManager for resource type retrieval

The change to use configManager.getResourceBuildingProduced(buildingId) for retrieving the building resource type is consistent with the overall approach of centralized configuration management. This enhances maintainability and flexibility in managing building-related data.


62-62: Updated image background color

The CSS class change from "bg-black/40" to "bg-brown/40" for the building image is a minor visual update. This change likely improves the aesthetic appeal of the component without affecting its functionality.

client/src/ui/components/worldmap/leaderboard/LeaderboardPanel.tsx (2)

2-2: LGTM: Import statement added correctly.

The import of configManager from "@/dojo/setup" is properly formatted and consistent with the project structure. This import is necessary for the subsequent changes in the file.


Line range hint 16-121: Consider performance optimization and test updates.

While the changes improve flexibility, consider the following suggestions:

  1. Performance Optimization: Memoize the pointsForWin value to prevent unnecessary recalculations.
const pointsForWin = useMemo(() => configManager.getHyperstructureConfig().pointsForWin, []);
  1. Test Updates: Ensure that unit tests for this component are updated to mock the configManager and verify the calculation with different configuration values.

To verify the impact of these changes, please run the following script:

This script will help identify if there are existing tests for the LeaderboardPanel and if they include mocks for the configManager. The results will guide further testing efforts.

client/src/ui/components/structures/construction/StructureConstructionMenu.tsx (3)

1-9: Improved modularity with configManager

The changes to the import statements reflect a shift towards using configManager for accessing configuration values, which improves modularity and maintainability. The addition of multiplyByPrecision suggests an enhancement in precision handling for calculations.


48-48: Centralized structure cost management

The use of configManager.structureCosts[building] for cost retrieval centralizes the management of structure costs. This change improves maintainability and consistency across the application.


Line range hint 1-126: Overall improvement in configuration management and code consistency

The changes in this file demonstrate a significant shift towards centralized configuration management using configManager. This approach enhances modularity, maintainability, and consistency across the application. Key improvements include:

  1. Standardized precision handling with multiplyByPrecision.
  2. Centralized structure cost management.
  3. Flexible access to hyperstructure-specific configurations.

These changes contribute to a more robust and maintainable codebase. Consider implementing the suggested refactoring to further improve code organization and reusability.

client/src/ui/components/military/ArmyList.tsx (6)

2-2: LGTM: Centralized configuration management

The addition of configManager import is a good practice. It centralizes configuration management, which can improve maintainability and consistency across the application.


12-12: LGTM: Updated imports

The removal of EternumGlobalConfig import and addition of BuildingType to the existing import statement from "@bibliothecadao/eternum" align well with the changes in the component's logic. This update maintains clean and relevant imports.


46-47: LGTM: Centralized troop configuration

The introduction of troopConfig using configManager.getTroopConfig() is a good approach. It centralizes troop-related configurations, which can make the code more maintainable and easier to update in the future.


52-61: LGTM: Updated maxAmountOfAttackingArmies calculation

The calculation of maxAmountOfAttackingArmies has been successfully updated to use troopConfig properties. This change maintains the original logic while utilizing the new centralized configuration approach. The code remains clear and consistent with the rest of the changes.


101-101: LGTM: Dynamic max armies display

The update to use troopConfig.maxArmiesPerStructure in the display message is a good improvement. It ensures that the UI always reflects the current configuration, making the component more maintainable and less prone to inconsistencies if the max armies value changes in the future.


Line range hint 1-155: Overall assessment: Excellent refactoring

The changes in this file demonstrate a well-executed refactoring to use centralized configuration management. The consistent use of configManager and troopConfig throughout the component improves maintainability and makes the code more robust to future configuration changes. The logic of the component remains intact while benefiting from these improvements. Great job on this refactoring!

client/src/ui/components/resources/ResourceChip.tsx (2)

1-1: LGTM: Improved import statements for better configurability.

The changes in the import statements reflect a shift from using static data (WEIGHTS_GRAM) to a more dynamic configuration approach using configManager. This change enhances the flexibility and maintainability of the resource weight management system.

Also applies to: 3-3


41-41: LGTM: Enhanced flexibility in resource weight calculation.

The updated maxAmountStorable calculation now uses configManager.getResourceWeight(resourceId) instead of a static WEIGHTS_GRAM object. This change:

  1. Aligns with the new import statements.
  2. Allows for more dynamic resource weight management.
  3. Maintains backwards compatibility with the fallback value of 1000.
  4. Improves system flexibility, enabling easier updates to resource weights without modifying the component.

This approach enhances the maintainability and scalability of the resource management system.

client/src/dojo/modelManager/ProductionManager.ts (5)

1-1: LGTM: Import of multiplyByPrecision utility function.

The addition of the multiplyByPrecision utility function to the imports is a good practice. It centralizes precision calculations, which can help maintain consistency and reduce errors throughout the codebase.


77-83: LGTM: Improved getStoreCapacity method implementation.

The changes to the getStoreCapacity method are well-implemented:

  1. Using multiplyByPrecision centralizes precision handling.
  2. configManager.getCapacityConfig improves maintainability by removing hard-coded values.
  3. The use of gramToKg function makes the capacity calculations more intuitive.

These modifications enhance the clarity and maintainability of the code while preserving the original logic.


103-105: LGTM: Improved balance calculation in _balance method.

The modifications to the balance calculation are well-implemented:

  1. Consistent use of multiplyByPrecision for precision handling.
  2. Utilization of configManager.getResourceWeight improves configurability and removes hard-coded values.

These changes enhance the maintainability and flexibility of the code while preserving the original calculation logic.


192-192: LGTM: Updated resource inputs source in _inputs_available method.

The change to use configManager.resourceInputs instead of RESOURCE_INPUTS_SCALED is a good improvement:

  1. It aligns with the overall strategy of using configManager for resource-related configurations.
  2. This modification enhances maintainability by centralizing resource input configurations.
  3. The core logic of the method remains intact, ensuring that functionality is preserved.

This update contributes to a more consistent and maintainable codebase.


Line range hint 1-238: Overall assessment: Excellent improvements to maintainability and configurability.

The changes made to the ProductionManager class are well-implemented and consistent throughout the file. Key improvements include:

  1. Centralized precision handling using the multiplyByPrecision utility function.
  2. Increased use of configManager for resource-related configurations, removing hard-coded values.
  3. Improved clarity in capacity and weight calculations.

These modifications enhance the overall maintainability, flexibility, and readability of the code while preserving the core functionality. Great job on these updates!

client/src/ui/components/worldmap/structures/StructureListItem.tsx (1)

12-12: Improved import structure and configuration management.

The addition of ResourcesIds, StructureType, and TickIds imports from "@bibliothecadao/eternum" and the removal of EternumGlobalConfig suggest a move towards more modular and centralized configuration management. This change enhances maintainability and reduces direct dependencies on global configurations.

sdk/packages/eternum/src/types/common.ts (2)

328-333: Improved mercenary configuration structure

The new structure for the mercenaries property in the Config interface provides more granular control over troop counts. By introducing upper and lower bounds for each troop type (knights, paladins, and crossbowmen), this change allows for:

  1. Greater flexibility in mercenary recruitment.
  2. The ability to introduce variability in mercenary composition.
  3. Fine-tuning of mercenary strength based on game balance requirements.

This is a positive change that enhances the configurability of the mercenary system.


Line range hint 1-373: Overall, good improvements to types and interfaces

The changes in this file enhance the game's type system by:

  1. Improving the configurability of the mercenary system with more granular control over troop counts.
  2. Adding a clear Player interface for managing player data.

These modifications contribute to better type safety and more flexible game mechanics. The code maintains good overall structure and consistency with the existing codebase.

client/src/dojo/modelManager/MarketManager.ts (6)

2-2: LGTM: Import statements updated correctly.

The changes in the import statements are consistent with the shift from using EternumGlobalConfig to configManager. This update suggests a move towards a more centralized configuration management approach, which can improve maintainability and flexibility.

Also applies to: 4-4


92-92: LGTM: Fee rate denominator source updated.

The change to obtain feeRateDenom from configManager.getBankConfig().lpFeesDenominator is consistent with the overall shift towards using configManager. The core logic of the method remains intact, ensuring that the functionality is preserved while improving configuration management.


117-117: LGTM: Fee rate denominator source updated.

The update to retrieve feeRateDenom from configManager.getBankConfig().lpFeesDenominator aligns with the overall transition to using configManager. The core functionality of the method is preserved, maintaining the integrity of the input price calculation while improving configuration management.


143-143: LGTM: Fee rate denominator source updated.

The modification to fetch feeRateDenom from configManager.getBankConfig().lpFeesDenominator is in line with the overall transition to configManager. The core logic for calculating Lords input for resource output remains intact, ensuring that the functionality is preserved while improving configuration management.


175-175: LGTM: Fee rate denominator source updated.

The update to retrieve feeRateDenom from configManager.getBankConfig().lpFeesDenominator aligns with the overall transition to using configManager. The core functionality for calculating resource input for Lords output is maintained, preserving the method's integrity while improving configuration management.


Line range hint 1-265: Summary: Improved configuration management in MarketManager

The changes in this file consistently replace EternumGlobalConfig with configManager for obtaining the fee rate denominator. This shift towards a more centralized configuration management approach through configManager can lead to improved maintainability and flexibility in the codebase.

Key points:

  1. Import statements have been updated to reflect the change.
  2. All methods using feeRateDenom now obtain it from configManager.getBankConfig().lpFeesDenominator.
  3. The core functionality of the MarketManager class and its methods remains intact.

These changes are well-implemented and should make future updates to configuration values easier to manage.

client/src/hooks/helpers/useRealm.tsx (1)

2-2: LGTM: Import of configManager

The addition of configManager import from @/dojo/setup is a good practice. It centralizes configuration management and allows for more flexible and maintainable code.

client/src/hooks/helpers/useStructures.tsx (1)

7-7: LGTM: Import addition for DONKEY_ENTITY_TYPE

The addition of DONKEY_ENTITY_TYPE to the import statement is appropriate, as it's now being used in the useStructuresFromPosition function. This change aligns with the shift in how speed configuration is retrieved for the donkey entity type.

client/src/ui/modules/onboarding/Steps.tsx (3)

5-5: LGTM: New import added correctly

The new import for configManager is correctly placed and necessary for the changes in the StepFive component.


36-36: Background color change: Verify visual consistency

The background color has been changed from bg-black/90 to bg-brown. This change looks good and might improve the overall visual theme.

Please verify that this color change is consistent with the design system and doesn't negatively impact the readability or contrast of the content within the container.


355-358: Configuration management update: Verify configManager functionality

The changes from EternumGlobalConfig.tick.armiesTickIntervalInSeconds to configManager.getTick(TickIds.Armies) look good. This update likely improves the flexibility of configuration management in the game.

Please ensure that:

  1. The configManager.getTick(TickIds.Armies) method is correctly implemented and returns the expected value.
  2. The TickIds.Armies constant is properly defined and imported if necessary.
  3. This change is consistent across all components that previously used EternumGlobalConfig.tick.armiesTickIntervalInSeconds.

You can verify this by running the following script:

✅ Verification successful

Configuration management update: Verified configManager functionality

All changes have been successfully implemented:

  • EternumGlobalConfig.tick.armiesTickIntervalInSeconds is no longer used.
  • configManager.getTick(TickIds.Armies) is consistently implemented across the codebase.
  • TickIds.Armies is properly defined and imported where necessary.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of EternumGlobalConfig.tick.armiesTickIntervalInSeconds
rg "EternumGlobalConfig\.tick\.armiesTickIntervalInSeconds" --type typescript

# Check for the correct usage of configManager.getTick
rg "configManager\.getTick\(TickIds\.Armies\)" --type typescript

# Verify the import and usage of TickIds
rg "import.*TickIds" --type typescript
rg "TickIds\.Armies" --type typescript

Length of output: 368


Script:

#!/bin/bash
# Search for any remaining usage of EternumGlobalConfig.tick.armiesTickIntervalInSeconds in .ts and .tsx files
fd -e ts -e tsx --exec rg "EternumGlobalConfig\.tick\.armiesTickIntervalInSeconds"

# Check for the correct usage of configManager.getTick in .ts and .tsx files
fd -e ts -e tsx --exec rg "configManager\.getTick\(TickIds\.Armies\)"

# Verify the import and usage of TickIds in .ts and .tsx files
fd -e ts -e tsx --exec rg "import.*TickIds"
fd -e ts -e tsx --exec rg "TickIds\.Armies"

Length of output: 2973

client/src/ui/components/hyperstructures/StructureCard.tsx (4)

1-1: LGTM: Import statement for configManager added.

The import of configManager from "@/dojo/setup" has been correctly added. This is likely used to replace the hardcoded MAX_TROOPS_PER_ARMY constant with a configurable value, which improves the flexibility of the codebase.


159-160: LGTM: Dynamic maxTroopCountPerArmy constant added.

The addition of maxTroopCountPerArmy using configManager.getTroopConfig().maxTroopCount is a good improvement. It replaces the hardcoded MAX_TROOPS_PER_ARMY constant with a configurable value, enhancing the flexibility of the codebase. This change allows for easier adjustments to the maximum troop count without modifying the component code.


189-189: LGTM: Remaining troops calculation updated with dynamic maxTroopCountPerArmy.

The calculation for remaining troops has been correctly updated to use the dynamic maxTroopCountPerArmy instead of the hardcoded constant. This change maintains the existing logic while improving flexibility. The consistent use of BigInt ensures compatibility with the rest of the codebase.


250-250: LGTM: Warning message updated with dynamic maxTroopCountPerArmy.

The warning message for maximum troops per attacking army has been correctly updated to use the dynamic maxTroopCountPerArmy. The use of formatNumber function ensures that the displayed value is properly formatted for readability. This change maintains consistency with the new configurable maximum troop count.

client/src/ui/components/trading/MarketOrderPanel.tsx (3)

2-2: Improved configuration management

The addition of configManager and the use of DONKEY_ENTITY_TYPE instead of EternumGlobalConfig suggests a move towards more centralized and maintainable configuration management. This change is likely to improve the overall structure and flexibility of the application.

Also applies to: 15-15


60-62: Enhanced UI consistency

The addition of rounded-xl to the className improves the visual consistency of the MarketResource component, aligning it with the overall design aesthetic of the application.


164-165: Improved UI and user experience

The updates to the MarketOrders component enhance the visual appeal and improve the user experience:

  1. The market price display now has a more flexible layout with improved padding and rounded corners.
  2. The background color for the locked resources message has been changed to brown, which likely aligns better with the overall theme.
  3. The layout for displaying resource information has been restructured for better clarity.

These changes contribute to a more intuitive and visually consistent interface.

Also applies to: 169-175, 177-177, 182-182, 201-203

client/src/dojo/modelManager/utils/LeaderboardUtils.ts (3)

15-16: Approved: Use of ClientConfigManager instance

Initializing configManager using the singleton instance enhances consistency by ensuring that the configuration is managed centrally.


28-30: Approved: Retrieving pointsOnCompletion from configuration

Fetching pointsOnCompletion via configManager ensures that the point values are centralized and configurable, enhancing maintainability.


32-32: Consider verifying the accumulation of points for large contributions

When calculating total completion points, if contribution.amount can be a large bigint, ensure that summing these values does not introduce precision errors when converted to number.

To verify if there are any potential issues with large values, you can search for usages of contribution.amount and check how they are handled elsewhere in the codebase:

This script searches for all instances of contribution.amount to help you review its handling and ensure consistency.

client/src/ui/components/hints/Resources.tsx (4)

1-1: LGTM!

The import of configManager is correctly added and used appropriately in the code.


6-6: LGTM!

The imports from @bibliothecadao/eternum are appropriate and necessary for the functionality.


37-38: LGTM!

The calculation for storage capacity using configManager.getCapacityConfig and EternumGlobalConfig.resources.resourceMultiplier is accurate and correctly implemented.


71-71: LGTM!

The usage of configManager.getResourceOutputs(resourceId) appropriately retrieves the resource output amounts.

client/src/hooks/helpers/useHyperstructures.tsx (1)

2-3: Imports added are appropriate for the updated functionality

The addition of configManager, divideByPrecision, and toHexString imports is necessary for the new logic implementation and seems correct.

client/src/ui/components/worldmap/armies/ArmyInfoLabel.tsx (2)

16-16: Updated import statement to use TickIds

The import of TickIds from @bibliothecadao/eternum aligns with the updated configuration management approach, enhancing modularity and maintainability.


113-113: Verify the correctness of the remainingCapacity check

Ensure that configManager.getExploreReward() returns the expected value for this comparison. If remainingCapacity is miscalculated or the reward value is incorrect, it may prevent users from exploring when they should be able to.

Consider checking the values returned by configManager.getExploreReward() and confirm that remainingCapacity is accurately computed. If necessary, adjust the logic to align with the intended functionality.

client/src/ui/components/hints/TheMap.tsx (2)

2-2: Good practice: Centralizing configuration with configManager

Importing configManager and using it to retrieve configuration values enhances maintainability by centralizing the configuration logic.


47-48: Efficient retrieval of stamina costs

Using configManager.getTravelStaminaCost() and configManager.getExploreStaminaCost() improves code clarity and ensures stamina costs are sourced from a single point of truth.

client/src/ui/components/hyperstructures/HyperstructurePanel.tsx (5)

3-3: Correctly imported configManager for dynamic configurations

The addition of configManager improves the component's flexibility by accessing dynamic configuration values.


15-16: Utility functions imported appropriately

The import of multiplyByPrecision and other utility functions ensures accurate computations and enhances code reuse.


65-65: Enhanced precision in amount calculation using multiplyByPrecision

Applying multiplyByPrecision(amount) ensures that contribution amounts are correctly scaled according to the system's precision requirements.


86-86: Replaced static costs with dynamic configuration

Utilizing configManager.hyperstructureTotalCosts instead of hardcoded values increases maintainability and allows for dynamic updates to hyperstructure costs.


204-204: Utilized dynamic pointsPerCycle from configManager

Switching to configManager.getHyperstructureConfig().pointsPerCycle ensures consistency with the global configuration and enhances flexibility.

sdk/packages/eternum/src/constants/global.ts (4)

11-11: Added RESOURCE_RARITY to imports

The constant RESOURCE_RARITY is now imported, making it available for use in this file.


20-21: New constants for population configuration IDs

The constants BUILDING_CATEGORY_POPULATION_CONFIG_ID and POPULATION_CONFIG_ID have been added, which will be useful for identifying population-related configurations.


99-104: Defined mercenary troop count bounds

The lower and upper bounds for mercenary troops (KNIGHTS, PALADINS, CROSSBOWMEN) have been set appropriately.


133-133: Included resourceRarity in resources configuration

resourceRarity has been added to the resources configuration, enhancing resource management capabilities.

client/src/ui/modules/entity-details/BuildingEntityDetails.tsx (4)

22-22: Import Addition Approved

The addition of divideByPrecision to the imports is appropriate and correctly supports precision handling in balance checks.


201-201: Proper Calculation of Immunity End Timestamp

The calculation of immunityEndTimestamp accurately utilizes configManager.getBattleGraceTickCount() and configManager.getTick(TickIds.Armies) to determine the immunity period.


221-228: Resource Balance Comparison Updated Correctly

The checkBalance function now properly uses divideByPrecision to ensure that the resource balance comparison accounts for the correct precision. This enhances the accuracy of resource checks before upgrading the realm level.


308-308: Dynamic Retrieval of Upgrade Costs

Replacing REALM_UPGRADE_COSTS with configManager.realmUpgradeCosts improves flexibility by retrieving the realm upgrade costs dynamically from the configuration manager. This change enhances maintainability and ensures the costs are always up-to-date.

client/src/hooks/helpers/useQuests.tsx (6)

2-2: Approved: Added Import for SetupResult

The import of SetupResult from @/dojo/setup is appropriate and necessary for the updated function signatures.


9-9: Approved: Added Import for Account and AccountInterface

The import of Account and AccountInterface from "starknet" is correct and required for handling account-related functionalities.


74-74: Approved: Updated Function Signature for useQuestDependencies

The function useQuestDependencies now accepts setup and account as parameters, improving modularity and making dependencies explicit.


77-79: Approved: Entity Query for EntityOwner

The use of useEntityQuery with HasValue(setup.components.EntityOwner, { entity_owner_id: structureEntityId || 0 }) is appropriate for fetching entities owned by the specified structure.


83-89: Approved: Updated Quest Dependencies Initialization

The initialization of quest dependencies with the updated parameters enhances the functionality and ensures that quests are accurately reflected based on the current state.


Line range hint 254-254: Approved: Function useBuildingQuantities

The function useBuildingQuantities with the signature (structureEntityId: ID | undefined) remains consistent and correctly retrieves building quantities based on the provided structureEntityId.

client/src/dojo/modelManager/ArmyMovementManager.ts (6)

17-17: Import statement of getComponentValue and Entity is appropriate.

The import from @dojoengine/recs ensures that getComponentValue and Entity are available for use in the updated code.


97-97: Stamina check now correctly uses dynamic value from configuration.

The condition stamina.amount < configManager.getExploreStaminaCost() dynamically retrieves the explore stamina cost, ensuring flexibility.


112-112: Dynamic explore reward check implemented correctly.

Using configManager.getExploreReward() makes the reward value configurable and adaptable.


121-121: Calculation of max stamina steps now uses dynamic travel stamina cost.

The updated formula ensures that changes in travel stamina cost in the configuration are reflected in the calculation.


250-250: Optimistic stamina update now uses dynamic explore stamina cost.

Passing configManager.getExploreStaminaCost() ensures the stamina cost is consistent with the configuration.


289-289: Optimistic stamina update for travel now correctly calculates total cost.

The multiplication of configManager.getTravelStaminaCost() by pathLength correctly computes the total stamina cost for the travel action.

client/src/ui/utils/utils.tsx (1)

1-2: Imports added for ClientComponents and ClientConfigManager

The new imports are necessary for the updated functionality and are correctly referenced in the code.

client/src/ui/components/quest/questDetails.tsx (1)

210-210: Use of configManager enhances maintainability

Replacing hardcoded values with configManager methods improves maintainability and ensures that configuration changes propagate correctly throughout the application.

Also applies to: 247-267, 286-286, 323-343

client/src/dojo/modelManager/ConfigManager.ts (1)

224-231: Check for undefined weightConfig before accessing properties

In getResourceWeight (lines 224-231), if weightConfig is undefined, accessing weightConfig?.weight_gram will result in undefined, and the method will return 0.

Ensure that this behavior is intentional and that returning 0 is appropriate when weightConfig is not found. If not, consider handling the undefined case explicitly.

Run the following script to verify if any weightConfig instances could be undefined:

client/src/dojo/contractComponents.ts (3)

554-560: Addition of new properties in HyperstructureConfig is correct

The new properties points_per_cycle, points_for_win, and points_on_completion are appropriately added with correct types RecsType.BigInt. The metadata types array has been updated correspondingly to include "u128" types, which accurately reflect the properties' types.

Also applies to: 565-565


1238-1258: TravelFoodCostConfig component added correctly

The TravelFoodCostConfig component has been introduced with the correct properties and types. The metadata accurately reflects the types of the properties, ensuring consistency between the component definition and its metadata.


1301-1301: Metadata types in TroopConfig updated correctly

The types array in the metadata has been updated to include the new property max_troop_count, with the type "u64", which accurately reflects the property's type RecsType.Number.

client/src/ui/components/hints/WorldStructures.tsx (2)

1-1: Import statement added correctly

The configManager is properly imported from "@/dojo/setup", ensuring access to configuration data.


91-93: Dynamic configuration enhances flexibility

Using configManager.getHyperstructureConfig().pointsPerCycle ensures that the points per tick are dynamically retrieved, improving maintainability by avoiding hard-coded values.

Comment on lines +70 to +73
const buildingPopulation = configManager.getBuildingPopConfig(building).population;
const basePopulationCapacity = configManager.getBasePopulationCapacity();

return (realm?.population || 0) + buildingPopulation <= basePopulationCapacity + (realm?.capacity || 0);
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

Inconsistent Usage of Configuration Constants Detected

While the changes to the hasEnoughPopulationForBuilding function are aligned with the centralized configManager approach, several parts of the codebase still directly use BASE_POPULATION_CAPACITY and BUILDING_POPULATION. To ensure full consistency and maintainability, please refactor these instances to utilize configManager.

Affected areas:

  • sdk/packages/eternum/src/constants/global.ts
  • balancing/src/components/modules/building-table.tsx
🔗 Analysis chain

Approve changes: Consistent use of centralized configuration

The modifications to hasEnoughPopulationForBuilding function align well with the new centralized configuration management approach. The use of configManager to retrieve building population and base population capacity enhances consistency and maintainability.

Suggestion for improvement:
Consider specifying the type of the realm parameter for better type safety. For example:

export const hasEnoughPopulationForBuilding = (realm: RealmInterface, building: number) => {
  // ... (rest of the function)
};

Let's verify if configManager is used consistently across the codebase:


Let's re-run the verification with adjusted search parameters to ensure consistent usage of configManager across .ts, .tsx, and .js files:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of configManager across the codebase

# Test 1: Search for direct uses of BASE_POPULATION_CAPACITY or BUILDING_POPULATION
echo "Checking for direct uses of BASE_POPULATION_CAPACITY or BUILDING_POPULATION:"
rg --type typescript --type javascript 'BASE_POPULATION_CAPACITY|BUILDING_POPULATION'

# Test 2: Search for uses of configManager methods
echo "Checking for uses of configManager methods:"
rg --type typescript --type javascript 'configManager\.(getBuildingPopConfig|getBasePopulationCapacity)'

# Test 3: Check for any remaining imports of BASE_POPULATION_CAPACITY or BUILDING_POPULATION
echo "Checking for imports of BASE_POPULATION_CAPACITY or BUILDING_POPULATION:"
rg --type typescript --type javascript 'import.*BASE_POPULATION_CAPACITY|import.*BUILDING_POPULATION'

Length of output: 818


Script:

#!/bin/bash
# Description: Check for consistent usage of configManager across the codebase using file extensions

# Test 1: Search for direct uses of BASE_POPULATION_CAPACITY or BUILDING_POPULATION
echo "Checking for direct uses of BASE_POPULATION_CAPACITY or BUILDING_POPULATION in .ts, .tsx, .js files:"
rg -g "*.ts" -g "*.tsx" -g "*.js" 'BASE_POPULATION_CAPACITY|BUILDING_POPULATION'

# Test 2: Search for uses of configManager methods
echo "Checking for uses of configManager methods in .ts, .tsx, .js files:"
rg -g "*.ts" -g "*.tsx" -g "*.js" 'configManager\.(getBuildingPopConfig|getBasePopulationCapacity)'

# Test 3: Check for any remaining imports of BASE_POPULATION_CAPACITY or BUILDING_POPULATION
echo "Checking for imports of BASE_POPULATION_CAPACITY or BUILDING_POPULATION in .ts, .tsx, .js files:"
rg -g "*.ts" -g "*.tsx" -g "*.js" 'import.*BASE_POPULATION_CAPACITY|import.*BUILDING_POPULATION'

Length of output: 3633

import { useMemo } from "react";
import useUIStore from "../../../../hooks/store/useUIStore";
import { TickIds } from "@bibliothecadao/eternum";
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

Remaining usages of EternumGlobalConfig Found

The verification revealed that EternumGlobalConfig is still in use across multiple files in the codebase. This indicates that the refactoring to TickIds is not yet complete and may lead to inconsistencies.

  • Files still using EternumGlobalConfig:
    • sdk/packages/eternum/src/utils/index.ts
    • client/src/ui/components/hyperstructures/StructureCard.tsx
    • client/src/dojo/modelManager/ConfigManager.ts
    • (and others as listed in the shell script output)

Please ensure that all instances of EternumGlobalConfig are appropriately updated to maintain consistency and prevent potential issues.

🔗 Analysis chain

Approve import change and verify usage

The import change from EternumGlobalConfig to TickIds suggests a move towards a more modular configuration system. This is generally a good practice for maintainability and flexibility.

To ensure this change is consistent across the codebase, please run the following script:

This will help ensure that the refactoring has been applied consistently throughout the project.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of TickIds and absence of EternumGlobalConfig

# Test 1: Check for any remaining usage of EternumGlobalConfig
echo "Checking for any remaining usage of EternumGlobalConfig:"
rg "EternumGlobalConfig" --type typescript

# Test 2: Verify the usage of TickIds
echo "Verifying the usage of TickIds:"
rg "TickIds" --type typescript

Length of output: 339


Script:

#!/bin/bash
# Description: Verify the usage of TickIds and absence of EternumGlobalConfig by searching .ts and .tsx files

# Test 1: Check for any remaining usage of EternumGlobalConfig
echo "Checking for any remaining usage of EternumGlobalConfig in .ts and .tsx files:"
rg "EternumGlobalConfig" --glob "*.ts" --glob "*.tsx"

# Test 2: Verify the usage of TickIds
echo "Verifying the usage of TickIds in .ts and .tsx files:"
rg "TickIds" --glob "*.ts" --glob "*.tsx"

Length of output: 11690

Comment on lines +18 to +22
Number(resourceQuantity / BigInt(configManager.getResourcePrecision())) *
configManager.getResourceRarity(resourceType);
const totalContributableAmount = configManager.getHyperstructureTotalContributableAmount();

return effectiveContribution / totalContributableAmount;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential loss of precision when converting bigint to number

In the calculation of effectiveContribution, converting a bigint to a number using Number() can lead to loss of precision for large values exceeding Number.MAX_SAFE_INTEGER. This may result in inaccurate computations of contribution percentages.

Consider performing calculations using bigint arithmetic and converting to number only once you're certain the value is within the safe integer range. Here's a possible refactor:

-  const effectiveContribution =
-    Number(resourceQuantity / BigInt(configManager.getResourcePrecision())) *
-    configManager.getResourceRarity(resourceType);
-  const totalContributableAmount = configManager.getHyperstructureTotalContributableAmount();
-  return effectiveContribution / totalContributableAmount;
+  const effectiveContribution =
+    (resourceQuantity * BigInt(configManager.getResourceRarity(resourceType))) /
+    BigInt(configManager.getResourcePrecision());
+  const totalContributableAmount = BigInt(configManager.getHyperstructureTotalContributableAmount());
+  return Number(effectiveContribution) / Number(totalContributableAmount);

This refactor maintains precision during calculations by using bigint throughout and converts to number only when necessary.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Number(resourceQuantity / BigInt(configManager.getResourcePrecision())) *
configManager.getResourceRarity(resourceType);
const totalContributableAmount = configManager.getHyperstructureTotalContributableAmount();
return effectiveContribution / totalContributableAmount;
const effectiveContribution =
(resourceQuantity * BigInt(configManager.getResourceRarity(resourceType))) /
BigInt(configManager.getResourcePrecision());
const totalContributableAmount = BigInt(configManager.getHyperstructureTotalContributableAmount());
return Number(effectiveContribution) / Number(totalContributableAmount);

@@ -27,7 +21,7 @@ export const TravelInfo = ({
const [resourceWeight, setResourceWeight] = useState(0);
const [donkeyBalance, setDonkeyBalance] = useState(0);
const neededDonkeys = Math.ceil(
divideByPrecision(resourceWeight) / Number(EternumGlobalConfig.carryCapacityGram[CapacityConfigCategory.Donkey]),
divideByPrecision(resourceWeight) / configManager.getCapacityConfig(CapacityConfigCategory.Donkey),
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle potential division by zero

When calculating neededDonkeys, ensure that configManager.getCapacityConfig(CapacityConfigCategory.Donkey) does not return zero to avoid a division by zero error. Consider adding error handling or a default value to handle this scenario gracefully.

Apply this diff to add a safeguard:

 const neededDonkeys = Math.ceil(
-  divideByPrecision(resourceWeight) / configManager.getCapacityConfig(CapacityConfigCategory.Donkey),
+  divideByPrecision(resourceWeight) / Math.max(configManager.getCapacityConfig(CapacityConfigCategory.Donkey), 1),
 );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
divideByPrecision(resourceWeight) / configManager.getCapacityConfig(CapacityConfigCategory.Donkey),
divideByPrecision(resourceWeight) / Math.max(configManager.getCapacityConfig(CapacityConfigCategory.Donkey), 1),

@@ -70,13 +64,13 @@ export const Resources = () => {
const ResourceTable = () => {
const resourceTable = useMemo(() => {
const resources = [];
for (const resourceId of Object.keys(RESOURCE_INPUTS_SCALED) as unknown as ResourcesIds[]) {
for (const resourceId of Object.keys(configManager.resourceInputs) as unknown as ResourcesIds[]) {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid unsafe casting; improve type safety when iterating over resource IDs.

Casting Object.keys(configManager.resourceInputs) to ResourcesIds[] using as unknown as is unsafe because Object.keys returns an array of strings, which may not align with the ResourcesIds enum values.

Consider mapping the keys to numbers and asserting them as ResourcesIds to enhance type safety:

-for (const resourceId of Object.keys(configManager.resourceInputs) as unknown as ResourcesIds[]) {
+for (const key of Object.keys(configManager.resourceInputs)) {
+  const resourceId = Number(key) as ResourcesIds;

This ensures that resourceId is correctly typed and avoids unsafe casting.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for (const resourceId of Object.keys(configManager.resourceInputs) as unknown as ResourcesIds[]) {
for (const key of Object.keys(configManager.resourceInputs)) {
const resourceId = Number(key) as ResourcesIds;

Comment on lines +985 to +998
RealmLevelConfig: (() => {
return defineComponent(
world,
{ level: RecsType.Number, required_resources_id: RecsType.Number, required_resource_count: RecsType.Number },
{
metadata: {
namespace: "eternum",
name: "RealmLevelConfig",
types: ["u8", "u32", "u8"],
customTypes: [],
},
},
);
})(),
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

New component RealmLevelConfig added correctly

The RealmLevelConfig component has been introduced with appropriate properties and matching metadata. However, consider specifying more explicit RecsType types to enhance clarity and ensure type safety.

For instance, since level corresponds to "u8" in the metadata, you could use RecsType.Number8 if available. This approach can help prevent potential type mismatches and improve code readability.

Comment on lines +999 to +1012
RealmMaxLevelConfig: (() => {
return defineComponent(
world,
{ config_id: RecsType.Number, max_level: RecsType.Number },
{
metadata: {
namespace: "eternum",
name: "RealmMaxLevelConfig",
types: ["u32", "u8"],
customTypes: [],
},
},
);
})(),
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

New component RealmMaxLevelConfig added correctly

The RealmMaxLevelConfig component has been added with correct properties and metadata. Similar to the previous comment, consider using explicit RecsType types for clarity.

For example, since max_level corresponds to "u8" in the metadata, using RecsType.Number8 (if available) instead of RecsType.Number would enhance type specificity.

@@ -1230,6 +1285,7 @@
crossbowman_strength: RecsType.Number,
advantage_percent: RecsType.Number,
disadvantage_percent: RecsType.Number,
max_troop_count: RecsType.Number,
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

Inconsistent Usage of max_troop_count in TroopConfig

The property max_troop_count is not consistently included in all instances of TroopConfig. Specifically, in client/src/dojo/modelManager/ConfigManager.ts, the property is referenced as maxTroopCount instead of max_troop_count.

  • client/src/dojo/modelManager/ConfigManager.ts uses maxTroopCount instead of max_troop_count.
🔗 Analysis chain

Addition of max_troop_count to TroopConfig

The new property max_troop_count has been added to the TroopConfig component with the appropriate type RecsType.Number. Please ensure that all instances where TroopConfig is used are updated to accommodate this new property to maintain consistency across the codebase.

Run the following script to verify that all usages of TroopConfig have been updated appropriately:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all usages of `TroopConfig` include `max_troop_count`

# Test: Search for definitions and usages of `TroopConfig` and check for `max_troop_count` property
# Expect: All instances of `TroopConfig` should include `max_troop_count`

rg --type ts 'TroopConfig' -A 15 | rg 'max_troop_count'

Length of output: 406

Comment on lines +109 to +111
const constructionCost = configManager.structureCosts[StructureType.Hyperstructure]
.filter((cost) => cost.resource !== ResourcesIds["AncientFragment"])
.map((cost) => ({ ...cost }));
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify constructionCost by removing unnecessary .map

The .map function is spreading each cost into a new object without modifications. Since the objects remain the same, the .map step can be omitted.

Apply this diff to simplify the code:

 const constructionCost = configManager.structureCosts[StructureType.Hyperstructure]
   .filter((cost) => cost.resource !== ResourcesIds["AncientFragment"])
-  .map((cost) => ({ ...cost }));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const constructionCost = configManager.structureCosts[StructureType.Hyperstructure]
.filter((cost) => cost.resource !== ResourcesIds["AncientFragment"])
.map((cost) => ({ ...cost }));
const constructionCost = configManager.structureCosts[StructureType.Hyperstructure]
.filter((cost) => cost.resource !== ResourcesIds["AncientFragment"]);

Comment on lines +56 to +60
const creationCost = configManager.structureCosts[structureId]
.filter((cost) => cost.resource === ResourcesIds["AncientFragment"])
.map((cost) => ({
...cost,
}));
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify creationCost by removing unnecessary .map

The .map function is spreading each cost into a new object without modifications. Since no properties are being altered, the .map step can be omitted for clarity.

Apply this diff to simplify the code:

 const creationCost = configManager.structureCosts[structureId]
   .filter((cost) => cost.resource === ResourcesIds["AncientFragment"])
-  .map((cost) => ({
-    ...cost,
-  }));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const creationCost = configManager.structureCosts[structureId]
.filter((cost) => cost.resource === ResourcesIds["AncientFragment"])
.map((cost) => ({
...cost,
}));
const creationCost = configManager.structureCosts[structureId]
.filter((cost) => cost.resource === ResourcesIds["AncientFragment"]);

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

🧹 Outside diff range and nitpick comments (5)
client/src/dojo/modelManager/ProductionManager.ts (3)

52-55: New timeUntilFinishTick method added

The addition of the timeUntilFinishTick method is a good improvement. It provides a clear way to calculate the remaining time until a production finishes.

Consider using Math.max for improved readability:

- return finishTick > currentTick ? finishTick - currentTick : 0;
+ return Math.max(0, finishTick - currentTick);

97-106: New balanceFromComponents method added

The addition of the balanceFromComponents method is a good improvement. It provides a public interface to calculate balance based on various components without exposing the private _calculateBalance method.

For consistency with other method signatures in the class, consider using resourceId: ResourcesIds instead of resourceId: ResourcesIds, (remove the trailing comma):

public balanceFromComponents(
-   resourceId: ResourcesIds,
+   resourceId: ResourcesIds
    rate: number,
    sign: boolean,
    resourceBalance: bigint | undefined,
    productionDuration: number,
    depletionDuration: number,
  ): number {
  // ...
}

Line range hint 108-149: New private _calculateBalance method added

The addition of the _calculateBalance method is a significant improvement:

  1. It centralizes the balance calculation logic, improving maintainability.
  2. It handles both positive and negative net rates correctly.
  3. It considers store capacity and resource weight in calculations.
  4. The use of multiplyByPrecision ensures consistent precision handling.

Consider adding comments to explain the logic for each case (positive rate, negative rate, and no rate change) to improve readability and maintainability.

client/src/ui/modules/entity-details/BuildingEntityDetails.tsx (2)

200-202: LGTM: Improved flexibility in immunity duration calculation.

The use of configManager methods enhances the configurability of the immunity duration. This change aligns well with the summary's mention of improving flexibility in timing logic.

Consider extracting this calculation into a separate function for improved readability:

const calculateImmunityEndTimestamp = (createdAt: number) => {
  return createdAt + configManager.getBattleGraceTickCount() * configManager.getTick(TickIds.Armies);
};

// Usage
const immunityEndTimestamp = useMemo(() => calculateImmunityEndTimestamp(Number(structure.created_at)), [structure.created_at]);

This would make the code more self-documenting and easier to maintain.


219-223: LGTM: Enhanced resource management with improved precision.

The use of configManager.realmUpgradeCosts and divideByPrecision improves the accuracy and maintainability of balance checks. These changes align well with the summary's mention of enhancing resource management capabilities.

Consider extracting the balance check logic into a separate function for improved readability:

const hasEnoughResources = (cost: Record<number, { resource: number; amount: number }>) => {
  return Object.entries(cost).every(([resourceId, { resource, amount }]) => {
    const balance = getBalance(structureEntityId, resource);
    return divideByPrecision(balance.balance) >= amount;
  });
};

// Usage
const checkBalance = useMemo(() => {
  if (!getNextRealmLevel) return false;
  const cost = configManager.realmUpgradeCosts[getNextRealmLevel];
  return hasEnoughResources(cost);
}, [getBalance, structureEntityId, getNextRealmLevel]);

This would make the code more modular and easier to understand.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0e25f47 and 51fddb3.

📒 Files selected for processing (6)
  • client/src/dojo/modelManager/BattleManager.ts (10 hunks)
  • client/src/dojo/modelManager/ProductionManager.ts (8 hunks)
  • client/src/dojo/modelManager/tests/BattleManager.test.ts (5 hunks)
  • client/src/ui/components/resources/ResourceChip.tsx (5 hunks)
  • client/src/ui/modules/entity-details/BuildingEntityDetails.tsx (4 hunks)
  • client/src/ui/modules/military/battle-view/BattleActions.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • client/src/dojo/modelManager/tests/BattleManager.test.ts
  • client/src/ui/components/resources/ResourceChip.tsx
  • client/src/ui/modules/military/battle-view/BattleActions.tsx
🧰 Additional context used
🔇 Additional comments (9)
client/src/dojo/modelManager/ProductionManager.ts (5)

1-1: Improved precision handling with multiplyByPrecision

The addition of multiplyByPrecision to the imports is a good improvement. This utility function can centralize precision-related calculations, making the code more maintainable and less prone to errors when dealing with resource precision.


82-88: Improved getStoreCapacity method

The refactoring of the getStoreCapacity method is a good improvement:

  1. Using multiplyByPrecision centralizes precision handling.
  2. The logic for calculating store capacity has been simplified.
  3. The use of gramToKg improves readability.

These changes make the code more maintainable and less prone to errors when dealing with unit conversions and precision.


142-149: Refactored _balance method

The refactoring of the _balance method is a good improvement:

  1. It simplifies the method by delegating the calculation to _calculateBalance.
  2. This change reduces code duplication and improves maintainability.
  3. All necessary parameters are correctly passed to _calculateBalance.

These changes make the code more organized and easier to understand.


218-218: Updated input source in _inputs_available method

The change from RESOURCE_INPUTS_SCALED to configManager.resourceInputs is a good improvement:

  1. It suggests a more flexible approach to managing resource inputs.
  2. Using configManager allows for easier configuration changes without modifying the code.

Please verify that configManager.resourceInputs is properly initialized and contains the correct data for all resource types. Run the following script to check the structure and content of resourceInputs:

#!/bin/bash
# Search for the initialization of resourceInputs in configManager
rg 'resourceInputs\s*=' --type typescript

32-32: Simplified netRate method signature

The removal of the currentTick parameter from the netRate method simplifies its signature. This is a good change if the current tick is not necessary for the calculation.

Please verify that this change doesn't affect the correctness of calculations or its usage in other parts of the codebase. Run the following script to check for any remaining uses of netRate with a parameter:

✅ Verification successful

Verified Removal of currentTick Parameter from netRate

All existing calls to netRate have been updated to match the new signature without parameters. The change maintains the correctness of calculations and does not impact other parts of the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining calls to netRate with parameters
rg 'netRate\s*\([^)]*\)' --type typescript

Length of output: 78


Script:

#!/bin/bash
# Search for any remaining calls to netRate with parameters in .ts and .tsx files
rg 'netRate\s*\([^)]*\)' --glob '*.ts' --glob '*.tsx'

Length of output: 857

client/src/ui/modules/entity-details/BuildingEntityDetails.tsx (4)

22-22: LGTM: Improved imports for enhanced precision and configurability.

The addition of divideByPrecision and TickIds imports, along with REALM_MAX_LEVEL, suggests improvements in resource management precision and timing logic configurability. These changes align well with the summary's mention of enhancing resource management capabilities.

Also applies to: 31-35


213-213: LGTM: Improved maintainability with REALM_MAX_LEVEL constant.

The use of REALM_MAX_LEVEL instead of a hardcoded value enhances code maintainability and readability. This change aligns with best practices for avoiding magic numbers in the code.


302-302: LGTM: Consistent use of configManager for upgrade costs.

The use of configManager.realmUpgradeCosts in the UI rendering ensures consistency with the balance check logic. This change maintains a single source of truth for upgrade costs, improving maintainability and reducing the risk of inconsistencies.


Line range hint 1-328: Overall assessment: Improved resource management and configurability

The changes in this file significantly enhance the resource management capabilities and configurability of the BuildingEntityDetails component. Key improvements include:

  1. More precise resource calculations using divideByPrecision.
  2. Increased flexibility in timing logic with the use of configManager and TickIds.
  3. Improved maintainability through the use of constants like REALM_MAX_LEVEL.
  4. Consistent use of configManager for upgrade costs across balance checks and UI rendering.

These modifications align well with the pull request's objectives of enhancing claimability logic and improving resource management. The changes also contribute to better code maintainability and flexibility for future updates.

Consider the suggested minor improvements for readability and modularity in the previous comments to further enhance the code quality.

Comment on lines +210 to +232
const remainingKnights =
Number(cloneArmy.troops.knight_count) *
this.getRemainingPercentageOfTroops(battle_army.troops.knight_count, battle_army_lifetime.troops.knight_count);
cloneArmy.troops.knight_count = BigInt(
remainingKnights - (remainingKnights % EternumGlobalConfig.resources.resourcePrecision),
);

const remainingPaladins =
Number(cloneArmy.troops.paladin_count) *
this.getRemainingPercentageOfTroops(battle_army.troops.paladin_count, battle_army_lifetime.troops.paladin_count);
cloneArmy.troops.paladin_count = BigInt(
remainingPaladins - (remainingPaladins % EternumGlobalConfig.resources.resourcePrecision),
);

const remainingCrossbowmen =
Number(cloneArmy.troops.crossbowman_count) *
this.getRemainingPercentageOfTroops(
battle_army.troops.crossbowman_count,
battle_army_lifetime.troops.crossbowman_count,
);
cloneArmy.troops.crossbowman_count = BigInt(
remainingCrossbowmen - (remainingCrossbowmen % EternumGlobalConfig.resources.resourcePrecision),
);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider refactoring troop calculations for improved maintainability

The current implementation calculates remaining troops for each type (knights, paladins, crossbowmen) separately, leading to repetitive code. Consider refactoring this section to use a loop or a helper function to reduce duplication and improve maintainability.

Here's a suggested refactoring:

private calculateRemainingTroops(
  cloneArmy: ArmyInfo,
  battle_army: ComponentValue<ClientComponents["Battle"]["schema"]["defence_army"]>,
  battle_army_lifetime: ComponentValue<ClientComponents["Battle"]["schema"]["defence_army_lifetime"]>
) {
  const troopTypes = ['knight', 'paladin', 'crossbowman'] as const;
  
  troopTypes.forEach(type => {
    const remaining = Number(cloneArmy.troops[`${type}_count`]) *
      this.getRemainingPercentageOfTroops(
        battle_army.troops[`${type}_count`],
        battle_army_lifetime.troops[`${type}_count`]
      );
    cloneArmy.troops[`${type}_count`] = BigInt(
      remaining - (remaining % EternumGlobalConfig.resources.resourcePrecision)
    );
  });
}

// Usage in getUpdatedArmy method:
this.calculateRemainingTroops(cloneArmy, battle_army, battle_army_lifetime);

This refactoring reduces code duplication and makes it easier to add or modify troop types in the future.

Comment on lines +502 to 505
private getRemainingPercentageOfTroops(current_troops: bigint, lifetime_troops: bigint): number {
if (lifetime_troops === 0n) return 0;
return Number(current_troops) / Number(lifetime_troops);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using BigInt operations for higher precision

The current implementation converts BigInt values to Number for the calculation, which could lead to precision loss for very large numbers. Consider using BigInt operations throughout to maintain precision.

Here's a suggested modification:

private getRemainingPercentageOfTroops(current_troops: bigint, lifetime_troops: bigint): number {
  if (lifetime_troops === 0n) return 0;
  // Use BigInt division and then convert to number at the end
  return Number((current_troops * 10000n) / lifetime_troops) / 10000;
}

This approach performs the division using BigInt and only converts to a number at the end, maintaining higher precision. The multiplication by 10000 and subsequent division is used to simulate a percentage calculation with two decimal places of precision.

* bump

* change ci

---------

Co-authored-by: aymericdelab <[email protected]>
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 (1)
scripts/deploy.sh (1)

Line range hint 1-23: Consider updating related documentation and scripts.

The version updates for both katana and torii are consistent and appropriate. However, it's important to ensure that these changes are reflected in any related documentation or scripts.

Please review and update the following if necessary:

  1. Any documentation that references the katana or torii versions.
  2. CI/CD pipelines that might be using these versions.
  3. README files or setup instructions for developers.
  4. Any other scripts in the project that interact with katana or torii deployments.

This will help maintain consistency across your project and prevent potential issues for other developers or in different environments.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 51fddb3 and 78a9a12.

⛔ Files ignored due to path filters (1)
  • contracts/Scarb.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • .github/workflows/test-contracts.yml (1 hunks)
  • contracts/Scarb.toml (2 hunks)
  • contracts/manifests/dev/deployment/manifest.json (42 hunks)
  • contracts/manifests/dev/deployment/manifest.toml (21 hunks)
  • scripts/deploy.sh (2 hunks)
🧰 Additional context used
🔇 Additional comments (18)
contracts/manifests/dev/deployment/manifest.json (9)

3461-3482: Updated set_mercenaries_config function signature

The set_mercenaries_config function signature has been updated. Instead of accepting a single troops parameter of type Troops, it now accepts six separate parameters for different troop types and bounds.

This change provides more granular control over the mercenaries configuration, allowing for independent setting of lower and upper bounds for each troop type.

Let's verify if this change has been properly implemented in the contract code and if all calls to this function have been updated:

#!/bin/bash
# Search for the old function signature
rg "fn set_mercenaries_config\(troops: Troops\)" --type cairo
# Search for the new function signature
rg "fn set_mercenaries_config\(.*knights_lower_bound.*knights_upper_bound.*paladins_lower_bound.*paladins_upper_bound.*crossbowmen_lower_bound.*crossbowmen_upper_bound.*\)" --type cairo
# Search for function calls to set_mercenaries_config
rg "set_mercenaries_config\(" --type cairo

32314-32335: Updated input parameters for mercenaries configuration

The input parameters for the mercenaries configuration have been updated to include separate fields for lower and upper bounds of each troop type (knights, paladins, crossbowmen) instead of a single troops field.

This change is consistent with the updates made to the MercenariesConfig struct and the set_mercenaries_config function signature.

Let's verify if these new parameters are used consistently across the codebase:

#!/bin/bash
# Search for functions or methods using these new parameters
rg "fn .*\(.*knights_lower_bound.*knights_upper_bound.*paladins_lower_bound.*paladins_upper_bound.*crossbowmen_lower_bound.*crossbowmen_upper_bound.*\)" --type cairo

31890-31916: Updated MercenariesConfig struct

The MercenariesConfig struct has been updated to include separate fields for lower and upper bounds of each troop type (knights, paladins, crossbowmen) instead of a single troops field.

This change aligns with the updated set_mercenaries_config function signature and provides more detailed configuration options for mercenaries.

Let's verify if this struct is consistently used across the codebase:

#!/bin/bash
# Search for the old MercenariesConfig struct
rg "struct MercenariesConfig \{[^}]*troops:" --type cairo
# Search for the new MercenariesConfig struct
rg "struct MercenariesConfig \{[^}]*knights_lower_bound:" --type cairo
# Search for usages of MercenariesConfig
rg "MercenariesConfig" --type cairo

Line range hint 1-32335: Summary of changes to the manifest file

The changes in this manifest file reflect a comprehensive update to the contract system:

  1. New deployments of multiple contracts, including the World contract and various other contracts, as evidenced by updated addresses and class hashes.
  2. Modification of the MercenariesConfig struct and related functions to provide more granular control over troop configurations.
  3. Renaming of the contract_name function to name across multiple contracts for better consistency with standard naming conventions.

These changes appear to be part of a coordinated effort to improve the contract system's functionality and maintainability. The modifications to the mercenaries configuration, in particular, suggest an enhancement in the game's mechanics related to troop management.

To ensure the completeness and consistency of these changes, consider running the following final verifications:

#!/bin/bash
# Verify that all contracts in the manifest have been updated
rg '"kind": "DojoContract"' contracts/manifests/dev/deployment/manifest.json | wc -l

# Check for any remaining references to the old 'Troops' type
rg "Troops" --type cairo

# Verify that all contracts now use the 'name' function instead of 'contract_name'
rg "fn contract_name" --type cairo
rg "fn name" --type cairo

# Check for any inconsistencies in the use of the new mercenaries configuration
rg "MercenariesConfig" --type cairo

These verifications will help ensure that the changes have been applied consistently across the entire codebase.


31925-31926: Updated class hash for MercenariesConfig

The class_hash and original_class_hash for the MercenariesConfig struct have been updated. This change is consistent with the modifications made to the struct's fields.

Let's verify if this new class hash is used consistently across the codebase:

#!/bin/bash
# Search for the new class hash
rg "0x12247bf8d7b37069a7c9b217db67538f14d0bae3b72478b20c3c6011493da57" --type json --type cairo

1237-1239: Updated World contract deployment details

The address, transaction_hash, and block_number for the World contract have been updated. This indicates a new deployment of the contract.

Note that the block_number has decreased from 65 to 50. This might indicate a redeployment on a different network or a reset of the development environment.

Let's verify if this new address is referenced correctly in other parts of the codebase:

✅ Verification successful

World contract address correctly referenced

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the new World contract address in other files
rg "0x320b2713e324fe3125bbc42d85ff69cb3c0908b436fa38a35746dbc45deeb11" --type json --type cairo

Length of output: 430


Script:

#!/bin/bash
# Corrected script to search for the new World contract address in JSON and relevant files
rg "0x320b2713e324fe3125bbc42d85ff69cb3c0908b436fa38a35746dbc45deeb11" --type json --type js --type ts --type py --type go

Length of output: 255


4-5: Updated class hashes for the World contract

The class_hash and original_class_hash for the World contract have been updated. This change likely reflects a new version of the contract being deployed.

To ensure consistency, let's verify if this class hash is used elsewhere in the codebase:

✅ Verification successful

Class hash verification succeeded

The updated class_hash is only present in contracts/manifests/dev/deployment/manifest.json, ensuring that the changes are confined to this configuration file.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the new class hash in other files
rg "0x6f38d5d9507c5d9546290e1a27e309efe5a9af3770b6cc1627db4a1b90a7dce" --type json

Length of output: 430


Script:

#!/bin/bash
# Corrected script to search for the new class hash in JSON files
rg "0x6f38d5d9507c5d9546290e1a27e309efe5a9af3770b6cc1627db4a1b90a7dce" --type json

Length of output: 363


1292-1292: Updated function name from contract_name to name

The function name has been changed from contract_name to name across multiple contracts. This change improves consistency with standard naming conventions for contract interfaces.

Let's verify if this change has been consistently applied across the codebase:

Also applies to: 1615-1615, 2052-2052, 2517-2517, 3877-3877, 4157-4157, 4415-4415, 4634-4634, 4984-4984, 5375-5375, 5691-5691, 5969-5969, 6230-6230, 6546-6546, 6874-6874, 7178-7178, 7464-7464, 7808-7808


1258-1260: Updated contract deployment details for multiple contracts

The address, class_hash, and original_class_hash have been updated for multiple contracts. This indicates a new deployment of these contracts, likely due to code changes or a new deployment environment.

Let's verify if these new addresses and class hashes are consistently used across the codebase:

Also applies to: 1581-1583, 2018-2020, 2483-2485, 3843-3845, 4123-4125, 4381-4383, 4600-4602, 4950-4952, 5341-5343, 5657-5659, 5935-5937, 6196-6198, 6512-6514, 6840-6842, 7144-7146, 7430-7432, 7774-7776

contracts/Scarb.toml (2)

9-9: Dependency version update looks good, but verify compatibility.

The update of the dojo dependency from v1.0.0-alpha.12 to v1.0.0-alpha.16 is noted. This change seems intentional and follows semantic versioning.

To ensure smooth integration:

  1. Review the changelog for dojo between these versions to understand new features or breaking changes.
  2. Verify that your project is compatible with this new version, especially considering it's an alpha release.
  3. Check if any other dependencies in your project rely on dojo and may need updates as well.

Would you like me to search for any potential compatibility issues in the codebase?


19-19: Newline addition is a good practice.

Adding a newline at the end of the file is a good practice. It ensures proper file termination and can prevent issues with certain tools or version control systems.

scripts/deploy.sh (2)

14-14: Approve version update for katana deployment.

The katana deployment version has been updated from v1.0.0-alpha.12 to v1.0.0-alpha.16. This change is likely to include improvements or new features.

Please ensure that this new version is compatible with the rest of your system. Consider running the following commands to verify the compatibility and check for any breaking changes:


23-23: Approve version update for torii deployment.

The torii deployment version has been updated from v1.0.0-alpha.12 to v1.0.0-alpha.16, consistent with the katana update.

Please ensure that this new version of torii is compatible with the updated katana version and the rest of your system. Consider running the following commands to verify the compatibility:

.github/workflows/test-contracts.yml (1)

52-52: Dojo version update: Verify compatibility and test thoroughly

The Dojo release artifact version has been updated from v1.0.0-alpha.12 to v1.0.0-alpha.16. This change may introduce new features, bug fixes, or potential breaking changes.

To ensure this update doesn't negatively impact the project:

  1. Verify that v1.0.0-alpha.16 is the intended version for this update.
  2. Review the changelog or release notes for Dojo v1.0.0-alpha.16 to understand the changes introduced.
  3. Ensure all tests pass with the new version.
  4. Check if any project code needs to be updated to accommodate changes in Dojo v1.0.0-alpha.16.
contracts/manifests/dev/deployment/manifest.toml (4)

Line range hint 26-339: Contract configurations updated

The contract configurations have been updated with new class hashes and addresses. These changes appear to be consistent across all contract entries and likely reflect a new deployment or version of the contracts.

To ensure these changes are consistent and no unintended modifications were made, run the following script:

#!/bin/bash
# Description: Verify the consistency of contract configuration updates

# Test: Check for any remaining old class hashes or addresses
echo "Checking for any remaining old class hashes or addresses in the contracts section:"
sed -n '/\[\[contracts\]\]/,/\[\[models\]\]/p' contracts/manifests/dev/deployment/manifest.toml | grep -E "0x[a-fA-F0-9]{64}" | sort | uniq -c

# Test: Verify that all contract entries have been updated
echo "Verifying that all contract entries have been updated:"
sed -n '/\[\[contracts\]\]/,/\[\[models\]\]/p' contracts/manifests/dev/deployment/manifest.toml | grep -E "class_hash = |original_class_hash = |address = " | wc -l

Line range hint 2074-2113: MercenariesConfig model restructured

The MercenariesConfig model has been significantly restructured:

  1. The 'troops' field has been removed.
  2. New fields for knights, paladins, and crossbowmen have been added, each with lower and upper bounds.

This change provides more granular control over different troop types, which could impact game balance and mechanics. Ensure that all systems interacting with this model have been updated accordingly.

To verify the impact of these changes and ensure all related code has been updated, run the following script:

#!/bin/bash
# Description: Verify the impact of MercenariesConfig changes

# Test: Search for uses of the old 'troops' field
echo "Searching for uses of the old 'troops' field:"
rg --type rust "MercenariesConfig.*troops"

# Test: Search for uses of the new troop-specific fields
echo "Searching for uses of the new troop-specific fields:"
rg --type rust "MercenariesConfig.*(knights|paladins|crossbowmen)_(lower|upper)_bound"

# Test: Check for any remaining references to the old model structure
echo "Checking for any remaining references to the old model structure:"
rg --type rust "MercenariesConfig" -C 5

3-8: World configuration updated

The world configuration has been updated with new class hashes, addresses, and block number. These changes appear to be part of a deployment update.

To ensure these changes are consistent across the codebase, run the following script:

#!/bin/bash
# Description: Verify the consistency of world configuration values across the codebase

# Test: Search for occurrences of the old and new values
echo "Searching for old and new class_hash:"
rg --type toml "0x6f4515274ee23404789c3351a77107d0ec07508530119822046600ca6948d6e"
rg --type toml "0x6f38d5d9507c5d9546290e1a27e309efe5a9af3770b6cc1627db4a1b90a7dce"

echo "Searching for old and new address:"
rg --type toml "0x76ca3dfc3e96843716f882546f0db96b7da0cf988bdba284b469d0defb2f48f"
rg --type toml "0x320b2713e324fe3125bbc42d85ff69cb3c0908b436fa38a35746dbc45deeb11"

echo "Searching for old and new transaction_hash:"
rg --type toml "0x73f424096734f925628f50730e27889506b6b9141efd4aed165165ef8367ce5"
rg --type toml "0x5a4deb5ecebc548f10b969db5496f9605a3b862dc766bb419c42615ff735760"

echo "Searching for old and new block_number:"
rg --type toml "block_number = 65"
rg --type toml "block_number = 50"

Line range hint 1-2853: Comprehensive manifest update

This manifest file has undergone significant changes, including:

  1. Updated world configuration
  2. Updated contract configurations with new class hashes and addresses
  3. Restructured MercenariesConfig model

While these changes appear appropriate for a deployment update, it's crucial to ensure all modifications are intentional and no unintended changes have been introduced.

To perform a comprehensive verification of the changes, run the following script:

Please review the output of this script carefully to ensure all changes are as expected.

✅ Verification successful

✅ Manifest Update Verified Successfully

The manifest.toml file has been thoroughly reviewed and verified. All changes related to class hashes, addresses, and other deployment-specific configurations align with the expected updates. Additionally, the number of model definitions remains consistent, and no new or removed models have been introduced inadvertently.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Comprehensive verification of manifest changes

# Test: Compare the old and new versions of the file
echo "Generating a diff of the manifest file:"
git diff HEAD~1 contracts/manifests/dev/deployment/manifest.toml > manifest_diff.txt

# Test: Check for any unexpected changes
echo "Checking for unexpected changes:"
grep -vE "(class_hash|original_class_hash|address|transaction_hash|block_number)" manifest_diff.txt

# Test: Verify that all model definitions are present
echo "Verifying all model definitions are present:"
grep -c "\[\[models\]\]" contracts/manifests/dev/deployment/manifest.toml

# Test: Check for any removed or added models
echo "Checking for removed or added models:"
diff <(grep "\[\[models\]\]" contracts/manifests/dev/deployment/manifest.toml | sort) <(git show HEAD~1:contracts/manifests/dev/deployment/manifest.toml | grep "\[\[models\]\]" | sort)

# Cleanup
rm manifest_diff.txt

Length of output: 1158


Script:

#!/bin/bash
# Description: Comprehensive verification of manifest.toml changes

# Step 1: Generate a diff of the manifest file
echo "Generating a diff of the manifest file:"
git diff HEAD~1 contracts/manifests/dev/deployment/manifest.toml > manifest_diff.txt

# Step 2: Check for any unexpected changes excluding specific keys
echo "Checking for any unexpected changes (excluding class_hash, original_class_hash, address, transaction_hash, block_number):"
grep -vE "(class_hash|original_class_hash|address|transaction_hash|block_number)" manifest_diff.txt

# Step 3: Verify the number of [[models]] sections matches the previous version
echo "Verifying the number of [[models]] sections:"
current_models_count=$(grep -c "\[\[models\]\]" contracts/manifests/dev/deployment/manifest.toml)
previous_models_count=$(git show HEAD~1:contracts/manifests/dev/deployment/manifest.toml | grep -c "\[\[models\]\]")

echo "Current number of models: $current_models_count"
echo "Previous number of models: $previous_models_count"

if [ "$current_models_count" -eq "$previous_models_count" ]; then
    echo "Model count verification passed."
else
    echo "Model count mismatch detected."
fi

# Step 4: Check for any removed or added models by comparing model tags
echo "Checking for removed or added models based on tags:"
current_model_tags=$(grep -E 'tag = "[^"]+"' contracts/manifests/dev/deployment/manifest.toml | sort)
previous_model_tags=$(git show HEAD~1:contracts/manifests/dev/deployment/manifest.toml | grep -E 'tag = "[^"]+"' | sort)

echo "Differences in model tags:"
diff <(echo "$current_model_tags") <(echo "$previous_model_tags")

Length of output: 21308


Script:

#!/bin/bash
# Description: Comprehensive verification of manifest.toml changes with improved error handling

# Define temporary files
CURRENT_MODELS_TAGS=$(mktemp)
PREVIOUS_MODELS_TAGS=$(mktemp)
DIFF_OUTPUT=$(mktemp)

# Ensure temporary files are removed on exit
trap 'rm -f "$CURRENT_MODELS_TAGS" "$PREVIOUS_MODELS_TAGS" "$DIFF_OUTPUT"' EXIT

# Step 1: Generate a diff of the manifest file
echo "Generating a diff of the manifest file:"
git diff HEAD~1 contracts/manifests/dev/deployment/manifest.toml > manifest_diff.txt

# Step 2: Check for any unexpected changes excluding specific keys
echo "Checking for any unexpected changes (excluding class_hash, original_class_hash, address, transaction_hash, block_number):"
grep -vE "(class_hash|original_class_hash|address|transaction_hash|block_number)" manifest_diff.txt > unexpected_changes.txt

if [ -s unexpected_changes.txt ]; then
    echo "Unexpected changes detected:"
    cat unexpected_changes.txt
else
    echo "No unexpected changes found."
fi

# Step 3: Verify the number of [[models]] sections matches the previous version
echo "Verifying the number of [[models]] sections:"
current_models_count=$(grep -c "\[\[models\]\]" contracts/manifests/dev/deployment/manifest.toml)
previous_models_count=$(git show HEAD~1:contracts/manifests/dev/deployment/manifest.toml | grep -c "\[\[models\]\]")

echo "Current number of models: $current_models_count"
echo "Previous number of models: $previous_models_count"

if [ "$current_models_count" -eq "$previous_models_count" ]; then
    echo "Model count verification passed."
else
    echo "Model count mismatch detected."
fi

# Step 4: Check for any removed or added models by comparing model tags
echo "Checking for removed or added models based on tags:"

# Extract current model tags
grep -E 'tag = "[^"]+"' contracts/manifests/dev/deployment/manifest.toml | sort > "$CURRENT_MODELS_TAGS"

# Extract previous model tags
git show HEAD~1:contracts/manifests/dev/deployment/manifest.toml | grep -E 'tag = "[^"]+"' | sort > "$PREVIOUS_MODELS_TAGS"

# Compare the tags
diff "$CURRENT_MODELS_TAGS" "$PREVIOUS_MODELS_TAGS" > "$DIFF_OUTPUT"

if [ -s "$DIFF_OUTPUT" ]; then
    echo "Differences in model tags detected:"
    cat "$DIFF_OUTPUT"
else
    echo "No differences in model tags. No models were added or removed."
fi

# Cleanup is handled by the trap

Length of output: 7018

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.

4 participants