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 1 commit
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
44 changes: 37 additions & 7 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 { useCallback, useEffect, useState } from "react";
import { TypeP } from "../typography/type-p";
import { ShowSingleResource } from "../ui/SelectResources";
import { Button } from "../ui/button";
Expand All @@ -16,6 +16,27 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from ".
import { getSeasonAddresses } from "../ui/utils/utils";
import { BridgeFees } from "./bridge-fees";

function debounce<T extends (...args: any[]) => void>(func: T, wait: number): T & { cancel: () => void } {
let timeout: NodeJS.Timeout | null = null;

const debounced = (...args: Parameters<T>) => {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
func(...args);
}, wait);
};

debounced.cancel = () => {
if (timeout) {
clearTimeout(timeout);
}
};

return debounced as T & { cancel: () => void };
}

export const BridgeOutStep2 = () => {
const { address } = useAccount();

Expand Down Expand Up @@ -103,18 +124,27 @@ export const BridgeOutStep2 = () => {
),
);
};

const debouncedUpdateResources = useCallback(
debounce((selectedDonkeyIds: Set<bigint>) => {
updateResourcesFromSelectedDonkeys(selectedDonkeyIds);
}, 10000),
[],
);

useEffect(() => {
const newSelected = new Set<bigint>();

donkeyInfos?.forEach((donkey) => {
if (Number(donkey?.donkeyArrivalTime) * 1000 <= Date.now()) {
newSelected.add(BigInt(donkey?.donkeyEntityId || 0));
}
newSelected.add(BigInt(donkey?.donkeyEntityId || 0));
});

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

return () => {
debouncedUpdateResources.cancel();
};
}, [donkeyInfos, debouncedUpdateResources]);

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