Skip to content

Commit

Permalink
start listen launch program job request
Browse files Browse the repository at this point in the history
  • Loading branch information
MSghais committed Aug 6, 2024
1 parent 97d806f commit 56e86e6
Show file tree
Hide file tree
Showing 8 changed files with 119 additions and 67 deletions.
15 changes: 15 additions & 0 deletions askeladd-dvm-marketplace/src/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -400,4 +400,19 @@ main {
border-radius: 0.25rem;
transition: all 0.3s ease;
text-shadow: none;
}

.basic-button {
/* width: 100%; */
background: var(--neon-blue);
color: #000000;
border: 1px solid #000000;
box-shadow: 0 0 2px var(--neon-blue);
text-transform: uppercase;
letter-spacing: 1px;
font-weight: bold;
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
transition: all 0.3s ease;
text-shadow: none;
}
65 changes: 43 additions & 22 deletions askeladd-dvm-marketplace/src/app/launch-program/page.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
"use client";

import { useState, useEffect } from "react";
import { useState, useEffect, useMemo } from "react";
import { NDKEvent, NDKKind } from '@nostr-dev-kit/ndk';
import { useSendNote } from "@/hooks/useSendNote";
import { useFetchEvents } from "@/hooks/useFetchEvents";
import { APPLICATION_PUBKEY_DVM, ASKELADD_RELAY } from "@/constants/relay";
import { Event as EventNostr, SimplePool } from "nostr-tools";
import { ASKELADD_KINDS, ConfigHandle, IGenerateZKPRequestDVM, IProgramParams } from "@/types";
import { ASKELADD_KINDS, ConfigHandle, ContractUploadType, IGenerateZKPRequestDVM, IProgramParams, KIND_JOB_ADD_PROGRAM } from "@/types";
import EventCard from "../components/EventCard";
import { generateContentAndTags } from "../utils/generateAppHandler";
import { HowItWork } from "../components/description";
Expand Down Expand Up @@ -34,7 +34,11 @@ export default function LaunchProgram() {
const [claim, setClaim] = useState<number>(443693538);
const [inputIndex, setInputsIndex] = useState(0)
const [isOpenForm, setIsOpenForm] = useState(false)
const [form, setForm] = useState({})
const [formState, setForm] = useState({})

const form = useMemo(() => {
return formState
}, [formState])
const [formType, setFormType] = useState({})
const [formEncrypted, setFormEncrypted] = useState({})
const [programParam, setProgramParam] = useState<IProgramParams>({
Expand Down Expand Up @@ -127,6 +131,7 @@ export default function LaunchProgram() {
const pubkey = await window.nostr.getPublicKey();
let created_at = new Date().getTime();
setPublicKey(pubkey)
return pubkey;
}

} catch (e) {
Expand Down Expand Up @@ -230,14 +235,15 @@ export default function LaunchProgram() {
}

const content = JSON.stringify({
request: form,
request: {...form},
program: {
contract_name: programParam?.contract_name,
internal_contract_name: programParam?.internal_contract_name,
contract_reached: programParam?.contract_reached,
contract_name: programParam?.contract_name ?? "test",
// internal_contract_name: programParam?.internal_contract_name ?? "test",
contract_reached: programParam?.contract_reached ?? ContractUploadType.Ipfs,
inputs: Object.fromEntries(inputs),
inputs_types: undefined,
inputs_encrypted: Object.fromEntries(inputs_encrypted)
inputs_encrypted: Object.fromEntries(inputs_encrypted),
tags:tags
}
})

Expand All @@ -248,24 +254,25 @@ export default function LaunchProgram() {
const pool = new SimplePool();
let pubkey;
if (typeof window !== "undefined" && window.nostr) {
let pubkey = await connectExtension()

console.log("pubkey", pubkey)
// await connectExtension()
if (!publicKey) return;
if (!publicKey && !pubkey) return;
if (!content) return;

let created_at = new Date().getTime();
const event = await window.nostr.signEvent({
pubkey: publicKey ?? pubkey,
created_at: created_at,
kind: NDKKind.AppHandler,
kind: KIND_JOB_ADD_PROGRAM,
tags: tags,
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])
const eventID = await Promise.any(pool.publish(ASKELADD_RELAY, event as EventNostr));
console.log("eventID", eventID[0])
setIsNeedLoadEvents(true)

} else {
Expand Down Expand Up @@ -334,21 +341,35 @@ export default function LaunchProgram() {
<div key={i}>
<p >{`${key}`}</p>
<p>{`Name: ${value}`}</p>
<input
className='text-black'
placeholder="Name of your input"
name={key}
onChange={handleChange}
></input>
<div className="flex flex-direction">
<input
className='text-black'
placeholder="Name of your input"
name={key}
onChange={handleChange}
></input>
<button

className="p-1"
onClick={() => {
const { [key]: removeKey, ...newObject } = form;
setForm({ ...newObject })
setInputsIndex(inputIndex-1)
const { [key]:removeKeyEncrypted, ...newFormEncrypted } = formEncrypted;

setFormEncrypted({ ...newFormEncrypted })

}}>X</button>
</div>

</div>
)
})}
<button
className="bg-blue border border-r-3 secondary-button w-full"
className="bg-blue border border-r-3 secondary-button w-full my-5"
onClick={() => {
setInputsIndex(inputIndex + 1);
setForm({ ...form, [inputIndex + 1]: inputIndex + 1 })
// form[String(inputIndex + 1).toString()] = (inputIndex + 1).toString()
}}
>
Add input
Expand All @@ -358,7 +379,7 @@ export default function LaunchProgram() {
<div className="max-w-md mx-auto bg-dark-purple p-6 rounded-lg shadow-neon mt-8 relative game-screen">
<p>Inputs encrypted</p>

<button onClick={handleLoadFormEncrypted}> Load inputs to continue settings</button>
<button className="basic-button" onClick={handleLoadFormEncrypted}> Load inputs to continue settings</button>
{formEncrypted && Object.entries(formEncrypted).map(([key, value], i) => {
return (
<div key={i}>
Expand Down
1 change: 1 addition & 0 deletions askeladd-dvm-marketplace/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ export enum ProgramInternalContractName {

export enum ContractUploadType {
InternalAskeladd = "InternalAskeladd",
Ipfs = "Ipfs",
}

export interface IProgramParams {
Expand Down
5 changes: 2 additions & 3 deletions crates/core/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,8 @@ impl Database {
CREATE TABLE IF NOT EXISTS stwo_prover_launched (
id TEXT PRIMARY KEY,
request_json TEXT NOT NULL,
program_param TEXT NOT NULL,
response_json TEXT,
status TEXT NOT NULL,
program TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
Expand Down Expand Up @@ -98,7 +97,7 @@ impl Database {
let request_json = serde_json::to_string(request).unwrap();
let program_json = serde_json::to_string(program).unwrap();
self.conn.execute(
"INSERT INTO stwo_prover_launched (id, request_json, status, program) VALUES (?1, ?2, ?3)",
"INSERT INTO stwo_prover_launched (id, request_json, status, program) VALUES (?1, ?2, ?3, ?4)",
params![job_id, request_json, RequestStatus::Pending.to_string(), program_json.to_string()],
)?;
Ok(())
Expand Down
7 changes: 4 additions & 3 deletions crates/core/src/dvm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ pub mod types {
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum ContractUploadType {
InternalAskeladd,
Ipfs,
// URl,
// BackendEndpoint,
// Ipfs,
}

// Enum for internal_name program on ASKELADD
Expand All @@ -65,8 +65,9 @@ pub mod types {
pub contract_reached: ContractUploadType,
pub contract_name: Option<String>,
pub internal_contract_name: Option<ProgramInternalContractName>,
pub tags: Option<Tag>, /* For External program
* pub endpoint:Option<String>, */
pub tags: Option<Vec<Tag>>,
// For External program
// pub endpoint:Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
Expand Down
83 changes: 47 additions & 36 deletions crates/core/src/dvm/service_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,16 +115,6 @@ impl ServiceProvider {

info!("Subscribed to proving requests, waiting for requests...");

// Start handling Nostr notifications
self.nostr_client
.handle_notifications(|notification| async {
match self.handle_notification(notification).await {
Ok(result) => Ok(result),
Err(e) => Err(Box::new(e) as Box<dyn Error>),
}
})
.await?;

// Start JOB LAUNCH PROGRAM subscription
let launch_program_req_id = SubscriptionId::new(&self.settings.launch_program_req_id);
let filter_launch_program = Filter::new()
Expand All @@ -141,7 +131,9 @@ impl ServiceProvider {
.await
.map_err(|e| ServiceProviderError::NostrSubscriptionError(e.to_string()))?;

// Start handling LAUNCH_PROGRAM
info!("Subscribed to launch program, waiting for requests...");

// Start handling Nostr notifications
self.nostr_client
.handle_notifications(|notification| async {
match self.handle_notification(notification).await {
Expand Down Expand Up @@ -309,43 +301,62 @@ impl ServiceProvider {
info!("LAUNCH_PROGRAM request received [{}]", event.id);

let job_id = event.id.to_string();
println!("job_id {:?}", job_id);

let tags = &event.tags;
let params = extract_params_from_tags(tags);

println!("params {:?}", params);

println!("event {:?}", event.content);

// Deserialze content
let zkp_request = ServiceProvider::deserialize_zkp_request_data(&event.content.to_owned())?;
// let zkp_request =
// ServiceProvider::deserialize_zkp_request_data(&event.content.to_owned())?;
// let params_program: Option<ProgramParams> = zkp_request.program.clone();
// println!("zkp_request {:?}", zkp_request);

// Request on the content
// Check request of the launch_program
let request_str = serde_json::to_string(&zkp_request.request).unwrap();
// let request_str = serde_json::to_string(&request).unwrap();
let request_value = serde_json::from_str(&request_str).unwrap();
let request_str = serde_json::to_string(&event.content).unwrap();
// let request_str = serde_json::to_string(&zkp_request.request).unwrap();
let request_value: Value = serde_json::from_str(&request_str).unwrap();
println!("request_value {:?}", request_value);

// TAGS
let program_str = serde_json::to_string(&zkp_request.program).unwrap();
let program_value = serde_json::from_str(&program_str).unwrap();

// Look if this program is already launched and save
if let Some(status) = self.db.get_program_status(&job_id)? {
match status {
RequestStatus::Completed => {
info!("Request {} already processed, skipping", &job_id);
return Ok(());
// let program_str = serde_json::to_string(&zkp_request.program).unwrap();
let program_value: Value = serde_json::from_str(&request_str).unwrap();
println!("program_value {:?}", program_value);

let zkp_request =
match ServiceProvider::deserialize_zkp_request_data(&event.content.to_owned()) {
Ok(zkp) => zkp,
Err(e) => {
println!("{:?}", e);
return Err(e);
}
RequestStatus::Failed => {
info!("Request {} failed before, retrying", &job_id);
}
RequestStatus::Pending => {
info!("Request {} is already pending, skipping", &job_id);
return Ok(());
}
}
} else {
self.db
.insert_program_launched(&job_id, &request_value, &program_value)?;
}
};
println!("zkp_request {:?}", zkp_request);
// TODO
// Look if this program is already launched and save
// if let Some(status) = self.db.get_program_status(&job_id)? {
// match status {
// RequestStatus::Completed => {
// info!("Request LAUNCH_PROGRAM {} already processed, skipping", &job_id);
// return Ok(());
// }
// RequestStatus::Failed => {
// info!("Request LAUNCH_PROGRAM {} failed before, retrying", &job_id);
// }
// RequestStatus::Pending => {
// info!("Request LAUNCH_PROGRAM {} is already pending, skipping", &job_id);
// return Ok(());
// }
// }
// } else {
// self.db
// .insert_program_launched(&job_id, &request_value, &program_value)?;
// }

// Look program param

Expand Down
4 changes: 4 additions & 0 deletions crates/core/src/prover_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ impl ProverService {
match p.contract_reached {
ContractUploadType::InternalAskeladd => {
self.internal_program(request, request_str, p)
}
ContractUploadType::Ipfs => {
println!("TODO implement IPFS WASM");
Err("IPFS_CONTRACT_IN_PROCESS".to_string())
} // => Err(ProverServiceError::NoProgramParam.to_string()),
}
} else {
Expand Down
6 changes: 3 additions & 3 deletions crates/stwo_wasm/src/poseidon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub const N_LOG_INSTANCES_PER_ROW: usize = 3;
pub const LOG_N_ROWS: u32 = 8;
pub const LOG_EXPAND: u32 = 2;
pub const LOG_N_LANES: u32 = 4;
const N_STATE: usize = 16;
// const N_STATE: usize = 16;

#[wasm_bindgen]
extern "C" {
Expand Down Expand Up @@ -75,7 +75,7 @@ impl PoseidonStruct {

// Draw lookup element.
// let lookup_elements = LookupElements::draw(channel);
let lookup_elements = LookupElements::draw(channel, N_STATE * 2);
let lookup_elements = LookupElements::draw(channel);

// let component = PoseidonComponent {
// Precompute twiddles.
Expand Down Expand Up @@ -179,7 +179,7 @@ impl PoseidonStruct {
tree_builder.commit(channel);

// Draw lookup element.
let lookup_elements = LookupElements::draw(channel, N_STATE * 2);
let lookup_elements = LookupElements::draw(channel);

// Interaction trace.
let (trace, claimed_sum) = gen_interaction_trace(log_n_rows, lookup_data, &lookup_elements);
Expand Down

0 comments on commit 56e86e6

Please sign in to comment.