Skip to content

Commit

Permalink
Merge pull request #2 from D9J9V/release
Browse files Browse the repository at this point in the history
Release
  • Loading branch information
D9J9V authored Sep 1, 2024
2 parents 44ad445 + f219b45 commit 7afbb54
Show file tree
Hide file tree
Showing 7 changed files with 226 additions and 102 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"factory:test": "yarn workspace @sv/vara-factory test",
"factory:clippy": "yarn workspace @sv/vara-factory clippy",
"factory:fmt": "yarn workspace @sv/vara-factory fmt",
"factory:generate-client": "yarn workspace @sv/vara/factory generate-js-client",
"factory:create-example": "yarn workspace @sv/vara-factory run-example create_trivia",
"factory:play-example": "yarn workspace @sv/vara-factory run-example play_trivia"
},
Expand Down
27 changes: 16 additions & 11 deletions packages/nextjs/contracts/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ export type TriviaError =
| "rewardTransferFailed"
| "unauthorized"
| "questionAnswerMismatch"
| "notificationFailed";
| "notificationFailed"
| "triviaAlreadyCompleted";

export interface Trivia {
questions: Array<string>;
correct_answers: Array<string>;
reward: number | string | bigint;
owner: ActorId;
is_completed: boolean;
}

export class TriviaFactory {
Expand All @@ -40,13 +42,15 @@ export class TriviaFactory {
"Unauthorized",
"QuestionAnswerMismatch",
"NotificationFailed",
"TriviaAlreadyCompleted",
],
},
Trivia: {
questions: "Vec<String>",
correct_answers: "Vec<String>",
reward: "u128",
owner: "[u8;32]",
is_completed: "bool",
},
};

Expand Down Expand Up @@ -95,15 +99,15 @@ export class Trivia {
questions: Array<string>,
correct_answers: Array<string>,
reward: number | string | bigint,
): TransactionBuilder<{ ok: null } | { err: TriviaError }> {
): TransactionBuilder<{ ok: number } | { err: TriviaError }> {
if (!this._program.programId) throw new Error("Program ID is not set");
return new TransactionBuilder<{ ok: null } | { err: TriviaError }>(
return new TransactionBuilder<{ ok: number } | { err: TriviaError }>(
this._program.api,
this._program.registry,
"send_message",
["Trivia", "CreateTrivia", questions, correct_answers, reward],
"(String, String, Vec<String>, Vec<String>, u128)",
"Result<Null, TriviaError>",
"Result<u32, TriviaError>",
this._program.programId,
);
}
Expand Down Expand Up @@ -168,9 +172,7 @@ export class Trivia {
.toHex();
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId || "",
origin: originAddress
? decodeAddress(originAddress)
: ZERO_ADDRESS.toString(),
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
Expand Down Expand Up @@ -217,12 +219,13 @@ export class Trivia {
}

public async getTrivias(
index: number,
originAddress?: string,
value?: number | string | bigint,
atBlock?: `0x${string}`,
): Promise<Array<Trivia>> {
): Promise<{ ok: Trivia } | { err: TriviaError }> {
const payload = this._program.registry
.createType("(String, String)", ["Trivia", "GetTrivias"])
.createType("(String, String, u32)", ["Trivia", "GetTrivias", index])
.toHex();
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId || "",
Expand All @@ -237,10 +240,12 @@ export class Trivia {
this._program.registry.createType("String", reply.payload).toString(),
);
const result = this._program.registry.createType(
"(String, String, Vec<Trivia>)",
"(String, String, Result<Trivia, TriviaError>)",
reply.payload,
);
return result[2].toJSON() as unknown as Array<Trivia>;
return result[2].toJSON() as unknown as
| { ok: Trivia }
| { err: TriviaError };
}

public subscribeToTriviaCreatedEvent(
Expand Down
1 change: 1 addition & 0 deletions packages/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"start": "next start",
"lint": "next lint",
"check-types": "tsc --noEmit",
"generate-js-client": "sails-js generate ./target/wasm32-unknown-unknown/release/trivia_factory.idl -o ../../packages/nextjs/src/contracts/lib -n TriviaFactory",
"vercel": "vercel",
"vercel:yolo": "vercel --build-env NEXT_PUBLIC_IGNORE_BUILD_ERROR=true"
},
Expand Down
147 changes: 101 additions & 46 deletions packages/nextjs/src/app/create-new/page.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { TriviaFactory } from "../../../contracts/lib"; // Asegúrate de que la ruta sea correcta
import { GearApi } from "@gear-js/api";

export default function CrearPregunta() {
const [preguntas, setPreguntas] = useState([
{ pregunta: "", respuestaCorrecta: "" }, // Initial question
{ pregunta: "", respuestaCorrecta: "" },
]);
const [reward, setReward] = useState("");
const [triviaId, setTriviaId] = useState<number | null>(null);
const router = useRouter();

const handlePreguntaChange = (index: number, event: any) => {
const nuevasPreguntas = [...preguntas];
Expand All @@ -23,19 +29,58 @@ export default function CrearPregunta() {
setPreguntas([...preguntas, { pregunta: "", respuestaCorrecta: "" }]);
};

const handleSubmit = (event: any) => {
const handleRewardChange = (event: any) => {
setReward(event.target.value);
};

const handleSubmit = async (event: any) => {
event.preventDefault();
// Aquí puedes manejar la lógica para guardar todas las preguntas y las respuestas
console.log("Preguntas:", preguntas);
try {
// Inicializar GearApi (asegúrate de tener la URL correcta del nodo)
const api = await GearApi.create({
providerAddress: "wss://testnet.vara.network",
});

// Inicializar TriviaFactory (asegúrate de tener el ID del programa correcto)
const triviaFactory = new TriviaFactory(
api,
"0xbc8087ea07aa3de19bc73b0e75ac710f4258a681ab98268a8f8f5f227d7f35ab",
);

const questions = preguntas.map((p) => p.pregunta);
const answers = preguntas.map((p) => p.respuestaCorrecta);

const result = await triviaFactory.trivia
.createTrivia(questions, answers, BigInt(reward))
.signAndSend(); // Asegúrate de manejar la firma de la transacción

// Suponiendo que el resultado contiene el ID de la trivia creada
if (result && typeof result === "object" && "ok" in result) {
const okResult = result.ok;
if (typeof okResult === "number") {
setTriviaId(okResult);
}
}
const modalElement = document.getElementById(
"my_modal_1",
) as HTMLDialogElement;
if (modalElement) {
modalElement.showModal();
} else if (result && typeof result === "object" && "err" in result) {
console.error("Error creating trivia:", result.err);
} else {
console.error("Unexpected result structure:", result);
}
} catch (error) {
console.error("Error creating trivia:", error);
}
};

return (
<div className="container mx-auto p-8 ">
<div className="container mx-auto p-8 ">
<div className="grid grid-cols-2">
<h1 className="text-3xl font-bold mb-6">Create new question</h1>
<button className="btn ustify-self-end">Fund a trivia game</button>
</div>
<div className="grid grid-cols-2">
<h1 className="text-3xl font-bold mb-6">Create new trivia</h1>
<button className="btn justify-self-end">Fund a trivia game</button>
</div>

<form
Expand All @@ -49,14 +94,13 @@ export default function CrearPregunta() {
className="block text-gray-700 text-sm font-bold mb-2"
htmlFor={`pregunta-${index}`}
>
{" "}
  Question {index + 1}:
Question {index + 1}:
</label>
<input
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
id={`pregunta-${index}`}
type="text"
placeholder="Escribe tu pregunta aquí"
placeholder="Write your question here"
value={preguntaObj.pregunta}
onChange={(event) => handlePreguntaChange(index, event)}
required
Expand All @@ -74,7 +118,7 @@ export default function CrearPregunta() {
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
id={`respuestaCorrecta-${index}`}
type="text"
placeholder="Escribe la respuesta correcta"
placeholder="Write the correct answer"
value={preguntaObj.respuestaCorrecta}
onChange={(event) =>
handleRespuestaCorrectaChange(index, event)
Expand All @@ -85,45 +129,56 @@ export default function CrearPregunta() {
</div>
))}

<div className="mb-6">
<label
className="block text-gray-700 text-sm font-bold mb-2"
htmlFor="reward"
>
Reward (in tokens):
</label>
<input
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
id="reward"
type="number"
placeholder="Enter reward amount"
value={reward}
onChange={handleRewardChange}
required
/>
</div>

<div className="flex items-center justify-between">
<div>
<button
type="button" // Important: prevent form submission
className="btn btn-lg mt-10 btn-glass mb-5"
onClick={handleAddQuestion}
>
Next
</button>
</div>
<button
className="btn btn-lg mt-10 btn-glass mb-5"
onClick={() => {
const modalElement = document.getElementById(
"my_modal_1"
) as HTMLDialogElement;
if (modalElement) {
modalElement.showModal();
} else {
console.error("Modal element not found!");
}
}}
type="button"
className="btn btn-lg mt-10 btn-glass mb-5"
onClick={handleAddQuestion}
>
Create
Add Question
</button>
<button type="submit" className="btn btn-lg mt-10 btn-glass mb-5">
Create Trivia
</button>

<dialog id="my_modal_1" className="modal">
<div className="modal-box">
<h3 className="font-bold text-lg">Hello!</h3>
<p className="py-4">Trivia ID</p>
<div className="modal-action">
<form method="dialog">
<button className="btn">Close</button>
</form>
</div>
</div>
</dialog>
</div>
</form>

<dialog id="my_modal_1" className="modal">
<div className="modal-box">
<h3 className="font-bold text-lg">Trivia Created!</h3>
<p className="py-4">
Your trivia has been created successfully. Trivia ID: {triviaId}
</p>
<div className="modal-action">
<form method="dialog">
<button
className="btn"
onClick={() => router.push("/play-trivia")}
>
Go to Play Trivia
</button>
</form>
</div>
</div>
</dialog>
</div>
);
}
Loading

0 comments on commit 7afbb54

Please sign in to comment.