1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use std::convert::TryFrom;
use js_sys::Uint8Array;
use wasm_bindgen::prelude::*;
use ergo_lib::ast::constant::TryExtractFrom;
use crate::utils::I64;
#[wasm_bindgen]
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct Constant(ergo_lib::ast::constant::Constant);
#[wasm_bindgen]
impl Constant {
pub fn decode_from_base16(base16_bytes_str: String) -> Result<Constant, JsValue> {
let bytes = ergo_lib::chain::Base16DecodedBytes::try_from(base16_bytes_str.clone())
.map_err(|_| {
JsValue::from_str(&format!(
"failed to decode base16 from: {}",
base16_bytes_str.clone()
))
})?;
ergo_lib::ast::constant::Constant::try_from(bytes)
.map_err(|e| JsValue::from_str(&format! {"{:?}", e}))
.map(Constant)
}
pub fn encode_to_base16(&self) -> String {
self.0.base16_str()
}
pub fn from_i32(v: i32) -> Constant {
Constant(v.into())
}
pub fn to_i32(&self) -> Result<i32, JsValue> {
i32::try_extract_from(self.0.clone()).map_err(|e| JsValue::from_str(&format! {"{:?}", e}))
}
pub fn from_i64(v: &I64) -> Constant {
Constant(i64::from((*v).clone()).into())
}
pub fn to_i64(&self) -> Result<I64, JsValue> {
i64::try_extract_from(self.0.clone())
.map_err(|e| JsValue::from_str(&format! {"{:?}", e}))
.map(I64::from)
}
pub fn from_byte_array(v: &[u8]) -> Constant {
Constant(v.to_vec().into())
}
pub fn to_byte_array(&self) -> Result<Uint8Array, JsValue> {
Vec::<u8>::try_extract_from(self.0.clone())
.map(|v| Uint8Array::from(v.as_slice()))
.map_err(|e| JsValue::from_str(&format! {"{:?}", e}))
}
}
impl From<ergo_lib::ast::constant::Constant> for Constant {
fn from(c: ergo_lib::ast::constant::Constant) -> Self {
Constant(c)
}
}
impl From<Constant> for ergo_lib::ast::constant::Constant {
fn from(c: Constant) -> Self {
c.0
}
}