|
1 | 1 | use wasm_bindgen::prelude::*; |
| 2 | +use wasm_bindgen_futures::js_sys::{self, Reflect}; |
2 | 3 |
|
3 | 4 | #[derive(Debug, thiserror::Error)] |
4 | 5 | pub enum Error { |
@@ -131,11 +132,75 @@ impl Error { |
131 | 132 | } |
132 | 133 |
|
133 | 134 | impl From<Error> for JsValue { |
134 | | - fn from(val: Error) -> JsValue { |
135 | | - if let Error::JsVal(e) = val { |
136 | | - e |
137 | | - } else { |
138 | | - format!("{val}").into() |
| 135 | + fn from(err: Error) -> Self { |
| 136 | + if let Error::JsVal(e) = err { |
| 137 | + return e; |
| 138 | + } |
| 139 | + |
| 140 | + let msg = format!("{err}"); |
| 141 | + let code = err.code(); |
| 142 | + |
| 143 | + let js_error = js_sys::Error::new(&msg); |
| 144 | + |
| 145 | + js_error.set_name("LwkError"); |
| 146 | + |
| 147 | + let _ = Reflect::set(&js_error, &JsValue::from("code"), &JsValue::from(code)); |
| 148 | + |
| 149 | + if let Error::Boltz(e) = err { |
| 150 | + if let Ok(magic_routing_hint) = MagicRoutingHint::try_from(e) { |
| 151 | + let _ = Reflect::set( |
| 152 | + &js_error, |
| 153 | + &JsValue::from("details"), |
| 154 | + &magic_routing_hint.into(), |
| 155 | + ); |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + JsValue::from(js_error) |
| 160 | + } |
| 161 | +} |
| 162 | + |
| 163 | +/// A struct representing a magic routing hint, with details on how to pay directly without using Boltz |
| 164 | +#[wasm_bindgen] |
| 165 | +pub struct MagicRoutingHint { |
| 166 | + address: String, |
| 167 | + amount: u64, |
| 168 | + uri: String, |
| 169 | +} |
| 170 | + |
| 171 | +#[wasm_bindgen] |
| 172 | +impl MagicRoutingHint { |
| 173 | + /// The address to pay directly to |
| 174 | + pub fn address(&self) -> String { |
| 175 | + self.address.clone() |
| 176 | + } |
| 177 | + |
| 178 | + /// The amount to pay directly to |
| 179 | + pub fn amount(&self) -> u64 { |
| 180 | + self.amount |
| 181 | + } |
| 182 | + |
| 183 | + /// The URI to pay directly to |
| 184 | + pub fn uri(&self) -> String { |
| 185 | + self.uri.clone() |
| 186 | + } |
| 187 | +} |
| 188 | + |
| 189 | +impl TryFrom<lwk_boltz::Error> for MagicRoutingHint { |
| 190 | + type Error = (); |
| 191 | + |
| 192 | + fn try_from(err: lwk_boltz::Error) -> Result<Self, Self::Error> { |
| 193 | + match err { |
| 194 | + lwk_boltz::Error::MagicRoutingHint { |
| 195 | + address, |
| 196 | + amount, |
| 197 | + uri, |
| 198 | + } => Ok(Self { |
| 199 | + address, |
| 200 | + amount, |
| 201 | + uri, |
| 202 | + }), |
| 203 | + _ => Err(()), |
139 | 204 | } |
140 | 205 | } |
141 | 206 | } |
0 commit comments