-
Notifications
You must be signed in to change notification settings - Fork 35
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
base: main
Are you sure you want to change the base?
Rc 1 #1851
Conversation
Feat guild chat
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
You are out of MentatBot reviews. Your usage will refresh October 21 at 07:00 AM. |
WalkthroughThis pull request introduces several changes across multiple files, primarily enhancing the claimability logic in the Changes
Possibly related PRs
Suggested reviewers
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
fix: claim on structures + selected army
There was a problem hiding this 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 retrievalThe use of the
useEntities
hook to directly accessplayerStructures
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 maintainabilityThe changes in this file represent a positive refactoring effort:
- Introduction of the
useEntities
custom hook improves state management.- Simplification of player structures retrieval enhances code readability.
- 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 suggestionThe changes effectively implement the new
useEntities
hook:
- Direct destructuring of
playerStructures
simplifies the code.- 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 theuseOwnArmiesByPosition
hook to potentially improve performance.Also applies to: 28-28
Line range hint
19-165
: LGTM: Component structure maintained with improved data accessThe refactoring has been implemented smoothly:
- Overall component logic and structure remain intact.
- Changes are localized to data fetching, improving maintainability.
- 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 inuseMemo
forgetPlayerStructures
In the
getPlayerStructures
function, the dependency array foruseMemo
incorrectly includesotherRealms
instead ofplayerStructures
. This may cause the memoized value to not update correctly whenplayerStructures
changes.Apply this diff to correct the dependency array:
- }, [otherRealms, filterFn]); + }, [playerStructures, filterFn]);
Line range hint
160-164
: Fix incorrect dependencies inuseMemo
forgetOtherStructures
Similarly, in the
getOtherStructures
function, the dependency array foruseMemo
incorrectly includesotherRealms
instead ofotherStructures
. 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
⛔ 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 includeplayerStructures
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.tsAlso applies to: 14-14
1-1
: LGTM! Consider verifying the impact of import changes.The shift from
useDojo
touseEntities
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
andgetPlayerStructures
are no longer used inMilitary.tsx
.useEntities
is correctly exported fromclient/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.tsLength 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" fiLength 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" fiLength of output: 935
client/src/ui/modules/entity-details/Entities.tsx (2)
3-3
: LGTM: Improved state management with custom hookThe change from importing
getPlayerStructures
touseEntities
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 functionThe 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 theuseEntities
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 accessThe changes to the import statements are consistent with the described refactoring:
- Adding
useEntities
suggests a more centralized approach to accessing entity data.- 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)' ./contractsLength of output: 357
Fix/market crash
update market
There was a problem hiding this 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 likebg-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 addedmb-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 detectionThe 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:
- The transformation logic for the image has been simplified, which improves maintainability.
- 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 ofvw
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:
- Consider extracting color values into a centralized theme configuration for easier management and consistency across the application.
- Evaluate the accessibility of the new color scheme, ensuring sufficient contrast for readability.
- 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 commentThere'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 stylesThe 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:
- Define CSS classes for positioning in your stylesheet:
.tooltip-position { position: absolute; transition: left 0.1s, top 0.1s; }
- 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, })} >
- 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`); } };
- 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 clarityThe changes improve the grid header's appearance and clarity:
- Adding
py-2
to the grid container provides better vertical spacing.- Including "Resource" text in the first column header clarifies its purpose.
- 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 readabilityThe 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
: Usesborder-black/10
client/src/ui/elements/Button.tsx
: Useshover: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
andhover: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:
- Background colors have been changed from black to brown.
- Hover states have been adjusted to use gold or lighter brown shades.
- 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 typographyThe 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:
- Conduct a thorough visual review of all pages and components that use headings.
- Test the new font across different browsers, devices, and screen sizes to ensure consistent rendering and readability.
- Consider creating before/after screenshots for the design team to review and approve.
- Update any design documentation or style guides to reflect this change.
- 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 consistencyThe background color of the notification div has been changed from
bg-black/90
tobg-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 maintainabilityWhile the color change looks good, here are some suggestions to improve the overall component:
The component has multiple responsibilities. Consider breaking it down into smaller, more focused components for better maintainability.
Extract hardcoded values as constants. For example:
const QUESTS_THRESHOLD = 8;Then use
QUESTS_THRESHOLD
instead of8
in the condition.Improve type safety by replacing
any
with a proper type for quests:const completedQuests = quests?.filter((quest: Quest) => quest.status === QuestStatus.Claimed);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
andbattleEntityId
are undefined:address={battleSide === BattleSide.Attack ? account.address : battleEntityId?.toString() ?? 'unknown'}This ensures that the
EntityAvatar
always receives a valid string value for itsaddress
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 addstext-white
for better readability against the brown background.client/src/ui/modules/military/battle-view/BattleProgressBar.tsx (2)
146-146
: LGTM: Enhanced progress bar stylingThe 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 layoutThe 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 iconsThe 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
tobg-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 functionalityThe 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 componentThe new ChatSelect component is a well-implemented addition to the Chat functionality. It provides:
- Efficient channel selection, including support for guild channels
- A search feature for filtering channels, enhancing user experience
- 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 reusabilityWhile the changes and additions to this file are generally well-implemented, there are a few areas where we could improve code organization and reusability:
File size: The file has grown quite large. Consider splitting it into separate files for each main component (Chat, Messages, ChatSelect) to improve maintainability.
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; };
- 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 layoutThe changes to the market price container improve the visual appearance and layout:
- Added
rounded-xl
class for consistency with other components.- Adjusted padding and used flex layout for better organization of information.
- 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 representationThe changes to the OrderRow component enhance its appearance and readability:
- Added
rounded
class for consistency with other components.- Implemented a grid system for better organization of order details.
- 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 torounded-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 interactionThe changes to the OrderCreation component improve its usability and visual consistency:
- Added
rounded-xl
class to the main container for consistency with other components.- Implemented flex layout with gap for better spacing and organization.
- 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 interactionThe changes in this file significantly improve the visual consistency and user experience of the trading interface:
- Consistent use of rounded corners (
rounded-xl
) across components.- Improved layout and spacing using flex and grid systems.
- Enhanced visual representation of resources using ResourceIcon components.
- 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
⛔ 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 colorThe 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:
- Ensure this change is consistent with the overall design system and color palette of the application.
- Verify that the new brown background provides sufficient contrast with the text and other elements within the container for accessibility purposes.
- 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.
- 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
andisCategory
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 ingetStructureCategory
is also a good practice for handling potential undefined values.
35-35
: Good code organizationThe 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 reusabilityThe changes to the
motion.img
component look good overall. Here are some points to consider:
- The image size has increased from 44 to 56 units. Please verify that this change doesn't negatively impact the layout.
- 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.
- 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 maindiv
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 theclassName
prop and the updates to thecount
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 brownThe background color of the tooltip has been changed from
bg-black/90
tobg-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
tobg-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" -cLength 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" -cLength 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
tobg-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
tobg-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
tobg-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:
- The new color scheme maintains or improves readability and contrast for all content.
- The changes align with the overall design system and accessibility guidelines of the application.
- Similar updates are applied consistently across other components if necessary.
To fully validate these changes:
- Test the component with various content and screen settings to ensure optimal visibility and readability.
- Review the component in the context of the entire application to confirm design consistency.
- 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 appealThe addition of
bg-brown
,rounded-2xl
, andp-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
tobg-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:
- Check if this color change is part of a broader design update.
- Ensure the new brown background provides sufficient contrast with the text color for readability.
- 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
tobg-brown
in thedefault
style is consistent with the updates made to theprimary
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 fontsThe 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:
- Does this change align with the overall design system of the application?
- Have you tested the readability and appearance of "Bokor" across different screen sizes and devices?
- Are there any specific headings that should retain the previous font for design purposes?
- 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 importThe 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:
- Is this font being used extensively throughout the application to justify the additional resource load?
- Have you considered using font subsetting to reduce the file size if only specific characters are needed?
- 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.cssLength 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 changeThe background color for the
Listbox.Options
component is now always set to "bg-brown", regardless of theprops.style
value. This change removes the ability to have a black background whenprops.style === "black"
.
If this change is intentional to standardize the appearance:
- Consider removing the conditional statement entirely, as it no longer affects the outcome.
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
tomy-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:
- Check that the added top margin doesn't create unintended spacing at the beginning of the list.
- Confirm that the change doesn't cause any overflow issues in the parent container.
- 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
andbg-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 theBattleProgressBar
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:
- Changing from
bg-[#1b1a1a]
tobg-brown
aligns the color scheme with what seems to be an updated design system.- Adding
bg-hex-bg
introduces a hexagonal background pattern, which is thematically appropriate for a battle view.- Switching from
h-[35vh]
tomin-h-[40vh]
allows for more responsive behavior, accommodating varying content sizes.- 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
andbg-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 inBattle.tsx
is isolated. The new classesbg-brown
andbg-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 SelectContentThe change from
bg-black/90
tobg-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:
- If the new brown background contrasts well with the text color.
- If it aligns with other dropdown menus or similar UI elements in the application.
107-107
: LGTM: Layout improvement for SelectItemThe 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:
- Please verify that the text and check icon are properly aligned at the edges of the dropdown.
- Check if this change maintains consistency with other similar UI elements in the application.
- 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 componentThe changes made to the Select component are purely cosmetic and should enhance its visual appeal:
- The background color of SelectContent has been updated to a brown shade, potentially improving theme consistency.
- 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:
- Test the Select component with various content types and lengths.
- Verify the appearance on different screen sizes and devices.
- 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 oftooltipText
property enhances component flexibility.The new optional
tooltipText
property in theProps
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 newtooltipText
property. This change is consistent with theProps
type modification and maintains the existing default behavior forwithTooltip
.
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:
- The addition of the
tooltipText
property improves reusability.- The tooltip styling changes likely contribute to better UI consistency.
- 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 layoutThe 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:
- Main container background changed from
bg-black/40
tobg-brown/40
and addedbg-hex-bg
.- Hover effect on event items changed from
hover:bg-black/20
tohover: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:
- The overall appearance of the event stream container
- The visibility and readability of event items
- The effectiveness of the hover effect on event items
- The impact of the
bg-hex-bg
class on the background appearanceAlso 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:
- 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.
- Verify design: Ensure that these changes have been reviewed and approved by the design team.
- Cross-browser testing: Verify that the new colors render consistently across different browsers and devices.
- Accessibility check: Confirm that the new color scheme maintains sufficient contrast ratios for readability and meets accessibility standards.
- 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:
- Update the PR description with the context for these changes.
- Confirm that the design team has approved these changes.
- Perform cross-browser testing and report the results.
- Run an accessibility check on the new color scheme and report the results.
- 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:
- Use this utility only when necessary and when alternative navigation methods are available.
- Ensure that the content is still accessible and navigable, especially for keyboard users.
- 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:
- Conduct a thorough visual review of all affected components and pages.
- Test the application across different browsers and devices to verify cross-browser compatibility.
- Perform accessibility testing, especially for areas where the 'no-scrollbar' utility is applied.
- 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 inArmyInfoLabel.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
tobg-brown/70
for the background color is approved. This modification enhances the visual appearance of theInputResourcesPrice
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 elementsThe 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 stylingThe 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 stylingThe 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 structureThe changes to the header section enhance both the visual appeal and the semantic structure of the component:
- Centering the title and using an
h1
element improves the visual hierarchy and semantic meaning.- 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 layoutThe 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 issuesThe changes to the MarketModal component focus on enhancing the user interface and improving the overall layout. Key improvements include:
- Addition of intuitive icons to tab labels
- Improved modal container styling
- Simplified Select component styling
- Enhanced header layout and structure
- 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 memoizationThe addition of memoized
lordsBalance
andresourceBalance
variables is a good optimization. It prevents unnecessary recalculations and simplifies balance retrieval throughout the component.
70-71
: LGTM: Simplified and consistent balance checkThe 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 calculationThe 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 suggestionConsider consistent max value handling for all resources
While adding a
max
prop to theResourceBar
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 useresourceBalance
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:
- The 'ACCOUNT_CHANGE_EVENT' is properly handled across the application.
- The 250ms timeout before navigation is necessary and doesn't cause any noticeable delay for users.
- 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:
- Consistent styling and layout across steps.
- Introduction of new components like SettleRealmComponent and ContainerWithSquire.
- Clear progression through the onboarding steps with informative content.
- 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:
- Conduct thorough end-to-end testing of the entire onboarding flow.
- Verify that all new components (e.g., SettleRealmComponent) function as intended.
- Review the content of each step for clarity and completeness.
- 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 usageThe new imports and the use of the
useCallback
hook are appropriate for the changes made to the component. The addition ofuseGuilds
andCHAT_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 supportThe Messages component has been successfully updated to handle guild messages. The changes include:
- Proper identification of guild messages
- Updated message key generation to include guild messages
- 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 cornersThe 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
tobg-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 generationThe
getMessageKey
function is properly imported from"../chat/utils"
to generate unique keys for chat tabs.
27-27
: Retrieve 'addTab' from chat storeThe
addTab
function is correctly retrieved from the chat store usinguseChatStore
, ensuring proper tab management.
127-127
: Update background color for player name displayThe background color class is updated to
bg-brown/20
, enhancing the visual consistency of the player name display.
"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", |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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 useshover:text-brown
- The
opaque
style useshover: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} /> |
There was a problem hiding this comment.
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 theTroopRow
component's prop types inTroops.tsx
andCombat.tsx
. - Verify that the
TroopRow
component utilizes thedefending
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)) && ( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
{!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)
addTab({ | ||
name: playerName, | ||
key: getMessageKey(account.address, selectedPlayer), | ||
address: toHexString(selectedPlayer), | ||
displayed: true, | ||
lastSeen: new Date(), | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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
There was a problem hiding this 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' parametersThe key-value pairs for
crossbowmen_lower_bound
andcrossbowmen_upper_bound
are split across multiple lines, whereas the previous entries forknights
andpaladins
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
📒 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 toSetMercenariesConfigProps
interface with considerationsThe 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 theTroops
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 configurationThe 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 componentsWhile 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 oldtroops
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 javascriptLength 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 maintainabilityReplacing 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 GoodThe addition of transferring rewards to the mine structure enhances the functionality by ensuring the mine entity receives the appropriate rewards upon discovery.
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(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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
fromtransaction_hash
salt_two.low
fromblock_timestamp
salt_three.low
fromnonce
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.
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, |
There was a problem hiding this comment.
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.
knights_lower_bound: u64, | ||
knights_upper_bound: u64, | ||
paladins_lower_bound: u64, | ||
paladins_upper_bound: u64, | ||
crossbowmen_lower_bound: u64, | ||
crossbowmen_upper_bound: u64, |
There was a problem hiding this comment.
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.
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)> | ||
); |
There was a problem hiding this comment.
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,
}
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 | ||
}) | ||
); |
There was a problem hiding this comment.
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.
Enh/client config manager
There was a problem hiding this 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 functionalityThe 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()
orconfigManager.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 managementThe 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 calculationThe 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 ifrealm
orresourcesInputs
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 approachThe changes in the import statements reflect a shift towards a more centralized and flexible configuration management system. By using
configManager
andTickIds
, 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 calculationThe 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 maintainabilityThe 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:
- 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;
- 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 methodThe change from
EternumGlobalConfig.stamina.travelCost
toconfigManager.getTravelStaminaCost()
is consistent with the new configuration management approach. This modification:
- Aligns with the centralized configuration management introduced earlier.
- 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 (viamultiplyByPrecision
) needs careful consideration.To ensure the refactoring is complete and consistent:
- Verify that
configManager.realmUpgradeCosts
provides correctly scaled values that don't require additional precision handling.- Check if precision handling is needed in the
ResourceCost
component or anywhere else where these costs are displayed or used in calculations.- 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 configManagerThe 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
toconfigManager
DetectedThe verification revealed that
EternumGlobalConfig
is still used extensively across multiple files in the codebase. This indicates that the refactoring toconfigManager
is not yet fully implemented.Actions Required:
- Complete Refactoring: Ensure that all instances of
EternumGlobalConfig
are replaced withconfigManager
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 impactThe changes in this file represent a positive step towards more flexible and maintainable configuration management. The shift from
EternumGlobalConfig
toconfigManager
is well-implemented and consistent within this component.To ensure consistency across the entire application:
- Verify that similar changes have been made in other components that previously used
EternumGlobalConfig
.- Consider updating the project documentation to reflect this new approach to configuration management.
- 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 ofconfigManager
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 documentationThe 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 valuesWhile 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 retrievalThe use of
configManager.getCapacityConfig(CapacityConfigCategory.Donkey)
is a good improvement:
- It centralizes configuration management.
- It allows for easier updates to capacity values.
- 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 displayThe use of
configManager.getResourceWeight(ResourcesIds.<Resource>)
is a good improvement:
- It centralizes configuration management for resource weights.
- It allows for easier updates to weight values.
- 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:
- Introducing centralized configuration management through
configManager
.- Improving resource input handling with a more flexible approach.
- 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:
- Consider extracting the resource filtering logic into a separate utility function for reusability.
- 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 alongsidecurrencyIntlFormat
. This change, combined with the removal of theEternumGlobalConfig
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 thedivideByPrecision
function instead of directly accessingEternumGlobalConfig.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 logicThe changes enhance the robustness and maintainability of the building data retrieval logic. However, there are a couple of suggestions for further improvement:
- Replace
isNaN
withNumber.isNaN
for safer number checking:if (Number.isNaN(Number(buildingId))) continue;
- 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 mappingThe 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 handlingThe change from a static config value to
configManager.getExploreReward()
improves flexibility and centralization of configuration management. However, consider the following suggestions:
- Optimize performance by memoizing the result of
getExploreReward()
usinguseMemo
to prevent unnecessary recalculations on each render.- Add error handling in case
configManager
is undefined orgetExploreReward()
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 checkThe use of
multiplyByPrecision
standardizes precision handling, aligning with the overall shift towards usingconfigManager
. 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 StructureInfoThe changes to cost retrieval and
perTick
calculation align with the centralized configuration management approach. The use ofconfigManager.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 ofgenerateMockTroopConfig
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:
- Use more realistic values for some parameters to better represent actual game scenarios.
- Add JSDoc comments to explain the purpose and usage of the function.
- 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
: ImprovedimmunityEndTimestamp
calculation.The updated calculation of
immunityEndTimestamp
usingconfigManager
methods enhances flexibility and maintainability. It also introduces a more type-safe approach withTickIds.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 consistencyThe addition of the
Player
interface is a good improvement, providing a clear structure for player data. It includes essential properties likeentity_id
,address
(usingContractAddress
type, which is good for blockchain integration), andaddressName
for human-readable identification.For consistency with other parts of the codebase, consider using the
ID
type alias for theentity_id
property:export interface Player { entity_id: ID; address: ContractAddress; addressName: string; }This change would align the
Player
interface with the usage ofID
type throughout the rest of the file.client/src/hooks/helpers/useRealm.tsx (2)
227-228
: LGTM: Improved hasCapacity calculationThe 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 getRealmsThe modification to use
configManager.getBasePopulationCapacity()
in thegetRealms
function maintains consistency with theuseGetRealm
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 retrievalThe modification to use
configManager.getSpeedConfig(DONKEY_ENTITY_TYPE)
instead ofEternumGlobalConfig.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:
- Using
configManager
instead of a global config enhances modularity and flexibility.- 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:
- It allows for dynamic configuration of speed values.
- 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:
- The shift to using
configManager
allows for more dynamic and centralized configuration management.- The introduction of
DONKEY_ENTITY_TYPE
improves type safety and code readability.- 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 dynamicmaxTroopCountPerArmy
value obtained from theconfigManager
. 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 duplicationThe 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 componentThe changes to the OrderRow component bring several improvements:
- Updated styling with rounded corners for better visual consistency.
- Improved travel time calculation using
configManager
, enhancing maintainability.- 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 calculationThe changes to the OrderCreation component and the addition of the
calculateDonkeysNeeded
function bring several improvements:
- Updated styling with rounded corners for better visual consistency.
- Improved accuracy in calculating maximum values for NumberInput components using
divideByPrecision
.- 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 ofCapacityConfigCategory.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 componentThe changes made to the MarketOrderPanel component and its sub-components bring significant improvements:
- Enhanced configuration management with the introduction of
configManager
.- Improved visual consistency across all components with the addition of rounded corners and better layout structures.
- More accurate calculations and display logic for resource amounts and prices.
- Better code organization with the introduction of the
calculateDonkeysNeeded
function.- 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:
- Consider adding more comments to explain complex logic, especially in areas dealing with resource calculations and conversions.
- Look for opportunities to extract repeated logic into reusable functions, particularly for price and resource amount calculations.
- Ensure that all error cases are properly handled, especially when dealing with user inputs and API calls.
To improve the overall architecture:
- Consider creating a separate utility file for common functions like
calculateDonkeysNeeded
and other resource-related calculations.- Evaluate the possibility of using React Context or a state management library to handle shared state, which could simplify prop drilling in nested components.
- 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 dependenciesIncluding
resourceWeight
anddonkeyBalance
in the dependency array of theuseEffect
hook may cause an infinite loop. These state variables are updated within theuseEffect
, which triggers a re-render and re-runs theuseEffect
again. To prevent this, removeresourceWeight
anddonkeyBalance
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 forcost
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 statementThe 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 inuseMemo
HookIn 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
: EnsuretickIntervalInSeconds
is valid to prevent division by zeroWhile the default value of
tickIntervalInSeconds
is set to1
using the|| 1
fallback, consider explicitly handling cases whereconfigManager.getTick(TickIds.Armies)
might return0
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 clarityThe 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
📒 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 managementThe changes in the import statements, specifically the addition of
configManager
and the removal ofEternumGlobalConfig
, 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 calculationThe modification in stamina cost calculation logic, utilizing
configManager.getTravelStaminaCost()
andconfigManager.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
andmultiplyByPrecision
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:
- It uses
configManager.getCapacityConfig
, allowing for more flexible and centralized configuration management.- The addition of
multiplyByPrecision
ensures accurate calculations, mitigating potential floating-point precision issues.- 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:
- The overall structure and logic flow of the component remain intact.
- Performance optimizations using
useMemo
are preserved.- 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:
- Introduce centralized configuration management through
configManager
.- Enhance precision in storehouse capacity calculations using
multiplyByPrecision
.- 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 modularityThe addition of
configManager
import and removal ofRESOURCE_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 maintainabilityThe 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 configurationThe introduction of
configManager
import and removal of constant imports (BASE_POPULATION_CAPACITY
andBUILDING_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 managementThe 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:
- Enhances modularity and flexibility in managing configurations.
- Makes the code more testable by allowing easier mocking of configuration values.
- Centralizes configuration management, reducing the risk of inconsistencies across the application.
Line range hint
1-62
: Overall impact: Improved configuration management without functional changesThe changes in this file represent a positive step towards better configuration management:
- The core functionality of the
StaminaResource
component remains intact.- The transition from a global config object to a centralized config manager improves modularity and maintainability.
- 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 toconfigManager.getTravelStaminaCost()
. The usage ofconfigManager.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 hardcodedREALM_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
toconfigManager
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 theRealm.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.tsxLength 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.tsxLength of output: 863
client/src/ui/elements/ArmyCapacity.tsx (1)
2-2
: Approved: Improved configuration managementThe introduction of
configManager
from "@/dojo/setup" is a positive change. This shift from a static configuration (previouslyEternumGlobalConfig
) 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 assessmentThe modifications to
StructureLabel.tsx
represent a positive step towards improved modularity and configuration management. The shift fromEternumGlobalConfig
to a more specific tick management system usingTickIds
andconfigManager
methods suggests a more flexible approach to handling game timings.Key points:
- The import changes and calculation modifications are consistent and well-implemented.
- The core functionality of the component remains intact.
- 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 centralizationThe changes to the import statements are well-considered:
- Adding
configManager
import centralizes configuration management.- Including
CapacityConfigCategory
andResourcesIds
in the existing import improves type safety.- 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 improvedTransfers
componentThe changes to the
Transfers
component are well-implemented:
- The overall structure and functionality of the component remain intact.
- Configuration retrieval is improved without affecting the component's core logic.
- 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:
- No references to
EternumGlobalConfig
orWEIGHTS_GRAM
remain.- All resource weight retrievals utilize
configManager
.- 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.tsxLength 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.tsxLength 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 ofRESOURCE_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 declaringresourcesInputs
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 managementThe 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 retrievalThe 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 colorThe 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:
- Performance Optimization: Memoize the
pointsForWin
value to prevent unnecessary recalculations.const pointsForWin = useMemo(() => configManager.getHyperstructureConfig().pointsForWin, []);
- 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 configManagerThe changes to the import statements reflect a shift towards using
configManager
for accessing configuration values, which improves modularity and maintainability. The addition ofmultiplyByPrecision
suggests an enhancement in precision handling for calculations.
48-48
: Centralized structure cost managementThe 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 consistencyThe 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:
- Standardized precision handling with
multiplyByPrecision
.- Centralized structure cost management.
- 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 managementThe 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 importsThe 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 configurationThe introduction of
troopConfig
usingconfigManager.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 calculationThe calculation of
maxAmountOfAttackingArmies
has been successfully updated to usetroopConfig
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 displayThe 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 refactoringThe changes in this file demonstrate a well-executed refactoring to use centralized configuration management. The consistent use of
configManager
andtroopConfig
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 usingconfigManager
. 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 usesconfigManager.getResourceWeight(resourceId)
instead of a staticWEIGHTS_GRAM
object. This change:
- Aligns with the new import statements.
- Allows for more dynamic resource weight management.
- Maintains backwards compatibility with the fallback value of 1000.
- 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 ofmultiplyByPrecision
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: ImprovedgetStoreCapacity
method implementation.The changes to the
getStoreCapacity
method are well-implemented:
- Using
multiplyByPrecision
centralizes precision handling.configManager.getCapacityConfig
improves maintainability by removing hard-coded values.- 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:
- Consistent use of
multiplyByPrecision
for precision handling.- 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 ofRESOURCE_INPUTS_SCALED
is a good improvement:
- It aligns with the overall strategy of using
configManager
for resource-related configurations.- This modification enhances maintainability by centralizing resource input configurations.
- 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:
- Centralized precision handling using the
multiplyByPrecision
utility function.- Increased use of
configManager
for resource-related configurations, removing hard-coded values.- 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
, andTickIds
imports from "@bibliothecadao/eternum" and the removal ofEternumGlobalConfig
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 structureThe new structure for the
mercenaries
property in theConfig
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:
- Greater flexibility in mercenary recruitment.
- The ability to introduce variability in mercenary composition.
- 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 interfacesThe changes in this file enhance the game's type system by:
- Improving the configurability of the mercenary system with more granular control over troop counts.
- 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
toconfigManager
. 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
fromconfigManager.getBankConfig().lpFeesDenominator
is consistent with the overall shift towards usingconfigManager
. 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
fromconfigManager.getBankConfig().lpFeesDenominator
aligns with the overall transition to usingconfigManager
. 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
fromconfigManager.getBankConfig().lpFeesDenominator
is in line with the overall transition toconfigManager
. 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
fromconfigManager.getBankConfig().lpFeesDenominator
aligns with the overall transition to usingconfigManager
. 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 MarketManagerThe changes in this file consistently replace
EternumGlobalConfig
withconfigManager
for obtaining the fee rate denominator. This shift towards a more centralized configuration management approach throughconfigManager
can lead to improved maintainability and flexibility in the codebase.Key points:
- Import statements have been updated to reflect the change.
- All methods using
feeRateDenom
now obtain it fromconfigManager.getBankConfig().lpFeesDenominator
.- 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 configManagerThe 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_TYPEThe addition of
DONKEY_ENTITY_TYPE
to the import statement is appropriate, as it's now being used in theuseStructuresFromPosition
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 correctlyThe new import for
configManager
is correctly placed and necessary for the changes in theStepFive
component.
36-36
: Background color change: Verify visual consistencyThe background color has been changed from
bg-black/90
tobg-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: VerifyconfigManager
functionalityThe changes from
EternumGlobalConfig.tick.armiesTickIntervalInSeconds
toconfigManager.getTick(TickIds.Armies)
look good. This update likely improves the flexibility of configuration management in the game.Please ensure that:
- The
configManager.getTick(TickIds.Armies)
method is correctly implemented and returns the expected value.- The
TickIds.Armies
constant is properly defined and imported if necessary.- 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
functionalityAll 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 typescriptLength 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 hardcodedMAX_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
usingconfigManager.getTroopConfig().maxTroopCount
is a good improvement. It replaces the hardcodedMAX_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 offormatNumber
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 managementThe addition of
configManager
and the use ofDONKEY_ENTITY_TYPE
instead ofEternumGlobalConfig
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 consistencyThe 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 experienceThe updates to the MarketOrders component enhance the visual appeal and improve the user experience:
- The market price display now has a more flexible layout with improved padding and rounded corners.
- The background color for the locked resources message has been changed to brown, which likely aligns better with the overall theme.
- 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 ofClientConfigManager
instanceInitializing
configManager
using the singleton instance enhances consistency by ensuring that the configuration is managed centrally.
28-30
: Approved: RetrievingpointsOnCompletion
from configurationFetching
pointsOnCompletion
viaconfigManager
ensures that the point values are centralized and configurable, enhancing maintainability.
32-32
: Consider verifying the accumulation of points for large contributionsWhen calculating total completion points, if
contribution.amount
can be a largebigint
, ensure that summing these values does not introduce precision errors when converted tonumber
.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
andEternumGlobalConfig.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 functionalityThe addition of
configManager
,divideByPrecision
, andtoHexString
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 useTickIds
The import of
TickIds
from@bibliothecadao/eternum
aligns with the updated configuration management approach, enhancing modularity and maintainability.
113-113
: Verify the correctness of theremainingCapacity
checkEnsure that
configManager.getExploreReward()
returns the expected value for this comparison. IfremainingCapacity
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 thatremainingCapacity
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 withconfigManager
Importing
configManager
and using it to retrieve configuration values enhances maintainability by centralizing the configuration logic.
47-48
: Efficient retrieval of stamina costsUsing
configManager.getTravelStaminaCost()
andconfigManager.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 configurationsThe addition of
configManager
improves the component's flexibility by accessing dynamic configuration values.
15-16
: Utility functions imported appropriatelyThe import of
multiplyByPrecision
and other utility functions ensures accurate computations and enhances code reuse.
65-65
: Enhanced precision in amount calculation using multiplyByPrecisionApplying
multiplyByPrecision(amount)
ensures that contribution amounts are correctly scaled according to the system's precision requirements.
86-86
: Replaced static costs with dynamic configurationUtilizing
configManager.hyperstructureTotalCosts
instead of hardcoded values increases maintainability and allows for dynamic updates to hyperstructure costs.
204-204
: Utilized dynamic pointsPerCycle from configManagerSwitching to
configManager.getHyperstructureConfig().pointsPerCycle
ensures consistency with the global configuration and enhances flexibility.sdk/packages/eternum/src/constants/global.ts (4)
11-11
: AddedRESOURCE_RARITY
to importsThe constant
RESOURCE_RARITY
is now imported, making it available for use in this file.
20-21
: New constants for population configuration IDsThe constants
BUILDING_CATEGORY_POPULATION_CONFIG_ID
andPOPULATION_CONFIG_ID
have been added, which will be useful for identifying population-related configurations.
99-104
: Defined mercenary troop count boundsThe lower and upper bounds for mercenary troops (
KNIGHTS
,PALADINS
,CROSSBOWMEN
) have been set appropriately.
133-133
: IncludedresourceRarity
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 ApprovedThe addition of
divideByPrecision
to the imports is appropriate and correctly supports precision handling in balance checks.
201-201
: Proper Calculation of Immunity End TimestampThe calculation of
immunityEndTimestamp
accurately utilizesconfigManager.getBattleGraceTickCount()
andconfigManager.getTick(TickIds.Armies)
to determine the immunity period.
221-228
: Resource Balance Comparison Updated CorrectlyThe
checkBalance
function now properly usesdivideByPrecision
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 CostsReplacing
REALM_UPGRADE_COSTS
withconfigManager.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 forSetupResult
The import of
SetupResult
from@/dojo/setup
is appropriate and necessary for the updated function signatures.
9-9
: Approved: Added Import forAccount
andAccountInterface
The import of
Account
andAccountInterface
from"starknet"
is correct and required for handling account-related functionalities.
74-74
: Approved: Updated Function Signature foruseQuestDependencies
The function
useQuestDependencies
now acceptssetup
andaccount
as parameters, improving modularity and making dependencies explicit.
77-79
: Approved: Entity Query forEntityOwner
The use of
useEntityQuery
withHasValue(setup.components.EntityOwner, { entity_owner_id: structureEntityId || 0 })
is appropriate for fetching entities owned by the specified structure.
83-89
: Approved: Updated Quest Dependencies InitializationThe 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: FunctionuseBuildingQuantities
The function
useBuildingQuantities
with the signature(structureEntityId: ID | undefined)
remains consistent and correctly retrieves building quantities based on the providedstructureEntityId
.client/src/dojo/modelManager/ArmyMovementManager.ts (6)
17-17
: Import statement ofgetComponentValue
andEntity
is appropriate.The import from
@dojoengine/recs
ensures thatgetComponentValue
andEntity
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()
bypathLength
correctly computes the total stamina cost for the travel action.client/src/ui/utils/utils.tsx (1)
1-2
: Imports added forClientComponents
andClientConfigManager
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 ofconfigManager
enhances maintainabilityReplacing 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 undefinedweightConfig
before accessing propertiesIn
getResourceWeight
(lines 224-231), ifweightConfig
isundefined
, accessingweightConfig?.weight_gram
will result inundefined
, and the method will return0
.Ensure that this behavior is intentional and that returning
0
is appropriate whenweightConfig
is not found. If not, consider handling theundefined
case explicitly.Run the following script to verify if any
weightConfig
instances could beundefined
:client/src/dojo/contractComponents.ts (3)
554-560
: Addition of new properties inHyperstructureConfig
is correctThe new properties
points_per_cycle
,points_for_win
, andpoints_on_completion
are appropriately added with correct typesRecsType.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 correctlyThe
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 inTroopConfig
updated correctlyThe
types
array in the metadata has been updated to include the new propertymax_troop_count
, with the type"u64"
, which accurately reflects the property's typeRecsType.Number
.client/src/ui/components/hints/WorldStructures.tsx (2)
1-1
: Import statement added correctlyThe
configManager
is properly imported from"@/dojo/setup"
, ensuring access to configuration data.
91-93
: Dynamic configuration enhances flexibilityUsing
configManager.getHyperstructureConfig().pointsPerCycle
ensures that the points per tick are dynamically retrieved, improving maintainability by avoiding hard-coded values.
const buildingPopulation = configManager.getBuildingPopConfig(building).population; | ||
const basePopulationCapacity = configManager.getBasePopulationCapacity(); | ||
|
||
return (realm?.population || 0) + buildingPopulation <= basePopulationCapacity + (realm?.capacity || 0); |
There was a problem hiding this comment.
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"; |
There was a problem hiding this comment.
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
Number(resourceQuantity / BigInt(configManager.getResourcePrecision())) * | ||
configManager.getResourceRarity(resourceType); | ||
const totalContributableAmount = configManager.getHyperstructureTotalContributableAmount(); | ||
|
||
return effectiveContribution / totalContributableAmount; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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[]) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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; |
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: [], | ||
}, | ||
}, | ||
); | ||
})(), |
There was a problem hiding this comment.
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.
RealmMaxLevelConfig: (() => { | ||
return defineComponent( | ||
world, | ||
{ config_id: RecsType.Number, max_level: RecsType.Number }, | ||
{ | ||
metadata: { | ||
namespace: "eternum", | ||
name: "RealmMaxLevelConfig", | ||
types: ["u32", "u8"], | ||
customTypes: [], | ||
}, | ||
}, | ||
); | ||
})(), |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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
usesmaxTroopCount
instead ofmax_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
const constructionCost = configManager.structureCosts[StructureType.Hyperstructure] | ||
.filter((cost) => cost.resource !== ResourcesIds["AncientFragment"]) | ||
.map((cost) => ({ ...cost })); |
There was a problem hiding this comment.
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.
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"]); |
const creationCost = configManager.structureCosts[structureId] | ||
.filter((cost) => cost.resource === ResourcesIds["AncientFragment"]) | ||
.map((cost) => ({ | ||
...cost, | ||
})); |
There was a problem hiding this comment.
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.
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"]); |
…ource-prod-fragment-mines
…nt-mines fix: resource prod fragment mines
There was a problem hiding this 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
: NewtimeUntilFinishTick
method addedThe 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
: NewbalanceFromComponents
method addedThe 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 ofresourceId: 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 addedThe addition of the
_calculateBalance
method is a significant improvement:
- It centralizes the balance calculation logic, improving maintainability.
- It handles both positive and negative net rates correctly.
- It considers store capacity and resource weight in calculations.
- 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
anddivideByPrecision
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
📒 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 withmultiplyByPrecision
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
: ImprovedgetStoreCapacity
methodThe refactoring of the
getStoreCapacity
method is a good improvement:
- Using
multiplyByPrecision
centralizes precision handling.- The logic for calculating store capacity has been simplified.
- 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
methodThe refactoring of the
_balance
method is a good improvement:
- It simplifies the method by delegating the calculation to
_calculateBalance
.- This change reduces code duplication and improves maintainability.
- 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
methodThe change from
RESOURCE_INPUTS_SCALED
toconfigManager.resourceInputs
is a good improvement:
- It suggests a more flexible approach to managing resource inputs.
- 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 ofresourceInputs
:#!/bin/bash # Search for the initialization of resourceInputs in configManager rg 'resourceInputs\s*=' --type typescript
32-32
: SimplifiednetRate
method signatureThe removal of the
currentTick
parameter from thenetRate
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 fromnetRate
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 typescriptLength 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
andTickIds
imports, along withREALM_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 configurabilityThe changes in this file significantly enhance the resource management capabilities and configurability of the BuildingEntityDetails component. Key improvements include:
- More precise resource calculations using
divideByPrecision
.- Increased flexibility in timing logic with the use of
configManager
andTickIds
.- Improved maintainability through the use of constants like
REALM_MAX_LEVEL
.- 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.
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), | ||
); |
There was a problem hiding this comment.
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.
private getRemainingPercentageOfTroops(current_troops: bigint, lifetime_troops: bigint): number { | ||
if (lifetime_troops === 0n) return 0; | ||
return Number(current_troops) / Number(lifetime_troops); | ||
} |
There was a problem hiding this comment.
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]>
There was a problem hiding this 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:
- Any documentation that references the katana or torii versions.
- CI/CD pipelines that might be using these versions.
- README files or setup instructions for developers.
- 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
⛔ 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
: Updatedset_mercenaries_config
function signatureThe
set_mercenaries_config
function signature has been updated. Instead of accepting a singletroops
parameter of typeTroops
, 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 configurationThe 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 theset_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 structThe
MercenariesConfig
struct has been updated to include separate fields for lower and upper bounds of each troop type (knights, paladins, crossbowmen) instead of a singletroops
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 fileThe changes in this manifest file reflect a comprehensive update to the contract system:
- New deployments of multiple contracts, including the World contract and various other contracts, as evidenced by updated addresses and class hashes.
- Modification of the
MercenariesConfig
struct and related functions to provide more granular control over troop configurations.- Renaming of the
contract_name
function toname
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 cairoThese verifications will help ensure that the changes have been applied consistently across the entire codebase.
31925-31926
: Updated class hash for MercenariesConfigThe
class_hash
andoriginal_class_hash
for theMercenariesConfig
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 detailsThe
address
,transaction_hash
, andblock_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 cairoLength 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 goLength of output: 255
4-5
: Updated class hashes for the World contractThe
class_hash
andoriginal_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 incontracts/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 jsonLength of output: 430
Script:
#!/bin/bash # Corrected script to search for the new class hash in JSON files rg "0x6f38d5d9507c5d9546290e1a27e309efe5a9af3770b6cc1627db4a1b90a7dce" --type jsonLength of output: 363
1292-1292
: Updated function name fromcontract_name
toname
The function name has been changed from
contract_name
toname
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 contractsThe
address
,class_hash
, andoriginal_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 fromv1.0.0-alpha.12
tov1.0.0-alpha.16
is noted. This change seems intentional and follows semantic versioning.To ensure smooth integration:
- Review the changelog for
dojo
between these versions to understand new features or breaking changes.- Verify that your project is compatible with this new version, especially considering it's an alpha release.
- 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 thoroughlyThe 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:
- Verify that v1.0.0-alpha.16 is the intended version for this update.
- Review the changelog or release notes for Dojo v1.0.0-alpha.16 to understand the changes introduced.
- Ensure all tests pass with the new version.
- 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 updatedThe 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 restructuredThe MercenariesConfig model has been significantly restructured:
- The 'troops' field has been removed.
- 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 updatedThe 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 updateThis manifest file has undergone significant changes, including:
- Updated world configuration
- Updated contract configurations with new class hashes and addresses
- 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.txtLength 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 trapLength of output: 7018
Summary by CodeRabbit
Release Notes
New Features
DefenderPresent
to improve claimability logic in battle management.divideByPrecision
for enhanced resource management in the building entity details.timeUntilFinishTick
in theProductionManager
for better production timing calculations.Bug Fixes
BattleManager
.BattleActions
component to prevent unhandled promise rejections.UI Improvements
ResourceChip
component for more dynamic balance calculations.BattleActions
component.Chores