From c880537353154b25fd2467c979d2925c1e2f9cb1 Mon Sep 17 00:00:00 2001
From: Trevor Arjeski <trevor.arjeski@crypto.com>
Date: Fri, 26 Aug 2022 15:08:11 +0300
Subject: [PATCH] Fix dependency issues

1. Reorganize dependencies and remove requirements ("=") on wasm-bindgen
   and js-sys, due to conflicts that can occur when using this crate.
2. Replace wasm-bindgen's "serde-serialize" feature with
   serde-wasm-bindgen due to cyclical dependency issue.

Relates to:
https://github.com/tkaitchuck/aHash/issues/95
https://github.com/rustwasm/wasm-bindgen/pull/3031
---
 rust/Cargo.lock   | 18 +++++++++++---
 rust/Cargo.toml   |  8 +++---
 rust/src/utils.rs | 62 ++++++++++++++++++++---------------------------
 3 files changed, 45 insertions(+), 43 deletions(-)

diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index ed3fd470..f61f7368 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -76,6 +76,7 @@ dependencies = [
  "rand_os",
  "schemars",
  "serde",
+ "serde-wasm-bindgen",
  "serde_json",
  "sha2",
  "wasm-bindgen",
@@ -238,9 +239,9 @@ checksum = "dc6f3ad7b9d11a0c00842ff8de1b60ee58661048eb8049ed33c73594f359d7e6"
 
 [[package]]
 name = "js-sys"
-version = "0.3.51"
+version = "0.3.55"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "83bdfbace3a0e81a4253f73b49e960b053e396a11012cbd49b9b74d6a2b67062"
+checksum = "7cc9ffccd38c451a86bf13657df244e9c3f37493cce8e5e21e940963777acc84"
 dependencies = [
  "wasm-bindgen",
 ]
@@ -554,6 +555,17 @@ dependencies = [
  "serde_derive",
 ]
 
+[[package]]
+name = "serde-wasm-bindgen"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1cfc62771e7b829b517cb213419236475f434fb480eddd76112ae182d274434a"
+dependencies = [
+ "js-sys",
+ "serde",
+ "wasm-bindgen",
+]
+
 [[package]]
 name = "serde_derive"
 version = "1.0.117"
@@ -657,8 +669,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "632f73e236b219150ea279196e54e610f5dbafa5d61786303d4da54f84e47fce"
 dependencies = [
  "cfg-if 1.0.0",
- "serde",
- "serde_json",
  "wasm-bindgen-macro",
 ]
 
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 4690998d..f3b8bb36 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -32,7 +32,6 @@ num-integer = "0.1.45"
 # feature or this one
 clear_on_drop = { version = "0.2", features = ["no_cc"] }
 itertools = "0.10.1"
-getrandom = { version = "0.2.3", features = ["js"] }
 rand = "0.8.4"
 schemars = "0.8.8"
 serde = { version = "1.0", features = ["derive"] }
@@ -41,12 +40,15 @@ serde = { version = "1.0", features = ["derive"] }
 [target.'cfg(not(all(target_arch = "wasm32", not(target_os = "emscripten"))))'.dependencies]
 rand_os = "0.1"
 noop_proc_macro = "0.3.0"
+getrandom = "0.2.3"
 
 # wasm
 [target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies]
-wasm-bindgen = { version = "=0.2.78", features = ["serde-serialize"] }
+serde-wasm-bindgen = "0.4.3"
+wasm-bindgen = "=0.2.78"
 rand_os = { version = "0.1", features = ["wasm-bindgen"] }
-js-sys = "=0.3.51"
+js-sys = "0.3.51"
+getrandom = { version = "0.2.3", features = ["js"] }
 
 [profile.release]
 # Tell `rustc` to optimize for small code size.
diff --git a/rust/src/utils.rs b/rust/src/utils.rs
index 0bc7233e..9d78789f 100644
--- a/rust/src/utils.rs
+++ b/rust/src/utils.rs
@@ -4,6 +4,7 @@ use cbor_event::{
     se::{Serialize, Serializer},
 };
 use hex::FromHex;
+use itertools::Itertools;
 use num_bigint::Sign;
 use serde_json;
 use std::convert::TryFrom;
@@ -13,7 +14,6 @@ use std::{
     io::{BufRead, Seek, Write},
     ops::{Rem, Sub},
 };
-use itertools::Itertools;
 
 use super::*;
 use crate::error::{DeserializeError, DeserializeFailure};
@@ -43,7 +43,7 @@ macro_rules! to_from_json {
 
             #[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))]
             pub fn to_js_value(&self) -> Result<JsValue, JsError> {
-                JsValue::from_serde(&self)
+                serde_wasm_bindgen::to_value(&self)
                     .map_err(|e| JsError::from_str(&format!("to_js_value: {}", e)))
             }
 
@@ -252,7 +252,11 @@ impl BigNum {
     }
 
     pub fn max(a: &BigNum, b: &BigNum) -> BigNum {
-        if a.less_than(b) { b.clone() } else { a.clone() }
+        if a.less_than(b) {
+            b.clone()
+        } else {
+            a.clone()
+        }
     }
 }
 
@@ -1351,47 +1355,36 @@ struct OutputSizeConstants {
 
 // <TODO:REMOVE_AFTER_BABBAGE>
 fn quot<T>(a: T, b: T) -> T
-    where T: Sub<Output=T> + Rem<Output=T> + Div<Output=T> + Copy + Clone + std::fmt::Display {
+where
+    T: Sub<Output = T> + Rem<Output = T> + Div<Output = T> + Copy + Clone + std::fmt::Display,
+{
     (a - (a % b)) / b
 }
 
 // <TODO:REMOVE_AFTER_BABBAGE>
-fn bundle_size(
-    assets: &Value,
-    constants: &OutputSizeConstants,
-) -> usize {
+fn bundle_size(assets: &Value, constants: &OutputSizeConstants) -> usize {
     // based on https://github.com/input-output-hk/cardano-ledger-specs/blob/master/doc/explanations/min-utxo-alonzo.rst
     match &assets.multiasset {
         None => 2, // coinSize according the minimum value function
-        Some (assets) => {
-            let num_assets = assets.0
-                .values()
-                .fold(
-                    0,
-                    | acc, next| acc + next.len()
-                );
-            let sum_asset_name_lengths = assets.0
+        Some(assets) => {
+            let num_assets = assets.0.values().fold(0, |acc, next| acc + next.len());
+            let sum_asset_name_lengths = assets
+                .0
                 .values()
                 .flat_map(|assets| assets.0.keys())
                 .unique_by(|asset| asset.name())
-                .fold(
-                    0,
-                    | acc, next| acc + next.0.len()
-                );
-            let sum_policy_id_lengths = assets.0
-                .keys()
-                .fold(
-                    0,
-                    | acc, next| acc + next.0.len()
-                );
+                .fold(0, |acc, next| acc + next.0.len());
+            let sum_policy_id_lengths = assets.0.keys().fold(0, |acc, next| acc + next.0.len());
             // converts bytes to 8-byte long words, rounding up
             fn roundup_bytes_to_words(b: usize) -> usize {
                 quot(b + 7, 8)
             }
-            constants.k0 + roundup_bytes_to_words(
-                (num_assets * constants.k1) + sum_asset_name_lengths +
-                    (constants.k2 * sum_policy_id_lengths)
-            )
+            constants.k0
+                + roundup_bytes_to_words(
+                    (num_assets * constants.k1)
+                        + sum_asset_name_lengths
+                        + (constants.k2 * sum_policy_id_lengths),
+                )
         }
     }
 }
@@ -1399,7 +1392,7 @@ fn bundle_size(
 // <TODO:REMOVE_AFTER_BABBAGE>
 fn _min_ada_required_legacy(
     assets: &Value,
-    has_data_hash: bool, // whether the output includes a data hash
+    has_data_hash: bool,          // whether the output includes a data hash
     coins_per_utxo_word: &BigNum, // protocol parameter (in lovelace)
 ) -> Result<BigNum, JsError> {
     // based on https://github.com/input-output-hk/cardano-ledger-specs/blob/master/doc/explanations/min-utxo-alonzo.rst
@@ -1472,11 +1465,8 @@ impl MinOutputAdaCalculator {
             coins_per_word: &Coin,
         ) -> Result<Coin, JsError> {
             // <TODO:REMOVE_AFTER_BABBAGE>
-            let legacy_coin = _min_ada_required_legacy(
-                &output.amount(),
-                output.has_data_hash(),
-                coins_per_word,
-            )?;
+            let legacy_coin =
+                _min_ada_required_legacy(&output.amount(), output.has_data_hash(), coins_per_word)?;
             //according to https://hydra.iohk.io/build/15339994/download/1/babbage-changes.pdf
             //See on the page 9 getValue txout
             let result = BigNum::from(output.to_bytes().len())