use js_export_macro::js_export;
use miden_client::Word;
use miden_client::note::{Note as NativeNote, NoteId};
use crate::platform::{JsErr, from_str_err};
use crate::{WebClient, js_error_with_context};
#[js_export]
impl WebClient {
#[js_export(js_name = "sendPrivateNote")]
pub async fn send_private_note(
&self,
note: crate::models::note::Note,
address: crate::models::address::Address,
inclusion_proof: crate::models::note_inclusion_proof::NoteInclusionProof,
) -> Result<(), JsErr> {
let mut guard = self.get_mut_inner().await;
let client = guard
.as_mut()
.ok_or_else(|| from_str_err("Client not initialized. Call createClient() first."))?;
let native_note: NativeNote = note.into();
client
.send_private_note_with_proof(native_note, &address.into(), inclusion_proof.into())
.await
.map_err(|e| js_error_with_context(e, "failed sending private note"))?;
Ok(())
}
#[js_export(js_name = "sendPrivateOutputNote")]
pub async fn send_private_output_note(
&self,
note_id: String,
address: crate::models::address::Address,
) -> Result<(), JsErr> {
let mut guard = self.get_mut_inner().await;
let client = guard
.as_mut()
.ok_or_else(|| from_str_err("Client not initialized. Call createClient() first."))?;
let note_id: NoteId = NoteId::from_raw(
Word::try_from(note_id)
.map_err(|err| js_error_with_context(err, "failed to parse output note id"))?,
);
let record = client
.get_output_note(note_id)
.await
.map_err(|e| js_error_with_context(e, "failed reading output note"))?
.ok_or_else(|| from_str_err("No output note found for the given id"))?;
let proof = record.inclusion_proof().cloned().ok_or_else(|| {
from_str_err(
"output note has no inclusion proof; sync past the block that committed it",
)
})?;
let native_note: NativeNote = record.try_into().map_err(|e| {
js_error_with_context(e, "output note has no details to relay (recipient unknown)")
})?;
client
.send_private_note_with_proof(native_note, &address.into(), proof)
.await
.map_err(|e| js_error_with_context(e, "failed sending private output note"))?;
Ok(())
}
#[js_export(js_name = "fetchPrivateNotes")]
pub async fn fetch_private_notes(&self) -> Result<(), JsErr> {
let mut guard = self.get_mut_inner().await;
let client = guard
.as_mut()
.ok_or_else(|| from_str_err("Client not initialized. Call createClient() first."))?;
client
.fetch_private_notes()
.await
.map_err(|e| js_error_with_context(e, "failed fetching private notes"))?;
Ok(())
}
}