use js_export_macro::js_export;
use miden_client::PrettyPrint;
use miden_client::note::{NoteScript as NativeNoteScript, StandardNote};
use super::word::Word;
use crate::js_error_with_context;
use crate::models::package::Package;
use crate::platform::{JsBytes, JsErr};
use crate::utils::{deserialize_from_bytes, serialize_to_bytes};
#[derive(Clone)]
#[js_export]
pub struct NoteScript(NativeNoteScript);
#[js_export]
impl NoteScript {
#[js_export(js_name = toString)]
#[allow(clippy::inherent_to_string)]
pub fn to_string(&self) -> String {
self.0.to_pretty_string()
}
pub fn serialize(&self) -> JsBytes {
serialize_to_bytes(&self.0)
}
pub fn deserialize(bytes: JsBytes) -> Result<NoteScript, JsErr> {
deserialize_from_bytes::<NativeNoteScript>(&bytes).map(NoteScript)
}
pub fn p2id() -> Self {
StandardNote::P2ID.script().into()
}
pub fn p2ide() -> Self {
StandardNote::P2IDE.script().into()
}
pub fn swap() -> Self {
StandardNote::SWAP.script().into()
}
pub fn root(&self) -> Word {
miden_client::Word::from(self.0.root()).into()
}
#[js_export(js_name = "fromPackage")]
pub fn from_package(package: &Package) -> Result<NoteScript, JsErr> {
let native_package: miden_client::vm::Package = package.into();
let native_note_script = NativeNoteScript::from_package(&native_package)
.map_err(|e| js_error_with_context(e, "failed to create note script from package"))?;
Ok(native_note_script.into())
}
}
impl From<NativeNoteScript> for NoteScript {
fn from(native_note_script: NativeNoteScript) -> Self {
NoteScript(native_note_script)
}
}
impl From<&NativeNoteScript> for NoteScript {
fn from(native_note_script: &NativeNoteScript) -> Self {
NoteScript(native_note_script.clone())
}
}
impl From<NoteScript> for NativeNoteScript {
fn from(note_script: NoteScript) -> Self {
note_script.0
}
}
impl From<&NoteScript> for NativeNoteScript {
fn from(note_script: &NoteScript) -> Self {
note_script.0.clone()
}
}