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

refactor + knip + prettier #2669

Merged
merged 4 commits into from
Jan 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions .knip.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"**/vitest**",
"client/apps/game/src/setupTests.ts",

"client/sdk/packages/**",
"packages/**",

"**/**__test__**/**",
"**/**__tests__**/**",
Expand All @@ -21,6 +21,11 @@
"client/apps/game-docs/docs/**",
"client/apps/game-docs/vocs.config.ts",

"client/apps/game/src/ui/modules/chat/**"
"client/apps/game/src/ui/modules/chat/**",

"config/**",
"contracts/**",

"**/global.d.ts"
]
}
4 changes: 3 additions & 1 deletion client/apps/game-docs/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
dist/
dist/
node_modules/
vocs.config.ts.timestamp-*.mjs
1 change: 1 addition & 0 deletions client/apps/game-docs/docs/components/QuestRewards.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ETERNUM_CONFIG } from "@/utils/config";
import { QuestType, findResourceById } from "@bibliothecadao/eternum";
import { addSpacesBeforeCapitals, formatAmount } from "../utils/formatting";
import ResourceIcon from "./ResourceIcon";
Expand Down
18 changes: 8 additions & 10 deletions client/apps/game-docs/docs/components/ResourceTable.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
import {
findResourceById,
RESOURCE_PRODUCTION_INPUT_RESOURCES,
RESOURCE_PRODUCTION_OUTPUT_AMOUNTS,
ResourcesIds,
} from "@bibliothecadao/eternum";
import { ETERNUM_CONFIG } from "@/utils/config";
import { findResourceById, RESOURCE_PRECISION, ResourcesIds } from "@bibliothecadao/eternum";
import { useMemo } from "react";
import ResourceIcon from "./ResourceIcon";

const eternumConfig = ETERNUM_CONFIG();

export default function ResourceTable() {
const resourceTable = useMemo(() => {
const resources = [];
for (const resourceId of Object.keys(RESOURCE_PRODUCTION_INPUT_RESOURCES) as unknown as ResourcesIds[]) {
for (const resourceId of Object.keys(eternumConfig.resources.resourceInputs) as unknown as ResourcesIds[]) {
if (resourceId === ResourcesIds.Lords) continue;
const calldata = {
resource: findResourceById(Number(resourceId)),
amount: RESOURCE_PRODUCTION_OUTPUT_AMOUNTS[resourceId],
amount: eternumConfig.resources.resourceInputs[resourceId],
resource_type: resourceId,
cost: RESOURCE_PRODUCTION_INPUT_RESOURCES[resourceId].map((cost: any) => ({
cost: eternumConfig.resources.resourceInputs[resourceId].map((cost: any) => ({
...cost,
amount: cost.amount * ETERNUM_CONFIG().resources.resourcePrecision,
amount: cost.amount * RESOURCE_PRECISION,
name: findResourceById(cost.resource)?.trait || "",
})),
};
Comment on lines +11 to 21
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

Improve type safety and error handling in resource processing.

The code uses unsafe type casting and lacks proper type definitions:

+interface ResourceCost {
+  resource: number;
+  amount: number;
+}
+
 const resourceTable = useMemo(() => {
   const resources = [];
-  for (const resourceId of Object.keys(eternumConfig.resources.resourceInputs) as unknown as ResourcesIds[]) {
+  const resourceIds = Object.keys(eternumConfig.resources.resourceInputs)
+    .filter((id): id is keyof typeof ResourcesIds => {
+      const numId = Number(id);
+      return !isNaN(numId) && Object.values(ResourcesIds).includes(numId);
+    });
+
+  for (const resourceId of resourceIds) {
     if (resourceId === ResourcesIds.Lords) continue;
+    
+    const resource = findResourceById(Number(resourceId));
+    if (!resource) {
+      console.warn(`Resource not found for ID: ${resourceId}`);
+      continue;
+    }
+
     const calldata = {
-      resource: findResourceById(Number(resourceId)),
+      resource,
       amount: eternumConfig.resources.resourceInputs[resourceId],
       resource_type: resourceId,
-      cost: eternumConfig.resources.resourceInputs[resourceId].map((cost: any) => ({
+      cost: eternumConfig.resources.resourceInputs[resourceId].map((cost: ResourceCost) => ({
         ...cost,
         amount: cost.amount * RESOURCE_PRECISION,
         name: findResourceById(cost.resource)?.trait || "",
       })),
     };

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

Expand Down
7 changes: 5 additions & 2 deletions client/apps/game-docs/docs/components/TroopsTable.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { ETERNUM_CONFIG } from "@/utils/config";
import { ResourcesIds, TROOPS_FOOD_CONSUMPTION, TROOPS_STAMINAS, findResourceById } from "@bibliothecadao/eternum";
import { formatAmount, formatNumberWithSpaces } from "../utils/formatting";
import ResourceIcon from "./ResourceIcon";

const eternumConfig = ETERNUM_CONFIG();

type TroopId = keyof typeof TROOPS_STAMINAS;

export default function TroopsTable() {
Expand Down Expand Up @@ -61,12 +64,12 @@ export default function TroopsTable() {
<div className="grid grid-cols-3 gap-2">
<div className="text-left">
<div>Travel</div>
<div className="text-gray-400">{formatNumberWithSpaces(ETERNUM_CONFIG().stamina.travelCost)}</div>
<div className="text-gray-400">{formatNumberWithSpaces(eternumConfig.stamina.travelCost)}</div>
</div>

<div className="text-left">
<div>Explore</div>
<div className="text-gray-400">{formatNumberWithSpaces(ETERNUM_CONFIG().stamina.exploreCost)}</div>
<div className="text-gray-400">{formatNumberWithSpaces(eternumConfig.stamina.exploreCost)}</div>
</div>

<div className="flex justify-center items-center mt-4">
Expand Down
7 changes: 7 additions & 0 deletions client/apps/game-docs/docs/utils/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Chain, getConfigFromNetwork } from "@config";
import { env } from "../../env";

export const ETERNUM_CONFIG = () => {
const config = getConfigFromNetwork(env.VITE_PUBLIC_CHAIN! as Chain);
return config;
};
Comment on lines +4 to +7
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

Add error handling and type safety for environment variable.

The non-null assertion (!) on env.VITE_PUBLIC_CHAIN could lead to runtime errors if the environment variable is missing. Consider adding proper validation:

 export const ETERNUM_CONFIG = () => {
-  const config = getConfigFromNetwork(env.VITE_PUBLIC_CHAIN! as Chain);
+  if (!env.VITE_PUBLIC_CHAIN) {
+    throw new Error('VITE_PUBLIC_CHAIN environment variable is required');
+  }
+  if (!Object.values(Chain).includes(env.VITE_PUBLIC_CHAIN as Chain)) {
+    throw new Error(`Invalid chain value: ${env.VITE_PUBLIC_CHAIN}`);
+  }
+  const config = getConfigFromNetwork(env.VITE_PUBLIC_CHAIN as Chain);
   return config;
 };
📝 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
export const ETERNUM_CONFIG = () => {
const config = getConfigFromNetwork(env.VITE_PUBLIC_CHAIN! as Chain);
return config;
};
export const ETERNUM_CONFIG = () => {
if (!env.VITE_PUBLIC_CHAIN) {
throw new Error('VITE_PUBLIC_CHAIN environment variable is required');
}
if (!Object.values(Chain).includes(env.VITE_PUBLIC_CHAIN as Chain)) {
throw new Error(`Invalid chain value: ${env.VITE_PUBLIC_CHAIN}`);
}
const config = getConfigFromNetwork(env.VITE_PUBLIC_CHAIN as Chain);
return config;
};

Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { RESOURCE_PRECISION } from "@bibliothecadao/eternum";

export function addSpacesBeforeCapitals(str: string): string {
return str.replace(/([A-Z])/g, " $1").trim();
}
Expand All @@ -8,11 +10,11 @@ export function formatNumberWithSpaces(number: number): string {

export const formatAmount = (amount: number) => {
if (amount < 1) {
return `${amount * ETERNUM_CONFIG().resources.resourcePrecision}`;
} else if (amount < ETERNUM_CONFIG().resources.resourcePrecision) {
return `${amount * RESOURCE_PRECISION}`;
} else if (amount < RESOURCE_PRECISION) {
return `${amount.toFixed(amount % 1 === 0 ? 0 : (amount % 1) % 0.1 === 0 ? 1 : 2)}K`;
} else {
return `${(amount / ETERNUM_CONFIG().resources.resourcePrecision).toFixed(amount % ETERNUM_CONFIG().resources.resourcePrecision === 0 ? 0 : (amount % ETERNUM_CONFIG().resources.resourcePrecision) % 10 === 0 ? 1 : 2)}M`;
return `${(amount / RESOURCE_PRECISION).toFixed(amount % RESOURCE_PRECISION === 0 ? 0 : (amount % RESOURCE_PRECISION) % 10 === 0 ? 1 : 2)}M`;
}
};

Expand All @@ -31,5 +33,5 @@ export function formatNumberWithCommas(number: number): string {
}

export const currencyFormat = (num: number, decimals: number): string => {
return formatNumber(num / ETERNUM_CONFIG().resources.resourcePrecision, decimals);
return formatNumber(num / RESOURCE_PRECISION, decimals);
};
3 changes: 3 additions & 0 deletions client/apps/game-docs/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const env = {
VITE_PUBLIC_CHAIN: process.env.VITE_PUBLIC_CHAIN || "mainnet",
} as const;
19 changes: 19 additions & 0 deletions client/apps/game-docs/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "bundler",
"allowJs": true,
"esModuleInterop": true,
"jsx": "preserve",
"paths": {
"@/*": ["./docs/*"],
"@config/*": ["../../../config/utils/utils/*"],
"@config": ["../../../config/utils/utils"]
},
"baseUrl": ".",
"skipLibCheck": true
},
"include": ["**/*.ts", "**/*.tsx", "**/*.md", "**/*.mdx"],
"exclude": ["node_modules"]
}
1 change: 1 addition & 0 deletions client/apps/game-docs/vocs.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export default defineConfig({
resolve: {
alias: {
"@": path.resolve(__dirname, "./docs"),
"@config": path.resolve(__dirname, "../../../config/utils/utils"),
},
},
publicDir: "../../common/public",
Expand Down
6 changes: 3 additions & 3 deletions client/apps/game/dojoConfig.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ETERNUM_CONFIG } from "@/utils/config";
import { Chain, getGameManifest } from "@config";
import { Chain, getGameManifest } from "@contracts";
import { createDojoConfig } from "@dojoengine/core";
import { env } from "./env";

Expand All @@ -14,7 +14,7 @@ const {
VITE_PUBLIC_CHAIN,
} = env;

const manifest = await getGameManifest(VITE_PUBLIC_CHAIN! as Chain);
const manifest = getGameManifest(VITE_PUBLIC_CHAIN! as Chain);

export const dojoConfig = createDojoConfig({
rpcUrl: VITE_PUBLIC_NODE_URL,
Expand All @@ -28,6 +28,6 @@ export const dojoConfig = createDojoConfig({
manifest,
});

const config = await ETERNUM_CONFIG();
const config = ETERNUM_CONFIG();
console.log("logging eternum configuration json from file");
console.log({ config });
14 changes: 0 additions & 14 deletions client/apps/game/src/dojo/debounced-queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
getEntitiesFromTorii,
getMarketFromTorii,
getOneKeyModelbyRealmEntityIdFromTorii,
getTwoKeyModelbyRealmEntityIdFromTorii,
} from "./queries";

// Queue class to manage requests
Expand Down Expand Up @@ -53,19 +52,6 @@ class RequestQueue {
const subscriptionQueue = new RequestQueue();
const marketQueue = new RequestQueue();

export const debouncedTwoKeyEntitiesFromTorii = debounce(
async <S extends Schema>(
client: ToriiClient,
components: Component<S, Metadata, undefined>[],
entityID: string[],
onComplete?: () => void,
) => {
await subscriptionQueue.add(() => getTwoKeyModelbyRealmEntityIdFromTorii(client, components, entityID), onComplete);
},
250,
{ leading: true },
);

export const debouncedGetOneKeyEntitiesByRealmEntityIdFromTorii = debounce(
async <S extends Schema>(
client: ToriiClient,
Expand Down
29 changes: 0 additions & 29 deletions client/apps/game/src/dojo/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,6 @@ import { Component, Metadata, Schema } from "@dojoengine/recs";
import { getEntities } from "@dojoengine/state";
import { PatternMatching, ToriiClient } from "@dojoengine/torii-client";
import { LogicalOperator } from "@dojoengine/torii-wasm";
// on hexception -> fetch below queries based on entityID

export const getTwoKeyModelbyRealmEntityIdFromTorii = async <S extends Schema>(
client: ToriiClient,
components: Component<S, Metadata, undefined>[],
entityID: string[],
) => {
await getEntities(
client,
{
Composite: {
operator: "Or",
clauses: [
...entityID.map((id) => ({
Keys: {
keys: [id, undefined],
pattern_matching: "VariableLen" as PatternMatching,
models: ["s1_eternum-BuildingQuantityv2"],
},
})),
],
},
},
components,
[],
["s1_eternum-BuildingQuantityv2"],
20_000,
);
};

export const getOneKeyModelbyRealmEntityIdFromTorii = async <S extends Schema>(
client: ToriiClient,
Expand Down
1 change: 0 additions & 1 deletion client/apps/game/src/hooks/context/policies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -714,5 +714,4 @@ export const policies: ContractPolicies = {
},
],
},

};
2 changes: 1 addition & 1 deletion client/apps/game/src/hooks/context/starknet-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ enum StarknetChainId {
SN_SEPOLIA = "0x534e5f5345504f4c4941",
}

const resourceAddresses = await getResourceAddresses();
const resourceAddresses = getResourceAddresses();

const LORDS = resourceAddresses["LORDS"][1].toString();
const otherResources = Object.entries(resourceAddresses)
Expand Down
8 changes: 1 addition & 7 deletions client/apps/game/src/hooks/helpers/use-quests.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import { useUIStore } from "@/hooks/store/use-ui-store";
import { Prize, QuestType } from "@bibliothecadao/eternum";
import { Prize, QuestStatus, QuestType } from "@bibliothecadao/eternum";
import { useDojo } from "@bibliothecadao/react";
import { useEntityQuery } from "@dojoengine/react";
import { getComponentValue, HasValue } from "@dojoengine/recs";
import { getEntityIdFromKeys } from "@dojoengine/utils";
import { useMemo } from "react";
import { QUEST_DETAILS } from "./use-starting-tutorial";

export enum QuestStatus {
InProgress,
Completed,
Claimed,
}

export const useQuests = () => {
const questStatus = useQuestClaimStatus();

Expand Down
15 changes: 8 additions & 7 deletions client/apps/game/src/three/managers/biome.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ import * as THREE from "three";
const MAP_AMPLITUDE = FixedTrait.fromInt(60n);
const MOISTURE_OCTAVE = FixedTrait.fromInt(2n);
const ELEVATION_OCTAVES = [
FixedTrait.fromInt(1n), // 1
FixedTrait.fromRatio(1n, 4n), // 0.25
FixedTrait.fromRatio(1n, 10n) // 0.1
FixedTrait.fromInt(1n), // 1
FixedTrait.fromRatio(1n, 4n), // 0.25
FixedTrait.fromRatio(1n, 10n), // 0.1
];
const ELEVATION_OCTAVES_SUM = ELEVATION_OCTAVES.reduce((a, b) => a.add(b), FixedTrait.ZERO);


export enum BiomeType {
DeepOcean = "DeepOcean",
Ocean = "Ocean",
Expand All @@ -29,7 +28,7 @@ export enum BiomeType {
TemperateRainForest = "TemperateRainForest",
SubtropicalDesert = "SubtropicalDesert",
TropicalSeasonalForest = "TropicalSeasonalForest",
TropicalRainForest = "TropicalRainForest"
TropicalRainForest = "TropicalRainForest",
}

export const BIOME_COLORS: Record<BiomeType, THREE.Color> = {
Expand Down Expand Up @@ -91,11 +90,13 @@ export class Biome {
return elevation.div(octavesSum).div(FixedTrait.fromInt(100n));
}


private calculateMoisture(col: number, row: number, mapAmplitude: Fixed, moistureOctave: Fixed): Fixed {
const moistureX = moistureOctave.mul(FixedTrait.fromInt(BigInt(col))).div(mapAmplitude);
const moistureZ = moistureOctave.mul(FixedTrait.fromInt(BigInt(row))).div(mapAmplitude);
const noise = snoise(Vec3.new(moistureX, FixedTrait.ZERO, moistureZ)).add(FixedTrait.ONE).mul(FixedTrait.fromInt(100n)).div(FixedTrait.fromInt(2n));
const noise = snoise(Vec3.new(moistureX, FixedTrait.ZERO, moistureZ))
.add(FixedTrait.ONE)
.mul(FixedTrait.fromInt(100n))
.div(FixedTrait.fromInt(2n));
return FixedTrait.floor(noise).div(FixedTrait.fromInt(100n));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const SelectedArmy = () => {
return <SelectedArmyContent selectedHex={selectedHex} />;
};

export const SelectedArmyContent = ({ selectedHex }: { selectedHex: HexPosition }) => {
const SelectedArmyContent = ({ selectedHex }: { selectedHex: HexPosition }) => {
const selectedEntityId = useUIStore((state) => state.armyActions.selectedEntityId);
const updateSelectedEntityId = useUIStore((state) => state.updateSelectedEntityId);

Expand Down
2 changes: 1 addition & 1 deletion client/apps/game/src/ui/modules/onboarding/steps.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ export const SettleRealm = ({ onPrevious }: { onPrevious: () => void }) => {
owner: account.address,
frontend: env.VITE_PUBLIC_CLIENT_FEE_RECIPIENT,
signer: account,
season_pass_address: await getSeasonPassAddress(),
season_pass_address: getSeasonPassAddress(),
});
setSelectedRealms([]);
onPrevious();
Expand Down
4 changes: 2 additions & 2 deletions client/apps/game/src/ui/modules/rewards/rewards.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export const Rewards = () => {

useEffect(() => {
const init = async () => {
const address = await getLordsAddress();
const address = getLordsAddress();
setLordsAddress(address);
};
init();
Expand Down Expand Up @@ -83,7 +83,7 @@ export const Rewards = () => {
}, [leaderboardManager]);

const claimRewards = useCallback(async () => {
const lordsAddress = await getLordsAddress();
const lordsAddress = getLordsAddress();
setIsLoading(true);
try {
await claim_leaderboard_rewards({
Expand Down
18 changes: 7 additions & 11 deletions client/apps/game/src/utils/addresses.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
import { Chain, getSeasonAddresses } from "@config";
import { Chain, getSeasonAddresses } from "@contracts";
import { env } from "../../env";

export const getResourceAddresses = async () => {
const addresses = (await getSeasonAddresses(env.VITE_PUBLIC_CHAIN as Chain)).resources;
export const getResourceAddresses = () => {
const addresses = getSeasonAddresses(env.VITE_PUBLIC_CHAIN as Chain).resources;
return addresses;
};

export const getSeasonPassAddress = async () => {
return (await getSeasonAddresses(env.VITE_PUBLIC_CHAIN as Chain)).seasonPass;
export const getSeasonPassAddress = () => {
return getSeasonAddresses(env.VITE_PUBLIC_CHAIN as Chain).seasonPass;
};

export const getLordsAddress = async () => {
return (await getSeasonAddresses(env.VITE_PUBLIC_CHAIN as Chain)).lords;
};

export const getRealmsAddress = async () => {
return (await getSeasonAddresses(env.VITE_PUBLIC_CHAIN as Chain)).realms;
export const getLordsAddress = () => {
return getSeasonAddresses(env.VITE_PUBLIC_CHAIN as Chain).lords;
};
Loading
Loading