move state and functions to commit component

This commit is contained in:
SamKry
2025-11-18 18:55:38 +01:00
parent 4ec03d7cdb
commit 04f8e66204
3 changed files with 100 additions and 132 deletions

View File

@@ -1,28 +1,66 @@
import { useState } from "react";
import Web3 from "web3";
interface CommitProps {
playMove: string;
setPlayMove: (v: string) => void;
handlePlay: () => void;
loading: boolean;
account: string;
contract: any;
bothPlayed: string;
handleBothPlayed: () => void;
revealTimeLeft: string;
handleRevealTimeLeft: () => void;
config: Config | null;
web3: Web3 | null;
setStatus: (status: string) => void;
}
export default function Commit({
playMove,
setPlayMove,
handlePlay,
loading,
account,
contract,
bothPlayed,
handleBothPlayed,
revealTimeLeft,
handleRevealTimeLeft,
config,
web3,
setStatus,
}: Readonly<CommitProps>) {
const [loading, setLoading] = useState(false);
const [playMove, setPlayMove] = useState<string>("");
const [bothPlayed, setBothPlayed] = useState<string>("");
// Commit phase read-only handlers
const handleBothPlayed = async () => {
if (!contract) return;
setLoading(true);
try {
const res = await contract.methods.bothPlayed().call();
setBothPlayed(res ? "true" : "false");
} catch (err: any) {
setStatus("Failed to fetch bothPlayed: " + err.message);
} finally {
setLoading(false);
}
};
const handlePlay = async () => {
if (!contract || !web3 || !account) return;
setLoading(true);
setStatus("");
try {
// playMove should be a hex string (bytes32)
const tx = contract.methods.play(playMove);
const gas = await tx.estimateGas({ from: account });
const result = await (globalThis as any).ethereum.request({
method: "eth_sendTransaction",
params: [
{
from: account,
to: config?.GAME_CONTRACT_ADDRESS,
data: tx.encodeABI(),
gas: web3.utils.toHex(gas),
chainId: web3.utils.toHex(await web3.eth.net.getId()),
},
],
});
setStatus("Play tx sent: " + result);
} catch (err: any) {
setStatus("Play failed: " + err.message);
} finally {
setLoading(false);
}
};
return (
<div className="border p-4 rounded-lg">
<h2 className="font-semibold mb-2">play(bytes32 encrMove)</h2>
@@ -42,11 +80,14 @@ export default function Commit({
</button>
<div className="mt-4 space-y-2">
<button onClick={handleBothPlayed} className="bg-gray-200 px-2 py-1 rounded">bothPlayed</button>
<button
onClick={handleBothPlayed}
className="bg-gray-200 px-2 py-1 rounded"
>
bothPlayed
</button>
<span className="ml-2 text-xs">{bothPlayed}</span>
<br />
<button onClick={handleRevealTimeLeft} className="bg-gray-200 px-2 py-1 rounded">revealTimeLeft</button>
<span className="ml-2 text-xs">{revealTimeLeft}</span>
</div>
</div>
);