Skip to content

Commit

Permalink
Fix frontend: Get job result, fix filter with kind + fetch events + j…
Browse files Browse the repository at this point in the history
…ob id (AbdelStark#15)

* fix filter with kind + fetch events + job id

* fix assert
  • Loading branch information
MSghais authored Jul 31, 2024
1 parent 9b3c322 commit cb56567
Show file tree
Hide file tree
Showing 4 changed files with 320 additions and 133 deletions.
295 changes: 191 additions & 104 deletions askeladd-dvm-marketplace/src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,36 +1,39 @@
"use client";

import { useState, useEffect } from "react";
import { NDKEvent} from '@nostr-dev-kit/ndk';
import { NDKEvent, NDKKind, NostrEvent } from '@nostr-dev-kit/ndk';
import { useNostrContext } from "@/context/NostrContext";
import { useSendNote } from "@/hooks/useSendNote";
import { JobResultProver, StarkProof } from "@/types";
import { JobResultProver, KIND_JOB_REQUEST, KIND_JOB_RESULT, StarkProof } from "@/types";
import init, { run_fibonacci_example, run_fibonacci_verify_exemple } from "../pkg/program_wasm";
import { useFetchEvents } from "@/hooks/useFetchEvents";
import { ASKELADD_RELAY } from "@/constants/relay";
import { Relay } from 'nostr-tools/relay'
import { verifyEvent, finalizeEvent, Event as EventNostr } from "nostr-tools";
import { Event as EventNostr, SimplePool } from "nostr-tools";
export default function Home() {
const [logSize, setLogSize] = useState<number>(5);
const [claim, setClaim] = useState<number>(443693538);
const [jobId, setJobId] = useState<string | null>(null);
const [jobId, setJobId] = useState<string | undefined>(undefined);
const [error, setError] = useState<string | undefined>()
const [starkProof, setStarkProof] = useState<any | undefined>()
// const [starkProof, setStarkProof] = useState<StarkProof | undefined>()
const [events, setEvents] = useState<NDKEvent[]>([])
const [selectedEvent, setSelectedEvent] = useState<NDKEvent | undefined>()
const [events, setEvents] = useState<EventNostr[] | NDKEvent[]>([])
const [selectedEvent, setSelectedEvent] = useState<EventNostr | undefined | NDKEvent>()
const [proofStatus, setProofStatus] = useState<
"idle" | "pending" | "received" | "verified"
>("idle");
const [proof, setProof] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [isInitialized, setIsInitialized] = useState(false);
const [isFetchJob, setIsFetchJob] = useState(false);
const [isWaitingJob, setIsWaitingJob] = useState(false);
const [timestampJob, setTimestampJob] = useState<number | undefined>();

const { ndk } = useNostrContext()
const { fetchEvents } = useFetchEvents()
const { fetchEvents, fetchEventsTools, setupSubscriptionNostr } = useFetchEvents()
const { sendNote, publishNote } = useSendNote()

// Init wasm module to run_fibonacci_verify
useEffect(() => {
init()
.then(() => setIsInitialized(true))
Expand All @@ -40,114 +43,196 @@ export default function Home() {
});
}, []);

useEffect(() => {
/** Effect to fetch the job result when a job request is sent */
const waitingForJobResult = async () => {
if (isFetchJob && jobId) return;
fetchEventsProof()
setIsLoading(false);
setIsWaitingJob(false)
}
const timeoutWaitingForJobResult = async () => {
console.log("waiting timeout")
setTimeout(() => {
waitingForJobResult()
}, 5000);
}

useEffect(() => {
if (jobId && !isFetchJob) {
waitingForJobResult()
}
}, [jobId, isFetchJob])
}, [jobId, isFetchJob, isWaitingJob])

/** Submit job with JOB_REQUEST 5600
* - Use extension NIP-7
* - Default public key demo
* - NDK generate key or import later
*/
const submitJob = async () => {
setIsLoading(true);
setProofStatus("pending");

// Mock event id
const eventId = Math.random().toString(36).substring(7);
setJobId(eventId);

const tags = [
['param', 'log_size', logSize.toString()],
['param', 'claim', claim.toString()],
['output', 'text/json']
];

const content = JSON.stringify({
request: {
log_size: logSize.toString(),
claim: claim.toString()
}

})

// Define the timestamp before which you want to fetch events
setTimestampJob(new Date().getTime())
/** Use Nostr extension to send event */
if (typeof window !== "undefined" && window.nostr) {
const pubkey = await window.nostr.getPublicKey();
let created_at = new Date().getTime();
const event = await window.nostr.signEvent({
pubkey: pubkey,
created_at: created_at,
kind: 5600,
tags: tags,
content: content
}) // takes an event object, adds `id`, `pubkey` and `sig` and returns it
if (event?.sig) {
setJobId(event?.sig);
}
const relay = await Relay.connect(ASKELADD_RELAY[0])
let eventID = await relay.publish(event as EventNostr)
console.log("eventID published", eventID)
if (eventID) {
setJobId(eventID);
try {
setIsLoading(true);
setIsFetchJob(false);
setProofStatus("pending");
const tags = [
['param', 'log_size', logSize.toString()],
['param', 'claim', claim.toString()],
['output', 'text/json']
];
const content = JSON.stringify({
request: {
log_size: logSize.toString(),
claim: claim.toString()
}
})
// Define the timestamp before which you want to fetch events
setTimestampJob(new Date().getTime() - 1000)
/** Use Nostr extension to send event */
if (typeof window !== "undefined" && window.nostr) {
const pubkey = await window.nostr.getPublicKey();
let created_at = new Date().getTime();
const event = await window.nostr.signEvent({
pubkey: pubkey,
created_at: created_at,
kind: 5600,
tags: tags,
content: content
}) // takes an event object, adds `id`, `pubkey` and `sig` and returns it
const pool = new SimplePool()
// Setup job request to fetch job id
// const poolRequest = await setupSubscriptionNostr({
// pubkey,
// filter: {
// authors: [pubkey],
// since: timestampJob,
// },
// onEventCallback: (event) => {
// console.log("Event job request received: ", event)
// setJobId(event?.id);
// setIsWaitingJob(true);
// if (jobId && event?.content?.includes(jobId)) {
// getDataOfEvent(event)
// }
// }
// })

/** @TODO why the event id is not return?
* - get the last event and fetch job_id event
* - check if events is sent with subscription
*
*/
// const relay = await Relay.connect(ASKELADD_RELAY[0])
// let eventID = await relay.publish(event as EventNostr);
const eventID = await Promise.any(pool.publish(ASKELADD_RELAY, event as EventNostr));
const { events } = await fetchEvents({
kind: KIND_JOB_REQUEST,
since: timestampJob
});
console.log("events job request", events);
if (events) {
const lastEvent = events[events?.length - 1]
const lastEventId = lastEvent?.id;
setJobId(lastEventId);
}
/** @TODO Subscribed to Job Result**/
/** Wait job result */
// let h = pool.subscribeMany(
// ASKELADD_RELAY,
// [
// {
// // since: timestampJob,
// kinds: [KIND_JOB_RESULT as NDKKind]
// },
// ],
// {
// onevent(event) {
// console.log("Event job result received: ", event?.id);
// console.log("jobID to find", jobId)
// if (jobId && event?.content?.includes(jobId)) {
// console.log("Event content include job id needed")
// getDataOfEvent(event)
// }
// // h.close();
// },
// onclose: () => {
// },
// oneose() {
// h.close()
// }
// }
// )
// const poolResult = await setupSubscriptionNostr({
// pubkey,
// filter: {
// // since: timestampJob,
// kinds: [KIND_JOB_RESULT as NDKKind]
// },
// onEventCallback: (event) => {
// console.log("Event job result received: ", event)
// if (jobId && event?.content?.includes(jobId)) {
// console.log("Event content include job id needed");
// getDataOfEvent(event)
// }
// }
// })
setIsWaitingJob(true)
} else {
// let { result, event } = await sendNote({ content, tags, kind: 5600 })
// console.log("event", event)
// if (event?.sig) {
// setJobId(event?.sig);
// }
// setIsWaitingJob(true)
/** NDK event
* Generate or import private key after
*/
}

/** check if events is sent */
const { events } = await fetchEvents(5600);
console.log("events job request", events);


} catch (e) {
} finally {
setIsLoading(false);
}
// let { result, event } = await sendNote({ content, tags, kind: 5600 })
// console.log("event", event)
// if (event?.sig) {
// setJobId(event?.sig);
// }
/** NDK event
* Generate or import private key after
*/

};

/** TODO fetch subscribed event */
// Fetch Job result from the Prover
/** TODO fetch subscribed event
* fix search jobId => check if relayer support NIP-50
* Fetch Job result from the Prover
* - Tags: By reply of the event_id of the job request?
* - By author
* - Timestamp since/until (doesn't work as expected for me)
*/
const fetchEventsProof = async () => {

// ndk.subscribe({ kinds: [0], authors: ["pubkey-2"] });

setIsFetchJob(false)

const { events } = await fetchEvents()
// const { events } = await fetchEventsTools({ until: timestampJob, kind: KIND_JOB_RESULT,
// // search:`${jobId}`,
// })
const { events } = await fetchEvents({
kind: KIND_JOB_RESULT,
// since: timestampJob,
// search:`${jobId}`,
})
console.log("events job result", events);
if (!events) return;
console.log("events", events);
setEvents(events)
// setEvents(events)
/** @TODO fetch the correct event
* - Tags: By reply of the event_id of the job request?
* - By author
* - Timestamp since/until (doesn't work as expected for me)
*/
let lastEvent = events[events?.length - 1]
// let lastEvent= events.find((e) => e?.id == "48b273cee7d08538604f1797c92685a4638d53a8fea56ff9fe48a436ad4a2e73")
if (!lastEvent) return;
setSelectedEvent(lastEvent)
setProof(lastEvent?.content)
getDataOfEvent(lastEvent);

}

const getDataOfEvent = (lastEvent?: NDKEvent | EventNostr) => {
setSelectedEvent(lastEvent);
if (!lastEvent || !lastEvent?.content) return;
setProof(lastEvent?.content?.toString())
const jobProofSerialize: JobResultProver = JSON.parse(lastEvent?.content)
console.log('jobProofSerialize serialize', jobProofSerialize);

const proofSerialize = jobProofSerialize?.response?.proof;
console.log('proof serialize', proofSerialize);
setStarkProof(proofSerialize);
setProofStatus("received");
}

const waitingForJobResult = async () => {
setTimeout(() => {
console.log("waiting timeout")
fetchEventsProof()
setIsLoading(false);

}, 5000);
return proofSerialize
}

const verifyProofHandler = async () => {
Expand All @@ -169,19 +254,19 @@ export default function Home() {
}

/** @TODO fix ERROR verify loop between all stark proof*/
for (let event of events) {
const jobProofSerialize: JobResultProver = JSON.parse(event?.content)
const proofSerialize = jobProofSerialize?.response?.proof;
const verify_result = run_fibonacci_verify_exemple(logSize, claim, JSON.stringify(proofSerialize));
console.log("loop verify result", verify_result.message);
console.log("loop verify success", verify_result.success);
if (verify_result?.success) {
console.log("is success verify result")
setProofStatus("verified");
} else {
setError(verify_result?.message)
}
}
// for (let event of events) {
// const jobProofSerialize: JobResultProver = JSON.parse(event?.content)
// const proofSerialize = jobProofSerialize?.response?.proof;
// const verify_result = run_fibonacci_verify_exemple(logSize, claim, JSON.stringify(proofSerialize));
// console.log("loop verify result", verify_result.message);
// console.log("loop verify success", verify_result.success);
// if (verify_result?.success) {
// console.log("is success verify result")
// setProofStatus("verified");
// } else {
// setError(verify_result?.message)
// }
// }
setIsLoading(false);
setIsFetchJob(true)
}
Expand Down Expand Up @@ -231,9 +316,11 @@ export default function Home() {
</button>
</div>

{isWaitingJob && <div className="spinner mt-4 mx-auto"></div>}

{jobId && (
<div className="mt-8 text-center">
<p>Job ID: {jobId}</p>
<p >Job ID: {jobId}</p>
<p>Status: {proofStatus}</p>
{isLoading && <div className="spinner mt-4 mx-auto"></div>}

Expand Down
Loading

0 comments on commit cb56567

Please sign in to comment.