Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/next' into bridge
Browse files Browse the repository at this point in the history
  • Loading branch information
RedBeardEth committed Dec 12, 2024
2 parents 0ca8635 + 2eae96c commit ddd42a2
Show file tree
Hide file tree
Showing 8 changed files with 94 additions and 52 deletions.
14 changes: 7 additions & 7 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@
"@bibliothecadao/eternum": "workspace:^",
"@cartridge/connector": "0.5.5",
"@cartridge/controller": "0.5.5",
"@dojoengine/core": "1.0.3-alpha.0",
"@dojoengine/torii-wasm": "1.0.3-alpha.0",
"@dojoengine/create-burner": "1.0.3-alpha.0",
"@dojoengine/react": "1.0.3-alpha.0",
"@dojoengine/core": "1.0.3-alpha.1",
"@dojoengine/torii-wasm": "1.0.3-alpha.1",
"@dojoengine/create-burner": "1.0.3-alpha.1",
"@dojoengine/react": "1.0.3-alpha.1",
"@dojoengine/recs": "^2.0.13",
"@dojoengine/state": "1.0.3-alpha.0",
"@dojoengine/torii-client": "1.0.3-alpha.0",
"@dojoengine/utils": "1.0.3-alpha.0",
"@dojoengine/state": "1.0.3-alpha.1",
"@dojoengine/torii-client": "1.0.3-alpha.1",
"@dojoengine/utils": "1.0.3-alpha.1",
"@headlessui/react": "^1.7.18",
"@latticexyz/utils": "^2.0.0-next.12",
"@radix-ui/react-collapsible": "^1.1.1",
Expand Down
20 changes: 7 additions & 13 deletions client/src/dojo/setup.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {
BUILDING_CATEGORY_POPULATION_CONFIG_ID,
HYPERSTRUCTURE_CONFIG_ID,
WORLD_CONFIG_ID,
WORLD_CONFIG_ID
} from "@bibliothecadao/eternum";
import { DojoConfig } from "@dojoengine/core";
import { getSyncEntities, getSyncEvents, syncEntities } from "@dojoengine/state";
Expand Down Expand Up @@ -30,32 +29,27 @@ export async function setup({ ...config }: DojoConfig) {
},
{
Keys: {
keys: [BUILDING_CATEGORY_POPULATION_CONFIG_ID.toString(), undefined],
keys: [WORLD_CONFIG_ID.toString(), undefined, undefined],
pattern_matching: "FixedLen",
models: [],
},
},
{
Keys: {
keys: [WORLD_CONFIG_ID.toString(), undefined],
pattern_matching: "VariableLen",
models: [],
},
},
{
Keys: {
keys: [WORLD_CONFIG_ID.toString()],
pattern_matching: "VariableLen",
pattern_matching: "FixedLen",
models: [],
},
},
{
Keys: {
keys: [HYPERSTRUCTURE_CONFIG_ID.toString()],
pattern_matching: "VariableLen",
keys: [BUILDING_CATEGORY_POPULATION_CONFIG_ID.toString(), undefined],
pattern_matching: "FixedLen",
models: [],
},
},


];

// fetch all existing entities from torii
Expand Down
8 changes: 7 additions & 1 deletion client/src/hooks/helpers/useEntities.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,12 @@ export const useEntitiesUtils = () => {
}
};

const getAddressName = (address: ContractAddress) => {
const addressName = getComponentValue(AddressName, getEntityIdFromKeys([BigInt(address)]));

return addressName ? shortString.decodeShortString(addressName.name.toString()) : undefined;
};

const getAddressNameFromEntity = (entityId: ID) => {
const address = getPlayerAddressFromEntity(entityId);
if (!address) return;
Expand All @@ -293,5 +299,5 @@ export const useEntitiesUtils = () => {
: undefined;
};

return { getEntityName, getEntityInfo, getAddressNameFromEntity, getPlayerAddressFromEntity };
return { getEntityName, getEntityInfo, getAddressName, getAddressNameFromEntity, getPlayerAddressFromEntity };
};
1 change: 0 additions & 1 deletion client/src/three/scenes/Worldmap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,6 @@ export default class WorldmapScene extends HexagonScene {
}

removeCachedMatricesAroundColRow(col: number, row: number) {
console.log("removing cache", col, row);
for (let i = -this.renderChunkSize.width / 2; i <= this.renderChunkSize.width / 2; i += 10) {
for (let j = -this.renderChunkSize.width / 2; j <= this.renderChunkSize.height / 2; j += 10) {
if (i === 0 && j === 0) {
Expand Down
2 changes: 1 addition & 1 deletion client/src/ui/components/trading/MarketTradingHistory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ export const MarketTradingHistory = () => {
{filteredTradeEvents
.sort((a, b) => b.event.eventTime.getTime() - a.event.eventTime.getTime())
.filter((trade) =>
selectedResourceId
trade.event.resourceGiven && trade.event.resourceTaken && selectedResourceId
? trade.event.resourceGiven.resourceId === selectedResourceId ||
trade.event.resourceTaken.resourceId === selectedResourceId
: true,
Expand Down
30 changes: 20 additions & 10 deletions client/src/ui/components/trading/TradeHistoryEvent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ export const TradeHistoryRowHeader = () => {

export const TradeHistoryEvent = ({ trade }: { trade: TradeEvent }) => {
const { getAddressNameFromEntity } = useEntitiesUtils();

const resourceTaken = trade.event.resourceTaken;
const resourceGiven = trade.event.resourceGiven;
if (!resourceTaken || !resourceGiven) {
return null;
}

const price = getLordsPricePerResource(trade.event.resourceGiven, trade.event.resourceTaken);
const taker = getAddressNameFromEntity(trade.event.takerId);

Expand All @@ -37,12 +44,12 @@ export const TradeHistoryEvent = ({ trade }: { trade: TradeEvent }) => {
<div className={`text-sm my-auto flex flex-row items-center justify-start`}>{taker}</div>
<div className="text-sm my-auto flex flex-row">
<div>{"bought"}</div>
<ResourceIcon resource={ResourcesIds[Number(trade.event.resourceTaken.resourceId)]} size={"sm"} />
<div>{`${currencyIntlFormat(divideByPrecision(trade.event.resourceTaken.amount), 2)} for ${currencyIntlFormat(
divideByPrecision(trade.event.resourceGiven.amount),
<ResourceIcon resource={ResourcesIds[Number(resourceTaken.resourceId)]} size={"sm"} />
<div>{`${currencyIntlFormat(divideByPrecision(resourceTaken.amount), 2)} for ${currencyIntlFormat(
divideByPrecision(resourceGiven.amount),
2,
)}`}</div>
<ResourceIcon resource={ResourcesIds[Number(trade.event.resourceGiven.resourceId)]} size={"sm"} />
<ResourceIcon resource={ResourcesIds[Number(resourceGiven.resourceId)]} size={"sm"} />
</div>
<div className="text-sm my-auto flex flex-row">
{currencyIntlFormat(Number(price), 2)}
Expand All @@ -52,9 +59,7 @@ export const TradeHistoryEvent = ({ trade }: { trade: TradeEvent }) => {
resource={
ResourcesIds[
Number(
trade.event.resourceTaken.resourceId === ResourcesIds.Lords
? trade.event.resourceGiven.resourceId
: trade.event.resourceTaken.resourceId,
resourceTaken.resourceId === ResourcesIds.Lords ? resourceGiven.resourceId : resourceTaken.resourceId,
)
]
}
Expand All @@ -66,8 +71,13 @@ export const TradeHistoryEvent = ({ trade }: { trade: TradeEvent }) => {
};

const getLordsPricePerResource = (resourceA: Resource, resourceB: Resource): number => {
const lordsResource = resourceA.resourceId === ResourcesIds.Lords ? resourceA : resourceB;
const otherResource = resourceA.resourceId === ResourcesIds.Lords ? resourceB : resourceA;
try {
const lordsResource = resourceA.resourceId === ResourcesIds.Lords ? resourceA : resourceB;
const otherResource = resourceA.resourceId === ResourcesIds.Lords ? resourceB : resourceA;

return Number(lordsResource.amount) / Number(otherResource.amount);
return Number(lordsResource.amount) / Number(otherResource.amount);
} catch (e) {
console.error(e);
return 0;
}
};
57 changes: 45 additions & 12 deletions client/src/ui/layouts/World.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { Leva } from "leva";
import { lazy, Suspense, useEffect, useState } from "react";
import { lazy, Suspense, useEffect, useMemo, useState } from "react";
import { Redirect } from "wouter";
import useUIStore from "../../hooks/store/useUIStore";

import { addToSubscription } from "@/dojo/queries";
import { useDojo } from "@/hooks/context/DojoContext";
import { PlayerStructure, useEntities } from "@/hooks/helpers/useEntities";
import { useStructureEntityId } from "@/hooks/helpers/useStructureEntityId";
import { useFetchBlockchainData } from "@/hooks/store/useBlockchainStore";
import { useWorldStore } from "@/hooks/store/useWorldLoading";
Expand Down Expand Up @@ -84,6 +85,7 @@ const MiniMapNavigation = lazy(() =>
);

export const World = ({ backgroundImage }: { backgroundImage: string }) => {
const [subscriptions, setSubscriptions] = useState<{ [entity: string]: boolean }>({});
const showBlankOverlay = useUIStore((state) => state.showBlankOverlay);
const isLoadingScreenEnabled = useUIStore((state) => state.isLoadingScreenEnabled);

Expand All @@ -103,12 +105,21 @@ export const World = ({ backgroundImage }: { backgroundImage: string }) => {

const dojo = useDojo();
const structureEntityId = useUIStore((state) => state.structureEntityId);
const position = useComponentValue(dojo.setup.components.Position, getEntityIdFromKeys([BigInt(structureEntityId)]));

const [lastFetchTimestamp, setLastFetchTimestamp] = useState<number>(Date.now());
const { playerStructures } = useEntities();
const structures = playerStructures();

const filteredStructures = useMemo(
() => structures.filter((structure: PlayerStructure) => !subscriptions[structure.entity_id.toString()]),
[structures, subscriptions],
);

const position = useComponentValue(dojo.setup.components.Position, getEntityIdFromKeys([BigInt(structureEntityId)]));

useEffect(() => {
if (!structureEntityId || subscriptions[structureEntityId.toString()]) return;
setWorldLoading(true);
setSubscriptions((prev) => ({ ...prev, [structureEntityId.toString()]: true }));
const fetch = async () => {
try {
await addToSubscription(
Expand All @@ -123,20 +134,42 @@ export const World = ({ backgroundImage }: { backgroundImage: string }) => {
setWorldLoading(false);
}

// const currentTime = Date.now();
// setLastFetchTimestamp((prevEndTime) => {
// if (prevEndTime === null) return currentTime;
// if (currentTime - prevEndTime >= 3000) {
// setWorldLoading(false);
// }
// return currentTime;
// });
console.log("world loading", worldLoading);
};

fetch();
}, [structureEntityId, subscriptions, setWorldLoading, setSubscriptions]);

useEffect(() => {
if (filteredStructures.length === 0) return;
setWorldLoading(true);
setSubscriptions((prev) => ({
...prev,
...Object.fromEntries(filteredStructures.map((structure) => [structure.entity_id.toString(), true])),
}));
const fetch = async () => {
try {
await Promise.all(
filteredStructures.map((structure: PlayerStructure) =>
addToSubscription(
dojo.network.toriiClient,
dojo.network.contractComponents as any,
structure.entity_id.toString(),
{ x: structure.position.x, y: structure.position.y },
),
),
);
} catch (error) {
console.error("Fetch failed", error);
} finally {
setWorldLoading(false);
}

console.log("world loading", worldLoading);
};

fetch();
}, [structureEntityId, setWorldLoading]);
}, [filteredStructures, setWorldLoading, setSubscriptions]);

return (
<div
Expand Down
14 changes: 7 additions & 7 deletions client/src/ui/modules/social/PlayerId.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export const PlayerId = ({

const { getEntityName } = useEntitiesUtils();

const { getAddressNameFromEntity } = useEntitiesUtils();
const { getAddressName } = useEntitiesUtils();

const playerEntityId = useMemo(() => {
if (!selectedPlayer) return;
Expand All @@ -83,9 +83,7 @@ export const PlayerId = ({
const playerName = useMemo(() => {
if (!selectedPlayer) return;

if (!playerEntityId) return;

const playerName = getAddressNameFromEntity(playerEntityId);
const playerName = getAddressName(selectedPlayer);
return playerName;
}, [selectedPlayer, playerEntityId]);

Expand All @@ -96,7 +94,9 @@ export const PlayerId = ({
SettleRealmData,
Array.from(runQuery([HasValue(SettleRealmData, { owner_address: selectedPlayer })]))[0],
);
return formatTime((useUIStore.getState()?.nextBlockTimestamp ?? 0) - (realmSettleData?.timestamp ?? 0));
return realmSettleData
? formatTime((useUIStore.getState()?.nextBlockTimestamp ?? 0) - (realmSettleData?.timestamp ?? 0))
: undefined;
}, [selectedPlayer, playerEntityId]);

const playerStructures = useMemo(() => {
Expand Down Expand Up @@ -140,10 +140,10 @@ export const PlayerId = ({
</div>

<div className="text-xs italic">
{hasBeenPlayingFor ? `Joined ${hasBeenPlayingFor} ago` : "No player selected"}
{hasBeenPlayingFor ? `Joined ${hasBeenPlayingFor} ago` : "Has not settled a realm yet"}
</div>

<div className="text-xs">{playerEntityId ? `Player ID: ${playerEntityId}` : "No player selected"}</div>
<div className="text-xs">{playerEntityId ? `Player ID: ${playerEntityId}` : ""}</div>
</div>
</div>

Expand Down

0 comments on commit ddd42a2

Please sign in to comment.