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

feature: allow multiple banks #2706

Merged
merged 3 commits into from
Feb 26, 2025
Merged

Conversation

credence0x
Copy link
Collaborator

@credence0x credence0x commented Feb 26, 2025

  • allows creation of 6 banks with centralized liquidity and decentralized fee collection

Summary by CodeRabbit

  • UI Improvements

    • Added modal title support and a new “primarySelected” button style for a more polished interface.
  • Gameplay Updates

    • Streamlined battle displays by removing legacy battle history and enemy army panels.
    • Enhanced resource production and transfer calculations for improved precision.
    • Refined troop and army management for more immediate gameplay responses.
  • Removed Features

    • Eliminated outdated battle management elements, simplifying the overall user experience.

Copy link

vercel bot commented Feb 26, 2025

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

Name Status Preview Comments Updated (UTC)
eternum ❌ Failed (Inspect) Feb 26, 2025 5:19am
eternum-docs ❌ Failed (Inspect) Feb 26, 2025 5:19am
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
eternum-landing ⬜️ Ignored (Inspect) Feb 26, 2025 5:19am

Copy link
Contributor

coderabbitai bot commented Feb 26, 2025

Walkthrough

This pull request introduces extensive refactoring and feature modifications across workflows, Dojo data querying and synchronization, UI components, Three.js managers, and resource management. Key updates include replacing debounced queries with synchronous data synchronization functions, removing outdated battle and combat components, updating naming conventions for entity IDs and components, and integrating environment‐specific logic in the Starknet provider. Several dependencies and configuration files have also been updated or removed to streamline testing and production workflows.

Changes

File(s) Change Summary
.github/workflows/test-contracts.yml, .github/workflows/test-season-pass.yml Updated test matrices, ignored paths, checkout actions and directories; bumped artifact and tool versions.
client/apps/game/.env.slot, client/apps/game/dojoConfig.ts, client/apps/game/package.json Updated environment variable values; removed unused configuration code; added new dependencies (e.g. predeployed connector, react-beautiful-dnd) and removed redundant entries.
client/apps/game/src/dojo/debounced-queries.ts, client/apps/game/src/dojo/queries.ts Removed debounce wrappers; replaced specific query functions; updated model/member names; eliminated obsolete query methods.
client/apps/game/src/dojo/sync.ts Added new sync functions: syncStructureData, syncPlayerStructuresData, and syncMarketAndBankData to streamline data retrieval and error handling.
client/apps/game/src/hooks/context/starknet-provider.tsx Integrated predeployed accounts for local chains; refactored connector selection logic based on environment ("local", "mainnet", "sepolia").
client/apps/game/src/hooks/helpers/use-navigate-to-realm-view-by-account.ts, client/apps/game/src/hooks/helpers/use-structure-entity-id.ts, client/apps/game/src/hooks/store/_three-store.ts Updated navigation and entity ID retrieval to use structure-base data and refined the paths data structure (from travelPaths to actionPaths).
client/apps/game/src/three/** (helpers, managers, scenes) Refactored pathfinding parameters; updated army-manager and minimap logic with new hex maps; removed battle manager and outdated biome files; introduced biome-colors.ts and new highlighting functions; adjusted component method signatures to use camelCase entity IDs.
client/apps/game/src/ui/components/** (various UI and modules) Streamlined UI by removing battle and combat-related components (e.g. battle-list-item, pillage-history, multiple battle views); updated resource, bank, construction, and trading components to use new capacity and resource manager logic; revised naming conventions and removed deprecated functionalities.
client/apps/game/src/ui/layouts/onboarding.tsx, client/apps/game/src/ui/layouts/world.tsx Onboarding updated with a new LocalStepOne component for local environments; world layout now calls sync functions instead of debounced queries and removes battle view elements.

Sequence Diagram(s)

sequenceDiagram
    participant U as User/App
    participant SP as StarknetProvider
    participant PA as PredeployedAccounts (Connector)
    participant CC as ControllerConnector

    U->>SP: Initialize provider
    SP->>SP: Check environment variable (chain)
    alt Chain = "local"
        SP->>PA: Call predeployedAccounts()
        PA-->>SP: Return predeployedAccountsConnector[]
        SP->>U: Return first predeployed account connector
    else Chain = "mainnet" or "sepolia"
        SP->>CC: Instantiate ControllerConnector with proper params
        CC-->>SP: Connector instance created
        SP->>U: Return new ControllerConnector
    end
Loading
sequenceDiagram
    participant W as World Component
    participant SY as Sync Functions
    participant DS as Dojo Setup
    participant UI as UI Store

    W->>SY: Call syncMarketAndBankData(...)
    W->>SY: Call syncPlayerStructuresData(...)
    W->>SY: Call syncStructureData(structureEntityId, setLoading, [position])
    SY->>DS: Retrieve updated market, structure, and player data
    DS-->>SY: Return synchronized data
    SY->>W: Update state with new entity data
    W->>UI: Render updated world view (armies, structures, explored hexes)
Loading

Possibly related PRs

  • feat: change to new torii queries  #2652: Updates to entity queries and data retrieval methods; relates to the transition from subscription-based methods to direct, synchronous data fetching.
  • fix: local selected unit #1839: Addressed modifications in battle management logic and unit selection; connected through the removal and refactoring of battle-related components.

Poem

I’m just a rabbit, hopping with glee,
In code I nibble bugs, setting data free.
From workflows to sync, each change is neat,
No more debouncing—now it’s fast on its feet!
With predeployed accounts and UI so bright,
I celebrate these changes deep into the night.
🐰💻 Hop, hop, hooray!

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

client/apps/game/src/dojo/queries.ts

Oops! Something went wrong! :(

ESLint: 9.20.1

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

client/apps/game/src/dojo/debounced-queries.ts

Oops! Something went wrong! :(

ESLint: 9.20.1

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

client/apps/game/src/dojo/sync.ts

Oops! Something went wrong! :(

ESLint: 9.20.1

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

  • 80 others

Tip

CodeRabbit's docstrings feature is now available as part of our Pro Plan! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.

✨ Finishing Touches
  • 📝 Generate Docstrings

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @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.

@credence0x credence0x changed the base branch from next to feat/new-combat February 26, 2025 05:19
Copy link

Failed to generate code suggestions for PR

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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently, please check "Code review limits" under "Moderation" settings.

Actionable comments posted: 14

🔭 Outside diff range comments (2)
client/apps/game/src/three/types/systems.ts (1)

31-38: 💡 Verification agent

🧩 Analysis chain

Unused type declaration: BattleSystemUpdate.

The pipeline has flagged that the BattleSystemUpdate type is exported but not used anywhere in the codebase.

Consider either removing this unused type or updating it if it will be used as part of this feature implementation.


🏁 Script executed:

#!/bin/bash
# Check if BattleSystemUpdate is used anywhere in the codebase
rg -l "BattleSystemUpdate" --type ts --type tsx

Length of output: 75


I'll run a new verification script that explicitly defines the tsx file type before searching. Please execute the following and verify the output:

If this search returns no results, it confirms that BattleSystemUpdate is indeed unused throughout the codebase, and you can either remove it or update its implementation as needed for the feature. Please verify the results and adjust accordingly.


🏁 Script executed:

#!/bin/bash
# Define tsx file type and check for any occurrence of "BattleSystemUpdate" in the repository
rg --type-add "tsx:*.tsx" -l "BattleSystemUpdate"

Length of output: 93


Action Required: Remove or update the unused export BattleSystemUpdate.

Our recent verification confirmed that the only occurrence of BattleSystemUpdate is its declaration in client/apps/game/src/three/types/systems.ts, and it isn’t referenced anywhere else in the codebase. Please remove this type if it isn’t needed, or update its implementation if it’s intended for upcoming feature work.

  • File: client/apps/game/src/three/types/systems.ts (Lines: 31-38)
🧰 Tools
🪛 GitHub Actions: knip

[warning] 31-31: Unused exported type 'BattleSystemUpdate'.

client/apps/game/src/three/scenes/constants.ts (1)

76-81: 💡 Verification agent

🧩 Analysis chain

Removed Settlement from structure type mappings.

The StructureType.Settlement has been removed from the structureTypeToBuildingType record. This change is likely part of the broader refactoring to support multiple banks, as the concept of settlements may have been obsoleted or merged with another structure type.


🏁 Script executed:

#!/bin/bash
# Check if there are any remaining references to StructureType.Settlement
rg "StructureType.Settlement" --type ts

Length of output: 173


Attention: Inconsistent removal of StructureType.Settlement

The removal of StructureType.Settlement from the structureTypeToBuildingType mapping in client/apps/game/src/three/scenes/constants.ts (lines 76–81) is confirmed. However, our verification indicates that StructureType.Settlement is still referenced in the tests (specifically in packages/core/src/managers/__tests__/battle-manager.test.ts via the generateMockStructure call).

  • File Update:

    • client/apps/game/src/three/scenes/constants.ts: StructureType.Settlement has been removed as expected.
  • Test Reference:

    • packages/core/src/managers/__tests__/battle-manager.test.ts: Contains a call to generateMockStructure(StructureType.Settlement). This reference may need to be updated or removed if the removal of settlements is intentional.

Please review and update the test file to align with the new structure type mapping.

🧹 Nitpick comments (39)
client/apps/game/src/ui/components/modal-container.tsx (1)

41-41: Consider adding an accessibility enhancement for the title.

The title implementation looks good, but for better accessibility, consider adding an aria-labelledby attribute to the modal container div and an id to the title div.

- <div className={`z-50 bg-brown/90 text-gold ${containerClasses} fixed overflow-hidden`} tabIndex={0}>
+ <div className={`z-50 bg-brown/90 text-gold ${containerClasses} fixed overflow-hidden`} tabIndex={0} aria-labelledby="modal-title">
  <div className="flex flex-col h-full">
    <div className="flex justify-between items-center p-2">
-     <div className="text-lg font-semibold text-gold px-4">{title}</div>
+     <div id="modal-title" className="text-lg font-semibold text-gold px-4">{title}</div>
client/apps/game/src/ui/components/resources/deposit-resources.tsx (1)

54-58: Refactored button text logic

The button text logic has been simplified to focus only on resource availability and weight. The conditional logic is clearer now but notice there are nested ternary operators which can reduce readability. Consider refactoring to improve readability.

-        {resources.length === 0 && weight?.weight && weight.weight > 0n
-          ? "Resources syncing..."
-          : resources.length === 0 && weight?.weight && weight.weight === 0n
-            ? "No resources to deposit"
-            : "Deposit Resources"}
+        {(() => {
+          if (resources.length === 0) {
+            if (weight?.weight && weight.weight > 0n) {
+              return "Resources syncing...";
+            } else if (weight?.weight && weight.weight === 0n) {
+              return "No resources to deposit";
+            }
+          }
+          return "Deposit Resources";
+        })()}
client/apps/game/src/ui/components/structures/worldmap/structure-card.tsx (2)

46-47: Ensure the memoized function includes all relevant dependencies.
Since dojo.setup.components is also referenced in the memoized callback, it’s best practice to include it in the dependency array to ensure the callback re-runs if dojo.setup.components changes.

Below is a suggested fix:

-    [structure?.owner],
+    [structure?.owner, dojo.setup.components],

186-186: Offer help with the “WIP” Troop Exchange.
The placeholder text indicates incomplete logic. Let me know if you’d like me to open a new issue or propose a draft implementation for the troop exchange functionality.

client/apps/game/src/ui/components/resources/resource-chip.tsx (1)

84-94: Added debug logging for resource information.

Added console logging for resource ID and trait information. This is helpful for debugging but should be removed or guarded with a development-only flag before production deployment.

Consider guarding the console.log with a development-only check to prevent unnecessary logging in production:

const icon = useMemo(() => {
-  console.log("Resource ID:", resourceId, "trait", findResourceById(resourceId)?.trait);
+  if (process.env.NODE_ENV === 'development') {
+    console.log("Resource ID:", resourceId, "trait", findResourceById(resourceId)?.trait);
+  }
  return (
    <ResourceIcon
      withTooltip={false}
      resource={findResourceById(resourceId)?.trait as string}
      size="sm"
      className="mr-3 self-center"
    />
  );
}, [resourceId, isLabor]);
client/apps/game/src/hooks/helpers/use-navigate-to-realm-view-by-account.ts (1)

18-21: Fix the typo in variable name "strucutureBase"

There's a spelling error in the variable name on line 18. It should be "structureBase" (with correct spelling) to match the variable used on line 21 and elsewhere in the file.

-      const strucutureBase = randomRealmEntity
+      const structureBase = randomRealmEntity
        ? getComponentValue(components.Structure, randomRealmEntity)?.base
        : undefined;
-      strucutureBase && navigateToHexView(new Position({ x: strucutureBase.coord_x, y: strucutureBase.coord_y }));
+      structureBase && navigateToHexView(new Position({ x: structureBase.coord_x, y: structureBase.coord_y }));
client/apps/game/src/hooks/helpers/use-structure-entity-id.ts (1)

30-31: Remove debugging console.log statement

The console.log statement should be removed before merging to production. Leaving debug logs in production code can impact performance and potentially leak sensitive information.

-    console.log({ occupier, structure, newStructureId });
-
client/apps/game/src/ui/components/resources/realm-transfer.tsx (1)

45-45: Updated resource balance calculation method

The component now uses balanceWithProduction instead of the previous balance method to calculate resource amounts. This change aligns with the centralized liquidity management goal mentioned in the PR objectives by considering production values in the balance calculation.

Make sure to update all other components that depend on this balance calculation to ensure consistency throughout the application.

client/apps/game/src/ui/elements/stamina-resource-cost.tsx (1)

2-15: Enhanced path-based stamina cost calculation

The component has been significantly refactored to handle dynamic path-based stamina costs rather than simple travel length calculations. This allows for more accurate resource management with:

  • Detailed path-specific stamina costs
  • Per-tile biome information
  • Visual feedback on sufficient/insufficient stamina

Consider adding error handling for edge cases where path might be empty or contain invalid data:

  const pathInfo = useMemo(() => {
    if (!stamina) return;
+   if (!path || path.length === 0) return {
+     isExplored,
+     totalCost: 0,
+     balanceColor: "text-order-brilliance",
+     balance: stamina.amount
+   };

    // Calculate total cost and collect biome info
    const totalCost = path.reduce((acc, tile) => {
-     return acc + (tile.staminaCost ?? 0);
+     return acc + (tile?.staminaCost ?? 0);
    }, 0);

Also applies to: 21-37

client/apps/game/src/ui/components/production/buildings-list.tsx (1)

51-54: Refactored resource management to use ResourceManager.

Instead of directly accessing component values, the code now uses the ResourceManager class to handle resource calculation, which provides better encapsulation and consistency, especially important when supporting multiple banks.

When introducing a new pattern like this, consider adding a small comment explaining the rationale, especially since this is part of a larger refactoring effort. It helps future developers understand why the change was made.

client/apps/game/src/ui/components/trading/market-trading-history.tsx (1)

44-48: Updated owner retrieval to use Structure component.

This change reflects the architectural shift to support multiple banks by retrieving ownership information from the Structure component instead of the Owner component. This approach allows for more flexible ownership management across multiple banks.

Consider extracting this owner retrieval logic into a reusable utility function since it's used multiple times in this file.

Also applies to: 50-54

client/apps/game/src/ui/components/trading/transfer-view.tsx (1)

48-54: Improved structure property access pattern

The code now directly accesses position and owner data from the structure object, reducing component dependencies and streamlining the code. Position is constructed directly from coordinates, and owner is accessed directly from the structure object.

Consider creating a helper function or utility to consistently transform structure data into the required format, especially since this pattern is repeated elsewhere in the codebase.

client/apps/game/src/ui/modules/entity-details/building-entity-details.tsx (1)

139-150: Refactored building destruction logic

The logic for checking if a building can be destroyed has been significantly improved:

  1. Now directly retrieves the structure using the Structure component
  2. Fetches population data from StructureBuildings instead of a different source
  3. More clearly compares population capacity using population?.population.max and population?.population.current

This approach simplifies the code flow and improves clarity in how population constraints are evaluated.

The nullish coalescing check on line 150 could be slightly simplified if population.population.max and population.population.current are guaranteed to be defined when population exists. Consider adding a type guard to make this more explicit.

client/apps/game/src/ui/components/military/structure-defence.tsx (1)

145-147: Hardcoded cooldown time value needs to be configurable.

The CooldownTimer is always initialized with 24 hours (24 * 60 * 60 seconds), but this should be configurable or passed through the cooldownSlots data.

interface CooldownTimerProps {
  slot: number;
  time: number; // seconds
}

// Then in the component usage
{cooldownSlots.includes(index) ? (
-  <CooldownTimer slot={index} time={24 * 60 * 60} />
+  <CooldownTimer slot={index} time={cooldownTimes[index] || 24 * 60 * 60} />
) : defense ? (

Consider adding a cooldownTimes property to the StructureDefenceProps interface:

interface StructureDefenceProps {
  maxDefenses: number; // 1-4
  troops: DefenseTroop[];
  cooldownSlots?: number[]; // Slots with active cooldown [1, 4]
  cooldownTimes?: Record<number, number>; // Map of slot index to cooldown time in seconds
}
client/apps/game/src/three/scenes/hexception.tsx (1)

625-625: Changed biome retrieval to use static method.

The code now uses Biome.getBiome() (static method) instead of this.biome.getBiome() (instance method), reflecting an architectural change in how biome data is accessed.

Since the biome property was removed from the HexceptionScene class, ensure that the static Biome.getBiome() method is properly implemented and accessible throughout the codebase. Consider adding error handling if the method could potentially return undefined values:

-const biome = Biome.getBiome(targetHex.col, targetHex.row);
+const biome = Biome.getBiome(targetHex.col, targetHex.row) || BiomeType.Grassland; // Provide fallback
client/apps/game/src/ui/components/military/troop-chip.tsx (1)

38-38: Tier display enhancements.

Exposing the tier value is helpful for clarity. If multiple tiers become more nuanced, you might consider styling or icons for each tier level (e.g., a different color or badge).

client/apps/game/src/three/helpers/pathfinding.ts (1)

79-79: Heuristic aligns with hex logic.

Using a hex distance as the heuristic is appropriate for this coordinate system, ensuring consistent calculations. If your domain expands—for example, to handle certain terrain costs—consider tweaking the heuristic to reflect that complexity.

client/apps/game/src/ui/components/military/army-chip.tsx (4)

79-80: Update conditional rendering to use a more specific property

The current condition uses army as a boolean check, which is too generic and may lead to unintended behavior. Consider using a more specific property of the army object that accurately reflects whether it's a defensive army.

-      ${army ? "defensive-army-selector" : "attacking-army-selector"}
+      ${army.isDefensive ? "defensive-army-selector" : "attacking-army-selector"}

107-108: Use type coercion for consistent comparison

The troops.count is a BigInt (indicated by the 0n literal), but the conditional rendering is using a direct comparison. It's better to explicitly compare with BigInt values for consistency.

-${army.troops.count === 0n ? "animate-pulse" : ""}
+${army.troops.count === 0n ? "animate-pulse" : ""}
-${army ? "defensive-army-edit-selector" : "attacking-army-edit-selector"}`}
+${army.isDefensive ? "defensive-army-edit-selector" : "attacking-army-edit-selector"}`}

137-138: Use consistent defensive/attacking army check

Similar to previous comments, the conditional here is using the army object itself as a boolean check, which should be replaced with a more specific property.

-${army ? "defensive-army-swap-selector" : "attacking-army-swap-selector"}
+${army.isDefensive ? "defensive-army-swap-selector" : "attacking-army-swap-selector"}

209-242: Re-implementation needed for ArmyMergeTroopsPanel

The ArmyMergeTroopsPanel is showing a work-in-progress message with most of its implementation commented out. This indicates a partial refactoring, which should be completed to maintain functionality for merging troops.

According to the PR description about allowing multiple banks, this component might need to be updated to handle troop movements between banks at different positions. Would you like me to help with reimplementing this component to support the new multi-bank feature?

client/apps/game/src/ui/components/worldmap/armies/action-info.tsx (1)

118-120: Potential issue with isExplored check

The isExplored check relies on the presence of biomeType in the last element of actionPath. This might cause unexpected behavior if actionPath is empty or undefined, as it would access properties of undefined.

-  const isExplored = useMemo(() => {
-    return actionPath?.[actionPath.length - 1].biomeType !== undefined;
-  }, [actionPath]);
+  const isExplored = useMemo(() => {
+    return actionPath && actionPath.length > 0 && actionPath[actionPath.length - 1].biomeType !== undefined;
+  }, [actionPath]);
client/apps/game/src/ui/components/military/army-management-card.tsx (1)

27-31: Keep troop-to-resource mapping updated if new troop types are introduced.
If additional troop types are added in the future, ensure they are mapped here to avoid undefined behavior.

client/apps/game/src/three/systems/system-manager.ts (1)

112-118: Placeholder fields need eventual resolution.
battleId, defender, and currentHealth are hardcoded. Since they’re marked as “todo,” consider finalizing or removing them soon.

client/apps/game/src/three/scenes/worldmap.tsx (3)

58-58: Memory considerations for storing biome info.
Switching from a set to a Map<number, BiomeType> is efficient for tile data, but note that large maps can be memory-intensive if the world is large.


495-589: Chunk-based updates for explored tiles.
Smart approach to re-render only relevant chunks. Confirm performance with large scale expansions.


341-356: Movement logic appears sound.
Consider adding error handling for moveArmy to provide user feedback if the call fails.

client/apps/game/src/ui/layouts/world.tsx (2)

120-130: Consider edge cases and potential duplicates in subscriptions.

This block adds structureEntityId, ADMIN_BANK_ENTITY_ID, and all filtered structures to the subscription object, which may lead to duplicates if they overlap. Additionally, if filteredStructures is very large, memory usage might grow quickly. Confirm that this approach remains performant for large numbers of structures.


187-187: Review necessity of the extra <div>.

This new <div> adds an additional wrapper. If it does not serve a styling or semantic purpose, consider removing it or using a fragment (<>) for cleaner markup.

client/apps/game/src/three/managers/army-manager.ts (1)

311-316: Refactor expanded moveArmy signature with caution.

This method now requires armyHexes, structureHexes, and exploredTiles. If these datasets become large or change frequently, consider caching or throttling calls to avoid performance slowdowns.

client/apps/game/src/ui/components/military/army-list.tsx (4)

35-35: Use a stable loading approach.

Switching to a boolean loading state is simpler than an enum, but confirm that you handle multiple async actions in parallel. If multiple operations can happen, consider implementing a reference count or separate flags to avoid collisions.


37-50: Clarify forced defensive army creation.

Subtracting one from maxArmiesPerStructure effectively forces the user to create a defensive army first. While it might be by design, this could cause confusion. A comment clarifying the rationale or a more explicit approach may help.


53-53: Avoid overloading a single structureArmies array for both attacking and defending counts.

Both numberAttackingArmies and numberDefensiveArmies are set to structureArmies.length. This lumps all armies together. If you plan to differentiate them later, keep logic consistent here or rename these variables to avoid confusion.

Also applies to: 58-58


100-100: Consider semantic grouping.

This <div className="flex justify-center gap-4 my-6"> might benefit from a more descriptive element or ARIA labels if multiple controls are grouped.

client/apps/game/src/dojo/sync.ts (4)

181-198: Event entities query with VariableLen key matching.

Consider adding granular logging for different event types to improve debug visibility.


316-345: New syncStructureData function.

As usage grows, consider grouping related fetches into smaller method calls to make error handling more granular.


347-411: syncPlayerStructuresData method.

This method fetches multiple sets of data in a row. If you’d like, I can help create a combined result structure or potential concurrency approach so multiple awaits run simultaneously.


413-442: syncMarketAndBankData method.

Suggest logging the query time for debouncedGetMarketFromTorii just like with the bank query to maintain consistent performance telemetry.

client/apps/game/src/ui/components/trading/market-order-panel.tsx (1)

606-606: Lords production manager includes production.

If Lords can also be passively produced, consider clarifying that in docs or inline comments to avoid confusion for new contributors.

🛑 Comments failed to post (14)
client/apps/game/src/ui/components/entities/entity.tsx (1)

76-76: ⚠️ Potential issue

Potential bug in arrival time calculation

The calculation Number(0) - currentBlockTimestamp will result in a negative time value, which seems incorrect. The original calculation likely used Number(arrival.arrivesAt) - currentBlockTimestamp to calculate the time remaining.

-          Arriving in {formatTime(Number(0) - currentBlockTimestamp)} to{" "}
+          Arriving in {formatTime(Number(arrival.arrivesAt) - currentBlockTimestamp)} to{" "}
📝 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.

          Arriving in {formatTime(Number(arrival.arrivesAt) - currentBlockTimestamp)} to{" "}
client/apps/game/src/ui/components/production/resource-production-controls.tsx (1)

114-114: 💡 Verification agent

🧩 Analysis chain

Method update: Use balanceWithProduction instead of balance.

Changed from resourceManager.balance(currentDefaultTick) to resourceManager.balanceWithProduction(currentDefaultTick), which suggests the balance calculation now incorporates production factors. This could be important for accurate resource management across multiple banks.

Let's check if this method is consistently updated across other components:


🏁 Script executed:

#!/bin/bash
# Check for any remaining instances of the old balance method
rg "resourceManager\.balance\(" --type ts --type tsx | grep -v "balanceWithProduction"

Length of output: 114


Action: Confirm consistent method update across the codebase

The update in
client/apps/game/src/ui/components/production/resource-production-controls.tsx (line 114) replaces

const balance = resourceManager.balance(currentDefaultTick);

with

const balance = resourceManager.balanceWithProduction(currentDefaultTick);

so that the balance calculation now correctly includes production factors. While our initial search encountered issues due to file type recognition, the new script above is configured to search both .ts and .tsx files for any remaining occurrences of resourceManager.balance( that haven't been updated.

Please run the above verification script and manually confirm that no outdated usages remain.


🏁 Script executed:

[run_scripts]
#!/bin/bash
echo "Searching in .ts files:"
rg "resourceManager\.balance\(" --glob "*.ts" | grep -v "balanceWithProduction"
echo "Searching in .tsx files:"
rg "resourceManager\.balance\(" --glob "*.tsx" | grep -v "balanceWithProduction"

Length of output: 484


Action: Address inconsistent method usage for resource management

The update in client/apps/game/src/ui/components/production/resource-production-controls.tsx correctly replaces

const balance = resourceManager.balance(currentDefaultTick);

with

const balance = resourceManager.balanceWithProduction(currentDefaultTick);

to incorporate production factors. However, our additional search in the codebase revealed an instance in:

  • File: packages/core/src/utils/resources.ts
    Line (approximate): where it calls const balance = resourceManager.balance();

Please review whether this outdated usage should also be updated to balanceWithProduction() for consistency and accurate resource management across multiple banks. If the differing usage is intentional due to context-specific logic, kindly add a clarifying comment in the file.

client/apps/game/src/ui/components/production/labor-production-controls.tsx (1)

74-75: ⚠️ Potential issue

Fix the hardcoded resource balance implementation.

The resource balance calculation has been replaced with a hardcoded value of 0 and a TODO comment. This prevents users from seeing or using their actual resource balances for labor production, making the feature non-functional.

Please implement the proper resource balance calculation. Likely this needs to be replaced with a call to a ResourceManager method, similar to changes made in other components like the production sidebar.

client/apps/game/src/ui/components/worldmap/structures/structure-label.tsx (1)

24-24: 💡 Verification agent

🧩 Analysis chain

Updated structure owner access pattern

The code has been modified to directly use structure?.owner instead of accessing structure?.owner.address. This change suggests the structure of the owner property has been simplified from an object to a direct value.


🏁 Script executed:

#!/bin/bash
# Check for other instances of owner.address to ensure consistent updates
echo "Checking for other instances of owner.address access pattern..."
rg "owner\.address" -t ts -t tsx

Length of output: 199


Below is a revised review comment with an updated verification step to ensure the new access pattern is applied consistently across the codebase:


Verify Updated Owner Access Pattern
The change from using structure?.owner.address to structure?.owner correctly reflects the simplified structure for the owner property. To ensure that no residual references to the old owner.address pattern remain, please re-run a verification search using the updated script below:

If this search returns no results, it confirms that all occurrences have been properly updated. Please verify the output manually.


🏁 Script executed:

[run_scripts]
#!/bin/bash
echo "Rechecking for any usage of 'owner.address' pattern in TypeScript files..."
rg "owner\.address" --glob "*.ts" --glob "*.tsx" .

Length of output: 815


Unified Owner Access Update Needed
The update in client/apps/game/src/ui/components/worldmap/structures/structure-label.tsx correctly simplifies the owner access by using structure?.owner instead of structure?.owner.address. However, a subsequent search detected that the old access pattern (owner.address) is still used elsewhere in the codebase:

  • client/apps/game/src/three/managers/structure-manager.ts

    • Usage instances:
      • isAddressEqualToAccount(owner.address)
      • structure.isMine = isAddressEqualToAccount(structure.owner.address)
  • client/apps/game/src/three/managers/army-manager.ts

    • Usage instances:
      • isAddressEqualToAccount(owner.address)
      • army.isMine = isAddressEqualToAccount(army.owner.address)

To ensure consistency with the new, simplified data structure for the owner property, please review and update these occurrences accordingly.

client/apps/game/src/ui/components/bank/swap.tsx (1)

54-58: ⚠️ Potential issue

TODO comment indicates incomplete work.

The bank protector logic has been commented out and marked as needing fixing. This suggests that the protection mechanism for banks is being redesigned to accommodate multiple banks.

Make sure to address this TODO before finalizing the PR. The bank protector logic may be crucial for security or gameplay balance, especially in a multi-bank system.

client/apps/game/src/three/managers/highlight-hex-manager.ts (1)

8-23: ⚠️ Potential issue

Remove unused exported function.

The exported function getHighlightColorForAction is not being used elsewhere in the codebase according to the pipeline warning. Either remove the export keyword or use this function in other parts of the codebase.

-export const getHighlightColorForAction = (actionType: ActionType): THREE.Vector3 => {
+const getHighlightColorForAction = (actionType: ActionType): THREE.Vector3 => {
📝 Committable suggestion

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

const getHighlightColorForAction = (actionType: ActionType): THREE.Vector3 => {
  switch (actionType) {
    case ActionType.Explore:
      return new THREE.Vector3(0.0, 1.5, 1.5); // More intense cyan
    case ActionType.Move:
      return new THREE.Vector3(0.0, 1.5, 0.0); // More intense green
    case ActionType.Attack:
      return new THREE.Vector3(2.0, 0.0, 0.0); // More intense red
    case ActionType.Help:
      return new THREE.Vector3(1.5, 0.0, 1.5); // More intense purple
    case ActionType.Build:
      return new THREE.Vector3(0.0, 0.0, 1.5); // More intense blue
    default:
      return new THREE.Vector3(1.5, 1.5, 1.5); // More intense white
  }
};
🧰 Tools
🪛 GitHub Actions: knip

[warning] 8-8: Unused export 'getHighlightColorForAction'.

client/apps/game/src/ui/components/military/structure-defence.tsx (1)

88-91: 🛠️ Refactor suggestion

Remove console.log statement before production.

The function logs the new defense order to the console but doesn't provide a way for parent components to use this updated order.

  const handleConfirm = () => {
-   console.log("New defense order confirmed:", defenseTroops);
    setIsReordering(false);
  };

Consider adding an onOrderChange callback prop to allow parent components to receive the updated order:

interface StructureDefenceProps {
  maxDefenses: number; // 1-4
  troops: DefenseTroop[];
  cooldownSlots?: number[]; // Slots with active cooldown [1, 4]
+  onOrderChange?: (newOrder: DefenseTroop[]) => void;
}

// Then update handleConfirm
const handleConfirm = () => {
-  console.log("New defense order confirmed:", defenseTroops);
+  onOrderChange?.(defenseTroops);
  setIsReordering(false);
};
📝 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.

interface StructureDefenceProps {
  maxDefenses: number; // 1-4
  troops: DefenseTroop[];
  cooldownSlots?: number[]; // Slots with active cooldown [1, 4]
  onOrderChange?: (newOrder: DefenseTroop[]) => void;
}

const handleConfirm = () => {
  onOrderChange?.(defenseTroops);
  setIsReordering(false);
};
client/apps/game/src/ui/components/worldmap/structures/structure-list-item.tsx (1)

76-76: ⚠️ Potential issue

Fix incorrect rendering of showButtons prop.

The boolean showButtons prop is being rendered directly in the JSX, which will display the text "true" or "false" when rendered. This was likely meant to conditionally render UI buttons.

-      {showButtons}
+      {showButtons && (
+        <div className="flex flex-col gap-2 ml-2">
+          {/* Add your buttons here */}
+        </div>
+      )}
📝 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.

      {showButtons && (
        <div className="flex flex-col gap-2 ml-2">
          {/* Add your buttons here */}
        </div>
      )}
client/apps/game/src/hooks/context/starknet-provider.tsx (2)

81-81: ⚠️ Potential issue

Unsafe type casting in connector prop.

The code uses a double type cast connector as never as Connector which is a workaround for type incompatibility. This might hide potential runtime errors.

Consider adding proper type handling:

-connectors={[connector as never as Connector]}
+connectors={connector ? [connector as Connector] : []}
📝 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.

      connectors={connector ? [connector as Connector] : []}

31-38: ⚠️ Potential issue

Potential race condition in predeployed accounts initialization.

The predeployed accounts are loaded asynchronously without proper error handling or safeguards. The predeployedAccountsConnector array might be empty when accessed in the useMemo hook if the promise hasn't resolved yet.

Consider adding error handling and a loading state:

+import { useEffect, useState } from "react";

+const [predeployedAccountsConnector, setPredeployedAccountsConnector] = useState<PredeployedAccountsConnector[]>([]);
+const [isLoading, setIsLoading] = useState(env.VITE_PUBLIC_CHAIN === "local");

+useEffect(() => {
  if (env.VITE_PUBLIC_CHAIN === "local") {
+    setIsLoading(true);
    predeployedAccounts({
      rpc: env.VITE_PUBLIC_NODE_URL as string,
      id: "katana",
      name: "Katana",
-    }).then((p) => (predeployedAccountsConnector = p));
+    })
+      .then((p) => setPredeployedAccountsConnector(p))
+      .catch((err) => console.error("Failed to load predeployed accounts:", err))
+      .finally(() => setIsLoading(false));
  }
+}, [env.VITE_PUBLIC_CHAIN]);
📝 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.

import { useEffect, useState } from "react";

// ... other imports and code

const [predeployedAccountsConnector, setPredeployedAccountsConnector] = useState<PredeployedAccountsConnector[]>([]);
const [isLoading, setIsLoading] = useState(env.VITE_PUBLIC_CHAIN === "local");

useEffect(() => {
  if (env.VITE_PUBLIC_CHAIN === "local") {
    setIsLoading(true);
    predeployedAccounts({
      rpc: env.VITE_PUBLIC_NODE_URL as string,
      id: "katana",
      name: "Katana",
    })
      .then((p) => setPredeployedAccountsConnector(p))
      .catch((err) => console.error("Failed to load predeployed accounts:", err))
      .finally(() => setIsLoading(false));
  }
}, [env.VITE_PUBLIC_CHAIN]);

// ... rest of the component code
client/apps/game/src/ui/components/military/army-management-card.tsx (2)

81-90: 🛠️ Refactor suggestion

Handle promise for asynchronous troop addition.
armyManager.addTroops is called without await. Consider awaiting the promise to handle errors or confirm transaction success before resetting the troop count.

 const handleBuyArmy = async () => {
   if (!selectedTroopType) return;
   setIsLoading(true);
   const troops = { /* omitted for brevity */ };
-  armyManager.addTroops(account, troops);
+  await armyManager.addTroops(account, troops).catch(console.error);
   setTroopCount(0);
   setIsLoading(false);
 };
📝 Committable suggestion

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

  const handleBuyArmy = async () => {
    if (!selectedTroopType) return;

    setIsLoading(true);
    const troops = {
      [ResourcesIds.Knight]: 0,
      [ResourcesIds.Crossbowman]: 0,
      [ResourcesIds.Paladin]: 0,
      [troopTypeToResourcesId[selectedTroopType]]: multiplyByPrecision(troopCount),
    };
    await armyManager.addTroops(account, troops).catch(console.error);
    setTroopCount(0);
    setIsLoading(false);
  };

135-135: ⚠️ Potential issue

Fix syntax error in the Paladin line.
There is an extra parenthesis after currencyFormat causing a parse error.

-  current: army?.troops.category === TroopType.Paladin ? currencyFormat(Number(army?.troops.count || 0), 0), 0) : 0,
+  current: army?.troops.category === TroopType.Paladin ? currencyFormat(Number(army?.troops.count || 0), 0) : 0,
📝 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.

      current: army?.troops.category === TroopType.Paladin ? currencyFormat(Number(army?.troops.count || 0), 0) : 0,
client/apps/game/src/three/managers/army-manager.ts (1)

326-330: 🛠️ Refactor suggestion

Extract stamina usage and path limit to a more flexible system.

Currently, the code uses Paladin stamina as a universal maximum. This may not scale if you introduce diverse troop types or unique stamina rules. Consider building a more generic approach to adapt to different unit types.

- // todo: currently taking max stamina of paladin as max stamina but need to refactor
- const maxTroopStamina = configManager.getTroopStaminaConfig(TroopType.Paladin);
- const maxHex = Math.floor(Number(maxTroopStamina) / configManager.getMinTravelStaminaCost());
+ // Proposed flexible system for multiple troop types or custom travel limits
+ const troopStamina = someDynamicTroopStamina(armyData.order, armyData.troops);
+ const maxHex = calculateMaxHexDistance(troopStamina);

Committable suggestion skipped: line range outside the PR's diff.

client/apps/game/src/ui/components/military/army-list.tsx (1)

64-65: 🛠️ Refactor suggestion

Improve error handling in handleCreateArmy.

Throwing an error if entity_id is undefined can abruptly break the UI. Consider user-friendly error messages or a fallback path. Also ensure that calling setLoading(true) is balanced with a guaranteed cleanup in case early returns occur.

Also applies to: 68-68, 71-71

@credence0x credence0x merged commit 85c80f4 into feat/new-combat Feb 26, 2025
7 of 16 checks passed
@credence0x credence0x deleted the feat/multiple-banks branch February 26, 2025 05:46
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.

1 participant