Skip to content

Commit

Permalink
Cleanup wasm errors
Browse files Browse the repository at this point in the history
  • Loading branch information
benthecarman committed Dec 13, 2023
1 parent c35f4f3 commit 0300510
Show file tree
Hide file tree
Showing 4 changed files with 158 additions and 135 deletions.
81 changes: 81 additions & 0 deletions kormir-wasm/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
use kormir::error::Error;
use wasm_bindgen::prelude::wasm_bindgen;

/// Kormir error type
#[derive(Debug, Clone)]
#[wasm_bindgen]
pub enum JsError {
/// Attempted to sign an event that was already signed
EventAlreadySigned,
/// Event data was not found
NotFound,
/// The storage failed to read/save the data
StorageFailure,
/// User gave an invalid outcome
InvalidOutcome,
/// An error that should never happen, if it does it's a bug
Internal,
/// An error with creating or sending Nostr events
Nostr,
}

impl From<Error> for JsError {
fn from(value: Error) -> Self {
match value {
Error::EventAlreadySigned => Self::EventAlreadySigned,
Error::NotFound => Self::NotFound,
Error::StorageFailure => Self::StorageFailure,
Error::InvalidOutcome => Self::InvalidOutcome,
Error::Internal => Self::Internal,
}
}
}

impl From<JsError> for Error {
fn from(value: JsError) -> Self {
match value {
JsError::EventAlreadySigned => Self::EventAlreadySigned,
JsError::NotFound => Self::NotFound,
JsError::StorageFailure => Self::StorageFailure,
JsError::InvalidOutcome => Self::InvalidOutcome,
JsError::Internal => Self::Internal,
JsError::Nostr => Self::Internal,
}
}
}

impl From<rexie::Error> for JsError {
fn from(_: rexie::Error) -> Self {
JsError::StorageFailure
}
}

impl From<serde_json::Error> for JsError {
fn from(_: serde_json::Error) -> Self {
JsError::StorageFailure
}
}

impl From<nostr::event::builder::Error> for JsError {
fn from(_: nostr::event::builder::Error) -> Self {
JsError::NotFound
}
}

impl From<nostr_sdk::client::Error> for JsError {
fn from(_: nostr_sdk::client::Error) -> Self {
JsError::Nostr
}
}

impl From<kormir::bitcoin::util::bip32::Error> for JsError {
fn from(_: kormir::bitcoin::util::bip32::Error) -> Self {
JsError::Internal
}
}

impl From<bip39::Error> for JsError {
fn from(_: bip39::Error) -> Self {
JsError::Internal
}
}
64 changes: 28 additions & 36 deletions kormir-wasm/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::error::JsError;
use crate::storage::{IndexedDb, MNEMONIC_KEY};
use bip39::Mnemonic;
use kormir::bitcoin::hashes::hex::ToHex;
Expand All @@ -9,6 +10,7 @@ use nostr::EventId;
use nostr_sdk::Client;
use wasm_bindgen::prelude::wasm_bindgen;

mod error;
mod storage;

#[derive(Debug, Clone)]
Expand All @@ -22,47 +24,42 @@ pub struct Kormir {

#[wasm_bindgen]
impl Kormir {
pub async fn new(relays: Vec<String>) -> Self {
let storage = IndexedDb::new().await.unwrap();
pub async fn new(relays: Vec<String>) -> Result<Kormir, JsError> {
let storage = IndexedDb::new().await?;

let mnemonic: Option<Mnemonic> = storage.get_from_indexed_db(MNEMONIC_KEY).await.unwrap();
let mnemonic: Option<Mnemonic> = storage.get_from_indexed_db(MNEMONIC_KEY).await?;
let xpriv = match mnemonic {
Some(mnemonic) => {
ExtendedPrivKey::new_master(Network::Bitcoin, &mnemonic.to_seed("")).unwrap()
}
Some(mnemonic) => ExtendedPrivKey::new_master(Network::Bitcoin, &mnemonic.to_seed(""))?,
None => {
let mut entropy: [u8; 16] = [0; 16];
getrandom::getrandom(&mut entropy).unwrap();

let mnemonic = Mnemonic::from_entropy(&entropy).unwrap();
storage
.save_to_indexed_db(MNEMONIC_KEY, &mnemonic)
.await
.unwrap();
ExtendedPrivKey::new_master(Network::Bitcoin, &mnemonic.to_seed("")).unwrap()
let mnemonic = Mnemonic::from_entropy(&entropy)?;
storage.save_to_indexed_db(MNEMONIC_KEY, &mnemonic).await?;
ExtendedPrivKey::new_master(Network::Bitcoin, &mnemonic.to_seed(""))?
}
};

let oracle = Oracle::from_xpriv(storage.clone(), xpriv).unwrap();
let oracle = Oracle::from_xpriv(storage.clone(), xpriv)?;

let client = Client::new(&oracle.nostr_keys());

for relay in relays.iter() {
#[cfg(target_arch = "wasm32")]
client.add_relay(relay.as_str()).await.unwrap();
client.add_relay(relay.as_str()).await?;

#[cfg(not(target_arch = "wasm32"))]
client.add_relay(relay.as_str(), None).await.unwrap();
client.add_relay(relay.as_str(), None).await?;
}

client.connect().await;

Self {
Ok(Kormir {
oracle,
storage,
client,
relays,
}
})
}

pub fn get_public_key(&self) -> String {
Expand All @@ -74,50 +71,45 @@ impl Kormir {
event_id: String,
outcomes: Vec<String>,
event_maturity_epoch: u32,
) -> String {
) -> Result<String, JsError> {
let (id, ann) = self
.oracle
.create_enum_event(event_id, outcomes, event_maturity_epoch)
.await
.unwrap();
.await?;

let event = kormir::nostr_events::create_announcement_event(
&self.oracle.nostr_keys(),
&ann,
&self.relays,
)
.unwrap();
)?;

self.storage
.add_announcement_event_id(id, event.id.to_hex())
.await
.unwrap();
.await?;

self.client.send_event(event).await.unwrap();
self.client.send_event(event).await?;

ann.encode().to_hex()
Ok(ann.encode().to_hex())
}

pub async fn sign_enum_event(&self, id: u32, outcome: String) -> String {
let attestation = self.oracle.sign_enum_event(id, outcome).await.unwrap();
pub async fn sign_enum_event(&self, id: u32, outcome: String) -> Result<String, JsError> {
let attestation = self.oracle.sign_enum_event(id, outcome).await?;

let event = self.storage.get_event(id).await.unwrap().unwrap();
let event_id = EventId::from_hex(event.attestation_event_id.unwrap()).unwrap();
let event = self.storage.get_event(id).await?.ok_or(JsError::NotFound)?;
let event_id = EventId::from_hex(event.announcement_event_id.unwrap()).unwrap();

let event = kormir::nostr_events::create_attestation_event(
&self.oracle.nostr_keys(),
&attestation,
event_id,
)
.unwrap();
)?;

self.storage
.add_attestation_event_id(id, event.id.to_hex())
.await
.unwrap();
.await?;

self.client.send_event(event).await.unwrap();
self.client.send_event(event).await?;

attestation.encode().to_hex()
Ok(attestation.encode().to_hex())
}
}
Loading

0 comments on commit 0300510

Please sign in to comment.