Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
SneakySensei committed Sep 7, 2024
1 parent 9936440 commit 0dc6984
Show file tree
Hide file tree
Showing 5 changed files with 167 additions and 83 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ export const RockPaperScissorsRoutes = (socket: Socket, io: Namespace) => {
await RedisClient.hgetall(currentSeasonKey),
);

if (!season) {
console.log("season", season);
if (!season.season_id) {
const data = await fetchCurrentSeason();
if (data) {
season = data;
Expand All @@ -47,7 +48,7 @@ export const RockPaperScissorsRoutes = (socket: Socket, io: Namespace) => {
}
}

if (!season) {
if (!season.season_id) {
throw Error(
"Internal server error. No Current Season found.",
);
Expand Down Expand Up @@ -194,7 +195,7 @@ export const RockPaperScissorsRoutes = (socket: Socket, io: Namespace) => {
await RedisClient.hgetall(currentSeasonKey),
);

if (!season) {
if (!season.season_id) {
throw Error(
"Internal server error. No Current Season found.",
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,17 @@

import EnemyScreen from "./EnemyScreen";
import PlayerScreen from "./PlayerScreen";
import useSocket from "@/hooks/useSocket";
import AttestModal from "@/shared/AttestModal";
import StakingModal from "@/shared/StakingModal";
import { API_REST_BASE_URL } from "@/utils/constants/api.constant";
import { useSelectedChainContext } from "@/utils/context/selected-chain.context";
import { useTierContext } from "@/utils/context/tiers.context";
import { useWeb3AuthContext } from "@/utils/context/web3auth.context";
import { MappedSeason, ResponseWithData } from "@/utils/types";
import { getSocketManager } from "@/utils/websockets";
import { RockPaperScissors } from "common";
import dynamic from "next/dynamic";
import { useEffect, useReducer, useRef, useState } from "react";
import { Socket } from "socket.io-client";
import { useEffect, useReducer, useState } from "react";

type Props = {
tier_id: string;
Expand Down Expand Up @@ -80,13 +79,10 @@ export default dynamic(
const player_user_id = user!.data.player_id;
const player_token = user!.token;

const socketRef = useRef<Socket>(
getSocketManager().socket(`/${RockPaperScissors.slug}`, {
auth: {
token: player_token,
},
}),
);
const socket = useSocket({
namespace: RockPaperScissors.slug,
auth_token: player_token,
});

const reducer = (
gameState: GameState,
Expand Down Expand Up @@ -137,7 +133,7 @@ export default dynamic(

if (gameState.state === "waiting") {
if (isFreeTier) {
socketRef.current.emit(
socket.handle.emit(
"staked" satisfies RockPaperScissors.StakedEvent["type"],
{
player_id: player_user_id,
Expand Down Expand Up @@ -318,82 +314,113 @@ export default dynamic(
}, []);

useEffect(() => {
const socket = socketRef.current;

socket.connect();
if (!socket.connected || !selectedChain) return;

socket.on("connect", () => {
console.log("socket connected", socket.connected); // true
});

socket.on("connect_error", (err) => {
const handleConnectError = (err: Error) => {
console.log(err.message); // prints the message associated with the error
});

socket.on("error", (err) => {
};
const handleError = (err: any) => {
console.error(err); // prints the message associated with the error
});

socket.onAny((event, ...args) => {
};
const handleAny = (event: any, ...args: any[]) => {
console.log("rx event", event, args);
});
socket.onAnyOutgoing((event, ...args) => {
};
const handleAnyOutgoing = (event: any, ...args: any[]) => {
console.log("tx event", event, args);
});
socket.on(
};

const handlePlayerJoined = (
payload: RockPaperScissors.PlayerJoinedEvent["payload"],
) => {
dispatch({ type: "player-joined", payload });
};
const handleStaking = (
payload: RockPaperScissors.StakingEvent["payload"],
) => {
dispatch({ type: "staking", payload });
};
const handleGameStart = (
payload: RockPaperScissors.GameStartEvent["payload"],
) => {
dispatch({ type: "game-start", payload });
};
const handleRoundEnd = (
payload: RockPaperScissors.RoundEndEvent["payload"],
) => {
dispatch({ type: "round-end", payload });
setTimeout(() => {
dispatch({ type: "next-round" });
}, 5000);
};
const handleGameEnd = (
payload: RockPaperScissors.GameEndEvent["payload"],
) => {
dispatch({ type: "game-end", payload });
};

socket.handle.on("connect_error", handleConnectError);
socket.handle.on("error", handleError);
socket.handle.onAny(handleAny);
socket.handle.onAnyOutgoing(handleAnyOutgoing);
socket.handle.on(
"player-joined" satisfies RockPaperScissors.PlayerJoinedEvent["type"],
(
payload: RockPaperScissors.PlayerJoinedEvent["payload"],
) => {
dispatch({ type: "player-joined", payload });
},
handlePlayerJoined,
);
socket.on(
socket.handle.on(
"staking" satisfies RockPaperScissors.StakingEvent["type"],
(payload: RockPaperScissors.StakingEvent["payload"]) => {
dispatch({ type: "staking", payload });
},
handleStaking,
);
socket.on(
socket.handle.on(
"game-start" satisfies RockPaperScissors.GameStartEvent["type"],
(payload: RockPaperScissors.GameStartEvent["payload"]) => {
dispatch({ type: "game-start", payload });
},
handleGameStart,
);
socket.on(
socket.handle.on(
"round-end" satisfies RockPaperScissors.RoundEndEvent["type"],
(payload: RockPaperScissors.RoundEndEvent["payload"]) => {
dispatch({ type: "round-end", payload });
setTimeout(() => {
dispatch({ type: "next-round" });
}, 5000);
},
handleRoundEnd,
);
socket.on(
socket.handle.on(
"game-end" satisfies RockPaperScissors.GameEndEvent["type"],
(payload: RockPaperScissors.GameEndEvent["payload"]) => {
dispatch({ type: "game-end", payload });
},
handleGameEnd,
);

socket.handle.emit(
"join" satisfies RockPaperScissors.JoinEvent["type"],
{
player_id: player_user_id,
game_id: RockPaperScissors.gameId,
tier_id: tier_id,
chain_id: parseInt(selectedChain.chainId, 16),
} satisfies RockPaperScissors.JoinEvent["payload"],
);
if (selectedChain) {
socket.emit(
"join" satisfies RockPaperScissors.JoinEvent["type"],
{
player_id: player_user_id,
game_id: RockPaperScissors.gameId,
tier_id: tier_id,
chain_id: parseInt(selectedChain.chainId, 16),
} satisfies RockPaperScissors.JoinEvent["payload"],
);
}
return () => {
socket.on("disconnect", (reason) => {
console.log(reason);
});

socket.disconnect();
return () => {
socket.handle.off("connect_error", handleConnectError);
socket.handle.off("error", handleError);
socket.handle.offAny(handleAny);
socket.handle.offAnyOutgoing(handleAnyOutgoing);
socket.handle.off(
"player-joined" satisfies RockPaperScissors.PlayerJoinedEvent["type"],
handlePlayerJoined,
);
socket.handle.off(
"staking" satisfies RockPaperScissors.StakingEvent["type"],
handleStaking,
);
socket.handle.off(
"game-start" satisfies RockPaperScissors.GameStartEvent["type"],
handleGameStart,
);
socket.handle.off(
"round-end" satisfies RockPaperScissors.RoundEndEvent["type"],
handleRoundEnd,
);
socket.handle.off(
"game-end" satisfies RockPaperScissors.GameEndEvent["type"],
handleGameEnd,
);
};
}, []);
}, [socket.connected]);

return (
<main className="relative flex h-full flex-col bg-neutral-100">
<EnemyScreen gameState={gameState} />
Expand All @@ -403,7 +430,8 @@ export default dynamic(
if (
gameState.state !== "ongoingRound" ||
gameState.moveSubmitted ||
!selectedChain
!selectedChain ||
!socket.connected
)
return;
const moveEvent: RockPaperScissors.MoveEvent = {
Expand All @@ -418,7 +446,8 @@ export default dynamic(
),
},
};
socketRef.current.emit(

socket.handle.emit(
moveEvent.type,
moveEvent.payload,
);
Expand Down Expand Up @@ -463,9 +492,13 @@ export default dynamic(
: ""
}
onSuccess={() => {
if (gameState.state !== "staking") return;
if (
gameState.state !== "staking" ||
!socket.connected
)
return;

socketRef.current.emit(
socket.handle.emit(
"staked" satisfies RockPaperScissors.StakedEvent["type"],
{
player_id: player_user_id,
Expand Down
48 changes: 48 additions & 0 deletions packages/frontend/src/hooks/useSocket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"use client";

import { socketManager } from "@/utils/websockets";
import { useEffect, useRef, useState } from "react";

type Props = {
namespace: string;
auth_token: string;
};
export default function useSocket({ namespace, auth_token }: Props) {
const [connected, setConnected] = useState(false);

const socketRef = useRef(
socketManager.socket(`/${namespace}`, {
auth: {
token: auth_token,
},
}),
);

useEffect(() => {
const socket = socketRef.current;

if (socket.connected) {
onConnect();
}

function onConnect() {
setConnected(true);
}

function onDisconnect() {
setConnected(false);
}

socket.on("connect", onConnect);
socket.on("disconnect", onDisconnect);
socket.connect();

return () => {
socket.off("connect", onConnect);
socket.off("disconnect", onDisconnect);
socket.disconnect();
};
}, []);

return { handle: socketRef.current, connected };
}
2 changes: 1 addition & 1 deletion packages/frontend/src/utils/constants/api.constant.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL;
export const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL!;
export const API_REST_BASE_URL = `${API_BASE_URL}/api/v1`;
12 changes: 7 additions & 5 deletions packages/frontend/src/utils/websockets.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
"use client";

import { API_BASE_URL } from "./constants/api.constant";
import { Manager } from "socket.io-client";

export const getSocketManager = () =>
new Manager(API_BASE_URL, {
closeOnBeforeunload: true,
withCredentials: true,
});
export const socketManager = new Manager(API_BASE_URL, {
withCredentials: true,
closeOnBeforeunload: true,
autoConnect: false,
});

0 comments on commit 0dc6984

Please sign in to comment.