pshenmic-dpp 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/.editorconfig +10 -0
  2. package/.gitattributes +4 -0
  3. package/.github/workflows/build.yml +46 -0
  4. package/.github/workflows/publish.yml +42 -0
  5. package/Cargo.lock +2241 -0
  6. package/Cargo.toml +18 -0
  7. package/README.md +74 -0
  8. package/dist/wasm/pshenmic_dpp.js +1130 -0
  9. package/package.json +25 -0
  10. package/packages/cbor-conversation/Cargo.toml +17 -0
  11. package/packages/cbor-conversation/src/lib.rs +26 -0
  12. package/packages/document/Cargo.toml +15 -0
  13. package/packages/document/src/lib.rs +58 -0
  14. package/packages/document/src/methods/js.rs +204 -0
  15. package/packages/document/src/methods/mod.rs +2 -0
  16. package/packages/document/src/methods/rust.rs +92 -0
  17. package/packages/document_batch/Cargo.toml +20 -0
  18. package/packages/document_batch/src/generators.rs +63 -0
  19. package/packages/document_batch/src/lib.rs +326 -0
  20. package/packages/enums/Cargo.toml +13 -0
  21. package/packages/enums/src/batch/batch_enum.rs +19 -0
  22. package/packages/enums/src/batch/mod.rs +1 -0
  23. package/packages/enums/src/keys/key_type.rs +36 -0
  24. package/packages/enums/src/keys/mod.rs +3 -0
  25. package/packages/enums/src/keys/purpose.rs +41 -0
  26. package/packages/enums/src/keys/security_level.rs +32 -0
  27. package/packages/enums/src/lib.rs +2 -0
  28. package/packages/mock_bls/Cargo.toml +12 -0
  29. package/packages/mock_bls/src/lib.rs +26 -0
  30. package/packages/private_key/Cargo.toml +13 -0
  31. package/packages/private_key/src/lib.rs +35 -0
  32. package/packages/public_key/Cargo.toml +15 -0
  33. package/packages/public_key/src/lib.rs +125 -0
  34. package/packages/utils/Cargo.toml +20 -0
  35. package/packages/utils/src/buffer.rs +29 -0
  36. package/packages/utils/src/lib.rs +351 -0
  37. package/scripts/build-js.sh +38 -0
  38. package/scripts/build.sh +35 -0
  39. package/src/lib.rs +2 -0
  40. package/tsconfig.json +18 -0
@@ -0,0 +1,125 @@
1
+ use dpp::identity::identity_public_key::accessors::v0::{
2
+ IdentityPublicKeyGettersV0, IdentityPublicKeySettersV0,
3
+ };
4
+ use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0;
5
+ use dpp::identity::{IdentityPublicKey, KeyType, Purpose, SecurityLevel, TimestampMillis};
6
+ use dpp::platform_value::BinaryData;
7
+ use dpp::platform_value::string_encoding::Encoding::Hex;
8
+ use js_sys::Boolean;
9
+ use pshenmic_dpp_enums::keys::key_type::KeyTypeWASM;
10
+ use pshenmic_dpp_enums::keys::purpose::PurposeWASM;
11
+ use pshenmic_dpp_enums::keys::security_level::SecurityLevelWASM;
12
+ use wasm_bindgen::prelude::wasm_bindgen;
13
+
14
+ #[wasm_bindgen(js_name = IdentityPublicKeyWASM)]
15
+ pub struct IdentityPublicKeyWASM {
16
+ public_key: IdentityPublicKey,
17
+ }
18
+
19
+ #[wasm_bindgen]
20
+ impl IdentityPublicKeyWASM {
21
+ #[wasm_bindgen]
22
+ pub fn new(
23
+ id: u32,
24
+ purpose: PurposeWASM,
25
+ security_level: SecurityLevelWASM,
26
+ key_type: KeyTypeWASM,
27
+ read_only: Boolean,
28
+ binary_data: &str,
29
+ disabled_at: Option<TimestampMillis>,
30
+ ) -> Self {
31
+ IdentityPublicKeyWASM {
32
+ public_key: IdentityPublicKey::from(IdentityPublicKeyV0 {
33
+ id,
34
+ purpose: Purpose::from(purpose),
35
+ security_level: SecurityLevel::from(security_level),
36
+ contract_bounds: None,
37
+ key_type: KeyType::from(key_type),
38
+ read_only: read_only.as_bool().unwrap(),
39
+ data: BinaryData::from_string(binary_data, Hex).unwrap(),
40
+ disabled_at,
41
+ }),
42
+ }
43
+ }
44
+ }
45
+
46
+ impl IdentityPublicKeyWASM {
47
+ pub fn get_key(&self) -> IdentityPublicKey {
48
+ self.public_key.clone()
49
+ }
50
+ }
51
+
52
+ #[wasm_bindgen]
53
+ impl IdentityPublicKeyWASM {
54
+ #[wasm_bindgen(js_name = getKeyId)]
55
+ pub fn get_key_id(&self) -> u32 {
56
+ self.public_key.id()
57
+ }
58
+
59
+ #[wasm_bindgen(js_name = getPurpose)]
60
+ pub fn get_purpose(&self) -> PurposeWASM {
61
+ PurposeWASM::from(self.public_key.purpose())
62
+ }
63
+
64
+ #[wasm_bindgen(js_name = getSecurityLevel)]
65
+ pub fn get_security_level(&self) -> SecurityLevelWASM {
66
+ SecurityLevelWASM::from(self.public_key.security_level())
67
+ }
68
+
69
+ #[wasm_bindgen(js_name = getKeyType)]
70
+ pub fn get_key_type(&self) -> KeyTypeWASM {
71
+ KeyTypeWASM::from(self.public_key.key_type())
72
+ }
73
+
74
+ #[wasm_bindgen(js_name = getReadOnly)]
75
+ pub fn get_read_only(&self) -> bool {
76
+ self.public_key.read_only()
77
+ }
78
+
79
+ #[wasm_bindgen(js_name = getData)]
80
+ pub fn get_data(&self) -> String {
81
+ self.public_key.data().to_string(Hex)
82
+ }
83
+
84
+ #[wasm_bindgen(js_name = getDisabledAt)]
85
+ pub fn get_disabled_at(&self) -> Option<u64> {
86
+ self.public_key.disabled_at()
87
+ }
88
+
89
+ #[wasm_bindgen(js_name = setKeyId)]
90
+ pub fn set_key_id(&mut self, key_id: u32) {
91
+ self.public_key.set_id(key_id)
92
+ }
93
+
94
+ #[wasm_bindgen(js_name = setPurpose)]
95
+ pub fn set_purpose(&mut self, purpose: PurposeWASM) {
96
+ self.public_key.set_purpose(Purpose::from(purpose))
97
+ }
98
+
99
+ #[wasm_bindgen(js_name = setSecurityLevel)]
100
+ pub fn set_security_level(&mut self, security_level: SecurityLevelWASM) {
101
+ self.public_key
102
+ .set_security_level(SecurityLevel::from(security_level))
103
+ }
104
+
105
+ #[wasm_bindgen(js_name = setKeyType)]
106
+ pub fn set_key_type(&mut self, key_type: KeyTypeWASM) {
107
+ self.public_key.set_key_type(KeyType::from(key_type))
108
+ }
109
+
110
+ #[wasm_bindgen(js_name = setReadOnly)]
111
+ pub fn set_read_only(&mut self, read_only: Boolean) {
112
+ self.public_key.set_read_only(read_only.as_bool().unwrap())
113
+ }
114
+
115
+ #[wasm_bindgen(js_name = setData)]
116
+ pub fn set_data(&mut self, binary_data: &str) {
117
+ let data = BinaryData::from_string(binary_data, Hex).unwrap();
118
+ self.public_key.set_data(data)
119
+ }
120
+
121
+ #[wasm_bindgen(js_name = setDisabledAt)]
122
+ pub fn set_disabled_at(&mut self, disabled_at: u64) {
123
+ self.public_key.set_disabled_at(disabled_at)
124
+ }
125
+ }
@@ -0,0 +1,20 @@
1
+ [package]
2
+ name = "pshenmic_dpp_utils"
3
+ version = "0.1.0"
4
+ edition = "2024"
5
+
6
+ [lib]
7
+ crate-type = ["cdylib", "lib"]
8
+
9
+ [dependencies]
10
+ wasm-bindgen = { version = "=0.2.100", features = ["serde-serialize"] }
11
+ anyhow = { version = "1.0.75" }
12
+ dpp = { git = "https://github.com/dashpay/platform", branch = "master", features = [
13
+ "platform-value",
14
+ "document-json-conversion"
15
+ ]}
16
+ js-sys = "0.3.53"
17
+ serde_json = { version = "1.0", features = ["preserve_order"] }
18
+ serde-wasm-bindgen = { git = "https://github.com/QuantumExplorer/serde-wasm-bindgen", branch = "feat/not_human_readable" }
19
+ serde = { version = "1.0.197", features = ["derive"] }
20
+ itertools = { version = "0.13" }
@@ -0,0 +1,29 @@
1
+ use js_sys::ArrayBuffer;
2
+ use wasm_bindgen::prelude::*;
3
+
4
+ #[wasm_bindgen]
5
+ extern "C" {
6
+ #[derive(PartialEq, Debug)]
7
+ pub type Buffer;
8
+
9
+ #[wasm_bindgen(constructor)]
10
+ pub fn new() -> Buffer;
11
+
12
+ #[wasm_bindgen(static_method_of = Buffer, js_name = from)]
13
+ pub fn from_bytes(js_sys: &[u8]) -> Buffer;
14
+
15
+ #[wasm_bindgen(static_method_of = Buffer, js_name = from)]
16
+ pub fn from_bytes_owned(js_sys: Vec<u8>) -> Buffer;
17
+
18
+ #[wasm_bindgen(static_method_of = Buffer, js_name = from)]
19
+ pub fn from_string(js_sys: String) -> Buffer;
20
+
21
+ #[wasm_bindgen(method, getter)]
22
+ pub fn buffer(this: &Buffer) -> ArrayBuffer;
23
+
24
+ #[wasm_bindgen(method, getter, js_name = byteOffset)]
25
+ pub fn byte_offset(this: &Buffer) -> u32;
26
+
27
+ #[wasm_bindgen(method, getter)]
28
+ pub fn length(this: &Buffer) -> u32;
29
+ }
@@ -0,0 +1,351 @@
1
+ mod buffer;
2
+
3
+ use anyhow::{Context, anyhow, bail};
4
+ use dpp::ProtocolError;
5
+ use dpp::identifier::Identifier;
6
+ use dpp::platform_value::Value;
7
+ use dpp::platform_value::string_encoding::Encoding;
8
+ use dpp::util::hash::hash_double_to_vec;
9
+ use itertools::Itertools;
10
+ use js_sys::Function;
11
+ use serde::de::DeserializeOwned;
12
+ use serde_json::Value as JsonValue;
13
+ use std::collections::BTreeMap;
14
+ use std::convert::TryInto;
15
+ use wasm_bindgen::JsValue;
16
+ use wasm_bindgen::{convert::RefFromWasmAbi, prelude::*};
17
+
18
+ pub trait ToSerdeJSONExt {
19
+ fn with_serde_to_json_value(&self) -> Result<JsonValue, JsValue>;
20
+ fn with_serde_to_platform_value(&self) -> Result<Value, JsValue>;
21
+ /// Converts the `JsValue` into `platform::Value`. It's an expensive conversion,
22
+ /// as `JsValue` must be stringified first
23
+ fn with_serde_to_platform_value_map(&self) -> Result<BTreeMap<String, Value>, JsValue>;
24
+ fn with_serde_into<D: DeserializeOwned>(&self) -> Result<D, JsValue>
25
+ where
26
+ D: for<'de> serde::de::Deserialize<'de> + 'static;
27
+ }
28
+
29
+ impl ToSerdeJSONExt for JsValue {
30
+ /// Converts the `JsValue` into `serde_json::Value`. It's an expensive conversion,
31
+ /// as `JsValue` must be stringified first
32
+ fn with_serde_to_json_value(&self) -> Result<JsonValue, JsValue> {
33
+ with_serde_to_json_value(self.clone())
34
+ }
35
+
36
+ /// Converts the `JsValue` into `platform::Value`. It's an expensive conversion,
37
+ /// as `JsValue` must be stringified first
38
+ fn with_serde_to_platform_value(&self) -> Result<Value, JsValue> {
39
+ with_serde_to_platform_value(self)
40
+ }
41
+
42
+ /// Converts the `JsValue` into `platform::Value`. It's an expensive conversion,
43
+ /// as `JsValue` must be stringified first
44
+ fn with_serde_to_platform_value_map(&self) -> Result<BTreeMap<String, Value>, JsValue> {
45
+ self.with_serde_to_platform_value()?
46
+ .into_btree_string_map()
47
+ .map_err(ProtocolError::ValueError)
48
+ .with_js_error()
49
+ }
50
+
51
+ /// converts the `JsValue` into any type that is supported by serde. It's an expensive conversion
52
+ /// as the `jsValue` must be stringified first
53
+ fn with_serde_into<D>(&self) -> Result<D, JsValue>
54
+ where
55
+ D: for<'de> serde::de::Deserialize<'de> + 'static,
56
+ {
57
+ with_serde_into(self)
58
+ }
59
+ }
60
+
61
+ pub fn to_vec_js<T>(iter: impl IntoIterator<Item = T>) -> Vec<JsValue>
62
+ where
63
+ T: Into<JsValue>,
64
+ {
65
+ iter.into_iter().map(|v| v.into()).collect()
66
+ }
67
+
68
+ #[allow(dead_code)]
69
+ #[deprecated(note = "This function is marked as unused.")]
70
+ #[allow(deprecated)]
71
+ pub fn to_vec_of_serde_values(
72
+ values: impl IntoIterator<Item = impl AsRef<JsValue>>,
73
+ ) -> Result<Vec<JsonValue>, JsValue> {
74
+ values
75
+ .into_iter()
76
+ .map(|v| v.as_ref().with_serde_to_json_value())
77
+ .collect()
78
+ }
79
+
80
+ pub fn to_vec_of_platform_values(
81
+ values: impl IntoIterator<Item = impl AsRef<JsValue>>,
82
+ ) -> Result<Vec<Value>, JsValue> {
83
+ values
84
+ .into_iter()
85
+ .map(|v| v.as_ref().with_serde_to_platform_value())
86
+ .collect()
87
+ }
88
+
89
+ pub fn into_vec_of<T>(iter: &[JsValue]) -> Vec<T>
90
+ where
91
+ T: for<'de> serde::de::Deserialize<'de>,
92
+ {
93
+ iter.iter()
94
+ .map(|v| serde_wasm_bindgen::from_value(v.clone()).expect("data malformed"))
95
+ .collect()
96
+ }
97
+
98
+ pub fn with_serde_to_json_value(data: JsValue) -> Result<JsonValue, JsValue> {
99
+ let data = stringify(&data)?;
100
+ let value: JsonValue = serde_json::from_str(&data)
101
+ .with_context(|| format!("cant convert {data:#?} to serde json value"))
102
+ .map_err(|e| format!("{e:#}"))?;
103
+ Ok(value)
104
+ }
105
+
106
+ pub fn with_serde_to_platform_value(data: &JsValue) -> Result<Value, JsValue> {
107
+ Ok(with_serde_to_json_value(data.clone())?.into())
108
+ }
109
+
110
+ pub fn with_serde_into<D>(data: &JsValue) -> Result<D, JsValue>
111
+ where
112
+ D: for<'de> serde::de::Deserialize<'de> + 'static,
113
+ {
114
+ let data = stringify(data)?;
115
+ let value: D = serde_json::from_str(&data)
116
+ .with_context(|| format!("cant convert {:#?} to serde json value", data))
117
+ .map_err(|e| format!("{:#}", e))?;
118
+ Ok(value)
119
+ }
120
+
121
+ pub fn stringify(data: &JsValue) -> Result<String, JsValue> {
122
+ let replacer_func = Function::new_with_args(
123
+ "key, value",
124
+ "return (value != undefined && value.type=='Buffer') ? value.data : value ",
125
+ );
126
+
127
+ let data_string: String =
128
+ js_sys::JSON::stringify_with_replacer(data, &JsValue::from(replacer_func))?.into();
129
+
130
+ Ok(data_string)
131
+ }
132
+
133
+ pub trait WithJsError<T> {
134
+ /// Converts the error into JsValue
135
+ fn with_js_error(self) -> Result<T, JsValue>;
136
+ }
137
+
138
+ impl<T> WithJsError<T> for Result<T, anyhow::Error> {
139
+ fn with_js_error(self) -> Result<T, JsValue> {
140
+ match self {
141
+ Ok(ok) => Ok(ok),
142
+ Err(error) => Err(format!("{error:#}").into()),
143
+ }
144
+ }
145
+ }
146
+
147
+ impl<T> WithJsError<T> for Result<T, ProtocolError> {
148
+ fn with_js_error(self) -> Result<T, JsValue> {
149
+ match self {
150
+ Ok(ok) => Ok(ok),
151
+ Err(error) => Err(JsValue::from_str(&error.to_string())),
152
+ }
153
+ }
154
+ }
155
+
156
+ pub trait IntoWasm {
157
+ fn to_wasm<T: RefFromWasmAbi<Abi = u32>>(&self, class_name: &str)
158
+ -> Result<T::Anchor, JsValue>;
159
+ }
160
+
161
+ impl IntoWasm for JsValue {
162
+ fn to_wasm<T: RefFromWasmAbi<Abi = u32>>(
163
+ &self,
164
+ class_name: &str,
165
+ ) -> Result<T::Anchor, JsValue> {
166
+ generic_of_js_val::<T>(self, class_name)
167
+ }
168
+ }
169
+
170
+ pub fn generic_of_js_val<T: RefFromWasmAbi<Abi = u32>>(
171
+ js_value: &JsValue,
172
+ class_name: &str,
173
+ ) -> Result<T::Anchor, JsValue> {
174
+ if !js_value.is_object() {
175
+ return Err(JsError::new(
176
+ format!("Value supplied as {} is not an object", class_name).as_str(),
177
+ )
178
+ .into());
179
+ }
180
+
181
+ let ctor_name = js_sys::Object::get_prototype_of(js_value)
182
+ .constructor()
183
+ .name();
184
+
185
+ if ctor_name == class_name {
186
+ let ptr = js_sys::Reflect::get(js_value, &JsValue::from_str("__wbg_ptr"))?;
187
+ let ptr_u32: u32 = ptr
188
+ .as_f64()
189
+ .ok_or_else(|| JsValue::from(JsError::new("Invalid JS object pointer")))?
190
+ as u32;
191
+ let reference = unsafe { T::ref_from_abi(ptr_u32) };
192
+ Ok(reference)
193
+ } else {
194
+ let error_string = format!(
195
+ "JS object constructor name mismatch. Expected {}, provided {}.",
196
+ class_name, ctor_name
197
+ );
198
+ Err(JsError::new(&error_string).into())
199
+ }
200
+ }
201
+
202
+ pub const SKIP_VALIDATION_PROPERTY_NAME: &str = "skipValidation";
203
+
204
+ pub fn get_bool_from_options(
205
+ options: JsValue,
206
+ property: &str,
207
+ default: bool,
208
+ ) -> Result<bool, JsValue> {
209
+ if options.is_object() {
210
+ let val2 = options.with_serde_to_json_value()?;
211
+ let kek = val2
212
+ .as_object()
213
+ .ok_or_else(|| JsError::new("Can't parse options"))?;
214
+ let kek2 = kek
215
+ .get(property)
216
+ .ok_or_else(|| JsError::new(&format!("Can't get property {} of options", property)))?;
217
+ Ok(kek2
218
+ .as_bool()
219
+ .ok_or_else(|| JsError::new(&format!("Option {} is not a boolean", property)))?)
220
+ } else {
221
+ Ok(default)
222
+ }
223
+ }
224
+
225
+ #[allow(dead_code)]
226
+ #[deprecated(note = "This function is marked as unused.")]
227
+ #[allow(deprecated)]
228
+ pub fn get_class_name(value: &JsValue) -> String {
229
+ js_sys::Object::get_prototype_of(value)
230
+ .constructor()
231
+ .name()
232
+ .into()
233
+ }
234
+
235
+ #[allow(dead_code)]
236
+ #[deprecated(note = "This function is marked as unused.")]
237
+ #[allow(deprecated)]
238
+ pub fn try_to_u64(value: JsValue) -> Result<u64, anyhow::Error> {
239
+ if value.is_bigint() {
240
+ js_sys::BigInt::new(&value)
241
+ .map_err(|e| anyhow!("unable to create bigInt: {}", e.to_string()))?
242
+ .try_into()
243
+ .map_err(|e| anyhow!("conversion of BigInt to u64 failed: {:#}", e))
244
+ } else if value.as_f64().is_some() {
245
+ let number = js_sys::Number::from(value);
246
+ convert_number_to_u64(number)
247
+ } else {
248
+ bail!("supported types are Number or BigInt")
249
+ }
250
+ }
251
+
252
+ pub fn convert_number_to_u64(js_number: js_sys::Number) -> Result<u64, anyhow::Error> {
253
+ if let Some(float_number) = js_number.as_f64() {
254
+ if float_number.is_nan() || float_number.is_infinite() {
255
+ bail!("received an invalid timestamp: the number is either NaN or Inf")
256
+ }
257
+ if float_number < 0. {
258
+ bail!("received an invalid timestamp: the number is negative");
259
+ }
260
+ if float_number.fract() != 0. {
261
+ bail!("received an invalid timestamp: the number is fractional")
262
+ }
263
+ if float_number > u64::MAX as f64 {
264
+ bail!("received an invalid timestamp: the number is > u64::max")
265
+ }
266
+
267
+ return Ok(float_number as u64);
268
+ }
269
+ bail!("the value is not a number")
270
+ }
271
+
272
+ pub fn generate_document_id_v0(
273
+ contract_id: &Identifier,
274
+ owner_id: &Identifier,
275
+ document_type_name: &str,
276
+ entropy: &[u8],
277
+ ) -> Identifier {
278
+ let mut buf: Vec<u8> = vec![];
279
+
280
+ buf.extend_from_slice(&contract_id.to_buffer());
281
+ buf.extend_from_slice(&owner_id.to_buffer());
282
+ buf.extend_from_slice(document_type_name.as_bytes());
283
+ buf.extend_from_slice(entropy);
284
+
285
+ Identifier::from_bytes(&hash_double_to_vec(&buf)).unwrap()
286
+ }
287
+
288
+ #[wasm_bindgen(raw_module = "../identifier_utils/Identifier.js")]
289
+ extern "C" {
290
+ #[derive(Debug, Clone)]
291
+ #[wasm_bindgen(js_name = default)]
292
+ pub type IdentifierWrapper; // Rename to IdentifierJS?
293
+
294
+ #[wasm_bindgen(constructor, js_class=default)]
295
+ pub fn new(buffer: JsValue) -> IdentifierWrapper;
296
+
297
+ #[wasm_bindgen(method, js_name=toBuffer)]
298
+ pub fn to_buffer(this: &IdentifierWrapper) -> Vec<u8>;
299
+ }
300
+
301
+ impl From<Identifier> for IdentifierWrapper {
302
+ fn from(s: Identifier) -> Self {
303
+ IdentifierWrapper::new(buffer::Buffer::from_bytes(s.as_slice()).into())
304
+ }
305
+ }
306
+
307
+ impl From<IdentifierWrapper> for Identifier {
308
+ fn from(s: IdentifierWrapper) -> Self {
309
+ Identifier::from_bytes(&s.to_buffer()).unwrap()
310
+ }
311
+ }
312
+
313
+ impl From<&IdentifierWrapper> for Identifier {
314
+ fn from(s: &IdentifierWrapper) -> Self {
315
+ Identifier::from_bytes(&s.to_buffer()).unwrap()
316
+ }
317
+ }
318
+
319
+ // Try to extract Identifier from **stringified** identifier_utils.
320
+ // The `js_value` can be a stringified instance of: `Identifier`, `Buffer` or `Array`
321
+ pub fn identifier_from_js_value(js_value: &JsValue) -> Result<Identifier, JsValue> {
322
+ if js_value.is_undefined() || js_value.is_null() {
323
+ wasm_bindgen::throw_val(JsValue::from_str(
324
+ "the identifier cannot be null or undefined",
325
+ ));
326
+ }
327
+
328
+ let value: serde_json::Value = js_value.with_serde_to_json_value()?;
329
+ match value {
330
+ serde_json::Value::Array(arr) => {
331
+ let bytes: Vec<u8> = arr.into_iter().map(value_to_u8).try_collect()?;
332
+ Identifier::from_bytes(&bytes)
333
+ .map_err(ProtocolError::ValueError)
334
+ .with_js_error()
335
+ }
336
+ serde_json::Value::String(string) => Identifier::from_string(&string, Encoding::Base58)
337
+ .map_err(ProtocolError::ValueError)
338
+ .with_js_error(),
339
+ _ => Err(JsValue::from_str("Invalid ID. Expected array or string")),
340
+ }
341
+ }
342
+
343
+ pub fn value_to_u8(v: serde_json::Value) -> Result<u8, JsValue> {
344
+ let number = v
345
+ .as_u64()
346
+ .ok_or_else(|| format!("failed converting {} into u64", v))?;
347
+ if number > u8::MAX as u64 {
348
+ JsValue::from_str("the integer in the array isn't a byte");
349
+ }
350
+ Ok(number as u8)
351
+ }
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env bash
2
+
3
+ ## Paths to distributive that exposed to library consumers
4
+ DIST_DIR="$PWD/dist"
5
+ DIST_WASM_DIR="$DIST_DIR/wasm"
6
+ DIST_WASM_BINARY_BASE_64="$DIST_WASM_DIR/pshenmic_dpp_bg.js"
7
+ DIST_WASM_BINARY_RAW="$DIST_WASM_DIR/pshenmic_dpp_bg.wasm"
8
+ DIST_WASM_JS="$DIST_WASM_DIR/pshenmic_dpp.js"
9
+
10
+ ## Paths to wasm files produced by wasm-bindgen
11
+ WASM_DIR="$PWD/wasm"
12
+ WASM_JS_CODE_PATH="$WASM_DIR/pshenmic_dpp.js"
13
+ WASM_BINARY_PATH="$WASM_DIR/pshenmic_dpp_bg.wasm"
14
+
15
+ # Create directory in dist to save transpiled wasm code and TS typings
16
+ mkdir -p $DIST_WASM_DIR
17
+
18
+ ## Converting wasm into base64 and saving it to dist folder
19
+
20
+ rm -rf $DIST_WASM_BINARY_BASE_64
21
+ rm -rf $DIST_WASM_BINARY_RAW
22
+ rm -rf $DIST_WASM_JS
23
+
24
+ if [[ "${RAW}" == "true" ]]; then
25
+ cp $WASM_BINARY_PATH $DIST_WASM_BINARY_RAW
26
+ else
27
+ echo "Converting wasm binary into base64 module"
28
+ WASM_BUILD_BASE_64=$(base64 -i "$WASM_BINARY_PATH")
29
+ echo 'module.exports = "'${WASM_BUILD_BASE_64}'"' > "$DIST_WASM_BINARY_BASE_64"
30
+ fi
31
+
32
+ ## Transpile ES Modules code to Common JS
33
+ ## and save directly to dist folder to avoid re-generating TS declarations
34
+ echo "Transpiling wasm ES Modules to CommonJS"
35
+ cp $WASM_JS_CODE_PATH $DIST_WASM_JS
36
+
37
+ echo "Cleaning wasm build"
38
+ rm -rf $WASM_DIR
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env bash
2
+ # shellcheck disable=SC2312
3
+
4
+ TARGET=wasm32-unknown-unknown
5
+
6
+ OUTPUT_DIR="${PWD}/wasm"
7
+ CARGO_BUILD_PROFILE="${CARGO_BUILD_PROFILE:-dev}"
8
+ PROFILE_ARG="--profile ${CARGO_BUILD_PROFILE}"
9
+ PROFILE=debug
10
+
11
+ OUTPUT_FILE="${PWD}/wasm/pshenmic_dpp_bg.wasm"
12
+
13
+ BUILD_COMMAND="cargo build --config net.git-fetch-with-cli=true --target=${TARGET} ${PROFILE_ARG}"
14
+ BINDGEN_COMMAND="wasm-bindgen --out-dir=${OUTPUT_DIR} --target=web --omit-default-module-path ${PWD}/target/${TARGET}/${PROFILE}/pshenmic_dpp.wasm"
15
+
16
+ if ! [[ -d ${OUTPUT_DIR} ]]; then
17
+ mkdir -p "${OUTPUT_DIR}"
18
+ fi
19
+
20
+ if [[ "${OSTYPE}" == "darwin"* ]]; then
21
+ AR_PATH=$(command -v llvm-ar)
22
+ CLANG_PATH=$(command -v clang)
23
+ AR=${AR_PATH} CC=${CLANG_PATH} ${BUILD_COMMAND}
24
+ AR=${AR_PATH} CC=${CLANG_PATH} ${BINDGEN_COMMAND}
25
+ else
26
+ ${BUILD_COMMAND}
27
+ ${BINDGEN_COMMAND}
28
+ fi
29
+
30
+ if command -v wasm-opt &> /dev/null; then
31
+ echo "Optimizing wasm using Binaryen"
32
+ wasm-opt -tnh --flatten --rereloop -Oz --gufa -Oz --gufa -Oz "$OUTPUT_FILE" -o "${OUTPUT_FILE}"
33
+ else
34
+ echo "wasm-opt command not found. Skipping wasm optimization."
35
+ fi
package/src/lib.rs ADDED
@@ -0,0 +1,2 @@
1
+ pub use pshenmic_dpp_document_batch::DocumentBatchWASM;
2
+ pub use pshenmic_dpp_document_search;
package/tsconfig.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "compilerOptions": {
3
+ "outDir": "./dist",
4
+ "noImplicitAny": true,
5
+ "module": "commonjs",
6
+ "target": "es2015",
7
+ "rootDir": "./lib",
8
+ "allowJs": false,
9
+ "moduleResolution": "node",
10
+ "esModuleInterop": true,
11
+ "declaration": true,
12
+ "lib": [
13
+ "es2015",
14
+ "dom"
15
+ ]
16
+ },
17
+ "include": ["lib/**/*.ts"],
18
+ }