From 201a8a36c5d6938fed939a695c1ff252469c3127 Mon Sep 17 00:00:00 2001 From: D9J9V Date: Wed, 4 Sep 2024 12:52:17 -0600 Subject: [PATCH] WIP: Critical features --- .../nextjs/src/app/create-trivia/page.tsx | 81 +++++---- packages/nextjs/src/app/play-trivia/page.tsx | 165 ++++++++++++------ 2 files changed, 148 insertions(+), 98 deletions(-) diff --git a/packages/nextjs/src/app/create-trivia/page.tsx b/packages/nextjs/src/app/create-trivia/page.tsx index 9435d56..7113aeb 100644 --- a/packages/nextjs/src/app/create-trivia/page.tsx +++ b/packages/nextjs/src/app/create-trivia/page.tsx @@ -3,10 +3,11 @@ import { useState } from "react"; import { useRouter } from "next/navigation"; import { TriviaFactory } from "../../../contracts/lib"; // Asegúrate de que la ruta sea correcta -import { GearApi, GasInfo } from "@gear-js/api"; +import { GearApi } from "@gear-js/api"; import { useAccount } from "@gear-js/react-hooks"; export default function CrearPregunta() { + const [isLoading, setIsLoading] = useState(false); const [preguntas, setPreguntas] = useState([ { pregunta: "", respuestaCorrecta: "" }, ]); @@ -14,7 +15,6 @@ export default function CrearPregunta() { const [triviaId, setTriviaId] = useState(null); const router = useRouter(); const { account } = useAccount(); - const [isLoading, setIsLoading] = useState(false); const handlePreguntaChange = ( index: number, @@ -42,7 +42,7 @@ export default function CrearPregunta() { setReward(event.target.value); }; - const handleSubmit = async (event: React.FormEvent) => { + const handleSubmit = async (event: any) => { event.preventDefault(); if (!account) { alert("Please connect your wallet first"); @@ -62,56 +62,52 @@ export default function CrearPregunta() { const questions = preguntas.map((p) => p.pregunta); const answers = preguntas.map((p) => p.respuestaCorrecta); - if (!triviaFactory.programId) { - throw new Error("Program ID is not set"); - } - - const gasLimit = await api.program.calculateGas.initCreate( - account.decodedAddress, - triviaFactory.programId, - "createTrivia", - { questions, answers }, - 0, - true, - ); + const rewardValue = BigInt(reward); - const { extrinsic } = await triviaFactory.triviaFactory.createTrivia( + const createTriviaMessage = triviaFactory.triviaFactory.createTrivia( questions, answers, ); - const signedExtrinsic = await extrinsic.signAndSend( - account.decodedAddress, - ); + await createTriviaMessage.withAccount(account.decodedAddress); + await createTriviaMessage.withValue(rewardValue); - await new Promise((resolve) => { - signedExtrinsic.once("InBlock", () => { - resolve(); - }); - }); + await createTriviaMessage.calculateGas(); - const triviaCreatedEvent = await new Promise<{ id: number }>( - (resolve) => { - triviaFactory.triviaFactory.subscribeToTriviaCreatedEvent((event) => { - if ("id" in event) { - resolve(event as { id: number }); - } - }); - }, - ); + const result = await createTriviaMessage.signAndSend(); - setTriviaId(triviaCreatedEvent.id); - const modalElement = document.getElementById( - "my_modal_1", - ) as HTMLDialogElement; - if (modalElement) { - modalElement.showModal(); + const isFinalized = await result.isFinalized; + + if (isFinalized) { + const response = await result.response(); + if (response && typeof response === "object" && "ok" in response) { + const okResult = response.ok; + if (typeof okResult === "number") { + setTriviaId(okResult); + const modalElement = document.getElementById( + "my_modal_1", + ) as HTMLDialogElement; + if (modalElement) { + modalElement.showModal(); + } + } + } else if ( + response && + typeof response === "object" && + "err" in response + ) { + console.error("Error creating trivia:", response.err); + alert(`Error creating trivia: ${response.err}`); + } else { + console.error("Unexpected response structure:", response); + alert("Unexpected error occurred"); + } + } else { + alert("Transaction was not finalized"); } } catch (error) { console.error("Error creating trivia:", error); - alert("Error creating trivia. Please try again."); - } finally { - setIsLoading(false); + alert(`Error creating trivia: ${error}`); } }; @@ -119,6 +115,7 @@ export default function CrearPregunta() {

Create new trivia

+
(null); const [currentQuestion, setCurrentQuestion] = useState(0); - const [selectedAnswer, setSelectedAnswer] = useState(""); + const [answers, setAnswers] = useState([]); const [showResult, setShowResult] = useState(false); const [result, setResult] = useState(""); + const [isLoading, setIsLoading] = useState(false); + const { account } = useAccount(); const handleTriviaIdChange = (event: React.ChangeEvent) => { setTriviaId(event.target.value); }; const loadTrivia = async () => { + setIsLoading(true); try { - const api = await GearApi.create(); - const triviaFactory = new TriviaFactory(api); + const api = await GearApi.create({ + providerAddress: "wss://testnet.vara.network", + }); + const triviaFactory = new TriviaFactory( + api, + "0xf5691c64eed986728bc5a263851b78ba867522289078b07ade779ca25f711b8b", + ); const loadedTrivia = await triviaFactory.triviaFactory.getTrivia( Number(triviaId), ); @@ -33,53 +42,79 @@ export default function PlayTrivia() { const [questions, reward, completed] = loadedTrivia.ok; setTrivia({ questions, reward, completed }); setCurrentQuestion(0); - setSelectedAnswer(""); + setAnswers(new Array(questions.length).fill("")); setShowResult(false); } else { console.error("Error loading trivia:", loadedTrivia.err); + setResult(`Error: ${loadedTrivia.err}`); + setShowResult(true); } } catch (error) { console.error("Error loading trivia:", error); + setResult("Error loading trivia. Please try again."); + setShowResult(true); + } finally { + setIsLoading(false); } }; - const handleAnswerClick = (answer: string) => { - setSelectedAnswer(answer); + const handleAnswerChange = (answer: string, index: number) => { + const newAnswers = [...answers]; + newAnswers[index] = answer; + setAnswers(newAnswers); }; - const handleNextQuestion = async () => { - if (!trivia) return; - - if (currentQuestion === trivia.questions.length - 1) { - try { - const api = await GearApi.create(); - const triviaFactory = new TriviaFactory(api); - const playResult = await triviaFactory.triviaFactory - .playTrivia(Number(triviaId), [selectedAnswer]) - .signAndSend(); - if ( - playResult && - typeof playResult === "object" && - "ok" in playResult - ) { - setResult(String(playResult.ok)); + const handleSubmit = async () => { + if (!account) { + alert("Please connect your wallet first"); + return; + } + setIsLoading(true); + try { + const api = await GearApi.create({ + providerAddress: "wss://testnet.vara.network", + }); + const triviaFactory = new TriviaFactory( + api, + "0xf5691c64eed986728bc5a263851b78ba867522289078b07ade779ca25f711b8b", + ); + + const playTriviaMessage = triviaFactory.triviaFactory.playTrivia( + Number(triviaId), + answers, + ); + + await playTriviaMessage.withAccount(account.decodedAddress); + await playTriviaMessage.calculateGas(); + + const result = await playTriviaMessage.signAndSend(); + + const isFinalized = await result.isFinalized; + + if (isFinalized) { + const response = await result.response(); + if (response && typeof response === "object" && "ok" in response) { + setResult(String(response.ok)); } else if ( - playResult && - typeof playResult === "object" && - "err" in playResult + response && + typeof response === "object" && + "err" in response ) { - setResult(`Error: ${String(playResult.err)}`); + setResult(`Error: ${String(response.err)}`); } else { setResult("Unexpected result structure"); } setShowResult(true); - } catch (error) { - console.error("Error playing trivia:", error); - setResult("Error playing trivia. Please try again."); + } else { + setResult("Transaction was not finalized"); + setShowResult(true); } - } else { - setCurrentQuestion(currentQuestion + 1); - setSelectedAnswer(""); + } catch (error) { + console.error("Error playing trivia:", error); + setResult("Error playing trivia. Please try again."); + setShowResult(true); + } finally { + setIsLoading(false); } }; @@ -96,46 +131,64 @@ export default function PlayTrivia() { value={triviaId} onChange={handleTriviaIdChange} /> -
{trivia && !showResult && ( <>

+ Question {currentQuestion + 1}:{" "} {trivia.questions[currentQuestion]}

-
    - {trivia.questions.map((option, index) => ( -
  • handleAnswerClick(option)} - > - {option} -
  • - ))} -
+ + handleAnswerChange(e.target.value, currentQuestion) + } + /> - {selectedAnswer && ( +
- )} + {currentQuestion < trivia.questions.length - 1 ? ( + + ) : ( + + )} +
)} {showResult && (
-

Trivia Result

+

Trivia Result

{result}

)}