Skip to content

Commit

Permalink
Clean/refacto (#26)
Browse files Browse the repository at this point in the history
* refacto home page form with hook and state

* clean program + internal + fetch + rename

* clean comment

* cargo fmt

* clean and refacto

* cargo fmt
  • Loading branch information
MSghais authored Aug 7, 2024
1 parent 5e56db3 commit 567bdb4
Show file tree
Hide file tree
Showing 27 changed files with 674 additions and 1,279 deletions.
256 changes: 29 additions & 227 deletions askeladd-dvm-marketplace/src/app/components/InternalProgram.tsx

Large diffs are not rendered by default.

253 changes: 37 additions & 216 deletions askeladd-dvm-marketplace/src/app/components/ProgramCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,49 +6,33 @@ import { useFetchEvents } from '@/hooks/useFetchEvents';
import { ASKELADD_RELAY } from '@/constants/relay';
import init, { verify_stark_proof, verify_stark_proof_wide_fibo, prove_and_verify, stark_proof_wide_fibo, prove_stark_proof_poseidon, verify_stark_proof_poseidon, prove_and_verify_fib, verify_stark_proof_fib } from "../../pkg"
import { useNostrContext } from '@/context/NostrContext';
import { useDVMState } from '@/hooks/useDVMState';
// Define the props for the component
interface TagsCardProps {
event?: NDKEvent | NostrEvent; // Array of array of strings
zkp_request?: IGenerateZKPRequestDVM
}
const ProgramCard: React.FC<TagsCardProps> = ({ event, zkp_request }) => {
// console.log("zkp_request config", zkp_request)
const { fetchEvents, fetchEventsTools, setupSubscriptionNostr } = useFetchEvents()
const { ndk, pool } = useNostrContext()
const inputs = zkp_request?.program?.inputs
const [form, setForm] = useState<any>(zkp_request?.request ? zkp_request?.request : inputs ? inputs : {})
// const [form, setForm] = useState<any>(zkp_request?.request ? zkp_request?.request : inputs ? Object.fromEntries(inputs) : {})
const [requestTemplate, setRequestTemplate] = useState<any>(zkp_request?.request ? zkp_request?.request : inputs ? Object.fromEntries(inputs) : {})
// const [requestValue, setRequetValue] = useState(inputs ? inputs Object.fromEntries(inputs) : {})
const [requestValue, setRequetValue] = useState<any>(inputs ? inputs : {})
const [isOpenForm, setIsOpenForm] = useState(false)
const [logSize, setLogSize] = useState<number>(5);
const [claim, setClaim] = useState<number>(443693538);
const [publicKey, setPublicKey] = useState<string | undefined>();
const [jobId, setJobId] = useState<string | undefined>();
const [error, setError] = useState<string | undefined>()
const [starkProof, setStarkProof] = useState<any | undefined>()
const [jobEventResult, setJobEventResult] = useState<NostrEvent | undefined | NDKEvent>()
const [seeTag, setSeeTag] = useState<boolean>(false)
const [proof, setProof] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [isInitialized, setIsInitialized] = useState(false);
const [isFetchJob, setIsFetchJob] = useState(false);
const [isLoadingJobResult, setIsLoadingJobResult] = useState(false);
const [isWaitingJob, setIsWaitingJob] = useState(false);
const [timestampJob, setTimestampJob] = useState<number | undefined>();
const [proofStatus, setProofStatus] = useState<
"idle" | "pending" | "received" | "verified"
>("idle");
const [selectedEvent, setSelectedEvent] = useState<NostrEvent | undefined | NDKEvent>()

const { fetchEventsProof, fetchJobRequest, starkProof, submitJob: submitJobModular, proof, proofStatus, setProof, setProofStatus } = useDVMState()

const program = zkp_request?.program;
const contract_reached = zkp_request?.program?.contract_reached;
let eventIdRequest = useMemo(() => {
return jobId
}, [jobId])

// Init wasm module to run_fibonacci_verify
useEffect(() => {
init()
Expand All @@ -70,87 +54,6 @@ const ProgramCard: React.FC<TagsCardProps> = ({ event, zkp_request }) => {
}, [jobId, jobEventResult, pool])


// const runSubscriptionEvent = (pool: SimplePool, pubkey?: string) => {

// // WebSocket connection setup
// // const ws = new WebSocket([ASKELADD_RELAY[0]]); // Replace with your Nostr relay URL

// // ws.onopen = () => {
// // // Subscribe to specific events, adjust filters as needed
// // ws.send(JSON.stringify({
// // "req": "EVENTS",
// // // "filter": {
// // // "#e": ["3a5f5b4..."] // Your event criteria here
// // // }
// // }));
// // };

// // ws.onmessage = (event) => {
// // const data = JSON.parse(event.data);
// // if (data) {
// // if (!jobId) return;
// // if (pubkey && data?.pubkey == pubkey) {
// // setJobId(data?.id)
// // }
// // // setEvents(currentEvents => [...currentEvents, data]);
// // }
// // };

// // ws.onerror = (error) => {
// // console.error("WebSocket error:", error);
// // };

// let poolSubscription = pool.subscribeMany(
// ASKELADD_RELAY,
// [
// // {
// // kinds: [KIND_JOB_REQUEST as NDKKind],
// // // since:timestampJob
// // // authors: pubkey ? [pubkey] : []
// // },
// {
// kinds: [KIND_JOB_RESULT as NDKKind],
// // since:timestampJob
// },
// ],
// {
// onevent(event) {
// // if (event?.kind == KIND_JOB_REQUEST) {
// // if (!jobId) return;
// // if (pubkey && event?.pubkey == pubkey) {
// // setJobId(event?.id)
// // }
// // poolSubscription.close();
// // }
// if (event?.kind == KIND_JOB_RESULT) {
// if (!jobId) return;
// let id = jobId ?? eventIdRequest;
// if (id && !jobEventResult) {
// console.log("Event job result received: ", event?.id);
// console.log("event job content result include job: ", id);
// let isIncludedJobId = event?.content?.includes(jobId)
// let jobEventResultFind = event?.content?.includes(jobId)
// console.log("isIncludedJobId", isIncludedJobId);
// if (isIncludedJobId) {
// console.log("Event JOB_RESULT find", jobEventResultFind);
// getDataOfEvent(event);
// setJobEventResult(event)
// }
// }
// poolSubscription.close();
// }
// },
// onclose: () => {
// poolSubscription.close()
// },
// oneose() {
// poolSubscription.close()
// }
// }
// )
// }


const timeoutWaitingForJobResult = async () => {
console.log("waiting timeout job result")
setTimeout(() => {
Expand All @@ -166,69 +69,6 @@ const ProgramCard: React.FC<TagsCardProps> = ({ event, zkp_request }) => {
setIsWaitingJob(false)
}

const fetchEventsProof = async () => {
console.log("fetch events job result proof")
// if(jobEventResult && jobId)return;
setIsFetchJob(false);
setIsLoadingJobResult(true);
const { events } = await fetchEventsTools({
kind: KIND_JOB_RESULT,
// since: timestampJob,
// search: jobId
// search: `#${jobId}`,
})
// console.log("events job result", events);
if (!events) return;
let lastEvent = events[events?.length - 1]
if (!lastEvent) return;
let id = jobId ?? eventIdRequest;
if (jobEventResult && jobEventResult?.id == id && proof && proofStatus != "pending") return;
if (id && !jobEventResult) {
let jobEventResultFind = events?.find((e) => e?.content?.includes(id))
console.log("jobEventResultFind", jobEventResultFind);
let filterJob = events?.filter((e) => e?.id?.includes(id))
// console.log("filterJob", filterJob);
if (jobEventResultFind?.id) {
console.log("Event JOB_RESULT find", jobEventResultFind);
getDataOfEvent(jobEventResultFind);
setJobEventResult(jobEventResultFind)
}
}
}

const getDataOfEvent = (lastEvent?: NDKEvent | NostrEvent) => {
if (!lastEvent || !lastEvent?.content) return;
setSelectedEvent(lastEvent);
setProof(lastEvent?.content?.toString())
const jobProofSerialize: any = JSON.parse(lastEvent?.content)
console.log('jobProofSerialize serialize', jobProofSerialize);
const proofSerialize = jobProofSerialize?.response?.proof;
console.log('proof serialize', proofSerialize);
setStarkProof(proofSerialize);
setProofStatus("received");
return proofSerialize
}

const fetchJobRequest = async (pubkey?: string) => {
const { events } = await fetchEventsTools({
kind: KIND_JOB_REQUEST,
since: timestampJob,
// authors: pubkey ? [pubkey] : []
});
console.log("events job request", events);
if (!events) return;
const lastEvent = events[0]
if (!lastEvent?.id) return;
const lastEventId = lastEvent?.id;
if (pubkey && pubkey == lastEvent?.pubkey) {
console.log("lastEventId", lastEventId)
setJobId(lastEventId);
eventIdRequest = lastEventId;
setIsWaitingJob(true)
}
}


/** Submit job with JOB_REQUEST 5600
* - Use extension NIP-7
* - Default public key demo
Expand All @@ -242,8 +82,8 @@ const ProgramCard: React.FC<TagsCardProps> = ({ event, zkp_request }) => {
setIsLoading(true);
setIsFetchJob(false);
setJobId(undefined)
setProofStatus("pending");
setProof(null);
// setProofStatus("pending");
// setProof(null);
setJobEventResult(undefined);
setError(undefined);
let tags: string[][] = [
Expand All @@ -268,62 +108,29 @@ const ProgramCard: React.FC<TagsCardProps> = ({ event, zkp_request }) => {
tags.push(["param", key, value])
}
console.log("inputs", Object.fromEntries(inputs))
const content = JSON.stringify({

let job_request: IGenerateZKPRequestDVM = {
// request: form,
request: Object.fromEntries(inputs),
program: {
contract_name: zkp_request?.program?.contract_name,
internal_contract_name: zkp_request?.program?.internal_contract_name,
contract_reached: zkp_request?.program?.contract_reached,
inputs: Object.fromEntries(inputs),
inputs_types: undefined,
inputs_encrypted: undefined
// inputs: Object.fromEntries(inputs),
inputs: inputs,
// inputs_types: undefined,
// inputs_encrypted: undefined
}
})
console.log("content", content)
// Define the timestamp before which you want to fetch events
setTimestampJob(new Date().getTime())
console.log("inputs", inputs)
/** Use Nostr extension to send event */
const pool = new SimplePool();
if (typeof window !== "undefined" && window.nostr) {
const pubkey = await window.nostr.getPublicKey();
let created_at = new Date().getTime();
setPublicKey(pubkey)
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
// Setup job request to fetch job id

/** @TODO why the event id is not return?
* - get the last event and fetch job_id event
* - check if events is sent with subscription
*
*/
// let eventID = await relay.publish(event as EventNostr);
const eventID = await Promise.any(pool.publish(ASKELADD_RELAY, event as NostrEvent));
console.log("eventID", eventID[0])
// await fetchJobRequest(pubkey)
// setIsWaitingJob(true);
// await timeoutWaitingForJobResult()

} else {

/** @TODO flow is user doesn't have NIP-07 extension */
// 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
*/
}

const content = JSON.stringify(job_request)
let res = await submitJobModular(5600,
Object.fromEntries(inputs),
job_request,
tags

)
return res;
} catch (e) {
} finally {
setIsLoading(false);
Expand All @@ -335,16 +142,30 @@ const ProgramCard: React.FC<TagsCardProps> = ({ event, zkp_request }) => {
try {
if (proof) {
setIsLoading(true);
// const inputs: Map<string, string> = new Map<string, string>();
// {
// Object.entries(form).map(([key, value]) => {
// inputs.set(key, value as string)
// }
// )
// }

const inputs: Map<string, string> = new Map<string, string>();
{
Object.entries(form).map(([key, value]) => {
inputs.set(key, value as string)

if (!requestValue[key]) {
inputs.set(key, value as string)
}

}
)
}


if (zkp_request?.program?.internal_contract_name == ProgramInternalContractName.WideFibonnaciProvingRequest) {
console.log("inputs")
console.log("zkp_request",zkp_request)

if (zkp_request?.program?.internal_contract_name == ProgramInternalContractName.WideFibonacciProvingRequest) {
let log_n_instances = inputs.get("log_n_instances");
let log_fibonacci_size = inputs.get("log_fibonacci_size");
if (!log_n_instances && !log_fibonacci_size) return;
Expand Down Expand Up @@ -382,7 +203,7 @@ const ProgramCard: React.FC<TagsCardProps> = ({ event, zkp_request }) => {
setError(verify_result?.message)
}
}
else if (zkp_request?.program?.internal_contract_name == ProgramInternalContractName.FibonnacciProvingRequest) {
else if (zkp_request?.program?.internal_contract_name == ProgramInternalContractName.FibonacciProvingRequest) {
const prove_result = prove_and_verify_fib(logSize, claim);
console.log("prove_result", prove_result);
const serialised_proof_from_nostr_event = JSON.stringify(starkProof);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ export const HowItWork = () => {

const [openHowItWork, setOpenHowItWork] = useState(false);


return(
<div onClick={() => setOpenHowItWork(!openHowItWork)}
className="max-w-sm cursor-pointer my-5 p-1 m-1 whitespace-pre-line break-words"
Expand Down
5 changes: 0 additions & 5 deletions askeladd-dvm-marketplace/src/app/config-marketplace/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { ASKELADD_KINDS, ConfigHandle } from "@/types";
import EventCard from "../components/EventCard";
import { generateContentAndTags } from "../utils/generateAppHandler";
import { HowItWork } from "../components/description";

export default function Home() {
const [publicKey, setPublicKey] = useState<string | undefined>();
const [appKind, setAppKind] = useState<ASKELADD_KINDS | undefined>(ASKELADD_KINDS.KIND_JOB_REQUEST)
Expand All @@ -28,7 +27,6 @@ export default function Home() {
const [isAdmin, setIsAdmin] = useState(false);
const [timestampJob, setTimestampJob] = useState<number | undefined>();
const { fetchEvents, fetchEventsTools, setupSubscriptionNostr } = useFetchEvents()
const { sendNote, publishNote } = useSendNote()

useEffect(() => {
if (isNeedLoadEvents || !isInitialized) {
Expand Down Expand Up @@ -60,7 +58,6 @@ export default function Home() {
setIsNeedLoadEvents(false)
}


/** Connect you */
const connectExtension = async () => {
try {
Expand Down Expand Up @@ -109,7 +106,6 @@ export default function Home() {
setError(undefined);

setTimestampJob(new Date().getTime())
/** Use Nostr extension to send event */
const pool = new SimplePool();
let pubkey;
if (typeof window !== "undefined" && window.nostr) {
Expand All @@ -130,7 +126,6 @@ export default function Home() {
content: content
}) // takes an event object, adds `id`, `pubkey` and `sig` and returns it
// Setup job request to fetch job id

// let eventID = await relay.publish(event as EventNostr);
const eventID = await Promise.any(pool.publish(ASKELADD_RELAY, event as EventNostr));
console.log("eventID", eventID[0])
Expand Down
Loading

0 comments on commit 567bdb4

Please sign in to comment.