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

merge #2608

Merged
merged 16 commits into from
Dec 27, 2024
Merged

merge #2608

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
7 changes: 4 additions & 3 deletions client/src/dojo/modelManager/LeaderboardManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,10 @@ export class LeaderboardManager {
getEntityIdFromKeys([BigInt(hyperstructure.entity_id), BigInt(i + 1)]),
);

const epochEndTimestamp = season.is_over
? season.ended_at
: nextEpoch?.start_timestamp ?? BigInt(currentTimestamp);
const epochEndTimestamp =
season.is_over && nextEpoch === undefined
? season.ended_at
: nextEpoch?.start_timestamp ?? BigInt(currentTimestamp);
const epochDuration = epochEndTimestamp - epoch.start_timestamp;

const nbOfCycles = Number(epochDuration) / ClientConfigManager.instance().getTick(TickIds.Default);
Expand Down
57 changes: 55 additions & 2 deletions client/src/dojo/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,38 @@ export async function setup(config: DojoConfig & { state: AppStore }) {
}

// fetch all existing entities from torii
setLoading(LoadingStateKey.Hyperstructure, true);
await getEntities(
network.toriiClient,
{
Composite: {
operator: "Or",
clauses: [
{
Keys: {
keys: [undefined, undefined],
pattern_matching: "FixedLen",
models: ["s0_eternum-Epoch", "s0_eternum-Progress"],
},
},
{
Keys: {
keys: [undefined, undefined, undefined],
pattern_matching: "FixedLen",
models: ["s0_eternum-Contribution"],
},
},
],
},
},
network.contractComponents as any,
[],
[],
40_000,
false,
).finally(() => {
setLoading(LoadingStateKey.Hyperstructure, false);
});

setLoading(LoadingStateKey.SingleKey, true);
await getEntities(
Expand Down Expand Up @@ -183,7 +215,28 @@ export async function setup(config: DojoConfig & { state: AppStore }) {

configManager.setDojo(components);

setLoading(LoadingStateKey.Events, true);
// setLoading(LoadingStateKey.Events, true);

await getEvents(
network.toriiClient,
network.contractComponents.events as any,
[],
[],
20000,
{
Keys: {
keys: [undefined],
pattern_matching: "VariableLen",
models: ["s0_eternum-GameEnded"],
},
},
false,
false,
)
// .finally(() => {
// setLoading(LoadingStateKey.Events, false);
// });

const eventSync = getEvents(
network.toriiClient,
network.contractComponents.events as any,
Expand All @@ -195,7 +248,7 @@ export async function setup(config: DojoConfig & { state: AppStore }) {
keys: [undefined],
pattern_matching: "VariableLen",
models: [
"s0_eternum-GameEnded",
// "s0_eternum-GameEnded",
"s0_eternum-HyperstructureFinished",
"s0_eternum-BattleClaimData",
"s0_eternum-BattleJoinData",
Expand Down
42 changes: 24 additions & 18 deletions client/src/ui/layouts/World.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { ADMIN_BANK_ENTITY_ID } from "@bibliothecadao/eternum";
import { getComponentValue } from "@dojoengine/recs";
import { getEntityIdFromKeys } from "@dojoengine/utils";
import { env } from "../../../env";
import { rewards } from "../components/navigation/Config";
import { IS_MOBILE } from "../config";
import { LoadingOroborus } from "../modules/loading-oroborus";
import { LoadingScreen } from "../modules/LoadingScreen";
Expand Down Expand Up @@ -230,25 +231,30 @@ export const World = ({ backgroundImage }: { backgroundImage: string }) => {
fetch();
}, []);

// useEffect(() => {
// const fetch = async () => {
// try {
// setLoading(LoadingStateKey.Hyperstructure, true);
// console.log("AddToSubscriptionStart - 4");
// await Promise.all([
// debouncedAddHyperstructureSubscription(dojo.network.toriiClient, dojo.network.contractComponents as any, () =>
// setLoading(LoadingStateKey.Hyperstructure, false),
// ),
// ]);
// } catch (error) {
// console.error("Fetch failed", error);
// } finally {
// // Ensure loading states are reset even if there's an error
// setLoading(LoadingStateKey.Hyperstructure, false);
// }
// };

// fetch();
// }, []);

const openPopup = useUIStore((state) => state.openPopup);
useEffect(() => {
const fetch = async () => {
try {
setLoading(LoadingStateKey.Hyperstructure, true);
console.log("AddToSubscriptionStart - 4");
await Promise.all([
debouncedAddHyperstructureSubscription(dojo.network.toriiClient, dojo.network.contractComponents as any, () =>
setLoading(LoadingStateKey.Hyperstructure, false),
),
]);
} catch (error) {
console.error("Fetch failed", error);
} finally {
// Ensure loading states are reset even if there's an error
setLoading(LoadingStateKey.Hyperstructure, false);
}
};

fetch();
openPopup(rewards);
}, []);

const battleViewContent = useMemo(
Expand Down
47 changes: 34 additions & 13 deletions client/src/ui/modules/rewards/Rewards.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import { shortString } from "starknet";
import { formatEther } from "viem";
import { env } from "../../../../env";

const REGISTRATION_DELAY = 1800; // 1 week
const REGISTRATION_DELAY = 60 * 60 * 24 * 4; // 4 days
const BRIDGE_OUT_DELAY = 60 * 60 * 24 * 2; // 2 days

export const Rewards = () => {
const {
Expand All @@ -35,6 +36,8 @@ export const Rewards = () => {

const [timeRemaining, setTimeRemaining] = useState<string>("");
const [isLoading, setIsLoading] = useState(false);
const [registrationTimeRemaining, setRegistrationTimeRemaining] = useState<string>("");
const [bridgeOutTimeRemaining, setBridgeOutTimeRemaining] = useState<string>("");

const prizePool = usePrizePool();
const togglePopup = useUIStore((state) => state.togglePopup);
Expand Down Expand Up @@ -77,15 +80,24 @@ export const Rewards = () => {
if (gameEnded) {
const calculateTimeRemaining = () => {
const currentTime = Math.floor(Date.now() / 1000);
const endTime = Number(gameEnded.timestamp + REGISTRATION_DELAY);

if (currentTime >= endTime) {
setTimeRemaining("Registration Closed");
return;
const registrationEndTime = Number(gameEnded.timestamp + REGISTRATION_DELAY);
const bridgeOutEndTime = Number(gameEnded.timestamp + BRIDGE_OUT_DELAY);

// Calculate registration time
if (currentTime >= registrationEndTime) {
setRegistrationTimeRemaining("Registration Closed");
} else {
const registrationDifference = registrationEndTime - currentTime;
setRegistrationTimeRemaining(formatTime(registrationDifference, undefined));
}

const difference = endTime - currentTime;
setTimeRemaining(formatTime(difference, undefined));
// Calculate bridge out time
if (currentTime >= bridgeOutEndTime) {
setBridgeOutTimeRemaining("Bridge Out Closed");
} else {
const bridgeOutDifference = bridgeOutEndTime - currentTime;
setBridgeOutTimeRemaining(formatTime(bridgeOutDifference, undefined));
}
};

calculateTimeRemaining();
Expand Down Expand Up @@ -135,10 +147,19 @@ export const Rewards = () => {
<div className="text-lg">{Number(formatEther(prizePool)).toFixed(2)} $LORDS</div>
</div>
</Compartment>
<Compartment>
</div>

<div className="grid grid-cols-2 gap-4">
<Compartment isCountdown>
<div className="text-center text-lg font-semibold self-center w-full">
<div className="text-md uppercase font-extrabold text-danger">Time left to register</div>
<div className="text-lg">{registrationTimeRemaining}</div>
</div>
</Compartment>
<Compartment isCountdown>
<div className="text-center text-lg font-semibold self-center w-full">
<div className="text-sm font-bold uppercase">Time left to register</div>
<div className="text-lg">{timeRemaining}</div>
<div className="text-md font-extrabold text-danger uppercase">Time left to bridge out</div>
<div className="text-lg">{bridgeOutTimeRemaining}</div>
</div>
</Compartment>
</div>
Expand Down Expand Up @@ -184,9 +205,9 @@ export const Rewards = () => {
);
};

const Compartment = ({ children }: { children: React.ReactNode }) => {
const Compartment = ({ children, isCountdown }: { children: React.ReactNode; isCountdown?: boolean }) => {
return (
<div className="flex flex-col w-full justify-center border-b border-brown/50 p-4 rounded-md bg-brown/50 bg-hex m-auto h-28">
<div className={`flex flex-col w-full justify-center border-b border-brown/50 p-4 rounded-md ${isCountdown ? 'bg-brown/70' : 'bg-brown/50'} bg-hex m-auto h-28 ${isCountdown ? 'border-2 border-danger/50' : ''}`}>
{children}
</div>
);
Expand Down
13 changes: 10 additions & 3 deletions contracts/src/systems/hyperstructure/contracts.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ trait IHyperstructureSystems<T> {
mod hyperstructure_systems {
use achievement::store::{Store, StoreTrait};
use core::array::ArrayIndex;
use core::poseidon::poseidon_hash_span;
use dojo::event::EventStorage;
use dojo::model::ModelStorage;

Expand Down Expand Up @@ -596,10 +597,16 @@ mod hyperstructure_systems {
let (hyperstructure_entity_id, index) = *hyperstructure_shareholder_epochs.at(i);

// ensure we don't double count points for the same hyperstructure
if points_already_added.get(hyperstructure_entity_id.into()) {
panic!("points already added for hyperstructure {}", hyperstructure_entity_id);

let points_already_added_key: felt252 = poseidon_hash_span(
array![hyperstructure_entity_id.into(), index.into()].span()
);

if points_already_added.get(points_already_added_key) {
panic!("points already added for hyperstructure {}, epoch {}", hyperstructure_entity_id, index);
};
points_already_added.insert(hyperstructure_entity_id.into(), true);

points_already_added.insert(points_already_added_key, true);

let epoch: Epoch = world.read_model((hyperstructure_entity_id, index));
let next_epoch: Epoch = world.read_model((hyperstructure_entity_id, index + 1));
Expand Down
12 changes: 7 additions & 5 deletions landing/src/dojo/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { createClientComponents } from "./createClientComponents";
import { createSystemCalls } from "./createSystemCalls";
import { ClientConfigManager } from "./modelManager/ConfigManager";
import { setupNetwork } from "./setupNetwork";
import { getEvents } from "@dojoengine/state";

export type SetupResult = Awaited<ReturnType<typeof setup>>;
export const configManager = ClientConfigManager.instance();
Expand Down Expand Up @@ -36,9 +37,9 @@ export async function setup({ ...config }: DojoConfig) {
const filteredEvents = [
"BurnDonkey",
// points
"HyperstructureCoOwnersChange",
"HyperstructureFinished",
"GameEnded",
// "HyperstructureCoOwnersChange",
// "HyperstructureFinished",
// "GameEnded",
];

const clauses: Clause[] = [
Expand Down Expand Up @@ -87,6 +88,7 @@ export async function setup({ ...config }: DojoConfig) {

const sync = await syncEntities(network.toriiClient, filteredModels as any, [], false);

*/
const eventSync = getEvents(
network.toriiClient,
network.contractComponents.events as any,
Expand All @@ -101,14 +103,14 @@ export async function setup({ ...config }: DojoConfig) {
false,
false,
);
*/

configManager.setDojo(components);

return {
network,
components,
systemCalls,
//sync,
/*eventSync,*/
eventSync,
};
}