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

Fix missing donkeys in bridge step 2 #2598

Merged
merged 3 commits into from
Dec 26, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
43 changes: 22 additions & 21 deletions landing/src/components/modules/bridge-out-step-2.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { displayAddress } from "@/lib/utils";
import { ADMIN_BANK_ENTITY_ID, RESOURCE_PRECISION, ResourcesIds } from "@bibliothecadao/eternum";
import { useAccount } from "@starknet-react/core";
import { ChevronDown, ChevronUp, Loader } from "lucide-react";
import { useEffect, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { TypeP } from "../typography/type-p";
import { ShowSingleResource } from "../ui/SelectResources";
import { Button } from "../ui/button";
Expand Down Expand Up @@ -86,23 +86,27 @@ export const BridgeOutStep2 = () => {
const [selectedDonkeys, setSelectedDonkeys] = useState<Set<bigint>>(new Set());
const [isTableOpen, setIsTableOpen] = useState(false);

const updateResourcesFromSelectedDonkeys = (selectedDonkeyIds: Set<bigint>) => {
const allResources = Array.from(selectedDonkeyIds).flatMap(
(id) =>
donkeyInfos?.find((d) => d?.donkeyEntityId && BigInt(d.donkeyEntityId) === id)?.donkeyResourceBalances || [],
);
const updateResourcesFromSelectedDonkeys = useMemo(
() => (selectedDonkeyIds: Set<bigint>) => {
const allResources = Array.from(selectedDonkeyIds).flatMap(
(id) =>
donkeyInfos?.find((d) => d?.donkeyEntityId && BigInt(d.donkeyEntityId) === id)?.donkeyResourceBalances || [],
);

setSelectedResourceIds(allResources.map((r) => r.resourceId as never));
setSelectedResourceAmounts(
allResources.reduce(
(acc, r) => ({
...acc,
[r.resourceId]: (acc[r.resourceId] || 0) + r.amount / RESOURCE_PRECISION,
}),
{},
),
);
},
[donkeyInfos, selectedDonkeys],
);
Comment on lines +89 to +108
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

Optimize memoization implementation

There are two issues with the current implementation:

  1. The dependency array includes selectedDonkeys but it's not used inside the memoized function.
  2. The memoization benefit is partially negated by creating new objects in every call.

Apply these optimizations:

 const updateResourcesFromSelectedDonkeys = useMemo(
   () => (selectedDonkeyIds: Set<bigint>) => {
     const allResources = Array.from(selectedDonkeyIds).flatMap(
       (id) =>
         donkeyInfos?.find((d) => d?.donkeyEntityId && BigInt(d.donkeyEntityId) === id)?.donkeyResourceBalances || [],
     );

     setSelectedResourceIds(allResources.map((r) => r.resourceId as never));
     setSelectedResourceAmounts(
       allResources.reduce(
         (acc, r) => {
-          return {
-            ...acc,
-            [r.resourceId]: (acc[r.resourceId] || 0) + r.amount / RESOURCE_PRECISION,
-          }
+          acc[r.resourceId] = (acc[r.resourceId] || 0) + r.amount / RESOURCE_PRECISION;
+          return acc;
         },
         {} as { [key: string]: number }
       ),
     );
   },
-  [donkeyInfos, selectedDonkeys],
+  [donkeyInfos],
 );
📝 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 updateResourcesFromSelectedDonkeys = useMemo(
() => (selectedDonkeyIds: Set<bigint>) => {
const allResources = Array.from(selectedDonkeyIds).flatMap(
(id) =>
donkeyInfos?.find((d) => d?.donkeyEntityId && BigInt(d.donkeyEntityId) === id)?.donkeyResourceBalances || [],
);
setSelectedResourceIds(allResources.map((r) => r.resourceId as never));
setSelectedResourceAmounts(
allResources.reduce(
(acc, r) => ({
...acc,
[r.resourceId]: (acc[r.resourceId] || 0) + r.amount / RESOURCE_PRECISION,
}),
{},
),
);
},
[donkeyInfos, selectedDonkeys],
);
const updateResourcesFromSelectedDonkeys = useMemo(
() => (selectedDonkeyIds: Set<bigint>) => {
const allResources = Array.from(selectedDonkeyIds).flatMap(
(id) =>
donkeyInfos?.find((d) => d?.donkeyEntityId && BigInt(d.donkeyEntityId) === id)?.donkeyResourceBalances || [],
);
setSelectedResourceIds(allResources.map((r) => r.resourceId as never));
setSelectedResourceAmounts(
allResources.reduce(
(acc, r) => {
acc[r.resourceId] = (acc[r.resourceId] || 0) + r.amount / RESOURCE_PRECISION;
return acc;
},
{} as { [key: string]: number }
),
);
},
[donkeyInfos],
);
🧰 Tools
🪛 Biome (1.9.4)

[error] 100-100: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)


setSelectedResourceIds(allResources.map((r) => r.resourceId as never));
setSelectedResourceAmounts(
allResources.reduce(
(acc, r) => ({
...acc,
[r.resourceId]: (acc[r.resourceId] || 0) + r.amount / RESOURCE_PRECISION,
}),
{},
),
);
};
useEffect(() => {
const newSelected = new Set<bigint>();

Expand All @@ -111,10 +115,7 @@ export const BridgeOutStep2 = () => {
newSelected.add(BigInt(donkey?.donkeyEntityId || 0));
}
});

setSelectedDonkeys(newSelected);
updateResourcesFromSelectedDonkeys(newSelected);
}, [donkeyInfos]);
}, [donkeyInfos, selectedDonkeys]);

const handleRefresh = () => {
setIsRefreshing(true);
Expand Down
213 changes: 114 additions & 99 deletions landing/src/hooks/helpers/useDonkeyArrivals.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ADMIN_BANK_ENTITY_ID, ID } from "@bibliothecadao/eternum";

import { useQuery } from "@tanstack/react-query";
import { useQueries, useQuery } from "@tanstack/react-query";
import { useMemo } from "react";
import { execute } from "../gql/execute";
import { GetEternumEntityOwnerQuery } from "../gql/graphql";
Expand All @@ -9,103 +9,118 @@ import { GET_ENTITY_DISTANCE } from "../query/position";
import { GET_ENTITIES_RESOURCES } from "../query/resources";

export function useDonkeyArrivals(realmEntityIds: ID[]) {
const filteredRealmIds = useMemo(() =>
realmEntityIds.filter(id => id !== 54),
[realmEntityIds]
);

const {
data: entityPositions,
isLoading: isLoadingPositions,
error: positionsError,
} = useQuery({
queryKey: ["entityPositionBank"],
queryFn: () => execute(GET_ENTITY_DISTANCE, { entityIds: [Number(ADMIN_BANK_ENTITY_ID)] }),
});

const {
data: donkeyEntities,
isLoading: isLoadingDonkeyEntityIds,
error: errorDonkeyEntityIds,
} = useQuery({
queryKey: ["donkeyEntityIds", filteredRealmIds],
queryFn: () => execute(GET_ETERNUM_ENTITY_OWNERS, { entityOwnerIds: filteredRealmIds }),
enabled: filteredRealmIds.length > 0,
const filteredRealmIds = useMemo(() => realmEntityIds.filter((id) => id !== 54), [realmEntityIds]);
bob0005 marked this conversation as resolved.
Show resolved Hide resolved

const {
data: entityPositions,
isLoading: isLoadingPositions,
error: positionsError,
} = useQuery({
queryKey: ["entityPositionBank"],
queryFn: () => execute(GET_ENTITY_DISTANCE, { entityIds: [Number(ADMIN_BANK_ENTITY_ID)] }),
});

Comment on lines +12 to +20
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

Consider refetch intervals for consistency.

This query for entityPositions doesn’t specify a refetchInterval, whereas donkey queries do. If real-time updates are required, set a consistent interval value.

// const {
// data: donkeyEntities,
// isLoading: isLoadingDonkeyEntityIds,
// error: errorDonkeyEntityIds,
// } = useQuery({
// queryKey: ["donkeyEntityIds", filteredRealmIds],
// queryFn: () => execute(GET_ETERNUM_ENTITY_OWNERS, { entityOwnerIds: filteredRealmIds }),
// enabled: filteredRealmIds.length > 0,
// refetchInterval: 10_000,
// });

const donkeyQueriesResults = useQueries({
queries: filteredRealmIds.map((realmId) => ({
queryKey: ["donkeyEntityIds", realmId],
queryFn: () => execute(GET_ETERNUM_ENTITY_OWNERS, { entityOwnerIds: [realmId] }),
enabled: !!realmId,
refetchInterval: 10_000,
staleTime: 5000,
})),
});

const donkeyEntities = useMemo(
() => ({
s0EternumEntityOwnerModels: {
edges: donkeyQueriesResults
.filter((result) => result.data)
.flatMap((result) => result.data?.s0EternumEntityOwnerModels?.edges || []),
},
}),
[donkeyQueriesResults],
);

const isLoadingDonkeyEntityIds = donkeyQueriesResults.some((result) => result.isLoading);
const errorDonkeyEntityIds = donkeyQueriesResults.find((result) => result.error)?.error;

const bankPosition = useMemo(
() =>
entityPositions?.s0EternumPositionModels?.edges?.find((entity) => entity?.node?.entity_id == ADMIN_BANK_ENTITY_ID)
?.node,
[entityPositions],
);

const donkeysAtBank = useMemo(() => {
if (!donkeyEntities?.s0EternumEntityOwnerModels?.edges || !bankPosition) return [];

return donkeyEntities.s0EternumEntityOwnerModels.edges.filter((edge) => {
const position = edge?.node?.entity?.models?.find((model) => model?.__typename === "s0_eternum_Position");
const resource = edge?.node?.entity?.models?.find(
(model) => model?.__typename === "s0_eternum_OwnedResourcesTracker",
);

return Boolean(
position?.x === bankPosition?.x && position?.y === bankPosition?.y && resource?.resource_types !== "0x0",
);
});

const bankPosition = useMemo(
() =>
entityPositions?.s0EternumPositionModels?.edges?.find((entity) => entity?.node?.entity_id == ADMIN_BANK_ENTITY_ID)
?.node,
[entityPositions],
);

const donkeysAtBank = useMemo(() => {
if (!donkeyEntities?.s0EternumEntityOwnerModels?.edges || !bankPosition) return [];

return donkeyEntities.s0EternumEntityOwnerModels.edges.filter((edge) => {
const position = edge?.node?.entity?.models?.find(
(model) => model?.__typename === "s0_eternum_Position"
);
const resource = edge?.node?.entity?.models?.find(
(model) => model?.__typename === "s0_eternum_OwnedResourcesTracker"
);

return Boolean(
position?.x === bankPosition?.x &&
position?.y === bankPosition?.y &&
resource?.resource_types !== "0x0"
);
});
}, [donkeyEntities, bankPosition]);

const donkeyEntityIds = useMemo(
() =>
donkeysAtBank?.map((edge) => edge?.node?.entity_id)
.filter((id): id is number => id != null) ?? [],
[donkeysAtBank],
);

const { data: donkeyResources } = useQuery({
queryKey: ["donkeyResources" + donkeyEntityIds],
queryFn: () => execute(GET_ENTITIES_RESOURCES, { entityIds: donkeyEntityIds }),
enabled: !!donkeyEntityIds,
});

const getDonkeyInfo = (
donkeyEntity: NonNullable<
NonNullable<NonNullable<GetEternumEntityOwnerQuery["s0EternumEntityOwnerModels"]>["edges"]>[number]
>,
) => {
const donkeyEntityId = donkeyEntity?.node?.entity_id;
const donkeyArrivalTime = donkeyEntity?.node?.entity?.models?.find(
(model) => model?.__typename === "s0_eternum_ArrivalTime",
)?.arrives_at;

const donkeyResourceBalances =
donkeyResources?.s0EternumResourceModels?.edges
?.filter((edge) => edge?.node?.entity_id === donkeyEntityId)
?.map((edge) => edge?.node)
?.map((node) => ({
resourceId: node?.resource_type,
amount: node?.balance,
}))
.filter((r) => Number(r.amount) > 0) ?? [];

return { donkeyEntityId, donkeyArrivalTime, donkeyResourceBalances };
};

const donkeyInfos = useMemo(() => {
return donkeysAtBank?.map((donkey) => donkey && getDonkeyInfo(donkey));
}, [donkeysAtBank, donkeyResources]);

return {
donkeyArrivals: donkeysAtBank,
donkeyInfos,
bankPosition,
donkeyResources,
isLoading: isLoadingPositions || isLoadingDonkeyEntityIds,
error: positionsError || errorDonkeyEntityIds,
};
}
}, [donkeyEntities, bankPosition]);

const donkeyEntityIds = useMemo(
() => donkeysAtBank?.map((edge) => edge?.node?.entity_id).filter((id): id is number => id != null) ?? [],
[donkeysAtBank],
);

const { data: donkeyResources } = useQuery({
queryKey: ["donkeyResources" + donkeyEntityIds],
queryFn: () => execute(GET_ENTITIES_RESOURCES, { entityIds: donkeyEntityIds }),
enabled: !!donkeyEntityIds,
});

const getDonkeyInfo = (
donkeyEntity: NonNullable<
NonNullable<NonNullable<GetEternumEntityOwnerQuery["s0EternumEntityOwnerModels"]>["edges"]>[number]
>,
) => {
const donkeyEntityId = donkeyEntity?.node?.entity_id;
const donkeyArrivalTime = donkeyEntity?.node?.entity?.models?.find(
(model) => model?.__typename === "s0_eternum_ArrivalTime",
)?.arrives_at;

const donkeyResourceBalances =
donkeyResources?.s0EternumResourceModels?.edges
?.filter((edge) => edge?.node?.entity_id === donkeyEntityId)
?.map((edge) => edge?.node)
?.map((node) => ({
resourceId: node?.resource_type,
amount: node?.balance,
}))
.filter((r) => Number(r.amount) > 0) ?? [];

return { donkeyEntityId, donkeyArrivalTime, donkeyResourceBalances };
};

const donkeyInfos = useMemo(() => {
return donkeysAtBank?.map((donkey) => donkey && getDonkeyInfo(donkey));
}, [donkeysAtBank, donkeyResources]);

return {
donkeyArrivals: donkeysAtBank,
donkeyInfos,
bankPosition,
donkeyResources,
isLoading: isLoadingPositions || isLoadingDonkeyEntityIds,
error: positionsError || errorDonkeyEntityIds,
};
}
Loading