Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rc 1 #1851

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

Rc 1 #1851

wants to merge 90 commits into from

Conversation

ponderingdemocritus
Copy link
Contributor

@ponderingdemocritus ponderingdemocritus commented Oct 15, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a new status DefenderPresent to improve claimability logic in battle management.
    • Introduced a new utility function divideByPrecision for enhanced resource management in the building entity details.
    • Added a new method timeUntilFinishTick in the ProductionManager for better production timing calculations.
    • Added new components for troop configuration, including RealmLevelConfig, RealmMaxLevelConfig, and TravelFoodCostConfig.
    • Enhanced the Hyperstructure model with a new access control mechanism, allowing for Public, Private, and GuildOnly access levels.
    • Implemented a new Season struct for managing seasonal state within the game.
    • Updated the SettleRealm struct to reflect changes in resource representation.
    • Integrated account-specific data into the quest management system for improved accuracy of quest statuses.
    • Introduced the BattleInfoLabel component to display ongoing battle information on the map.
    • Added the SelectedArmy component for improved army selection management.
  • Bug Fixes

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

    • Enhanced resource handling in the ResourceChip component for more dynamic balance calculations.
    • Minor adjustments to UI elements for better presentation, including updates to the BattleActions component.
    • Added conditional rendering in the QuestInfo component to provide contextual navigation information based on quest properties.
    • Updated the Battle component to use the new BattleProgress component for improved battle progress visualization.
  • Chores

    • Removed unused imports and streamlined hooks for better performance.
    • Updated the version of the Dojo dependency in configuration files.
    • Updated environment variables in deployment scripts for better contract management.
    • Added new entries to the .gitignore file to prevent sensitive information from being tracked.

Copy link

vercel bot commented Oct 15, 2024

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

Name Status Preview Comments Updated (UTC)
eternum ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 22, 2024 6:55pm

Copy link
Contributor

mentatbot bot commented Oct 15, 2024

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

Copy link
Contributor

coderabbitai bot commented Oct 15, 2024

Walkthrough

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

Changes

File Path Change Summary
client/src/dojo/modelManager/BattleManager.ts Added DefenderPresent to ClaimStatus enum; removed battleIsClaimable property; streamlined isClaimable method logic.
client/src/dojo/modelManager/__tests__/BattleManager.test.ts Updated test cases for isClaimable and isAttackable methods to reflect new claimability logic, including checks for defender presence.
client/src/dojo/modelManager/ProductionManager.ts Introduced multiplyByPrecision utility; refactored getStoreCapacity method; updated resource input handling; added timeUntilFinishTick method.
client/src/ui/modules/entity-details/BuildingEntityDetails.tsx Added divideByPrecision utility; replaced REALM_UPGRADE_COSTS with configManager.realmUpgradeCosts; updated CastleDetails component logic.
client/src/ui/modules/military/battle-view/BattleActions.tsx Updated state initialization, effect dependencies, and error handling in asynchronous functions; streamlined loading state management.
client/src/ui/components/resources/ResourceChip.tsx Updated imports and balance calculations; introduced useEffect for dynamic balance updates; simplified netRate calculation.
.github/workflows/test-contracts.yml Introduced a new GitHub Actions workflow for testing season pass contracts.
.gitignore Added entries for target and .snfoundry_cache directories to be ignored by Git.
.tool-versions Updated dojo package version from 1.0.0-alpha.12 to 1.0.0-alpha.17.
client/.env.preview Updated VITE_PUBLIC_WORLD_ADDRESS variable with a new Ethereum address.
client/.env.production Updated VITE_PUBLIC_WORLD_ADDRESS and added new environment variables for season pass, realms, and lords addresses.
client/src/data/orders.ts Restructured order_statments array, adding and removing several statements.
client/src/dojo/contractComponents.ts Enhanced Hyperstructure component with new properties; added new components for realm and travel configurations.
client/src/dojo/modelManager/__tests__/__BattleManagerMock__.ts Added generateMockTroopConfig function for troop management configuration.
client/src/hooks/helpers/useRealm.tsx Updated resource handling logic and population capacity calculations using configManager.
client/src/hooks/helpers/useStructures.tsx Updated logic for calculating travel time and resources to reflect changes in imports and resource handling.
client/src/ui/components/cityview/realm/SettleRealmComponent.tsx Simplified settleRealms function logic for creating calldata.
client/src/ui/components/construction/SelectPreviewBuilding.tsx Refactored building costs retrieval to use configManager; updated styling for BuildingCard.
client/src/ui/components/resources/RealmResourcesIO.tsx Streamlined resource consumption logic by centralizing input data through configManager.
client/src/ui/components/trading/RealmProduction.tsx Updated logic for filtering consumed resources to utilize configManager.
client/src/ui/utils/packedData.tsx Simplified unpackResources function and standardized naming of constants related to bit sizes.
config/index.ts Introduced checks for required environment variables and updated logic for selecting manifest files.
contracts/.tool-versions Updated dojo dependency version from 1.0.0-alpha.12 to 1.0.0-alpha.17.
contracts/src/models/hyperstructure.cairo Updated Hyperstructure struct to use Access enum for access control; added assert_access method for validation.
contracts/src/models/season.cairo Introduced a new Season struct for managing the state of a season.
contracts/src/models/structure.cairo Enhanced Structure and StructureCount models with new validation and conversion methods.
contracts/src/systems/bank/contracts/bank.cairo Updated methods to utilize new SeasonImpl for season validation.
contracts/src/systems/combat/contracts.cairo Transitioned to SeasonImpl for season validation across multiple combat-related functions.
discord-bot/src/events.rs Updated SettleRealm struct to reflect changes in resource representation.
discord-bot/src/types.rs Modified event parsing logic for SettleRealm to accommodate new data structure.
client/src/dojo/modelManager/TileManager.ts Enhanced resource type management in the _optimisticBuilding method.
client/src/hooks/helpers/useQuests.tsx Updated quest management logic to integrate account information.
client/src/ui/components/quest/QuestInfo.tsx Added new logic for displaying navigation instructions based on quest properties.
client/src/ui/components/quest/questDetails.tsx Enhanced quest details with dynamic configuration retrieval and improved formatting.

Possibly related PRs

  • fix: claim on structures + selected army #1847: This PR directly modifies the BattleManager class, adding the DefenderPresent status to the ClaimStatus enum and updating the isClaimable method, which aligns closely with the changes made in the main PR regarding claimability logic.
  • fix: local selected unit #1839: This PR involves modifications to the BattleActions component, which is closely tied to the battle mechanics being refined in the main PR, particularly in how battles and claims are managed.
  • client: battle time fix #1827: While this PR focuses on displaying battle time, it is related to the overall battle management system, which is a context in which the changes in the main PR are applied. However, the connection is more indirect compared to the others.

🐰 In the fields where battles rage,
A new status takes the stage.
Defender present, claims refined,
In the code, clarity we find.
With each change, our world will grow,
A rabbit's hop to victory's glow! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

fix: claim on structures + selected army
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
client/src/ui/components/quest/QuestInfo.tsx (1)

71-84: LGTM: New conditional rendering for navigation instructions

The addition of this block enhances the user experience by providing contextual navigation information based on the quest's view property and the current view state. The logic is sound and the use of conditional icons is intuitive.

Consider extracting the icon rendering logic into a separate component or function to improve readability. For example:

const NavigationIcon = ({ isCorrectView }: { isCorrectView: boolean }) => 
  isCorrectView ? <Check /> : <ShieldQuestion />;

// Usage in JSX
<NavigationIcon isCorrectView={(isMapView && quest.view === "WORLD") || (!isMapView && quest.view === "REALM")} />

This would make the main component's JSX cleaner and more focused on structure rather than logic.

client/src/ui/components/quest/questDetails.tsx (1)

Line range hint 219-294: Refactor duplicated code into a reusable component

The JSX code for the "Travel" and "Explore" sections in the quest description contains duplicated structures, particularly the tables displaying stamina costs and resource consumption per unit. Duplicated code can lead to maintenance challenges and inconsistencies in the future. Consider extracting the common elements into a reusable React component or function. This adheres to the DRY (Don't Repeat Yourself) principle and enhances maintainability and readability.

For example, you might create a FoodCostTable component that accepts props for the different configurations and renders the table accordingly.

Also applies to: 295-352

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d8c4cbf and a7bd7df.

📒 Files selected for processing (3)
  • client/src/hooks/helpers/useQuests.tsx (4 hunks)
  • client/src/ui/components/quest/QuestInfo.tsx (3 hunks)
  • client/src/ui/components/quest/questDetails.tsx (19 hunks)
🧰 Additional context used
🔇 Additional comments (15)
client/src/ui/components/quest/QuestInfo.tsx (3)

2-2: LGTM: New import for useQuery hook

The addition of the useQuery hook import is appropriate for the new functionality introduced in the component.


22-23: LGTM: Destructuring isMapView from useQuery hook

The addition of isMapView from the useQuery hook is appropriate for determining the current view state in the component.


Line range hint 1-138: Summary: Enhancements to QuestInfo component

The changes to this file successfully introduce new functionality to the QuestInfo component:

  1. The addition of the useQuery hook import and isMapView variable provides a way to determine the current view state.
  2. The new conditional rendering block enhances user experience by providing contextual navigation instructions based on the quest's view property and the current view state.

These modifications improve the component's interactivity and user-friendliness without introducing any apparent issues. The changes are well-integrated with the existing component structure.

client/src/hooks/helpers/useQuests.tsx (10)

1-2: Imports are appropriately added

The new imports from "@/dojo/modelManager/TileManager" and "@/dojo/setup" are correct and necessary for the updated functionalities.


9-9: Importing 'Account' and 'AccountInterface'

Successfully importing Account and AccountInterface from starknet allows for proper typing and usage within the file.


18-18: Added 'view' property to 'Quest' interface

Adding view: string; to the Quest interface enhances the quest data structure, potentially allowing for better rendering or identification of quests.


39-41: Note: Previous comment still applies regarding 'account.account'

Please refer to the previous review comment about the usage of account.account in line 41. Ensure that account.account is the correct value to pass to useQuestDependencies.


75-75: Updated 'useQuestDependencies' function signature

The function useQuestDependencies now accepts setup and account as parameters, which improves its modularity and allows for better control over the dependencies.


78-80: Verify handling of 'structureEntityId' when undefined

In line 79, entity_owner_id is set to structureEntityId || 0. Please ensure that passing 0 as entity_owner_id when structureEntityId is undefined is appropriate and does not lead to unintended query results or errors in useEntityQuery.


81-83: Note: Previous comment still applies regarding 'account.address'

Please refer to the previous review comment about ensuring account.address is defined before converting it to BigInt in line 82.


84-84: Ensure 'structureEntityId' validity in 'useBuildingQuantities'

In line 84, structureEntityId is passed to useBuildingQuantities. Verify that passing undefined or 0 as structureEntityId does not cause issues within useBuildingQuantities and that defaulting to 0 is acceptable in this context.


85-85: Validate usage of 'structureEntityId || 0' in 'useArmiesByEntityOwner'

In line 85, entity_owner_entity_id is assigned structureEntityId || 0. Ensure that using 0 when structureEntityId is undefined is suitable and that the function useArmiesByEntityOwner handles this case without errors.


90-90: Confirm default position when 'structureEntityId' is undefined

In line 90, if getEntityInfo(structureEntityId) returns undefined, structurePosition defaults to { x: 0, y: 0 }. Please verify that this default position is appropriate and does not cause issues in subsequent logic, especially in functions that rely on accurate positional data.

client/src/ui/components/quest/questDetails.tsx (2)

386-389: The typo in the description still exists. Please refer to the previous review comment regarding the correction of "You realm" to "Your realm" to fix this issue.


409-410: The inline expression {configManager.getCapacityConfig(CapacityConfigCategory.Donkey) / 1000} kg is not wrapped in an element, which might cause rendering issues. Please refer to the previous review comment about wrapping this expression in a <span> or another inline element for proper rendering.

import clsx from "clsx";
import { ResourceWeight } from "../resources/ResourceWeight";

interface StaticQuestInfo {
name: string;
view: string;
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Make 'view' property optional if not required for all quests

Currently, the view property is added to the StaticQuestInfo interface as a required field. Since some quests do not utilize this property (evidenced by it being set to an empty string ""), consider making the view property optional. This can be achieved by declaring it as view?: string;. This change enhances code clarity by allowing quests that do not need a view specification to omit the property altogether.

Apply this diff to make the view property optional:

 interface StaticQuestInfo {
   name: string;
-  view: string;
+  view?: string;
   description: string | React.ReactNode;
   steps: (string | React.ReactNode)[];
   prizes: Prize[];
   depth: number;
 }
📝 Committable suggestion

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

Suggested change
view: string;
interface StaticQuestInfo {
name: string;
view?: string;
description: string | React.ReactNode;
steps: (string | React.ReactNode)[];
prizes: Prize[];
depth: number;
}

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (7)
client/src/ui/components/construction/SelectPreviewBuilding.tsx (5)

Line range hint 37-280: Consider optimizing SelectPreviewBuildingMenu component

The changes to use configManager for resource and building cost calculations are good improvements. However, the component is quite large and complex. Consider breaking it down into smaller, more manageable sub-components to improve readability and maintainability.

Consider extracting the tab content generation logic into separate components. For example:

const ResourcesTab = ({ realmResourceIds, entityId, /* other props */ }) => {
  // ... existing logic for resources tab
};

const EconomicTab = ({ buildingTypes, entityId, /* other props */ }) => {
  // ... existing logic for economic tab
};

// ... similar components for other tabs

// Then in the main component:
const tabs = [
  {
    key: "resources",
    label: /* ... */,
    component: <ResourcesTab realmResourceIds={realmResourceIds} entityId={entityId} /* other props */ />,
  },
  // ... other tabs
];

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


Line range hint 393-515: Improved resource management in ResourceInfo component

The use of configManager for retrieving resource costs, building configurations, and resource outputs is a significant improvement. This centralization will make future updates easier and more consistent.

Consider memoizing the result of getResourceBuildingCosts to optimize performance, especially if this component is rendered frequently:

const buildingCost = useMemo(() => 
  getResourceBuildingCosts(entityId ?? 0, dojo, resourceId) ?? [],
  [entityId, dojo, resourceId]
);

This can help prevent unnecessary recalculations if the component re-renders without these dependencies changing.


Line range hint 517-644: Improved building information management in BuildingInfo component

The use of configManager for retrieving building configurations, costs, and resource production information is a positive change. This aligns well with the centralized configuration management approach.

Consider memoizing complex calculations or function calls that depend on props to optimize performance:

const buildingCost = useMemo(() => 
  getBuildingCosts(entityId ?? 0, dojo, buildingId) || [],
  [entityId, dojo, buildingId]
);

const resourceProduced = useMemo(() => 
  configManager.getResourceBuildingProduced(buildingId),
  [buildingId]
);

const ongoingCost = useMemo(() => 
  resourceProduced !== undefined ? configManager.resourceInputs[resourceProduced] || 0 : 0,
  [resourceProduced]
);

This can help prevent unnecessary recalculations, especially if this component is rendered frequently or as part of a list.


Line range hint 646-706: Improved utility functions with centralized configuration

The updates to getConsumedBy, getResourceBuildingCosts, and getBuildingCosts to use configManager are good improvements. They contribute to more consistent and maintainable code.

Consider optimizing the cost calculation logic in getResourceBuildingCosts and getBuildingCosts:

  1. The scaleFactor calculation (Math.max(0, buildingQuantity ?? 0 - 1)) is repeated in both functions. Consider extracting this into a separate utility function.

  2. The cost calculation formula is identical in both functions. You could create a generic function for this calculation:

const calculateCost = (baseCost: number, percentIncrease: number, quantity: number) => {
  const percentageAdditionalCost = (baseCost * (percentIncrease / 100)) / 100;
  const scaleFactor = Math.max(0, quantity - 1);
  return baseCost + scaleFactor * scaleFactor * percentageAdditionalCost;
};

Then use this function in both getResourceBuildingCosts and getBuildingCosts. This would reduce code duplication and make future updates easier.


Line range hint 724-755: Consider refactoring resourceIdToBuildingCategory to use centralized configuration

While this function wasn't changed in this update, consider refactoring it to align with the centralized configuration approach used elsewhere in the file.

You could potentially replace this function with a configuration map in configManager:

// In configManager
export const resourceIdToBuildingCategoryMap = {
  [ResourcesIds.Wheat]: BuildingType.Farm,
  [ResourcesIds.Fish]: BuildingType.FishingVillage,
  // ... other mappings
};

// Then replace the function with:
const resourceIdToBuildingCategory = (resourceId: ResourcesIds): BuildingType => {
  return configManager.resourceIdToBuildingCategoryMap[resourceId] || BuildingType.None;
};

This approach would centralize this mapping, making it easier to maintain and update in the future.

client/src/dojo/modelManager/ConfigManager.ts (2)

427-431: Integer division might lead to loss of precision

In getHyperstructureTotalContributableAmount(), you're summing up products of resource rarity and amount, both of which might be floating-point numbers. Ensure that the calculation accounts for decimal precision to avoid rounding errors that could affect gameplay balance.


499-506: Clarify units for base_cost_percent_increase

In getBuildingBaseCostPercentIncrease(), the value returned might represent a percentage. Ensure that the documentation or variable naming clarifies whether this value is a fraction (e.g., 0.1 for 10%) or an integer percentage (e.g., 10 for 10%). This can prevent confusion and potential miscalculations in cost scaling.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a7bd7df and e7e5e41.

📒 Files selected for processing (2)
  • client/src/dojo/modelManager/ConfigManager.ts (1 hunks)
  • client/src/ui/components/construction/SelectPreviewBuilding.tsx (14 hunks)
🧰 Additional context used
🔇 Additional comments (10)
client/src/ui/components/construction/SelectPreviewBuilding.tsx (3)

Line range hint 1-35: Improved configuration management with configManager

The introduction of configManager and the removal of hardcoded constants is a positive change. This centralization of configuration management can lead to easier maintenance and updates in the future. The use of divideByPrecision also suggests a more consistent approach to handling resource calculations.


Line range hint 282-391: Approved styling changes in BuildingCard

The styling changes from bg-black to bg-brown are minor but contribute to consistent theming. The component's logic remains unchanged, which is good for maintaining stability.


Line range hint 1-755: Overall improvements in configuration management and code structure

The refactoring efforts in this file have significantly improved the code's maintainability and consistency. The introduction of configManager and the removal of hardcoded constants centralize configuration management, which will make future updates easier and less error-prone.

Key improvements:

  1. Centralized configuration management with configManager
  2. Consistent approach to resource and building cost calculations
  3. Improved modularity in some components

Areas for potential further improvement:

  1. Breaking down large components into smaller, more manageable pieces
  2. Optimizing performance with memoization in complex calculations
  3. Further refactoring of utility functions to reduce code duplication

Overall, these changes represent a positive step towards a more maintainable and scalable codebase.

client/src/dojo/modelManager/ConfigManager.ts (7)

34-39: Initialization methods are properly invoked

All initialization methods are correctly called in the setDojo method, ensuring that the configuration data is loaded when the components are set.


50-55: Good use of a helper method to handle defaults

The getValueOrDefault method provides a clean way to handle cases where components might not be available, ensuring that default values are returned without repetitive null checks.


254-260: Verify the default value for getExploreReward

In the getExploreReward() method, the default value returned is 0 when the exploreConfig is undefined. Please verify if 0 is the appropriate default value for the explore reward, or if it should be a positive number to reflect expected gameplay mechanics.


234-242: Confirm default stamina cost values

In the methods getTravelStaminaCost() and getExploreStaminaCost(), the default value returned is 1 when the stamina configuration is undefined. Please confirm whether 1 is the intended default value for stamina costs, or if it should be adjusted to align with game balance considerations.


477-485: Consistency in default values for stamina configuration

In getTroopStaminaConfig(), the default value returned is 0 if the stamina configuration is undefined. Verify if 0 is appropriate as a default maximum stamina for troops, or if it should be a positive value to prevent troops from being unusable.


487-489: Resource rarity retrieval is clear and efficient

The getResourceRarity method effectively retrieves the rarity of a resource using the global configuration, enhancing readability and maintainability.


170-175: ⚠️ Potential issue

Ensure valid resource type for building configuration

In the initializeBuildingCosts() method, the resourceType is obtained using getResourceBuildingProduced, which may return 0 if the building type is not found in the buildingResourceProduced configuration. This could lead to fetching the wrong buildingConfig or an undefined one. Please ensure that resourceType is valid before proceeding, and handle cases where it might be 0 or invalid.

Consider adding a check to validate resourceType:

+ if (!resourceType) {
+   continue;
+ }

Comment on lines +443 to +451
return this.getValueOrDefault(() => {
const productionConfig = getComponentValue(
this.components.ProductionConfig,
getEntityIdFromKeys([BigInt(resourceType)]),
);

return Number(productionConfig?.amount ?? 0);
}, 0);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential inconsistency in resource output amounts

The getResourceOutputs method returns the amount from the ProductionConfig component without dividing by the resource precision. In other places, such as line 78 and 258, divideByPrecision is used when handling resource amounts. Consider applying divideByPrecision here for consistency and to ensure accurate calculations.

Apply this diff to address the inconsistency:

- return Number(productionConfig?.amount ?? 0);
+ return divideByPrecision(Number(productionConfig?.amount ?? 0));

Committable suggestion was skipped due to low confidence.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e7e5e41 and 20b6995.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (4)
  • client/src/ui/components/bank/LiquidityTable.tsx (1 hunks)
  • pnpm-workspace.yaml (1 hunks)
  • scripts/indexer.sh (2 hunks)
  • season_pass/scripts/deployment/.gitignore (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • season_pass/scripts/deployment/.gitignore
🧰 Additional context used
🔇 Additional comments (4)
pnpm-workspace.yaml (1)

8-8: LGTM: New package added to workspace

The addition of "season_pass/scripts/deployment" to the workspace packages is approved. This change aligns with the new functionality for building and deploying the "Eternum Season Pass Contract" mentioned in the pull request summary.

To ensure this change is reflected in the build process, please run the following script:

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

30-35: Improved code readability

The reformatting of the filter function enhances code readability while maintaining the same functionality. This change makes the code easier to understand and maintain.

scripts/indexer.sh (2)

38-40: Ensure cross-platform compatibility of sed -i commands

The sed -i '' syntax used in lines 38-40 is specific to BSD sed (commonly found on macOS). On GNU sed (commonly found on Linux), this syntax will cause an error due to the differing requirements for the -i (in-place edit) option.


48-48: Re-evaluate directory changes for script consistency

After executing the deployment scripts, the command cd ../../../ on line 48 may not return to the expected directory, depending on the nested depths of previous cd commands. This could potentially cause errors in subsequent commands.

@@ -35,4 +70,4 @@ fi

echo "----- Started indexer ----- "
rm torii.db
torii --world 0x76ca3dfc3e96843716f882546f0db96b7da0cf988bdba284b469d0defb2f48f --database torii.db --allowed-origins "*"
torii --world 0x320b2713e324fe3125bbc42d85ff69cb3c0908b436fa38a35746dbc45deeb11 --database torii.db --allowed-origins "*"
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid hardcoding the world address in the torii command

The torii command on line 73 uses a hardcoded --world address. To enhance maintainability and flexibility, consider using a variable or sourcing the address from an environment file. This approach makes it easier to update the address without modifying the script.

Apply this diff to use an environment variable:

-torii --world 0x320b2713e324fe3125bbc42d85ff69cb3c0908b436fa38a35746dbc45deeb11 --database torii.db --allowed-origins "*"
+WORLD_ADDRESS=0x320b2713e324fe3125bbc42d85ff69cb3c0908b436fa38a35746dbc45deeb11
+torii --world $WORLD_ADDRESS --database torii.db --allowed-origins "*"

Alternatively, source the WORLD_ADDRESS from an environment file:

# At the beginning of the script
source ./path/to/env_file

# Use the sourced variable
torii --world $WORLD_ADDRESS --database torii.db --allowed-origins "*"

* [client] show battle info on hover
Fixes #1865

* fix bug

* fix not clear hex

* show multiple battles

* add siege

* fix structure siege

* latest manifests
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 22

🧹 Outside diff range and nitpick comments (34)
season_pass/scripts/deployment/.env.example (3)

2-3: LGTM! Remember to update for production.

The local RPC and Starknet network configuration is appropriate for development.

Consider adding a comment to remind users to update these values for production deployment.


7-8: LGTM! Clear instructions for production deployment.

The separation of dev and prod address folders and the inclusion of an admin address are good practices.

Consider these minor improvements:

  1. Use a placeholder for the SEASON_PASS_ADMIN (e.g., <PRODUCTION_ADMIN_ADDRESS>).
  2. Add a comment explaining the significance of the SEASON_PASS_ADMIN role.

1-8: Overall, good template with room for improvement.

This .env.example file provides a helpful template for setting up the deployment environment. However, there are opportunities to enhance security practices and documentation.

General recommendations:

  1. Use placeholders for all sensitive information, even in example files.
  2. Add more detailed comments explaining the purpose and impact of each variable.
  3. Consider splitting the configuration into separate files for different environments (dev, staging, prod) to minimize the risk of using incorrect settings.
  4. Implement a secure secret management solution for handling sensitive data in production environments.
🧰 Tools
🪛 Gitleaks

5-6: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

contracts/Scarb.toml (1)

20-20: Consider adding configurations to the [profile.prod] section.

The addition of a production profile is a good practice. However, the section is currently empty. Consider adding any necessary production-specific configurations to this section.

client/.env.preview (1)

Line range hint 1-13: Review environment variable management and security practices.

While the changes to VITE_PUBLIC_WORLD_ADDRESS and VITE_PUBLIC_ACCOUNT_CLASS_HASH appear intentional, there are some general concerns:

  1. This file contains sensitive information (e.g., private keys). Consider using a secrets management system instead of storing these directly in environment files.
  2. Ensure that the preview environment is properly isolated from production and that these changes don't inadvertently affect other environments.
  3. Review your process for updating and managing environment variables across different deployment stages (development, preview, production) to maintain consistency and security.

Consider implementing a secrets management solution and reviewing your DevOps practices for handling environment-specific configurations.

🧰 Tools
🪛 Gitleaks

2-2: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

contracts/src/systems.cairo (1)

63-67: LGTM! Consider adding documentation for the new ownership module.

The addition of the ownership module follows the established structure and best practices of the project. It includes both contracts and tests submodules, which is consistent with other modules in the file.

Consider adding a brief comment above the ownership module to describe its purpose and functionality within the system. This would enhance code readability and maintainability.

client/.env.sample (4)

15-15: New environment variable added: VITE_SEASON_PASS_ADDRESS

The addition of this variable is consistent with the existing naming conventions and likely corresponds to a new feature or integration.

Consider adding a comment explaining the purpose of this variable and how it's used in the application. This will help other developers understand its significance.


16-16: New environment variable added: VITE_REALMS_ADDRESS

The addition of this variable is consistent with the existing naming conventions and likely corresponds to a feature or integration related to realms in the application.

Consider adding a comment explaining the purpose of this variable and how it's used in the application. This will help other developers understand its significance.


17-17: New environment variable added: VITE_LORDS_ADDRESS

The addition of this variable is consistent with the existing naming conventions and likely corresponds to a feature or integration related to "lords" in the application.

Consider adding a comment explaining the purpose of this variable and how it's used in the application. This will help other developers understand its significance.


Line range hint 1-18: Summary of changes to environment variables

The changes to this file include updates to existing variables and the addition of new ones, likely as part of a larger update or feature addition to the application. While the additions are consistent with existing conventions, there are two main points to address:

  1. Security: The presence of a private key in the VITE_PUBLIC_MASTER_PRIVATE_KEY variable poses a security risk. Consider removing sensitive information from this sample file and implementing a more secure method for managing such data.

  2. Documentation: The newly added variables (VITE_SEASON_PASS_ADDRESS, VITE_REALMS_ADDRESS, and VITE_LORDS_ADDRESS) would benefit from comments explaining their purpose and usage in the application.

Addressing these points will improve the security and maintainability of the project.

🧰 Tools
🪛 Gitleaks

2-2: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


6-6: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

client/src/hooks/store/useBlockchainStore.tsx (2)

47-47: Consider removing console.log statement

While logging can be useful during development, it's generally not recommended to leave console.log statements in production code. Consider removing or commenting out this line before merging to production.


Line range hint 50-56: Simplified timestamp logic, but consider optimization

The simplification of the timestamp fetching logic is good. However, updating the state on every interval, regardless of whether the timestamp has changed, could lead to unnecessary re-renders. Consider adding a check to only update the state if the new timestamp is different from the previous one.

Example:

const timestamp = Math.floor(Date.now() / 1000);
if (timestamp && timestamp !== previousTimestamp) {
  setNextBlockTimestamp(timestamp);
  // ... other state updates
}
contracts/src/utils/testing/constants.cairo (1)

64-67: LGTM: New function for ownership system models.

The ownership_systems_models function provides a centralized way to define models used in ownership systems, which is good for maintainability and configuration. The use of class hashes allows for dynamic loading of these models.

Consider updating the comment to be more specific:

-// SET ALL MODELS USED PER SYSTEM
+// Define all models used in ownership systems

This change would make the purpose of the function clearer and more aligned with its name.

contracts/src/systems/ownership/tests.cairo (4)

19-36: LGTM: Setup function is comprehensive.

The setup function initializes the testing environment thoroughly, covering world spawning, system deployment, and initial state setting. It provides a solid foundation for the subsequent tests.

Consider adding a brief comment explaining the purpose of setting the initial season, as its relevance to ownership tests isn't immediately clear.


39-49: LGTM: Ownership transfer test is functional.

The test effectively verifies the basic flow of ownership transfer. It correctly sets up the environment, executes the transfer, and checks the result.

Consider enhancing the test with the following:

  1. Check for any events emitted during the ownership transfer.
  2. Verify that the old owner no longer has ownership rights.
  3. Test boundary conditions, such as transferring to the zero address or the current owner.

52-60: LGTM: Non-owner transfer test is correctly implemented.

The test effectively verifies that non-owners cannot transfer ownership, using the #[should_panic] attribute to expect a specific error message.

Consider enhancing the test with the following:

  1. After the failed transfer attempt, verify that the owner hasn't changed.
  2. Test with different non-owner addresses to ensure consistent behavior.
  3. Consider adding a test for the case where the contract address is set to zero (if applicable in your system).

1-60: Overall: Well-structured and functional test suite for the ownership system.

The test file provides a solid foundation for testing the ownership system. It covers the basic scenarios of successful ownership transfer and unauthorized transfer attempts. The setup function is comprehensive and reusable across tests.

To further strengthen the test suite, consider:

  1. Adding tests for edge cases (e.g., transferring to zero address, self-transfer).
  2. Implementing more granular assertions to check system state before and after operations.
  3. Testing interaction with other systems, if applicable.
  4. Adding comments to explain the purpose of each test and any non-obvious setup steps.

These enhancements will increase the robustness and maintainability of your test suite.

contracts/scripts/contracts.sh (4)

27-28: LGTM! Consider addressing the Shellcheck warning.

The addition of the RESOURCE_BRIDGE_SYSTEMS export is consistent with other exports in the file. However, to address the Shellcheck warning and potentially improve error handling, consider separating the declaration and assignment:

-export RESOURCE_BRIDGE_SYSTEMS=$(get_contract_address "eternum-resource_bridge_systems")
+RESOURCE_BRIDGE_SYSTEMS=$(get_contract_address "eternum-resource_bridge_systems")
+export RESOURCE_BRIDGE_SYSTEMS

This change allows you to check the return value of get_contract_address if needed.

🧰 Tools
🪛 Shellcheck

[warning] 27-27: Declare and assign separately to avoid masking return values.

(SC2155)


59-60: LGTM! Consider addressing the Shellcheck warning.

The addition of the OWNERSHIP_SYSTEMS export is consistent with other exports in the file. However, to address the Shellcheck warning and potentially improve error handling, consider separating the declaration and assignment:

-export OWNERSHIP_SYSTEMS=$(get_contract_address "eternum-ownership_systems")
+OWNERSHIP_SYSTEMS=$(get_contract_address "eternum-ownership_systems")
+export OWNERSHIP_SYSTEMS

This change allows you to check the return value of get_contract_address if needed.

🧰 Tools
🪛 Shellcheck

[warning] 59-59: Declare and assign separately to avoid masking return values.

(SC2155)


61-62: LGTM! Consider addressing the Shellcheck warning.

The addition of the DEV_REALM_SYSTEMS export is consistent with other exports in the file. However, to address the Shellcheck warning and potentially improve error handling, consider separating the declaration and assignment:

-export DEV_REALM_SYSTEMS=$(get_contract_address "eternum-dev_realm_systems")
+DEV_REALM_SYSTEMS=$(get_contract_address "eternum-dev_realm_systems")
+export DEV_REALM_SYSTEMS

This change allows you to check the return value of get_contract_address if needed.

🧰 Tools
🪛 Shellcheck

[warning] 61-61: Declare and assign separately to avoid masking return values.

(SC2155)


Line range hint 27-86: Overall, the changes look good with minor suggestions for improvement.

The additions to contracts/scripts/contracts.sh are consistent with the existing code structure and enhance the script by adding new contract addresses. These modifications align well with the broader changes in the pull request, particularly the new ownership module.

To further improve the script, consider applying the suggested changes to address the Shellcheck warnings for all exports, not just the newly added ones. This would make the code more consistent and potentially improve error handling throughout the script.

Here's an example of how you could refactor the entire export section:

# Declare variables
DOJO_WORLD_ADDRESS=$(get_world_address)
CONFIG_SYSTEMS=$(get_contract_address "eternum-config_systems")
TRADE_SYSTEMS=$(get_contract_address "eternum-trade_systems")
# ... (repeat for all other systems)

# Export variables
export DOJO_WORLD_ADDRESS
export CONFIG_SYSTEMS
export TRADE_SYSTEMS
# ... (repeat for all other systems)

This refactoring would address all Shellcheck warnings and make the code more consistent.

🧰 Tools
🪛 Shellcheck

[warning] 57-57: Declare and assign separately to avoid masking return values.

(SC2155)


[warning] 59-59: Declare and assign separately to avoid masking return values.

(SC2155)


[warning] 61-61: Declare and assign separately to avoid masking return values.

(SC2155)

contracts/src/models/owner.cairo (3)

31-40: LGTM! Consider adding an event emission.

The transfer method is well-implemented with proper checks for non-zero address and preventing setting the same owner. The error messages are clear and informative.

Consider emitting an event after the ownership transfer to improve transparency and allow off-chain systems to track ownership changes easily. This could be implemented as follows:

fn transfer(ref self: Owner, new_owner: ContractAddress) {
    // ... existing checks ...

    // set the new owner
    let old_owner = self.address;
    self.address = new_owner;

    // Emit an event (assuming you have an event system)
    self.emit(OwnershipTransferred { old_owner, new_owner });
}

72-76: LGTM! Consider adding a comment explaining the test setup.

The test setup has been improved using spawn_eternum_custom and a more concise Realm initialization. This change maintains the test's purpose while simplifying the setup.

Consider adding a brief comment explaining the purpose of the spawn_eternum_custom call and the significance of the parameters passed to it. This would improve the test's readability and maintainability. For example:

// Initialize a test world with realm and entity_owner models
let world = spawn_eternum_custom(
    array![array![realm::TEST_CLASS_HASH, entity_owner::TEST_CLASS_HASH]], array![].span()
);

85-98: LGTM! Consider adding a positive test case.

The new test cases effectively cover important edge cases for the transfer method, ensuring it correctly handles attempts to set a zero address and the same address as the current owner.

To complement these negative test cases, consider adding a positive test case that verifies a successful ownership transfer. This would provide complete coverage of the transfer method's behavior. For example:

#[test]
fn owner_test_successful_transfer() {
    let mut owner = Owner { entity_id: 199999, address: contract_address_const::<1>() };
    let new_owner_address = contract_address_const::<2>();
    owner.transfer(new_owner_address);
    assert(owner.address == new_owner_address, 'Transfer failed');
}
client/src/hooks/store/_threeStore.tsx (1)

19-20: LGTM: New properties for battle interaction.

The addition of hoveredBattle property and setHoveredBattle method with Position | null types is appropriate. These changes likely support new functionality for battle interactions in the UI.

Consider adding a brief comment explaining the purpose of these new properties, especially how they interact with the battle management logic mentioned in the AI summary.

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

71-80: LGTM: Component updated with improved styling.

The BattleProgressBar has been replaced with BattleProgress, and the container's styling has been updated. These changes are consistent with the AI summary and should improve the battle view's appearance.

Consider adding a comment explaining the reason for the specific 40vh min-height, as it might help future maintainers understand the design decision.

contracts/scripts/system_models.json (1)

39-55: LGTM: New DEV_REALM_SYSTEMS array added.

The addition of the DEV_REALM_SYSTEMS array provides a clear categorization for development-specific realm systems. The entries are consistent with existing naming conventions and cover various aspects of realm management.

Consider adding a brief comment or documentation explaining the purpose and usage of this new array, especially how it differs from the existing REALM_SYSTEMS array.

client/src/ui/components/worldmap/battles/BattleLabel.tsx (6)

18-18: Use hook syntax to maintain reactivity with nextBlockTimestamp

Accessing useUIStore.getState().nextBlockTimestamp directly may bypass React's reactivity, potentially causing the component not to re-render when nextBlockTimestamp updates. Consider using the hook syntax to subscribe to changes.

Update the code as follows:

-  const currentTimestamp = useUIStore.getState().nextBlockTimestamp || 0;
+  const currentTimestamp = useUIStore((state) => state.nextBlockTimestamp) || 0;

29-29: Simplify className assignment by removing unnecessary template literal

The className prop uses a template literal without any dynamic expressions, which is unnecessary.

Update the code as follows:

-        <BaseThreeTooltip position={Position.CLEAN} className={`pointer-events-none w-[250px]`}>
+        <BaseThreeTooltip position={Position.CLEAN} className="pointer-events-none w-[250px]">

86-86: Remove unnecessary braces in className prop

The className prop is assigned using braces around a string, which is redundant.

Update the code as follows:

-      <ProgressBar className={"w-full"} attackingHealth={attackerHealth} defendingHealth={defenderHealth} />
+      <ProgressBar className="w-full" attackingHealth={attackerHealth} defendingHealth={defenderHealth} />

31-33: Simplify component structure by removing unnecessary <div>

The <div> inside the <Headline> component seems unnecessary and can be removed for cleaner code.

Update the code as follows:

-            <Headline className="text-center text-lg">
-              <div>{`Battles (${battles.length})`}</div>
-            </Headline>
+            <Headline className="text-center text-lg">{`Battles (${battles.length})`}</Headline>

63-77: Evaluate the necessity of useMemo for computed values

Using useMemo with currentTimestamp as a dependency may not provide performance benefits if currentTimestamp updates frequently. Since useMemo recomputes when dependencies change, the memoization might be ineffective here.

Consider removing useMemo or restructuring the code to optimize performance.


50-60: Define prop types outside of the component for clarity

For better readability and maintainability, define the prop types for BattleInfo using an interface or type alias outside of the component.

Example:

interface BattleInfoProps {
  battleEntityId: number;
  dojo: DojoResult;
  currentTimestamp: number;
  structure?: Structure;
}

const BattleInfo: React.FC<BattleInfoProps> = ({ battleEntityId, dojo, currentTimestamp, structure }) => { ... }
client/src/ui/modules/military/battle-view/BattleProgress.tsx (1)

Line range hint 73-88: Potential loss of precision when converting bigint to number

Converting bigint values to number can lead to loss of precision if the values exceed Number.MAX_SAFE_INTEGER. This may cause incorrect calculations for health percentages when dealing with large health values.

Consider handling bigint values without converting them to number. You can use libraries like big-integer or adjust your calculations to work with bigint arithmetic.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 20b6995 and dcc3c60.

⛔ Files ignored due to path filters (2)
  • contracts/Scarb.lock is excluded by !**/*.lock
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (35)
  • .github/workflows/test-contracts.yml (1 hunks)
  • .tool-versions (1 hunks)
  • client/.env.preview (1 hunks)
  • client/.env.production (2 hunks)
  • client/.env.sample (2 hunks)
  • client/dojoConfig.ts (1 hunks)
  • client/package.json (1 hunks)
  • client/src/dojo/setup.ts (1 hunks)
  • client/src/hooks/store/_threeStore.tsx (3 hunks)
  • client/src/hooks/store/useBlockchainStore.tsx (2 hunks)
  • client/src/three/scenes/Worldmap.ts (7 hunks)
  • client/src/ui/components/worldmap/battles/BattleLabel.tsx (1 hunks)
  • client/src/ui/layouts/World.tsx (7 hunks)
  • client/src/ui/modules/military/Military.tsx (1 hunks)
  • client/src/ui/modules/military/battle-view/Battle.tsx (2 hunks)
  • client/src/ui/modules/military/battle-view/BattleProgress.tsx (3 hunks)
  • config/package.json (1 hunks)
  • contracts/.tool-versions (1 hunks)
  • contracts/Scarb.toml (1 hunks)
  • contracts/dojo_dev.toml (1 hunks)
  • contracts/manifests/dev/deployment/manifest.toml (29 hunks)
  • contracts/scripts/contracts.sh (3 hunks)
  • contracts/scripts/env_variables.sh (2 hunks)
  • contracts/scripts/system_models.json (3 hunks)
  • contracts/src/models/owner.cairo (2 hunks)
  • contracts/src/systems.cairo (1 hunks)
  • contracts/src/systems/combat/contracts.cairo (12 hunks)
  • contracts/src/systems/ownership/contracts.cairo (1 hunks)
  • contracts/src/systems/ownership/tests.cairo (1 hunks)
  • contracts/src/utils/testing/config.cairo (1 hunks)
  • contracts/src/utils/testing/constants.cairo (2 hunks)
  • contracts/src/utils/testing/world.cairo (3 hunks)
  • scripts/deploy.sh (3 hunks)
  • sdk/packages/eternum/package.json (1 hunks)
  • season_pass/scripts/deployment/.env.example (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • .github/workflows/test-contracts.yml
  • .tool-versions
  • client/.env.production
  • contracts/.tool-versions
  • contracts/src/systems/combat/contracts.cairo
🧰 Additional context used
🪛 Gitleaks
client/.env.sample

2-2: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

contracts/dojo_dev.toml

7-7: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

contracts/scripts/env_variables.sh

6-6: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

season_pass/scripts/deployment/.env.example

5-6: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🪛 Biome
client/src/ui/modules/military/battle-view/BattleProgress.tsx

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

🪛 Shellcheck
contracts/scripts/contracts.sh

[warning] 27-27: Declare and assign separately to avoid masking return values.

(SC2155)


[warning] 59-59: Declare and assign separately to avoid masking return values.

(SC2155)


[warning] 61-61: Declare and assign separately to avoid masking return values.

(SC2155)

🔇 Additional comments (52)
sdk/packages/eternum/package.json (2)

25-25: Approve starknet update

The update of the starknet peer dependency from 6.7.0 to 6.11.0 is consistent with changes made in other package.json files across the project. This minor version update suggests improved functionality or bug fixes.


20-20: Approve @dojoengine/core update, but verify compatibility

The update of @dojoengine/core from 1.0.0-alpha.12 to 1.0.0-alpha.22 is a significant jump in alpha versions. While this aligns with updates in other parts of the project, it's important to ensure compatibility with the rest of the codebase.

Please run the following script to check for any breaking changes or deprecations:

✅ Verification successful

@dojoengine/core update verified successfully

No deprecations or related comments found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for breaking changes or deprecations in @dojoengine/core

# Test: Search for @dojoengine/core usage
rg -i '@dojoengine/core'

# Test: Check for any TODO, FIXME, or deprecated comments related to @dojoengine/core
rg -i '(TODO|FIXME|deprecated).*@dojoengine/core'

Length of output: 1369

contracts/Scarb.toml (2)

15-15: Clarify the purpose of the empty [[target.dojo]] section.

An empty [[target.dojo]] section has been added. Could you please clarify its intended purpose? If it's meant to be a placeholder for future configurations, consider adding a comment to indicate this.


9-13: LGTM! Verify compatibility with the updated dojo version.

The update of the dojo dependency to v1.0.0-alpha.17 is a good practice to stay current. The added blank line improves readability.

Please ensure that this update is compatible with your project and doesn't introduce any breaking changes. Run the following script to check for any compatibility issues:

client/src/ui/modules/military/Military.tsx (4)

10-10: Approve use of useEntities and verify its implementation.

The use of useEntities to obtain player structures simplifies data access and potentially improves performance.

To ensure the useEntities hook is implemented efficiently:

  1. Review the implementation of useEntities to confirm it's optimized for frequent calls.
  2. Verify that playerStructures is memoized if it's computationally expensive.

Run the following script to locate and examine the useEntities implementation:

#!/bin/bash
# Description: Locate and display the useEntities implementation

# Find the file containing useEntities
file=$(rg -l "export.*useEntities" src)

if [ -n "$file" ]; then
    echo "useEntities implementation found in: $file"
    echo "Contents of the file:"
    cat "$file"
else
    echo "useEntities implementation not found"
fi

Line range hint 1-20: Summary of changes and potential impact.

The modifications to the Military component represent a shift towards more efficient and direct data management:

  1. Removal of useDojo in favor of useEntities simplifies the data access pattern.
  2. Structure selection logic has been streamlined, improving readability.
  3. The overall component structure remains intact, maintaining its core functionality.

These changes likely contribute to better maintainability and potentially improved performance. However, it's crucial to ensure that all necessary data is still accessible and that the new patterns are consistently applied across the codebase.

To ensure the changes are part of a consistent pattern across the project, run the following script:

#!/bin/bash
# Description: Check for similar changes in other components

echo "Checking for components still using useDojo:"
rg "import.*useDojo" --type tsx --type ts

echo "Checking for components using useEntities:"
rg "import.*useEntities" --type tsx --type ts

echo "Checking for components with playerStructures usage:"
rg "playerStructures\(\)" --type tsx --type ts

Review the results to ensure consistency in the refactoring approach across the project.


12-12: Approve simplified structure selection logic with performance considerations.

The simplified logic for selecting a structure improves code readability and maintainability.

Consider the following performance aspects:

  1. If playerStructures() returns a large array, consider memoizing the result of find to prevent unnecessary re-computations.
  2. Verify that playerStructures() is not called excessively, especially if it triggers any expensive operations.

Run the following script to check the usage of playerStructures in this file:

#!/bin/bash
# Description: Check playerStructures usage in Military.tsx

echo "playerStructures usage in Military.tsx:"
rg "playerStructures" client/src/ui/modules/military/Military.tsx

If playerStructures is used frequently, consider optimizing its usage or memoizing its result.


1-12: Verify implications of removing useDojo.

The removal of useDojo aligns with the new approach of using useEntities. However, this change might have implications for how the component accesses global state or account information.

Please ensure that:

  1. All necessary data previously accessed through useDojo is now available via useEntities or other appropriate hooks.
  2. There are no unintended side effects in terms of component re-renders or performance.

Consider running the following script to check for any remaining useDojo usage in this file:

client/.env.preview (2)

4-4: Verify the new VITE_PUBLIC_ACCOUNT_CLASS_HASH value.

The VITE_PUBLIC_ACCOUNT_CLASS_HASH has been updated. Please ensure that:

  1. This new hash is correct and corresponds to the intended account class for the preview environment.
  2. All components relying on the account class hash have been tested with this new value.
  3. The change is intentional and aligns with any recent updates to the account system.

To verify the account class hash usage, run:

#!/bin/bash
# Description: Verify the account class hash usage across the codebase

# Test: Search for occurrences of the old and new account class hashes
echo "Occurrences of the old account class hash:"
rg "0x05400e90f7e0ae78bd02c77cd75527280470e2fe19c54970dd79dc37a9d3645c"

echo "Occurrences of the new account class hash:"
rg "0x07dc7899aa655b0aae51eadff6d801a58e97dd99cf4666ee59e704249e51adf2"

# Test: Check for any hardcoded account class hashes that might need updating
echo "Potential hardcoded account class hashes:"
rg "0x[a-fA-F0-9]{64}" --type ts --type tsx --type js --type jsx

3-3: Verify the new VITE_PUBLIC_WORLD_ADDRESS value.

The VITE_PUBLIC_WORLD_ADDRESS has been updated. Please ensure that:

  1. This new address is correct and corresponds to the intended world contract for the preview environment.
  2. All components interacting with the world contract have been tested with this new address.
  3. The change is intentional and aligns with any recent deployments or upgrades.

To verify the world contract address, run:

client/src/dojo/setup.ts (1)

18-18: Verify the impact of changing the third argument to undefined.

The change from [] to undefined for the third argument of getSyncEntities might alter the behavior of entity synchronization. This could potentially affect how entities are initially loaded or updated in the application.

To ensure this change doesn't introduce unexpected behavior, please run the following verification:

Additionally, please confirm that:

  1. This change aligns with the getSyncEntities function's expected behavior.
  2. There are no negative impacts on entity synchronization or initial data loading.
  3. The change is consistent with how getSyncEvents is called (which also uses undefined).

If you need help interpreting the results of the verification or making any necessary adjustments, please let me know.

contracts/scripts/env_variables.sh (2)

17-17: Verify the intended usage of SOZO_WORLD address.

The SOZO_WORLD address has been updated for the production environment, matching the value set for the development environment. This change addresses the inconsistency mentioned in the previous review.

Please confirm that using the same SOZO_WORLD address for both development and production environments is intentional. If not, consider using environment-specific addresses.

Run the following script to verify the usage of the new SOZO_WORLD address across the project:

#!/bin/bash
# Description: Verify the usage of new SOZO_WORLD address across the project

echo "Verifying usage of new SOZO_WORLD address:"
rg "0x320b2713e324fe3125bbc42d85ff69cb3c0908b436fa38a35746dbc45deeb11" --type-not sh

echo "Checking for any remaining instances of the old address:"
rg "0x76ca3dfc3e96843716f882546f0db96b7da0cf988bdba284b469d0defb2f48f" --type-not sh

5-7: ⚠️ Potential issue

Verify the updated values and consider security implications.

The DOJO_ACCOUNT_ADDRESS, DOJO_PRIVATE_KEY, and SOZO_WORLD variables have been updated with new values. Please ensure these changes are intentional and consistent across your development environment.

Run the following script to check for any remaining instances of the old values:

Additionally, consider the following security recommendation:

The DOJO_PRIVATE_KEY is potentially sensitive information. While it's common to have such keys in environment scripts for development, consider using a more secure method for managing sensitive data, such as environment-specific .env files that are not committed to the repository.

🧰 Tools
🪛 Gitleaks

6-6: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

client/src/hooks/store/useBlockchainStore.tsx (1)

38-45: LGTM: Improved variable scoping

Moving tickConfigArmies and tickConfigDefault declarations inside useEffect is a good practice. It ensures that the latest component values are used each time the effect runs, potentially avoiding stale data issues.

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

3-6: LGTM: New imports for owner and season models.

The added imports for Owner, OwnerCustomImpl, OwnerCustomTrait, owner, and season are appropriate for integrating ownership and season functionality into the testing constants. This aligns with the overall enhancements to ownership management mentioned in the PR summary.


Line range hint 1-67: Summary: Ownership and season model integration.

The changes to this file successfully integrate ownership and season models into the testing constants. The new imports and the ownership_systems_models function provide a foundation for ownership-related testing and system configuration. These additions align well with the PR's objective of enhancing ownership management across the system.

The existing constants and functions remain unchanged, preserving current functionality while extending the file's capabilities. This approach maintains backwards compatibility while allowing for new features to be developed and tested.

contracts/src/systems/ownership/tests.cairo (1)

1-17: LGTM: Imports and constants are well-defined.

The imports cover all necessary modules for the ownership system tests, and the constants are clearly defined with appropriate names.

client/package.json (8)

25-25: Verify compatibility with updated @dojoengine/torii-client version.

The @dojoengine/torii-client dependency has been updated from 1.0.0-alpha.14 to 1.0.0-alpha.22. As this is an alpha version update, it may include significant changes.

Please review the @dojoengine/torii-client changelog for any breaking changes or new features that might affect the project. You can use the following command to check for usage of @dojoengine/torii-client:

#!/bin/bash
# Search for @dojoengine/torii-client imports and usage
rg -i '@dojoengine/torii-client' --type ts --type tsx

26-26: Verify compatibility with updated @dojoengine/utils version.

The @dojoengine/utils dependency has been updated from 1.0.0-alpha.14 to 1.0.0-alpha.22. As this is an alpha version update, it may include significant changes.

Please review the @dojoengine/utils changelog for any breaking changes or new features that might affect the project. You can use the following command to check for usage of @dojoengine/utils:

#!/bin/bash
# Search for @dojoengine/utils imports and usage
rg -i '@dojoengine/utils' --type ts --type tsx

16-26: Consider the impact of multiple @dojoengine package updates.

This update includes version changes for multiple @dojoengine packages (core, create-burner, react, state, torii-client, utils) from 1.0.0-alpha.14 to 1.0.0-alpha.22, as well as an update to the Starknet peer dependency. While these updates likely bring improvements and new features, they may also introduce breaking changes or incompatibilities.

To ensure a smooth transition:

  1. Review the changelogs for all updated packages.
  2. Run the project's test suite to catch any immediate issues.
  3. Perform thorough manual testing, especially for features that rely heavily on these packages.
  4. Consider updating the project's documentation if any API changes affect usage patterns.

You can use the following command to get an overview of all @dojoengine package usage in the project:

#!/bin/bash
# Search for all @dojoengine package imports and usage
rg -i '@dojoengine/' --type ts --type tsx

22-22: Verify compatibility with updated @dojoengine/react version.

The @dojoengine/react dependency has been updated from 1.0.0-alpha.14 to 1.0.0-alpha.22. As this is an alpha version update, it may include significant changes.

Please review the @dojoengine/react changelog for any breaking changes or new features that might affect the project. You can use the following command to check for usage of @dojoengine/react:


21-21: Verify compatibility with updated @dojoengine/create-burner version.

The @dojoengine/create-burner dependency has been updated from 1.0.0-alpha.14 to 1.0.0-alpha.22. As this is an alpha version update, it may include significant changes.

Please review the @dojoengine/create-burner changelog for any breaking changes or new features that might affect the project. You can use the following command to check for usage of @dojoengine/create-burner:


20-20: Verify compatibility with updated @dojoengine/core version.

The @dojoengine/core dependency has been updated from 1.0.0-alpha.14 to 1.0.0-alpha.22. As this is an alpha version update, it may include significant changes.

Please review the @dojoengine/core changelog for any breaking changes or new features that might affect the project. You can use the following command to check for usage of @dojoengine/core:


24-24: Verify compatibility with updated @dojoengine/state version.

The @dojoengine/state dependency has been updated from 1.0.0-alpha.14 to 1.0.0-alpha.22. As this is an alpha version update, it may include significant changes.

Please review the @dojoengine/state changelog for any breaking changes or new features that might affect the project. You can use the following command to check for usage of @dojoengine/state:


16-16: Verify compatibility with updated Starknet version.

The Starknet peer dependency has been updated from 6.7.0 to 6.11.0. While this is a minor version update, it's important to ensure compatibility with the rest of the project.

Please review the Starknet changelog for any breaking changes or new features that might affect the project. You can use the following command to check for usage of Starknet-specific features:

contracts/scripts/contracts.sh (1)

69-69: LGTM! Echo statements are consistent and informative.

The addition of echo statements for RESOURCE_BRIDGE_SYSTEMS, OWNERSHIP_SYSTEMS, and DEV_REALM_SYSTEMS is consistent with other echo statements in the file. These additions provide useful information when the script is executed, making it easier to verify the exported addresses.

Also applies to: 85-86

contracts/src/models/owner.cairo (1)

63-67: LGTM! Imports are correctly updated.

The new imports provide the necessary types and utilities for the updated test module. They are appropriately placed and consistent with the changes made in the tests.

client/src/hooks/store/_threeStore.tsx (4)

3-3: LGTM: Import statement addition is appropriate.

The addition of the Position type import from "@bibliothecadao/eternum" is consistent with the new hoveredBattle property in the ThreeStore interface.


14-14: LGTM: Method signature update is consistent.

The change in the setSelectedHex method parameter type to HexPosition | null is consistent with the update to the selectedHex property type. This allows for clearing the selection by setting it to null.


61-61: LGTM: Implementation changes are consistent.

The updates to setSelectedHex, and the addition of hoveredBattle and setHoveredBattle in the createThreeStoreSlice function are consistent with the interface changes.

As mentioned earlier, consider adjusting the initialization of selectedHex to null instead of { col: 0, row: 0 } to align with its nullable type in the interface. Let's verify the current initialization:

#!/bin/bash
# Description: Check the initialization of selectedHex in createThreeStoreSlice

rg -n 'selectedHex:' client/src/hooks/store/_threeStore.tsx

Also applies to: 66-67


13-13: LGTM: Interface update improves flexibility.

The change to make selectedHex nullable (HexPosition | null) improves the flexibility of the ThreeStore interface. This allows for representing the absence of a selection.

However, please ensure that the initialization in createThreeStoreSlice is adjusted to align with this nullable type. You might want to initialize it as null instead of { col: 0, row: 0 }. Let's verify the initialization:

✅ Verification successful

Initialization of selectedHex aligns with the updated type.

The selectedHex is correctly initialized with { col: 0, row: 0 }, which is compatible with the HexPosition | null type. No adjustments are necessary unless a null initialization is specifically required for your application logic.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the initialization of selectedHex in createThreeStoreSlice

rg -n 'selectedHex:' client/src/hooks/store/_threeStore.tsx

Length of output: 212

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

14-14: LGTM: Import statement updated correctly.

The import statement has been updated to use the new BattleProgress component, which is consistent with the changes described in the AI summary.


Line range hint 1-124: Summary: Successful integration of new BattleProgress component.

The changes in this file are focused and align well with the AI summary. The BattleProgressBar has been replaced with BattleProgress, and minor styling updates have been made. These modifications appear to be part of a larger refactoring effort to improve the battle visualization.

The overall structure and logic of the Battle component remain intact, suggesting that this update should not introduce any breaking changes. The refactoring seems to enhance the clarity and potentially the functionality of the battle progress display.

To ensure the changes are consistent across the codebase, please run the following script:

This will help confirm that the refactoring has been applied consistently and that there are no lingering references to the old BattleProgressBar component.

✅ Verification successful

Verified: All instances of BattleProgressBar have been successfully replaced with BattleProgress. The refactoring is consistent across the codebase, and no issues were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify that BattleProgressBar has been replaced with BattleProgress throughout the codebase

echo "Checking for any remaining instances of BattleProgressBar:"
rg "BattleProgressBar" --type tsx --type ts

echo "Verifying BattleProgress usage:"
rg "BattleProgress" --type tsx --type ts

Length of output: 340


Script:

#!/bin/bash
# Verify that BattleProgressBar has been replaced with BattleProgress throughout the codebase

echo "Checking for any remaining instances of BattleProgressBar in .ts and .tsx files:"
rg "BattleProgressBar" --glob "*.ts" --glob "*.tsx"

echo "Verifying BattleProgress usage in .ts and .tsx files:"
rg "BattleProgress" --glob "*.ts" --glob "*.tsx"

Length of output: 820

contracts/scripts/system_models.json (4)

35-36: LGTM: New configurations added.

The additions of "TravelFoodCostConfig" and "SeasonConfig" to the CONFIG_SYSTEMS array are consistent with the existing structure and naming conventions. These new configurations likely support new features related to travel food costs and seasonal mechanics.


121-124: LGTM: Enhanced resource management capabilities.

The additions of "Quantity", "ArrivalTime", and "QuantityTracker" to the RESOURCE_SYSTEMS array enhance the resource management capabilities. These new entries are consistent with the existing naming conventions and likely support more detailed tracking of resources.


125-137: New RESOURCE_BRIDGE_SYSTEMS array added, but clarification needed.

The addition of the RESOURCE_BRIDGE_SYSTEMS array introduces a new category for resource bridge management. However, its entries are identical to those in the RESOURCE_SYSTEMS array.

Could you please clarify:

  1. The specific purpose of this new array and how it differs from RESOURCE_SYSTEMS?
  2. Whether this duplication is intentional or if there should be some differences between the two arrays?
  3. If there are plans to differentiate these arrays in the future?

This information will help ensure that we're not introducing unnecessary redundancy and that the purpose of each array is clear.


309-310: LGTM: New OWNERSHIP_SYSTEMS array added, but clarification would be helpful.

The addition of the OWNERSHIP_SYSTEMS array with the entry "Owner" introduces a new category for ownership-related systems. This is consistent with the existing structure and naming conventions.

Could you please provide some context on:

  1. The specific purpose of this new array and why it's separated from other system categories?
  2. Are there plans to add more ownership-related systems to this array in the future?

This information will help understand the rationale behind this new categorization and ensure it aligns with the overall system architecture.

client/src/ui/layouts/World.tsx (7)

12-15: LGTM: Efficient lazy loading of SelectedArmy component

The addition of the SelectedArmy component with lazy loading is a good practice. It helps to improve initial load time and overall performance by only loading the component when needed.


102-102: Verify impact of UI structure changes

Several significant changes have been made to the UI structure:

  1. Background color changed from black to brown (line 102).
  2. TopMiddleNavigation is now wrapped in a TopCenterContainer (lines 127-129).
  3. BottomNavigation replaced with SelectedArmy in BottomMiddleContainer (line 132).
  4. TopMiddleNavigation changed to TopLeftNavigation (line 144).

These changes could significantly impact the layout and user experience of the application.

Please ensure these changes align with the intended design and functionality:

  1. Verify the visual impact of the color change.
  2. Check that the new container structure doesn't introduce any layout issues.
  3. Confirm that replacing BottomNavigation with SelectedArmy doesn't remove any necessary navigation elements.
  4. Ensure that moving the navigation from middle to left doesn't negatively impact usability.

Consider running visual regression tests if available, or manually verify the layout in different screen sizes.

Also applies to: 127-129, 132-132, 144-144


48-50: Verify consistency of TopMiddleNavigation import change

The import path for TopMiddleNavigation has been updated from "TopMiddleNavigation" to "TopNavigation". This change is likely part of a larger restructuring of navigation components.

To ensure this change is consistent and doesn't introduce any errors, please run the following checks:

#!/bin/bash
# Check for any remaining imports from the old path
rg -t tsx 'from.*modules/navigation/TopMiddleNavigation'

# Verify the new import is used consistently
rg -t tsx 'from.*modules/navigation/TopNavigation'

# Check for any usages of TopMiddleNavigation component
rg -t tsx '<TopMiddleNavigation'

52-54: LGTM: BottomMiddleContainer import refined

The import for BottomMiddleContainer has been updated to use a more explicit syntax, extracting the default export. This change improves consistency with other imports in the file.

To ensure consistency across the codebase, you may want to check if this pattern should be applied to other imports:

#!/bin/bash
# Search for other potential candidates for this import pattern
rg -t tsx 'const \w+ = lazy\(\(\) => import\(".*"\)\)'

62-64: LGTM: TopLeftNavigation component added

The addition of the TopLeftNavigation component with lazy loading is consistent with the pattern used for other components. This suggests a well-thought-out expansion or restructuring of the navigation system.

To ensure proper integration, you may want to check its usage and relationship with other navigation components:

#!/bin/bash
# Search for TopLeftNavigation usage
rg -t tsx '<TopLeftNavigation'

# Check for any other Top*Navigation components
rg -t tsx 'const Top\w+Navigation = lazy'

37-37: LGTM: TopCenterContainer added

The addition of the TopCenterContainer component maintains consistency with the lazy loading pattern. The import syntax suggests it might have a default export, unlike some other components.

To ensure this component is used as intended, you may want to check its implementation and usage:

✅ Verification successful

Verified: TopCenterContainer Implementation and Usage Confirmed

The TopCenterContainer component is correctly implemented and utilized within the World.tsx layout.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for TopCenterContainer implementation
rg -t tsx 'export .*TopCenterContainer'

# Search for TopCenterContainer usage
rg -t tsx '<TopCenterContainer'

Length of output: 313


Script:

#!/bin/bash
# Search for TopCenterContainer implementation without specifying file type
rg 'export .*TopCenterContainer'

# Search for TopCenterContainer usage without specifying file type
rg '<TopCenterContainer'

# Alternatively, use fd to find all .tsx files and search within them
fd --extension tsx --exec rg '<TopCenterContainer'

Length of output: 291


23-26: LGTM: BattleInfoLabel component added

The addition of the BattleInfoLabel component is consistent with the lazy loading pattern used elsewhere. This is good for maintaining code style and performance.

Ensure that this component is properly integrated with the battle system. You may want to verify its usage in the render tree:

✅ Verification successful

Verified: BattleInfoLabel integration confirmed

The BattleInfoLabel component is properly imported and utilized within World.tsx, and its implementation exists in BattleLabel.tsx. No further integration issues detected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for BattleInfoLabel usage in TSX files
rg -t tsx 'BattleInfoLabel'

Length of output: 55


Script:

#!/bin/bash
# Search for BattleInfoLabel usage in .tsx files
rg 'BattleInfoLabel' --glob '*.tsx'

Length of output: 403

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

Line range hint 1-200: Verify impact on mercenary-related code across the codebase.

While the changes to set_mercenaries_config are well-implemented and localized, they may have implications for other parts of the codebase that interact with mercenary configurations.

To ensure full compatibility across the project, please run the following script to identify potential areas that might need updates:

#!/bin/bash
# Description: Identify mercenary-related code that might need updates

# Test: Search for mercenary-related function calls or configurations
rg -p 'mercenaries|troops|knights|paladins|crossbowmen' --type cairo --type typescript

Review the results to identify any code that might need to be updated to work with the new flexible mercenary configuration.

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

Line range hint 96-124: Config systems contract has been expanded.

The eternum-config_systems contract now includes additional systems such as set_season_config, set_mercenaries_config, and various other configuration setters. This expansion suggests more granular control over game parameters.


26-28: Multiple contracts have been updated with new addresses and class hashes.

Several contracts have new addresses and class hashes, indicating updates or redeployments. This includes changes to bank, building, combat, config, and other systems. New contracts like eternum-dev_realm_systems and eternum-dev_resource_systems have been added.

To ensure these changes are consistent across the codebase, run the following script:

#!/bin/bash
# Description: Verify contract updates and additions
# Test: Check for references to new contract addresses and class hashes
for address in 0x3f96056436be253753351fe689110ced7d53f5db3fd98f13df3f19058311b95 \
               0xfb4a9f1c17068cdd45ecbf21637d2a6ff2078edb64b8631e95d445365113cb \
               0x6bde5ad6204af5e31e9b66f687f5ccd84fcefa1b61dfba9bda8ca331252e641 \
               0x2e57f328fea661edb9a599af68443e1d39942b93884d2ca28c68d3f2d0ab2a3 \
               0x35f19ba2473243c902b1a88029655ffd0d24ff875abe9fc74808af973b41183 \
               0x3bde87d577c1a56fa4053ff9ff54c270c236dcf52b149416aa0aa1df261a781 \
               0x6e294d4c5d0668930c40c58a7f7cb2f9abf3a8609f4481bd94e5dff02a497e2; do
    rg $address --type toml
done

Also applies to: 43-45, 62-64, 85-87, 129-131, 143-153, 171-173, 185-187, 206-208, 225-227, 239-241, 253-255, 270-280, 298-300, 317-319, 335-337, 349-351, 367-369


3-8: World contract has been updated.

The world contract has new class hashes, address, and transaction hash. The block number has increased from 65 to 246, indicating progression in the blockchain. This update may introduce new features or fix issues in the previous version.

To ensure the update was applied correctly, run the following script:

✅ Verification successful

World contract update verified successfully.

The new class hash is correctly referenced in the contracts/manifests/dev/deployment/manifest.toml and contracts/manifests/prod/deployment/manifest.toml files.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the world contract update
# Test: Check if the new class hash is used in other parts of the codebase
rg -i "0x6f38d5d9507c5d9546290e1a27e309efe5a9af3770b6cc1627db4a1b90a7dce" --type toml

Length of output: 5580

contracts/src/utils/testing/world.cairo (1)

162-184: Function spawn_eternum_custom is well-implemented

The new function spawn_eternum_custom enhances flexibility by allowing custom models and owners to initialize the world. The overall implementation is clear, and the logic correctly aggregates unique models and assigns ownership.

client/src/three/scenes/Worldmap.ts (3)

264-267: Verify correct calculation of selected hex coordinates

In the onHexagonClick method, when setting the selected hex, the code adds FELT_CENTER to hexCoords.col and hexCoords.row. Please verify that adding FELT_CENTER is necessary and that it results in the correct coordinates. An incorrect calculation could lead to issues with hex selection or rendering.


166-169: Ensure the 'urlChanged' event is properly dispatched

An event listener for the 'urlChanged' event has been added to clear selections when the URL changes. Please verify that this event is being dispatched appropriately elsewhere in the codebase so that the listener functions as intended.

Run the following script to search for dispatches of the 'urlChanged' event:

#!/bin/bash
# Description: Search for occurrences where 'urlChanged' event is dispatched.

# Test: Find all dispatches of 'urlChanged' event. Expect: At least one result.
rg "dispatchEvent\s*\(\s*new\s+Event\('urlChanged'\)\s*\)" --type js --type ts

286-286: Ensure consistent use of null instead of undefined for selectedEntityId

The method onArmySelection now accepts selectedEntityId: ID | null instead of ID | undefined. Please ensure that all references to selectedEntityId use null to represent the absence of an ID. Check that any previous instances where selectedEntityId could be undefined are updated to null to maintain consistency and prevent potential bugs.

Run the following script to check for usages where selectedEntityId is compared to or assigned undefined:

Comment on lines +10 to +11
"@dojoengine/core": "1.0.0-alpha.21",
"starknet": "6.11.0"
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Dependency version inconsistencies detected.

  • @dojoengine/core is specified with multiple versions:

    • "1.0.0-alpha.22"
    • "1.0.0-alpha.21"
  • starknet has inconsistent version specifications:

    • "^6.8.0"
    • "6.11.0"

Please standardize the versions of @dojoengine/core and starknet across all project files to ensure compatibility and prevent potential issues.

🔗 Analysis chain

Verify dependency version consistency across the project.

The updates to @dojoengine/core (1.0.0-alpha.21) and starknet (6.11.0) align with the project's overall dependency updates. However, please note:

  1. Some project files use @dojoengine/core version 1.0.0-alpha.22. Ensure this slight version difference is intentional and doesn't cause compatibility issues.
  2. As @dojoengine/core is still in alpha, be cautious of potential instability or breaking changes in future updates.

To ensure consistency, run the following script:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for inconsistencies in @dojoengine/core and starknet versions across the project

echo "Checking @dojoengine/core versions:"
rg -g '*.json' '"@dojoengine/core":\s*"[^"]+"' --no-filename

echo -e "\nChecking starknet versions:"
rg -g '*.json' '"starknet":\s*"[^"]+"' --no-filename

Length of output: 495

Comment on lines +6 to +7
account_address = "0x127fd5f1fe78a71f8bcd1fec63e3fe2f0486b6ecd5c86a0466c3a21fa5cfcec"
private_key = "0xc5b2fcab997346f3ea1c00b002ecf6f382c5f9c9659a3894eb783c5320f912"
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Security Concern Confirmed: Exposed Private Key in Version Control

The file contracts/dojo_dev.toml is tracked in version control, exposing the private key and posing a significant security risk.

Recommendations:

  1. Immediate Action:
    • Remove the private_key from contracts/dojo_dev.toml.
    • Rotate the exposed private key to prevent unauthorized access.
  2. Secure Management:
    • Use environment variables or a secure secret management system to handle sensitive data.
  3. Prevent Future Exposure:
    • Add contracts/dojo_dev.toml to .gitignore to avoid tracking in version control.
    • Create a template file (e.g., contracts/dojo_dev.toml.example) with placeholder values for developers.
🔗 Analysis chain

Security Concern: Exposed Private Key

The private key is directly exposed in the configuration file, which poses a significant security risk. This is especially concerning if this file is tracked in version control.

Recommendations:

  1. Remove sensitive information from this file.
  2. Use environment variables or a secure secret management system to handle sensitive data.
  3. If this file is tracked in version control, consider using a template (e.g., dojo_dev.toml.example) with placeholder values.

To check if this file is tracked in version control, run:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the file is tracked in git
git ls-files --error-unmatch contracts/dojo_dev.toml
if [ $? -eq 0 ]; then
  echo "WARNING: contracts/dojo_dev.toml is tracked in version control"
else
  echo "contracts/dojo_dev.toml is not tracked in version control"
fi

Length of output: 231

🧰 Tools
🪛 Gitleaks

7-7: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

Comment on lines +4 to +5
export STARKNET_ACCOUNT_ADDRESS=0x127fd5f1fe78a71f8bcd1fec63e3fe2f0486b6ecd5c86a0466c3a21fa5cfcec
export STARKNET_ACCOUNT_PRIVATE_KEY=0xc5b2fcab997346f3ea1c00b002ecf6f382c5f9c9659a3894eb783c5320f912
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enhance security for sensitive information.

While these are example values, including private keys (even as examples) in version-controlled files can pose a security risk if misinterpreted.

Consider the following improvements:

  1. Replace the example private key with a placeholder (e.g., <YOUR_PRIVATE_KEY_HERE>).
  2. Add a comment emphasizing that users should never commit their actual private keys.
  3. Consider using a secure secret management solution for production deployments.

@@ -1,22 +1,15 @@
import { useDojo } from "@/hooks/context/DojoContext";
import { getPlayerStructures } from "@/hooks/helpers/useEntities";
import { useEntities } from "@/hooks/helpers/useEntities";
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Remaining useDojo imports detected.

Multiple files still import useDojo from @/hooks/context/DojoContext. Please update all instances to use useEntities to ensure consistency and reduce dependencies.

🔗 Analysis chain

Approve import changes and verify new hook usage.

The switch from useDojo to useEntities suggests an improvement in data management. This change likely reduces dependencies and provides more direct access to entity data.

To ensure consistency across the codebase, please run the following script to check for any remaining useDojo imports and useEntities usage:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for useDojo imports and useEntities usage

# Test 1: Search for remaining useDojo imports
echo "Checking for remaining useDojo imports:"
rg "import.*useDojo" --type tsx --type ts

# Test 2: Verify useEntities usage
echo "Verifying useEntities usage:"
rg "useEntities" --type tsx --type ts

Length of output: 293


Script:

#!/bin/bash
# Description: Check for remaining useDojo imports and useEntities usage

# Test 1: Search for remaining useDojo imports
echo "Checking for remaining useDojo imports:"
rg "import.*useDojo" --glob "*.ts" --glob "*.tsx"

# Test 2: Verify useEntities usage
echo "Verifying useEntities usage:"
rg "useEntities" --glob "*.ts" --glob "*.tsx"

Length of output: 16555

@@ -22,7 +22,7 @@ export const dojoConfig = createDojoConfig({
masterAddress: VITE_PUBLIC_MASTER_ADDRESS,
masterPrivateKey: VITE_PUBLIC_MASTER_PRIVATE_KEY,
accountClassHash:
VITE_PUBLIC_ACCOUNT_CLASS_HASH || "0x05400e90f7e0ae78bd02c77cd75527280470e2fe19c54970dd79dc37a9d3645c",
VITE_PUBLIC_ACCOUNT_CLASS_HASH || "0x07dc7899aa655b0aae51eadff6d801a58e97dd99cf4666ee59e704249e51adf2",
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Inconsistent VITE_PUBLIC_ACCOUNT_CLASS_HASH value found in .github/workflows/test-client.yml.

  • The VITE_PUBLIC_ACCOUNT_CLASS_HASH is set to "0x0" in .github/workflows/test-client.yml, which does not match the updated hash used in other .env files and client/dojoConfig.ts.
🔗 Analysis chain

Verify the new account class hash across the codebase.

The accountClassHash default value has been updated. This change appears to be part of a broader update across the codebase, including modifications to .env.preview and .env.production files.

To ensure consistency and correctness, please run the following script:

Ensure that:

  1. The new hash is present in the relevant .env files.
  2. There are no remaining instances of the old hash.
  3. The VITE_PUBLIC_ACCOUNT_CLASS_HASH values in .env files match the new hash.

If any inconsistencies are found, please update the relevant files to maintain consistency across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the new account class hash across the codebase

# Test 1: Check for the new hash in .env files
echo "Checking .env files for the new hash:"
rg "0x07dc7899aa655b0aae51eadff6d801a58e97dd99cf4666ee59e704249e51adf2" .env*

# Test 2: Check for any remaining instances of the old hash
echo "Checking for any remaining instances of the old hash:"
rg "0x05400e90f7e0ae78bd02c77cd75527280470e2fe19c54970dd79dc37a9d3645c"

# Test 3: Verify VITE_PUBLIC_ACCOUNT_CLASS_HASH in .env files
echo "Verifying VITE_PUBLIC_ACCOUNT_CLASS_HASH in .env files:"
rg "VITE_PUBLIC_ACCOUNT_CLASS_HASH" .env*

Length of output: 610


Script:

#!/bin/bash
# Description: Comprehensive verification of the account class hash across the entire codebase

# Test 1: Check for the new hash in all files
echo "Checking for the new account class hash in the codebase:"
rg "0x07dc7899aa655b0aae51eadff6d801a58e97dd99cf4666ee59e704249e51adf2" --hidden --ignore-dir={node_modules,dist,build}

# Test 2: Check for any remaining instances of the old hash in all files
echo "Checking for any remaining instances of the old account class hash in the codebase:"
rg "0x05400e90f7e0ae78bd02c77cd75527280470e2fe19c54970dd79dc37a9d3645c" --hidden --ignore-dir={node_modules,dist,build}

# Test 3: Verify all instances of VITE_PUBLIC_ACCOUNT_CLASS_HASH are updated
echo "Verifying all occurrences of VITE_PUBLIC_ACCOUNT_CLASS_HASH in the codebase:"
rg "VITE_PUBLIC_ACCOUNT_CLASS_HASH" --hidden --ignore-dir={node_modules,dist,build}

Length of output: 2187


Script:

#!/bin/bash
# Description: Comprehensive verification of the account class hash across the entire codebase with corrected rg commands

# Test 1: Check for the new hash in all files
echo "Checking for the new account class hash in the codebase:"
rg "0x07dc7899aa655b0aae51eadff6d801a58e97dd99cf4666ee59e704249e51adf2" --hidden --ignore-dir node_modules --ignore-dir dist --ignore-dir build

# Test 2: Check for any remaining instances of the old account class hash in all files
echo "Checking for any remaining instances of the old account class hash in the codebase:"
rg "0x05400e90f7e0ae78bd02c77cd75527280470e2fe19c54970dd79dc37a9d3645c" --hidden --ignore-dir node_modules --ignore-dir dist --ignore-dir build

# Test 3: Verify all instances of VITE_PUBLIC_ACCOUNT_CLASS_HASH are updated
echo "Verifying all occurrences of VITE_PUBLIC_ACCOUNT_CLASS_HASH in the codebase:"
rg "VITE_PUBLIC_ACCOUNT_CLASS_HASH" --hidden --ignore-dir node_modules --ignore-dir dist --ignore-dir build

Length of output: 2187


Script:

#!/bin/bash
# Description: Comprehensive verification of the account class hash across the entire codebase using --glob to exclude directories

# Test 1: Check for the new account class hash in all files except excluded directories
echo "Checking for the new account class hash in the codebase:"
rg "0x07dc7899aa655b0aae51eadff6d801a58e97dd99cf4666ee59e704249e51adf2" --hidden --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**'

# Test 2: Check for any remaining instances of the old account class hash in all files except excluded directories
echo "Checking for any remaining instances of the old account class hash in the codebase:"
rg "0x05400e90f7e0ae78bd02c77cd75527280470e2fe19c54970dd79dc37a9d3645c" --hidden --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**'

# Test 3: Verify all instances of VITE_PUBLIC_ACCOUNT_CLASS_HASH are updated in all files except excluded directories
echo "Verifying all occurrences of VITE_PUBLIC_ACCOUNT_CLASS_HASH in the codebase:"
rg "VITE_PUBLIC_ACCOUNT_CLASS_HASH" --hidden --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**'

Length of output: 2251

Comment on lines +82 to +85
<span className="">{Number(divideByPrecision(Number(attackerHealth.current))).toFixed(0)} troops</span>
<span className="font-bold">vs</span>
<span className="">{Number(divideByPrecision(Number(defenderHealth.current))).toFixed(0)} troops</span>
</div>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid precision loss when converting BigInt to Number

Converting BigInt values to Number can lead to precision loss for very large numbers. Ensure that health values stay within the safe integer range or consider displaying them without conversion to Number.

Consider using toString() for BigInt values, or handle large numbers appropriately to prevent precision loss.

-        <span className="">{Number(divideByPrecision(Number(attackerHealth.current))).toFixed(0)} troops</span>
+        <span className="">{divideByPrecision(attackerHealth.current).toString()} troops</span>

Committable suggestion was skipped due to low confidence.

const gradient = useMemo(() => {
const attackPercentage = parseFloat(attackingHealthPercentage);
const defendPercentage = parseFloat(defendingHealthPercentage);
return `linear-gradient(to right, #2B2E3E ${attackPercentage}%, #2B2E3E ${attackPercentage}%, #46201D ${attackPercentage}%, #46201D ${
attackPercentage + defendPercentage
}%)`;
}, [attackingHealthPercentage, defendingHealthPercentage]);
return (
<>
{!isNaN(Number(attackingHealthPercentage)) && !isNaN(Number(defendingHealthPercentage)) && (
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use Number.isNaN instead of isNaN to avoid type coercion

The global isNaN function performs type coercion, which can lead to unexpected results. Using Number.isNaN is safer as it doesn't coerce the value.

Apply this fix:

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

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

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

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

const playBattleVictory = useUiSounds(soundSelector.battleVictory).play;
const playBattleDefeat = useUiSounds(soundSelector.battleDefeat).play;

const attackerName = `${attackerArmies.length > 0 ? "Attackers" : "Empty"} ${ownArmySide === "Attack" ? "" : ""}`;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove redundant ternary operator in attackerName definition

The ternary operator ownArmySide === "Attack" ? "" : "" always returns an empty string, making it redundant.

Simplify the code by removing the redundant ternary operation:

 const attackerName = `${attackerArmies.length > 0 ? "Attackers" : "Empty"} ${ownArmySide === "Attack" ? "" : ""}`;
+const attackerName = `${attackerArmies.length > 0 ? "Attackers" : "Empty"}`;
📝 Committable suggestion

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

Suggested change
const attackerName = `${attackerArmies.length > 0 ? "Attackers" : "Empty"} ${ownArmySide === "Attack" ? "" : ""}`;
const attackerName = `${attackerArmies.length > 0 ? "Attackers" : "Empty"}`;

Comment on lines +37 to +46
useEffect(() => {
if (!timeLeft) return;
if (timeLeft.getTime() === 0) return;
const timer = setInterval(() => {
const date = new Date(0);
date.setTime(timeLeft.getTime() - 1000);
setTimeLeft(date);
}, 1000);
return () => clearInterval(timer);
}, [timeLeft]);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid multiple intervals by adjusting useEffect dependencies

The useEffect hook that sets up the interval depends on timeLeft, which updates every second due to setTimeLeft, causing the effect to rerun and create multiple intervals. This can lead to performance issues and unexpected behavior.

To fix this, set up the interval once by using an empty dependency array and update timeLeft using a functional state update. Clear the interval when timeLeft reaches zero.

 useEffect(() => {
-   if (!timeLeft) return;
-   if (timeLeft.getTime() === 0) return;
-   const timer = setInterval(() => {
-     const date = new Date(0);
-     date.setTime(timeLeft.getTime() - 1000);
-     setTimeLeft(date);
-   }, 1000);
+   if (!durationLeft) return;
+   const timer = setInterval(() => {
+     setTimeLeft((prevTimeLeft) => {
+       if (!prevTimeLeft) return prevTimeLeft;
+       const newTime = new Date(prevTimeLeft.getTime() - 1000);
+       if (newTime.getTime() <= 0) {
+         clearInterval(timer);
+         return new Date(0);
+       }
+       return newTime;
+     });
+   }, 1000);
    return () => clearInterval(timer);
- }, [timeLeft]);
+ }, []);

Committable suggestion was skipped due to low confidence.

Comment on lines +168 to +170
if model_added.get(model) == false {
model_added.insert(model, true);
world_models.append(model);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure proper model existence check in the dictionary

The condition model_added.get(model) == false may not correctly handle the case when model is not present in the dictionary. If model_added.get(model) returns None or raises an error for a missing key, this could lead to unexpected behavior.

Consider using !model_added.contains(model) to check if the model key is absent in the dictionary.

Apply this diff to fix the issue:

-            if model_added.get(model) == false {
+            if !model_added.contains(model) {
📝 Committable suggestion

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

Suggested change
if model_added.get(model) == false {
model_added.insert(model, true);
world_models.append(model);
if !model_added.contains(model) {
model_added.insert(model, true);
world_models.append(model);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants