Skip to content

Commit

Permalink
Merge pull request #7 from Avelous/staging
Browse files Browse the repository at this point in the history
Update to dice demo
  • Loading branch information
austintgriffith authored Feb 24, 2024
2 parents 0124e57 + 57e07a4 commit a95d75a
Show file tree
Hide file tree
Showing 9 changed files with 226 additions and 133 deletions.
4 changes: 1 addition & 3 deletions packages/backend/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ app.use(morgan("common"));
app.use(bodyParser.json({ limit: "30mb" }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
app.use(
cors({
origin: "*",
}),
cors(),
);

/**Ably Setup */
Expand Down
15 changes: 5 additions & 10 deletions packages/backend/vercel.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
{
"version": 2,
"name": "dice-demonstration-backend",
"builds": [
{ "src": "index.ts", "use": "@vercel/node" }
],
"routes": [
{ "src": "/(.*)", "dest": "/index.ts" }
]
}

"version": 2,
"name": "dice-demonstration-backend",
"builds": [{ "src": "index.ts", "use": "@vercel/node" }],
"routes": [{ "src": "/(.*)", "dest": "/index.ts" }]
}
8 changes: 4 additions & 4 deletions packages/nextjs/components/Wallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ export default function Wallet() {
<h2>Known Private Keys:</h2>
{extraPkDisplay}
<button
className="btn btn-primary btn-sm my-2"
className="btn btn-primary md:btn-sm btn-xs my-2"
onClick={() => {
const currentPrivateKey = window.localStorage.getItem("scaffoldEth2.burnerWallet.sk");
if (currentPrivateKey) {
Expand Down Expand Up @@ -280,7 +280,7 @@ export default function Wallet() {

<div className="flex justify-end gap-2 ">
<button
className="btn btn-primary btn-sm"
className="btn btn-primary md:btn-sm btn-xs "
onClick={() => {
pk == "" && selectedAddress ? setPK(selectedAddress) : setPK("");
setQr("");
Expand All @@ -290,7 +290,7 @@ export default function Wallet() {
{pk == "" ? "Private Key" : "Hide"}
</button>
<button
className="btn btn-primary btn-sm"
className="btn btn-primary md:btn-sm btn-xs"
onClick={() => {
qr == "" && selectedAddress ? setQr(selectedAddress) : setQr("");
setPK("");
Expand All @@ -300,7 +300,7 @@ export default function Wallet() {
{qr == "" ? "Receive" : "Hide"}
</button>
<button
className="btn btn-primary btn-sm"
className="btn btn-primary md:btn-sm btn-xs"
key="submit"
disabled={!amount || !toAddress || pk != "" || qr != ""}
onClick={() => {
Expand Down
42 changes: 27 additions & 15 deletions packages/nextjs/components/dicedemo/Congrats.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
import { Dispatch, SetStateAction } from "react";
import useGameData from "~~/hooks/useGameData";
import useSweepWallet from "~~/hooks/useSweepWallet";
import { Game } from "~~/types/game/game";

const Congrats = ({
isOpen,
setIsOpen,
message,
isHacked,
isWinner,
game,
token,
}: {
isOpen: boolean;
setIsOpen: Dispatch<SetStateAction<boolean>>;
message: string;
isHacked: boolean;
isWinner: boolean;
game: Game;
token: string;
}) => {
const closePopup = () => {
setIsOpen(false);
};

const { loadGameState } = useGameData();
const { game } = loadGameState();
const { sweepWallet } = useSweepWallet();
const { isSweeping } = useSweepWallet({ game: game, token: token });

return (
<div className=" overflow-hidden w-fit text-xs bg-base-200 h-full">
Expand All @@ -27,15 +31,23 @@ const Congrats = ({
<label onClick={closePopup} className="btn btn-sm btn-circle absolute right-2 top-2">
</label>
<p className="text-center mt-4">{message}</p>
<button
onClick={() => {
sweepWallet(game.privateKey);
}}
className="btn btn-primary"
>
Sweep Wallet
</button>

{isWinner && (
<div>Congrats, you found the hidden characters and have successfully swept the private Key</div>
)}
{!isWinner && isHacked && !game.winner && (
<div>
{isSweeping
? "Hidden characters found, Trying to Sweep the wallet ..."
: "Hidden characters found, Failed to sweep PrivateKey"}
</div>
)}
{!isWinner && isHacked && game.winner != undefined && (
<div>Hidden characters found but you were beaten to sweeping the private key by another wallet</div>
)}
{!isWinner && !isHacked && <div>Sorry fren, you lost</div>}

<div className="mt-5">The hidden characters are {Object.values(game.hiddenChars).join(", ")}</div>
</div>
</div>
)}
Expand Down
6 changes: 4 additions & 2 deletions packages/nextjs/components/dicedemo/GameCreateForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,11 @@ const GameCreationForm = () => {
max="64"
value={sliderValue}
onChange={handleSliderChange}
className="slider appearance-none w-full h-2 bg-primary rounded outline-none slider-thumb "
className="slider appearance-none w-[87%] h-2 bg-primary rounded outline-none slider-thumb "
/>
<span className="slider-value p-2 bg-primary font-bold rounded-md">{sliderValue}</span>
<span className="slider-value p-2 bg-primary w-[13%] font-bold rounded-md flex justify-center">
{sliderValue}
</span>
</div>
</label>
<br />
Expand Down
44 changes: 28 additions & 16 deletions packages/nextjs/components/dicedemo/GameJoinForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,37 +19,36 @@ const GameJoinForm = ({
const [scanning, setScanning] = useState(false);
const [loading, setLoading] = useState(false);

const { invite } = router.query;

const handleChange = (value: string) => {
setInviteCode(value);
};

const { address: playerAddress } = useAccount();
const serverUrl = serverConfig.isLocal ? serverConfig.localUrl : serverConfig.liveUrl;

const handleJoinGame = async (event: React.FormEvent) => {
event.preventDefault();
const handleJoinGame = async (invite: string) => {
setLoading(true);
const response = await fetch(`${serverUrl}/player/join`, {
method: "PATCH",
headers: {
Authorization: `Bearer`,
"Content-Type": "application/json",
},
body: JSON.stringify({ inviteCode, playerAddress }),
body: JSON.stringify({ inviteCode: invite, playerAddress }),
});

const updatedGame = await response.json();
saveGameState(JSON.stringify(updatedGame));
setLoading(false);
if (updatedGame.error) {
notification.error(updatedGame.error);
return;
}

saveGameState(JSON.stringify(updatedGame));

await router.push({
pathname: `/game/[id]`,
query: { id: inviteCode },
query: { id: invite },
});
notification.success("Joined game successfully");

Expand All @@ -70,31 +69,44 @@ const GameJoinForm = ({
setScanning(false);
};

const openCamera = () => {
setScanning(true);
};
// const openCamera = () => {
// setScanning(true);
// };

useEffect(() => {
if (labelRef.current) {
labelRef.current.focus();
}
}, []);

useEffect(() => {
if (invite) {
handleJoinGame(invite as string);
}
if (Object.keys(router.query).length > 0) {
router.replace({
pathname: router.pathname,
query: {},
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [invite]);

return (
<div className="">
<form onSubmit={handleJoinGame}>
<form onSubmit={() => handleJoinGame(inviteCode)}>
<label ref={labelRef}>
<h1> Enter Invite Code</h1>
<InputBase
name="inviteCode"
value={inviteCode}
placeholder="Invite Code"
onChange={handleChange}
suffix={
<button type="button" className={`btn btn-primary h-[2.2rem] min-h-[2.2rem] `} onClick={openCamera}>
Scan
</button>
}
// suffix={
// <button type="button" className={`btn btn-primary h-[2.2rem] min-h-[2.2rem] `} onClick={openCamera}>
// Scan
// </button>
// }
/>
</label>
<button className="btn btn-sm btn-primary mt-6" type="submit">
Expand Down
36 changes: 24 additions & 12 deletions packages/nextjs/hooks/useSweepWallet.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { useState } from "react";
import { ethers } from "ethers";
import { useAccount } from "wagmi";
import { Game } from "~~/types/game/game";
import { endGame } from "~~/utils/diceDemo/apiUtils";
import { getApiKey, getBlockExplorerTxLink, getTargetNetwork } from "~~/utils/scaffold-eth";
import { notification } from "~~/utils/scaffold-eth";

Expand All @@ -16,37 +19,42 @@ const TxnNotification = ({ message, blockExplorerLink }: { message: string; bloc
);
};

const useSweepWallet = () => {
const useSweepWallet = ({ game, token }: { game?: Game; token?: string }) => {
const { address } = useAccount();
const configuredNetwork = getTargetNetwork();
const apiKey = getApiKey();
const [isSweeping, setIsSweeping] = useState(false);

const provider = new ethers.providers.AlchemyProvider(configuredNetwork.network, apiKey);

const sweepWallet = async (privateKey: string) => {
setIsSweeping(true);
const wallet = new ethers.Wallet(privateKey, provider);
const balance = await wallet.getBalance();
if (balance.eq(0)) {
console.log("Wallet balance is 0");
notification.info("Wallet balance is 0");
const message = "Wallet balance is 0";
console.log(message);
setIsSweeping(false);
notification.info(message);
return;
}

const gasPrice = await provider.getGasPrice();

const gasLimit = 21000;
const gasCost = gasPrice.mul(gasLimit);
const gasLimit = 21000000;
const gasCost = gasPrice.mul(35000000); // gasLimit * 1.667

// const totalToSend = balance.sub(gasCost.mul(2));
let totalToSend = balance.sub(gasCost);
const totalToSend = balance.sub(gasCost);

const overshotPercentage = 2;
const overshotAmount = totalToSend.mul(overshotPercentage).div(100);
totalToSend = totalToSend.sub(overshotAmount);
console.log(totalToSend.toNumber());
console.log(gasCost.toNumber());

if (totalToSend.lte(0)) {
console.log("Balance is not enough to cover gas fees.");
notification.info("Balance is not enough to cover gas fees.");
const message = "Balance is not enough to cover gas fees.";
console.log(message);
setIsSweeping(false);
notification.info(message);
return;
}

Expand Down Expand Up @@ -76,7 +84,11 @@ const useSweepWallet = () => {
icon: "🎉",
},
);

endGame(game as Game, token as string, address as string);
setIsSweeping(false);
} catch (error: any) {
setIsSweeping(false);
if (notificationId) {
notification.remove(notificationId);
}
Expand All @@ -87,7 +99,7 @@ const useSweepWallet = () => {
console.log("Transaction sent:", txReceipt);
};

return { sweepWallet };
return { sweepWallet, isSweeping };
};

export default useSweepWallet;
Loading

0 comments on commit a95d75a

Please sign in to comment.