diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 3e7b7ce4..e332071d 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -42,6 +42,16 @@ jobs: - name: rust:build-browser run: | npm run rust:build-browser + - name: cargo-fmt + uses: actions-rs/cargo@v1 + with: + command: fmt + args: --all -- --check + - name: cargo-clippy + uses: actions-rs/cargo@v1 + with: + command: clippy + args: --workspace --all-features --all-targets -- --deny "clippy::all" - name: all:test run: cargo test - name: chain:install diff --git a/chain/rust/src/address.rs b/chain/rust/src/address.rs index 59d5f7dd..017857af 100644 --- a/chain/rust/src/address.rs +++ b/chain/rust/src/address.rs @@ -318,15 +318,12 @@ impl Address { data: &[u8], addr_size: usize, ) -> Result>, DeserializeFailure> { - if data.len() < addr_size { - Err(DeserializeFailure::CBOR(cbor_event::Error::NotEnough( - data.len(), - addr_size, - ))) - } else if data.len() > addr_size { - Ok(Some(data[addr_size..].to_vec())) - } else { - Ok(None) + match data.len().cmp(&addr_size) { + std::cmp::Ordering::Less => Err(DeserializeFailure::CBOR( + cbor_event::Error::NotEnough(data.len(), addr_size), + )), + std::cmp::Ordering::Greater => Ok(Some(data[addr_size..].to_vec())), + std::cmp::Ordering::Equal => Ok(None), } } match (header & 0xF0) >> 4 { @@ -1433,7 +1430,7 @@ mod tests { 255, 255, 255, 255, 255, 255, 255, 255, 127, 129, 255, 255, 255, 255, 255, 255, 255, 255, 127, 129, 255, 255, 255, 255, 255, 255, 255, 255, 127, ]; - let addr = Address::from_raw_bytes(&addr_bytes.clone()).unwrap(); + let addr = Address::from_raw_bytes(&addr_bytes).unwrap(); assert_eq!(addr_bytes, addr.to_raw_bytes()); } } diff --git a/chain/rust/src/auxdata/utils.rs b/chain/rust/src/auxdata/utils.rs index 55b7e1c9..b2306ec1 100644 --- a/chain/rust/src/auxdata/utils.rs +++ b/chain/rust/src/auxdata/utils.rs @@ -193,3 +193,9 @@ impl AuxiliaryData { } } } + +impl Default for AuxiliaryData { + fn default() -> Self { + Self::new() + } +} diff --git a/chain/rust/src/block/mod.rs b/chain/rust/src/block/mod.rs index 248b8925..731cd908 100644 --- a/chain/rust/src/block/mod.rs +++ b/chain/rust/src/block/mod.rs @@ -82,6 +82,7 @@ pub struct HeaderBody { } impl HeaderBody { + #[allow(clippy::too_many_arguments)] pub fn new( block_number: u64, slot: u64, diff --git a/chain/rust/src/builders/input_builder.rs b/chain/rust/src/builders/input_builder.rs index ace6cbfa..88fb3bc9 100644 --- a/chain/rust/src/builders/input_builder.rs +++ b/chain/rust/src/builders/input_builder.rs @@ -14,9 +14,9 @@ use crate::{ #[derive(Debug, thiserror::Error)] pub enum InputBuilderError { #[error("UTXO address was not a payment key: {0:?}")] - UTXOAddressNotPayment(Address), + UTXOAddressNotPayment(Box
), #[error("Missing the following witnesses for the input: {0:?}")] - MissingWitnesses(RequiredWitnessSet), + MissingWitnesses(Box), } pub fn input_required_wits( @@ -71,9 +71,9 @@ impl SingleInputBuilder { let required_wits_left = required_wits.clone(); if !required_wits_left.scripts.is_empty() { - return Err(InputBuilderError::UTXOAddressNotPayment( + return Err(InputBuilderError::UTXOAddressNotPayment(Box::new( self.utxo_info.address().clone(), - )); + ))); } Ok(InputBuilderResult { @@ -99,7 +99,9 @@ impl SingleInputBuilder { required_wits_left.scripts.remove(script_hash); if !required_wits_left.scripts.is_empty() { - return Err(InputBuilderError::MissingWitnesses(required_wits_left)); + return Err(InputBuilderError::MissingWitnesses(Box::new( + required_wits_left, + ))); } Ok(InputBuilderResult { @@ -138,7 +140,9 @@ impl SingleInputBuilder { .remove(&hash_plutus_data(&datum)); if required_wits_left.len() > 0 { - return Err(InputBuilderError::MissingWitnesses(required_wits_left)); + return Err(InputBuilderError::MissingWitnesses(Box::new( + required_wits_left, + ))); } Ok(InputBuilderResult { diff --git a/chain/rust/src/builders/redeemer_builder.rs b/chain/rust/src/builders/redeemer_builder.rs index 4db3236b..b76cc56b 100644 --- a/chain/rust/src/builders/redeemer_builder.rs +++ b/chain/rust/src/builders/redeemer_builder.rs @@ -129,7 +129,7 @@ impl RedeemerSetBuilder { ))); } RedeemerTag::Cert => { - let entry = self.cert.iter_mut().nth(key.index as usize).unwrap(); + let entry = self.cert.get_mut(key.index as usize).unwrap(); *entry = Some(UntaggedRedeemerPlaceholder::Full(UntaggedRedeemer::new( entry.as_ref().unwrap().data().clone(), ex_units, @@ -359,8 +359,8 @@ mod tests { let input_result = InputBuilderResult { input: TransactionInput::new(TransactionHash::from([0; 32]), 0), - utxo_info: ShelleyTxOut::new(address.clone(), Value::zero()).into(), - aggregate_witness: Some(data.clone()), + utxo_info: ShelleyTxOut::new(address, Value::zero()).into(), + aggregate_witness: Some(data), required_wits: RequiredWitnessSet::new(), }; diff --git a/chain/rust/src/builders/tx_builder.rs b/chain/rust/src/builders/tx_builder.rs index f25cadcd..1a32dd19 100644 --- a/chain/rust/src/builders/tx_builder.rs +++ b/chain/rust/src/builders/tx_builder.rs @@ -1829,7 +1829,9 @@ mod tests { use std::collections::BTreeMap; use std::ops::Deref; - use cml_core::metadata::{Metadata, TransactionMetadatum, TransactionMetadatumLabel, MetadatumMap}; + use cml_core::metadata::{ + Metadata, MetadatumMap, TransactionMetadatum, TransactionMetadatumLabel, + }; use cml_core::Int; use cml_crypto::{ Bip32PrivateKey, Bip32PublicKey, DatumHash, Deserialize, PrivateKey, RawBytesEncoding, @@ -1848,7 +1850,7 @@ mod tests { use crate::crypto::utils::make_vkey_witness; use crate::genesis::network_info::{plutus_alonzo_cost_models, NetworkInfo}; use crate::plutus::{PlutusScript, PlutusV1Script, PlutusV2Script, RedeemerTag}; - use crate::transaction::{NativeScript, RequiredSigners}; + use crate::transaction::NativeScript; use crate::{Script, SubCoin}; use super::*; @@ -1882,7 +1884,7 @@ mod tests { } fn fake_key_hash(x: u8) -> Ed25519KeyHash { - Ed25519KeyHash::from_raw_bytes(&vec![ + Ed25519KeyHash::from_raw_bytes(&[ x, 239, 181, 120, 142, 135, 19, 200, 68, 223, 211, 43, 46, 145, 222, 30, 48, 159, 239, 255, 213, 85, 248, 39, 204, 158, 225, 100, ]) @@ -2410,12 +2412,10 @@ mod tests { tx_builder.add_input(input).unwrap(); let input = { - let address = AddressContent::icarus_from_key( - spend, - NetworkInfo::testnet().protocol_magic().into(), - ) - .to_address() - .to_address(); + let address = + AddressContent::icarus_from_key(spend, NetworkInfo::testnet().protocol_magic()) + .to_address() + .to_address(); SingleInputBuilder::new( TransactionInput::new(genesis_id(), 0), TransactionOutput::new(address, Value::from(1_000_000), None, None), @@ -2455,7 +2455,7 @@ mod tests { let addr_net_0 = BaseAddress::new( NetworkInfo::testnet().network_id(), - spend_cred.clone(), + spend_cred, stake_cred.clone(), ) .to_address(); @@ -2473,7 +2473,7 @@ mod tests { tx_builder.add_mint(result).unwrap(); let mut mass = MultiAsset::new(); - mass.set(policy_id, name.clone(), amount); + mass.set(policy_id, name, amount); // One coin and the minted asset goes into the output let mut output_amount = Value::from(264); @@ -2535,7 +2535,7 @@ mod tests { let addr_net_0 = BaseAddress::new( NetworkInfo::testnet().network_id(), - spend_cred.clone(), + spend_cred, stake_cred.clone(), ) .to_address(); @@ -2837,7 +2837,7 @@ mod tests { final_tx.outputs[1] .amount() .multiasset - .get(&policy_id, &name) + .get(policy_id, &name) .unwrap(), ma_input1 + ma_input2 - ma_output1 ); @@ -3063,7 +3063,7 @@ mod tests { // add an input that contains an asset & ADA let output_amount = { let mut output_multiasset = MultiAsset::new(); - output_multiasset.set(policy_id.clone(), name.clone(), 100); + output_multiasset.set(policy_id, name, 100); Value::new(2_000_000, output_multiasset) }; @@ -3246,7 +3246,7 @@ mod tests { AssetName::new(vec![4u8, 5, 6, 7, 8, 9]).unwrap(), ]; - let multiasset = policy_ids.into_iter().zip(names.into_iter()).fold( + let multiasset = policy_ids.iter().zip(names.iter()).fold( MultiAsset::new(), |mut acc, (policy_id, name)| { acc.set(policy_id.clone(), name.clone(), 500); @@ -3516,11 +3516,11 @@ mod tests { let expected_input = input2 .utxo_info .amount() - .checked_add(&input3.utxo_info.amount()) + .checked_add(input3.utxo_info.amount()) .unwrap() - .checked_add(&input5.utxo_info.amount()) + .checked_add(input5.utxo_info.amount()) .unwrap() - .checked_add(&input6.utxo_info.amount()) + .checked_add(input6.utxo_info.amount()) .unwrap(); let expected_change = expected_input.checked_sub(&output_value).unwrap(); assert_eq!(expected_change, *change); @@ -3564,7 +3564,7 @@ mod tests { let mut ma2 = MultiAsset::new(); ma2.set(pid1.clone(), asset_name1.clone(), 20); ma2.set(pid2.clone(), asset_name3.clone(), 4); - let mut input2 = make_input(2u8, Value::new(10, ma2)); + let input2 = make_input(2u8, Value::new(10, ma2)); tx_builder.add_utxo(input2); let mut ma3 = MultiAsset::new(); @@ -3574,13 +3574,13 @@ mod tests { tx_builder.add_utxo(input3); let mut ma4 = MultiAsset::new(); - ma4.set(pid1.clone(), asset_name1.clone(), 10); + ma4.set(pid1.clone(), asset_name1, 10); ma4.set(pid1.clone(), asset_name2.clone(), 10); let input4 = make_input(4u8, Value::new(10, ma4)); tx_builder.add_utxo(input4); let mut ma5 = MultiAsset::new(); - ma5.set(pid1.clone(), asset_name2.clone(), 10); + ma5.set(pid1, asset_name2.clone(), 10); ma5.set(pid2.clone(), asset_name2.clone(), 3); let input5 = make_input(5u8, Value::new(10, ma5)); tx_builder.add_utxo(input5); @@ -3590,12 +3590,12 @@ mod tests { tx_builder.add_utxo(make_input(7u8, Value::from(100))); let mut ma8 = MultiAsset::new(); - ma8.set(pid2.clone(), asset_name2.clone(), 10); + ma8.set(pid2.clone(), asset_name2, 10); let input8 = make_input(8u8, Value::new(10, ma8)); tx_builder.add_utxo(input8); let mut ma9 = MultiAsset::new(); - ma9.set(pid2.clone(), asset_name3.clone(), 10); + ma9.set(pid2, asset_name3, 10); let input9 = make_input(9u8, Value::new(10, ma9)); tx_builder.add_utxo(input9); @@ -4032,17 +4032,15 @@ mod tests { ); let mut witness_set = TransactionWitnessSet::new(); - let mut vkw = Vec::new(); - vkw.push(make_vkey_witness( + witness_set.vkeywitnesses = Some(vec![make_vkey_witness( &hash_transaction(&body), &PrivateKey::from_normal_bytes( &hex::decode("c660e50315d76a53d80732efda7630cae8885dfb85c46378684b3c6103e1284a") .unwrap(), ) .unwrap(), - )); - witness_set.vkeywitnesses = Some(vkw); + )]); let final_tx = Transaction::new(body, witness_set, true, None); let deser_t = Transaction::from_cbor_bytes(&final_tx.to_cbor_bytes()).unwrap(); @@ -4193,9 +4191,7 @@ mod tests { let mut aux = AuxiliaryData::new_shelley(metadata); - let mut nats = Vec::new(); - nats.push(NativeScript::new_script_invalid_before(123)); - aux.add_native_scripts(nats); + aux.add_native_scripts(vec![NativeScript::new_script_invalid_before(123)]); aux } @@ -4237,7 +4233,7 @@ mod tests { let met = aux.metadata().unwrap(); assert_eq!(met.len(), 1); - assert_json_metadatum(&met.get(num).unwrap()); + assert_json_metadatum(met.get(num).unwrap()); } #[test] @@ -4263,7 +4259,7 @@ mod tests { let met = aux.metadata().unwrap(); assert_eq!(met.len(), 1); assert!(met.get(num1).is_none()); - assert_json_metadatum(&met.get(num2).unwrap()); + assert_json_metadatum(met.get(num2).unwrap()); } #[test] @@ -4288,7 +4284,7 @@ mod tests { let met = aux.metadata().unwrap(); assert_eq!(met.len(), 1); - assert_json_metadatum(&met.get(num).unwrap()); + assert_json_metadatum(met.get(num).unwrap()); } #[test] @@ -4309,8 +4305,8 @@ mod tests { let met = aux.metadata().unwrap(); assert_eq!(met.len(), 2); - assert_json_metadatum(&met.get(num1).unwrap()); - assert_json_metadatum(&met.get(num2).unwrap()); + assert_json_metadatum(met.get(num1).unwrap()); + assert_json_metadatum(met.get(num2).unwrap()); } #[test] @@ -4331,7 +4327,7 @@ mod tests { let met = aux.metadata().unwrap(); assert_eq!(met.len(), 1); - assert_json_metadatum(&met.get(num).unwrap()); + assert_json_metadatum(met.get(num).unwrap()); } #[test] @@ -4352,8 +4348,8 @@ mod tests { let met = aux.metadata().unwrap(); assert_eq!(met.len(), 2); - assert_json_metadatum(&met.get(num1).unwrap()); - assert_json_metadatum(&met.get(num2).unwrap()); + assert_json_metadatum(met.get(num1).unwrap()); + assert_json_metadatum(met.get(num2).unwrap()); } #[test] @@ -4394,7 +4390,7 @@ mod tests { let met = aux.metadata().unwrap(); assert_eq!(met.len(), 1); - assert_json_metadatum(&met.get(key).unwrap()); + assert_json_metadatum(met.get(key).unwrap()); } #[test] @@ -4420,7 +4416,7 @@ mod tests { let met = aux.metadata().unwrap(); assert_eq!(met.entries.len(), 2); - assert_json_metadatum(&met.get(key1).unwrap()); + assert_json_metadatum(met.get(key1).unwrap()); assert_eq!(*met.get(key2).unwrap(), val2); } @@ -4442,8 +4438,8 @@ mod tests { let met = aux.metadata().unwrap(); assert_eq!(met.entries.len(), 2); - assert_json_metadatum(&met.get(key1).unwrap()); - assert_json_metadatum(&met.get(key2).unwrap()); + assert_json_metadatum(met.get(key1).unwrap()); + assert_json_metadatum(met.get(key2).unwrap()); } fn create_asset_name() -> AssetName { @@ -4612,12 +4608,8 @@ mod tests { // One input from a related address let input = { let cred = StakeCredential::new_script(policy_id1.clone()); - let address = BaseAddress::new( - NetworkInfo::testnet().network_id(), - cred.clone(), - cred.clone(), - ) - .to_address(); + let address = BaseAddress::new(NetworkInfo::testnet().network_id(), cred.clone(), cred) + .to_address(); let builder = SingleInputBuilder::new( TransactionInput::new(genesis_id(), 0), TransactionOutput::new(address, Value::from(10_000_000), None, None), @@ -5053,9 +5045,10 @@ mod tests { // add input { - let mut required_signers = RequiredSigners::new(); - // real tx was using 5627217786eb781fbfb51911a253f4d250fdbfdcf1198e70d35985a9 instead - required_signers.push(private_key.to_public().hash()); + let required_signers = vec![ + // real tx was using 5627217786eb781fbfb51911a253f4d250fdbfdcf1198e70d35985a9 instead + private_key.to_public().hash(), + ]; let input_utxo = TransactionOutputBuilder::new() .with_address( @@ -5200,9 +5193,10 @@ mod tests { // add input { - let mut required_signers = RequiredSigners::new(); - // real tx was using 5627217786eb781fbfb51911a253f4d250fdbfdcf1198e70d35985a9 instead - required_signers.push(private_key.to_public().hash()); + let required_signers = vec![ + // real tx was using 5627217786eb781fbfb51911a253f4d250fdbfdcf1198e70d35985a9 instead + private_key.to_public().hash(), + ]; let input_utxo = TransactionOutputBuilder::new() .with_address( @@ -5377,9 +5371,10 @@ mod tests { // add input { - let mut required_signers = RequiredSigners::new(); - // real tx was using 5627217786eb781fbfb51911a253f4d250fdbfdcf1198e70d35985a9 instead - required_signers.push(private_key.to_public().hash()); + let required_signers = vec![ + // real tx was using 5627217786eb781fbfb51911a253f4d250fdbfdcf1198e70d35985a9 instead + private_key.to_public().hash(), + ]; let input_utxo = TransactionOutputBuilder::new() .with_address( diff --git a/chain/rust/src/builders/withdrawal_builder.rs b/chain/rust/src/builders/withdrawal_builder.rs index 07c96915..e48f5e4b 100644 --- a/chain/rust/src/builders/withdrawal_builder.rs +++ b/chain/rust/src/builders/withdrawal_builder.rs @@ -8,10 +8,10 @@ use crate::{address::RewardAddress, certs::StakeCredential, transaction::Require #[derive(Debug, thiserror::Error)] pub enum WithdrawalBuilderError { #[error("Missing the following witnesses for the withdrawal: {0:?}. ")] - MissingWitnesses(RequiredWitnessSet), + MissingWitnesses(Box), //#[error("Withdrawal required a script, not a payment key: {}", .to_address().to_bech32(None))] #[error("Withdrawal required a script, not a payment key")] - RequiredScript(RewardAddress), + RequiredScript(Box), } // comes from witsVKeyNeeded in the Ledger spec @@ -54,7 +54,9 @@ impl SingleWithdrawalBuilder { withdrawal_required_wits(&self.address, &mut required_wits); if !required_wits.scripts.is_empty() { - return Err(WithdrawalBuilderError::RequiredScript(self.address.clone())); + return Err(WithdrawalBuilderError::RequiredScript(Box::new( + self.address.clone(), + ))); } Ok(WithdrawalBuilderResult { @@ -78,7 +80,9 @@ impl SingleWithdrawalBuilder { required_wits_left.scripts.remove(&native_script.hash()); if !required_wits_left.scripts.is_empty() { - return Err(WithdrawalBuilderError::MissingWitnesses(required_wits_left)); + return Err(WithdrawalBuilderError::MissingWitnesses(Box::new( + required_wits_left, + ))); } Ok(WithdrawalBuilderResult { @@ -113,7 +117,9 @@ impl SingleWithdrawalBuilder { required_wits_left.scripts.remove(&script_hash); if required_wits_left.len() > 0 { - return Err(WithdrawalBuilderError::MissingWitnesses(required_wits_left)); + return Err(WithdrawalBuilderError::MissingWitnesses(Box::new( + required_wits_left, + ))); } Ok(WithdrawalBuilderResult { diff --git a/chain/rust/src/builders/witness_builder.rs b/chain/rust/src/builders/witness_builder.rs index 11fffe8e..2a1a75c5 100644 --- a/chain/rust/src/builders/witness_builder.rs +++ b/chain/rust/src/builders/witness_builder.rs @@ -385,8 +385,9 @@ impl TransactionWitnessSetBuilder { PlutusScriptWitness::Script(plutus_script) => { self.add_script(plutus_script.clone().into()); } - // We don't add the script references to the witness set - _ => (), + PlutusScriptWitness::Ref(_) => { + // We don't add the script references to the witness set + } } if let Some(data) = option { self.add_plutus_datum(data.clone()); @@ -761,6 +762,6 @@ mod tests { TransactionWitnessSet::from_cbor_bytes(&hex::decode(data).unwrap()).unwrap(); let round_trip = witness_set.to_cbor_bytes(); - assert_eq!(data, hex::encode(&round_trip)); + assert_eq!(data, hex::encode(round_trip)); } } diff --git a/chain/rust/src/byron/base58.rs b/chain/rust/src/byron/base58.rs index 822da258..09260082 100644 --- a/chain/rust/src/byron/base58.rs +++ b/chain/rust/src/byron/base58.rs @@ -109,9 +109,9 @@ fn base_encode(alphabet_s: &str, input: &[u8]) -> Vec { let mut digits = vec![0_u8]; for input in input.iter() { let mut carry = *input as u32; - for j in 0..digits.len() { - carry += (digits[j] as u32) << 8; - digits[j] = (carry % base) as u8; + for digit in digits.iter_mut() { + carry += (*digit as u32) << 8; + *digit = (carry % base) as u8; carry /= base; } @@ -142,15 +142,16 @@ fn base_decode(alphabet_s: &str, input: &[u8]) -> Result> { let mut bytes: Vec = vec![0]; let zcount = input.iter().take_while(|x| **x == alphabet[0]).count(); + #[allow(clippy::needless_range_loop)] for i in zcount..input.len() { let value = match alphabet.iter().position(|&x| x == input[i]) { Some(idx) => idx, None => return Err(Error::UnknownSymbol(i)), }; let mut carry = value as u32; - for j in 0..bytes.len() { - carry += bytes[j] as u32 * base; - bytes[j] = carry as u8; + for byte in bytes.iter_mut() { + carry += *byte as u32 * base; + *byte = carry as u8; carry >>= 8; } @@ -162,13 +163,9 @@ fn base_decode(alphabet_s: &str, input: &[u8]) -> Result> { let leading_zeros = bytes.iter().rev().take_while(|x| **x == 0).count(); if zcount > leading_zeros { if leading_zeros > 0 { - for _ in 0..(zcount - leading_zeros - 1) { - bytes.push(0); - } + bytes.resize(bytes.len() + zcount - leading_zeros - 1, 0); } else { - for _ in 0..zcount { - bytes.push(0); - } + bytes.resize(bytes.len() + zcount, 0); } } bytes.reverse(); diff --git a/chain/rust/src/byron/crc32.rs b/chain/rust/src/byron/crc32.rs index cb0d88f6..c58bdc7d 100644 --- a/chain/rust/src/byron/crc32.rs +++ b/chain/rust/src/byron/crc32.rs @@ -354,6 +354,12 @@ impl std::fmt::Display for Crc32 { } } +impl Default for Crc32 { + fn default() -> Self { + Self::new() + } +} + /// function is kept for compatibility. however prefer the /// `Crc32` structure. /// diff --git a/chain/rust/src/byron/utils.rs b/chain/rust/src/byron/utils.rs index 1a19f09f..844267a5 100644 --- a/chain/rust/src/byron/utils.rs +++ b/chain/rust/src/byron/utils.rs @@ -365,9 +365,7 @@ mod tests { fn assert_same_address(address: ByronAddress, xpub: chain_crypto::PublicKey) { assert!( address.content.identical_with_pubkey(xpub.clone().into()), - "expected public key {} to match address {}", - xpub, - address, + "expected public key {xpub} to match address {address}", ) } diff --git a/chain/rust/src/certs/mod.rs b/chain/rust/src/certs/mod.rs index 0453da11..f9bd29c9 100644 --- a/chain/rust/src/certs/mod.rs +++ b/chain/rust/src/certs/mod.rs @@ -22,6 +22,7 @@ use cml_core::ordered_hash_map::OrderedHashMap; use cml_core::serialization::{LenEncoding, StringEncoding}; use std::convert::TryFrom; +#[allow(clippy::large_enum_variant)] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)] pub enum Certificate { StakeRegistration(StakeRegistration), @@ -362,6 +363,7 @@ pub struct PoolParams { } impl PoolParams { + #[allow(clippy::too_many_arguments)] pub fn new( operator: Ed25519KeyHash, vrf_keyhash: VRFKeyHash, diff --git a/chain/rust/src/crypto/hash.rs b/chain/rust/src/crypto/hash.rs index daf05660..d49b9b9b 100644 --- a/chain/rust/src/crypto/hash.rs +++ b/chain/rust/src/crypto/hash.rs @@ -29,58 +29,15 @@ pub fn hash_script_data( encoding: Option<&TransactionWitnessSetEncoding>, ) -> ScriptDataHash { let mut buf = cbor_event::se::Serializer::new_vec(); - if redeemers.is_empty() && datums.is_some() { - /* - ; Finally, note that in the case that a transaction includes datums but does not - ; include any redeemers, the script data format becomes (in hex): - ; [ 80 | datums | A0 ] - ; corresponding to a CBOR empty list and an empty map (our apologies). - */ - buf.write_raw_bytes(&[0x80]).unwrap(); - buf.write_array_sz( - encoding - .as_ref() - .map(|encs| encs.plutus_datums_encoding) - .unwrap_or_default() - .to_len_sz(datums.unwrap().len() as u64, false), - ) - .unwrap(); - for datum in datums.unwrap() { - datum.serialize(&mut buf, false).unwrap(); - } - encoding - .as_ref() - .map(|encs| encs.plutus_datums_encoding) - .unwrap_or_default() - .end(&mut buf, false) - .unwrap(); - buf.write_raw_bytes(&[0xA0]).unwrap(); - } else { - /* - ; script data format: - ; [ redeemers | datums | language views ] - ; The redeemers are exactly the data present in the transaction witness set. - ; Similarly for the datums, if present. If no datums are provided, the middle - ; field is an empty string. - */ - buf.write_array_sz( - encoding - .as_ref() - .map(|encs| encs.redeemers_encoding) - .unwrap_or_default() - .to_len_sz(redeemers.len() as u64, false), - ) - .unwrap(); - for redeemer in redeemers { - redeemer.serialize(&mut buf, false).unwrap(); - } - encoding - .as_ref() - .map(|encs| encs.redeemers_encoding) - .unwrap_or_default() - .end(&mut buf, false) - .unwrap(); - if let Some(datums) = datums { + match datums { + Some(datums) if redeemers.is_empty() => { + /* + ; Finally, note that in the case that a transaction includes datums but does not + ; include any redeemers, the script data format becomes (in hex): + ; [ 80 | datums | A0 ] + ; corresponding to a CBOR empty list and an empty map (our apologies). + */ + buf.write_raw_bytes(&[0x80]).unwrap(); buf.write_array_sz( encoding .as_ref() @@ -98,9 +55,55 @@ pub fn hash_script_data( .unwrap_or_default() .end(&mut buf, false) .unwrap(); + buf.write_raw_bytes(&[0xA0]).unwrap(); } - buf.write_raw_bytes(&cost_models.language_views_encoding().unwrap()) + _ => { + /* + ; script data format: + ; [ redeemers | datums | language views ] + ; The redeemers are exactly the data present in the transaction witness set. + ; Similarly for the datums, if present. If no datums are provided, the middle + ; field is an empty string. + */ + buf.write_array_sz( + encoding + .as_ref() + .map(|encs| encs.redeemers_encoding) + .unwrap_or_default() + .to_len_sz(redeemers.len() as u64, false), + ) .unwrap(); + for redeemer in redeemers { + redeemer.serialize(&mut buf, false).unwrap(); + } + encoding + .as_ref() + .map(|encs| encs.redeemers_encoding) + .unwrap_or_default() + .end(&mut buf, false) + .unwrap(); + if let Some(datums) = datums { + buf.write_array_sz( + encoding + .as_ref() + .map(|encs| encs.plutus_datums_encoding) + .unwrap_or_default() + .to_len_sz(datums.len() as u64, false), + ) + .unwrap(); + for datum in datums { + datum.serialize(&mut buf, false).unwrap(); + } + encoding + .as_ref() + .map(|encs| encs.plutus_datums_encoding) + .unwrap_or_default() + .end(&mut buf, false) + .unwrap(); + } + buf.write_raw_bytes(&cost_models.language_views_encoding().unwrap()) + .unwrap(); + } } ScriptDataHash::from(blake2b256(&buf.finalize())) } diff --git a/chain/rust/src/plutus/utils.rs b/chain/rust/src/plutus/utils.rs index 03ae9d5c..67a61c8b 100644 --- a/chain/rust/src/plutus/utils.rs +++ b/chain/rust/src/plutus/utils.rs @@ -269,7 +269,7 @@ impl Deserialize for ConstrPlutusData { } impl CostModels { - pub fn as_map<'a>(&'a self) -> BTreeMap { + pub fn as_map(&self) -> BTreeMap { let mut map = BTreeMap::new(); if let Some(v1_costs) = &self.plutus_v1 { map.insert(Language::PlutusV1, &v1_costs[..]); @@ -429,6 +429,10 @@ impl PlutusMap { self.entries.len() } + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + /// Replaces all datums of a given key, if any exist. pub fn set(&mut self, key: PlutusData, value: PlutusData) { self.entries.retain(|(k, _)| *k != key); diff --git a/chain/rust/src/utils.rs b/chain/rust/src/utils.rs index 72d3070f..e80798af 100644 --- a/chain/rust/src/utils.rs +++ b/chain/rust/src/utils.rs @@ -70,15 +70,15 @@ impl From for Script { const BOUNDED_BYTES_CHUNK_SIZE: usize = 64; // to get around not having access from outside the library we just write the raw CBOR indefinite byte string code here -fn write_cbor_indefinite_byte_tag<'se, W: Write>( - serializer: &'se mut Serializer, -) -> cbor_event::Result<&'se mut Serializer> { +fn write_cbor_indefinite_byte_tag( + serializer: &mut Serializer, +) -> cbor_event::Result<&mut Serializer> { serializer.write_raw_bytes(&[0x5f]) } use cml_core::serialization::StringEncoding; -fn valid_indefinite_string_encoding(chunks: &Vec<(u64, cbor_event::Sz)>, total_len: usize) -> bool { +fn valid_indefinite_string_encoding(chunks: &[(u64, cbor_event::Sz)], total_len: usize) -> bool { let mut len_counter = 0; let valid_sz = chunks.iter().all(|(len, sz)| { len_counter += len; diff --git a/chain/wasm/package.json b/chain/wasm/package.json index 59fbc6a6..17c7cb2a 100644 --- a/chain/wasm/package.json +++ b/chain/wasm/package.json @@ -19,8 +19,7 @@ "js:publish-browser:beta": "npm run rust:build-browser && npm run js:prepublish && node ../../scripts/publish-helper chain -browser && cd publish && npm publish --tag beta --access public", "js:publish-asm:prod": "npm run rust:build-asm && npm run js:prepublish && node ../../scripts/publish-helper chain -asmjs && cd publish && npm publish --access public", "js:publish-asm:beta": "npm run rust:build-asm && npm run js:prepublish && node ../../scripts/publish-helper chain -asmjs && cd publish && npm publish --tag beta --access public", - "js:ts-json-gen": "cd json-gen && cargo +stable run && cd .. && node ../../scripts/run-json2ts.js && node ../../scripts/json-ts-types.js chain", - "postinstall": "git submodule update --init --recursive && cd binaryen; cmake . && make" + "js:ts-json-gen": "cd json-gen && cargo +stable run && cd .. && node ../../scripts/run-json2ts.js && node ../../scripts/json-ts-types.js chain" }, "husky": { "hooks": { diff --git a/chain/wasm/src/address.rs b/chain/wasm/src/address.rs index 9e557feb..583721a3 100644 --- a/chain/wasm/src/address.rs +++ b/chain/wasm/src/address.rs @@ -109,7 +109,7 @@ impl Address { pub fn to_json_value(&self) -> Result { serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsError::new(&format!("Address::to_js_value: {}", e))) + .map_err(|e| JsError::new(&format!("Address::to_js_value: {e}"))) } pub fn from_json(json: &str) -> Result { @@ -151,7 +151,7 @@ impl RewardAddress { pub fn to_json_value(&self) -> Result { serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsError::new(&format!("RewardAddress::to_js_value: {}", e))) + .map_err(|e| JsError::new(&format!("RewardAddress::to_js_value: {e}"))) } pub fn from_json(json: &str) -> Result { diff --git a/chain/wasm/src/assets/utils.rs b/chain/wasm/src/assets/utils.rs index d094a817..0cd09728 100644 --- a/chain/wasm/src/assets/utils.rs +++ b/chain/wasm/src/assets/utils.rs @@ -13,7 +13,11 @@ impl_wasm_map!( AssetName, Coin, AssetNameList, - MapAssetNameToCoin + MapAssetNameToCoin, + false, + true, + false, + true ); #[derive(Clone, Debug)] diff --git a/chain/wasm/src/builders/certificate_builder.rs b/chain/wasm/src/builders/certificate_builder.rs index e1e1b417..6e2a8620 100644 --- a/chain/wasm/src/builders/certificate_builder.rs +++ b/chain/wasm/src/builders/certificate_builder.rs @@ -68,7 +68,6 @@ impl SingleCertificateBuilder { required_signers: &RequiredSigners, ) -> Result { self.0 - .clone() .plutus_script( partial_witness.clone().into(), required_signers.clone().into(), diff --git a/chain/wasm/src/builders/mint_builder.rs b/chain/wasm/src/builders/mint_builder.rs index 797b2884..d187a6f3 100644 --- a/chain/wasm/src/builders/mint_builder.rs +++ b/chain/wasm/src/builders/mint_builder.rs @@ -43,7 +43,6 @@ impl SingleMintBuilder { witness_info: &NativeScriptWitnessInfo, ) -> MintBuilderResult { self.0 - .clone() .native_script(native_script.clone().into(), witness_info.clone().into()) .into() } @@ -54,7 +53,6 @@ impl SingleMintBuilder { required_signers: &RequiredSigners, ) -> MintBuilderResult { self.0 - .clone() .plutus_script( partial_witness.clone().into(), required_signers.clone().into(), diff --git a/chain/wasm/src/builders/redeemer_builder.rs b/chain/wasm/src/builders/redeemer_builder.rs index 6defd36d..be053a1c 100644 --- a/chain/wasm/src/builders/redeemer_builder.rs +++ b/chain/wasm/src/builders/redeemer_builder.rs @@ -76,7 +76,7 @@ impl RedeemerSetBuilder { /// note: will override existing value if called twice with the same key pub fn update_ex_units(&mut self, key: &RedeemerWitnessKey, ex_units: &ExUnits) { self.0 - .update_ex_units(key.clone().into(), ex_units.clone().into()); + .update_ex_units((*key).into(), ex_units.clone().into()); } pub fn add_spend(&mut self, result: &InputBuilderResult) { diff --git a/chain/wasm/src/builders/tx_builder.rs b/chain/wasm/src/builders/tx_builder.rs index 22be61a8..d09682a4 100644 --- a/chain/wasm/src/builders/tx_builder.rs +++ b/chain/wasm/src/builders/tx_builder.rs @@ -202,7 +202,7 @@ impl TransactionBuilder { } pub fn get_withdrawals(&self) -> Option { - self.0.get_withdrawals().map(|wd| wd.clone().into()) + self.0.get_withdrawals().map(|wd| wd.into()) } pub fn add_withdrawal(&mut self, result: &WithdrawalBuilderResult) { @@ -210,7 +210,7 @@ impl TransactionBuilder { } pub fn get_auxiliary_data(&self) -> Option { - self.0.get_auxiliary_data().map(|aux| aux.clone().into()) + self.0.get_auxiliary_data().map(|aux| aux.into()) } pub fn set_auxiliary_data(&mut self, new_aux_data: &AuxiliaryData) { @@ -227,7 +227,7 @@ impl TransactionBuilder { /// Returns a copy of the current mint state in the builder pub fn get_mint(&self) -> Option { - self.0.get_mint().map(|m| m.clone().into()) + self.0.get_mint().map(|m| m.into()) } pub fn new(cfg: &TransactionBuilderConfig) -> Self { @@ -341,7 +341,7 @@ impl TransactionBuilder { /// used to override the exunit values initially provided when adding inputs pub fn set_exunits(&mut self, redeemer: &RedeemerWitnessKey, ex_units: &ExUnits) { self.0 - .set_exunits(redeemer.clone().into(), ex_units.clone().into()) + .set_exunits((*redeemer).into(), ex_units.clone().into()) } /// warning: sum of all parts of a transaction must equal 0. You cannot just set the fee to the min value and forget about it @@ -390,7 +390,7 @@ impl TxRedeemerBuilder { /// used to override the exunit values initially provided when adding inputs pub fn set_exunits(&mut self, redeemer: &RedeemerWitnessKey, ex_units: &ExUnits) { self.0 - .set_exunits(redeemer.clone().into(), ex_units.clone().into()) + .set_exunits((*redeemer).into(), ex_units.clone().into()) } /// Transaction body with a dummy values for redeemers & script_data_hash @@ -493,6 +493,6 @@ impl SignedTxBuilder { } pub fn auxiliary_data(&self) -> Option { - self.0.auxiliary_data().map(|aux| aux.clone().into()) + self.0.auxiliary_data().map(|aux| aux.into()) } } diff --git a/chain/wasm/src/builders/withdrawal_builder.rs b/chain/wasm/src/builders/withdrawal_builder.rs index eef349c1..4a88e328 100644 --- a/chain/wasm/src/builders/withdrawal_builder.rs +++ b/chain/wasm/src/builders/withdrawal_builder.rs @@ -53,7 +53,6 @@ impl SingleWithdrawalBuilder { witness_info: &NativeScriptWitnessInfo, ) -> Result { self.0 - .clone() .native_script(native_script.as_ref(), witness_info.as_ref()) .map(Into::into) .map_err(Into::into) @@ -65,11 +64,7 @@ impl SingleWithdrawalBuilder { required_signers: RequiredSigners, ) -> Result { self.0 - .clone() - .plutus_script( - partial_witness.clone().into(), - required_signers.clone().into(), - ) + .plutus_script(partial_witness.into(), required_signers.into()) .map(Into::into) .map_err(Into::into) } diff --git a/chain/wasm/src/builders/witness_builder.rs b/chain/wasm/src/builders/witness_builder.rs index 278979d9..cf99c7c8 100644 --- a/chain/wasm/src/builders/witness_builder.rs +++ b/chain/wasm/src/builders/witness_builder.rs @@ -118,7 +118,7 @@ impl RequiredWitnessSet { } pub fn add_redeemer_tag(&mut self, redeemer: &RedeemerWitnessKey) { - self.0.add_redeemer_tag(redeemer.clone().into()); + self.0.add_redeemer_tag((*redeemer).into()); } pub fn add_all(&mut self, requirements: &RequiredWitnessSet) { @@ -178,7 +178,7 @@ impl TransactionWitnessSetBuilder { } pub fn add_plutus_datum(&mut self, plutus_datum: PlutusData) { - self.0.add_plutus_datum(plutus_datum.clone().into()); + self.0.add_plutus_datum(plutus_datum.into()); } pub fn get_plutus_datum(&self) -> PlutusDataList { diff --git a/chain/wasm/src/byron/crc32.rs b/chain/wasm/src/byron/crc32.rs index 005fe8ed..fe9c8da0 100644 --- a/chain/wasm/src/byron/crc32.rs +++ b/chain/wasm/src/byron/crc32.rs @@ -22,7 +22,7 @@ impl Crc32 { /// finalize the CRC32, recovering the computed value pub fn finalize(&self) -> u32 { - self.0.clone().finalize() + self.0.finalize() } } diff --git a/chain/wasm/src/byron/mod.rs b/chain/wasm/src/byron/mod.rs index 8fb518f9..5a5bfcd4 100644 --- a/chain/wasm/src/byron/mod.rs +++ b/chain/wasm/src/byron/mod.rs @@ -12,6 +12,7 @@ pub mod utils; pub use self::crc32::Crc32; pub use self::utils::{AddressId, ByronScript, ProtocolMagic, StakeholderId}; pub use cml_chain::byron::ByronAddrType; +use cml_core_wasm::{impl_wasm_cbor_event_serialize_api, impl_wasm_conversions}; use cml_crypto_wasm::{Bip32PublicKey, PublicKey}; use wasm_bindgen::prelude::{wasm_bindgen, JsValue}; @@ -19,34 +20,12 @@ use wasm_bindgen::prelude::{wasm_bindgen, JsValue}; #[wasm_bindgen] pub struct AddrAttributes(cml_chain::byron::AddrAttributes); -#[wasm_bindgen] -impl AddrAttributes { - pub fn to_cbor_bytes(&self) -> Vec { - cml_core::serialization::ToBytes::to_bytes(&self.0) - } - - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } +impl_wasm_conversions!(cml_chain::byron::AddrAttributes, AddrAttributes); - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } - - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_cbor_event_serialize_api!(AddrAttributes); +#[wasm_bindgen] +impl AddrAttributes { pub fn set_stake_distribution(&mut self, stake_distribution: &StakeDistribution) { self.0.stake_distribution = Some(stake_distribution.clone().into()) } @@ -67,11 +46,11 @@ impl AddrAttributes { } pub fn set_protocol_magic(&mut self, protocol_magic: &ProtocolMagic) { - self.0.protocol_magic = Some(protocol_magic.clone().into()) + self.0.protocol_magic = Some((*protocol_magic).into()) } pub fn protocol_magic(&self) -> Option { - self.0.protocol_magic.clone().map(std::convert::Into::into) + self.0.protocol_magic.map(std::convert::Into::into) } pub fn new() -> Self { @@ -79,56 +58,16 @@ impl AddrAttributes { } } -impl From for AddrAttributes { - fn from(native: cml_chain::byron::AddrAttributes) -> Self { - Self(native) - } -} - -impl From for cml_chain::byron::AddrAttributes { - fn from(wasm: AddrAttributes) -> Self { - wasm.0 - } -} - -impl AsRef for AddrAttributes { - fn as_ref(&self) -> &cml_chain::byron::AddrAttributes { - &self.0 - } -} - #[derive(Clone, Debug)] #[wasm_bindgen] pub struct AddressContent(cml_chain::byron::AddressContent); -#[wasm_bindgen] -impl AddressContent { - pub fn to_cbor_bytes(&self) -> Vec { - cml_core::serialization::ToBytes::to_bytes(&self.0) - } - - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } +impl_wasm_conversions!(cml_chain::byron::AddressContent, AddressContent); - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_cbor_event_serialize_api!(AddressContent); +#[wasm_bindgen] +impl AddressContent { pub fn address_id(&self) -> AddressId { self.0.address_id.clone().into() } @@ -149,182 +88,62 @@ impl AddressContent { Self(cml_chain::byron::AddressContent::new( address_id.clone().into(), addr_attributes.clone().into(), - addr_type.into(), + addr_type, )) } } -impl From for AddressContent { - fn from(native: cml_chain::byron::AddressContent) -> Self { - Self(native) - } -} - -impl From for cml_chain::byron::AddressContent { - fn from(wasm: AddressContent) -> Self { - wasm.0 - } -} - -impl AsRef for AddressContent { - fn as_ref(&self) -> &cml_chain::byron::AddressContent { - &self.0 - } -} - #[derive(Clone, Debug)] #[wasm_bindgen] pub struct ByronAddress(cml_chain::byron::ByronAddress); -#[wasm_bindgen] -impl ByronAddress { - pub fn to_cbor_bytes(&self) -> Vec { - cml_core::serialization::ToBytes::to_bytes(&self.0) - } +impl_wasm_conversions!(cml_chain::byron::ByronAddress, ByronAddress); - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } - - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_cbor_event_serialize_api!(ByronAddress); +#[wasm_bindgen] +impl ByronAddress { pub fn content(&self) -> AddressContent { self.0.content.clone().into() } pub fn crc(&self) -> Crc32 { - self.0.crc.clone().into() + self.0.crc.into() } pub fn new(content: &AddressContent, crc: &Crc32) -> Self { Self(cml_chain::byron::ByronAddress::new( content.clone().into(), - crc.clone().into(), + (*crc).into(), )) } } -impl From for ByronAddress { - fn from(native: cml_chain::byron::ByronAddress) -> Self { - Self(native) - } -} - -impl From for cml_chain::byron::ByronAddress { - fn from(wasm: ByronAddress) -> Self { - wasm.0 - } -} - -impl AsRef for ByronAddress { - fn as_ref(&self) -> &cml_chain::byron::ByronAddress { - &self.0 - } -} - #[derive(Clone, Debug)] #[wasm_bindgen] pub struct HDAddressPayload(cml_chain::byron::HDAddressPayload); -#[wasm_bindgen] -impl HDAddressPayload { - pub fn to_cbor_bytes(&self) -> Vec { - cml_core::serialization::ToBytes::to_bytes(&self.0) - } - - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } +impl_wasm_conversions!(cml_chain::byron::HDAddressPayload, HDAddressPayload); - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } - - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_cbor_event_serialize_api!(HDAddressPayload); +#[wasm_bindgen] +impl HDAddressPayload { pub fn get(&self) -> Vec { self.0.get().clone() } } -impl From for HDAddressPayload { - fn from(native: cml_chain::byron::HDAddressPayload) -> Self { - Self(native) - } -} - -impl From for cml_chain::byron::HDAddressPayload { - fn from(wasm: HDAddressPayload) -> Self { - wasm.0 - } -} - -impl AsRef for HDAddressPayload { - fn as_ref(&self) -> &cml_chain::byron::HDAddressPayload { - &self.0 - } -} - #[derive(Clone, Debug)] #[wasm_bindgen] pub struct SpendingData(cml_chain::byron::SpendingData); -#[wasm_bindgen] -impl SpendingData { - pub fn to_cbor_bytes(&self) -> Vec { - cml_core::serialization::ToBytes::to_bytes(&self.0) - } +impl_wasm_conversions!(cml_chain::byron::SpendingData, SpendingData); - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } - - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_cbor_event_serialize_api!(SpendingData); +#[wasm_bindgen] +impl SpendingData { pub fn new_spending_data_pub_key(pubkey: &Bip32PublicKey) -> Self { Self(cml_chain::byron::SpendingData::new_spending_data_pub_key( (*pubkey).clone().into(), @@ -385,24 +204,6 @@ impl SpendingData { } } -impl From for SpendingData { - fn from(native: cml_chain::byron::SpendingData) -> Self { - Self(native) - } -} - -impl From for cml_chain::byron::SpendingData { - fn from(wasm: SpendingData) -> Self { - wasm.0 - } -} - -impl AsRef for SpendingData { - fn as_ref(&self) -> &cml_chain::byron::SpendingData { - &self.0 - } -} - #[wasm_bindgen] pub enum SpendingDataKind { SpendingDataPubKey, @@ -414,34 +215,12 @@ pub enum SpendingDataKind { #[wasm_bindgen] pub struct StakeDistribution(cml_chain::byron::StakeDistribution); -#[wasm_bindgen] -impl StakeDistribution { - pub fn to_cbor_bytes(&self) -> Vec { - cml_core::serialization::ToBytes::to_bytes(&self.0) - } - - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } +impl_wasm_conversions!(cml_chain::byron::StakeDistribution, StakeDistribution); - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } - - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_cbor_event_serialize_api!(StakeDistribution); +#[wasm_bindgen] +impl StakeDistribution { pub fn new_single_key(stakeholder_id: &StakeholderId) -> Self { Self(cml_chain::byron::StakeDistribution::new_single_key( stakeholder_id.clone().into(), @@ -471,24 +250,6 @@ impl StakeDistribution { } } -impl From for StakeDistribution { - fn from(native: cml_chain::byron::StakeDistribution) -> Self { - Self(native) - } -} - -impl From for cml_chain::byron::StakeDistribution { - fn from(wasm: StakeDistribution) -> Self { - wasm.0 - } -} - -impl AsRef for StakeDistribution { - fn as_ref(&self) -> &cml_chain::byron::StakeDistribution { - &self.0 - } -} - #[wasm_bindgen] pub enum StakeDistributionKind { SingleKey, @@ -499,34 +260,12 @@ pub enum StakeDistributionKind { #[wasm_bindgen] pub struct ByronTxOut(cml_chain::byron::ByronTxOut); -#[wasm_bindgen] -impl ByronTxOut { - pub fn to_cbor_bytes(&self) -> Vec { - cml_core::serialization::ToBytes::to_bytes(&self.0) - } - - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } +impl_wasm_conversions!(cml_chain::byron::ByronTxOut, ByronTxOut); - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } - - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_cbor_event_serialize_api!(ByronTxOut); +#[wasm_bindgen] +impl ByronTxOut { pub fn address(&self) -> ByronAddress { self.0.address.clone().into() } @@ -542,21 +281,3 @@ impl ByronTxOut { )) } } - -impl From for ByronTxOut { - fn from(native: cml_chain::byron::ByronTxOut) -> Self { - Self(native) - } -} - -impl From for cml_chain::byron::ByronTxOut { - fn from(wasm: ByronTxOut) -> Self { - wasm.0 - } -} - -impl AsRef for ByronTxOut { - fn as_ref(&self) -> &cml_chain::byron::ByronTxOut { - &self.0 - } -} diff --git a/chain/wasm/src/byron/utils.rs b/chain/wasm/src/byron/utils.rs index 5fd25b7f..2c12ec59 100644 --- a/chain/wasm/src/byron/utils.rs +++ b/chain/wasm/src/byron/utils.rs @@ -116,7 +116,7 @@ impl AddressContent { pub fn icarus_from_key(key: &Bip32PublicKey, protocol_magic: &ProtocolMagic) -> AddressContent { cml_chain::byron::AddressContent::icarus_from_key( key.clone().into(), - protocol_magic.clone().into(), + (*protocol_magic).into(), ) .into() } @@ -136,7 +136,7 @@ impl ByronAddress { pub fn from_base58(s: &str) -> Result { cml_chain::byron::ByronAddress::from_base58(s) .map(Self) - .map_err(|e| JsError::new(&format!("ByronAddress::from_base58: {:?}", e))) + .map_err(|e| JsError::new(&format!("ByronAddress::from_base58: {e:?}"))) } pub fn is_valid(s: &str) -> bool { @@ -152,10 +152,7 @@ impl ByronAddress { } pub fn from_address_content(address_content: &AddressContent) -> Self { - cml_chain::byron::ByronAddress::from(cml_chain::byron::AddressContent::from( - address_content.clone(), - )) - .into() + cml_chain::byron::ByronAddress::from(address_content.as_ref().clone()).into() } } @@ -212,10 +209,6 @@ pub fn make_icarus_bootstrap_witness( addr: ByronAddress, key: &Bip32PrivateKey, ) -> BootstrapWitness { - cml_chain::byron::make_icarus_bootstrap_witness( - tx_body_hash.clone().into(), - addr.clone().into(), - key.as_ref(), - ) - .into() + cml_chain::byron::make_icarus_bootstrap_witness(tx_body_hash.into(), addr.into(), key.as_ref()) + .into() } diff --git a/chain/wasm/src/certs/mod.rs b/chain/wasm/src/certs/mod.rs index c8bffd3b..ed9d3f6e 100644 --- a/chain/wasm/src/certs/mod.rs +++ b/chain/wasm/src/certs/mod.rs @@ -330,7 +330,7 @@ impl MoveInstantaneousReward { pub fn new(pot: MIRPot, action: &MIRAction) -> Self { Self(cml_chain::certs::MoveInstantaneousReward::new( - pot.into(), + pot, action.clone().into(), )) } diff --git a/chain/wasm/src/plutus/mod.rs b/chain/wasm/src/plutus/mod.rs index 7c90896d..225d0aba 100644 --- a/chain/wasm/src/plutus/mod.rs +++ b/chain/wasm/src/plutus/mod.rs @@ -240,7 +240,7 @@ impl Redeemer { pub fn new(tag: RedeemerTag, index: u64, data: &PlutusData, ex_units: &ExUnits) -> Self { Self(cml_chain::plutus::Redeemer::new( - tag.into(), + tag, index, data.clone().into(), ex_units.clone().into(), diff --git a/chain/wasm/src/plutus/utils.rs b/chain/wasm/src/plutus/utils.rs index 1585b97f..a6506b71 100644 --- a/chain/wasm/src/plutus/utils.rs +++ b/chain/wasm/src/plutus/utils.rs @@ -1,6 +1,6 @@ use crate::{plutus::PlutusData, PlutusDataList, RedeemerList}; use cml_chain::plutus::Language; -use cml_core_wasm::impl_wasm_conversions; +use cml_core_wasm::{impl_wasm_cbor_json_api, impl_wasm_conversions}; use cml_crypto_wasm::ScriptHash; use wasm_bindgen::prelude::{wasm_bindgen, JsError, JsValue}; @@ -10,34 +10,12 @@ use super::{ExUnits, PlutusV1Script, PlutusV2Script}; #[wasm_bindgen] pub struct ConstrPlutusData(cml_chain::plutus::ConstrPlutusData); -#[wasm_bindgen] -impl ConstrPlutusData { - pub fn to_cbor_bytes(&self) -> Vec { - cml_chain::serialization::Serialize::to_cbor_bytes(&self.0) - } +impl_wasm_conversions!(cml_chain::plutus::ConstrPlutusData, ConstrPlutusData); - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_chain::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } - - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_cbor_json_api!(ConstrPlutusData); +#[wasm_bindgen] +impl ConstrPlutusData { pub fn alternative(&self) -> u64 { self.0.alternative } @@ -54,30 +32,14 @@ impl ConstrPlutusData { } } -impl From for ConstrPlutusData { - fn from(native: cml_chain::plutus::ConstrPlutusData) -> Self { - Self(native) - } -} - -impl From for cml_chain::plutus::ConstrPlutusData { - fn from(wasm: ConstrPlutusData) -> Self { - wasm.0 - } -} - -impl AsRef for ConstrPlutusData { - fn as_ref(&self) -> &cml_chain::plutus::ConstrPlutusData { - &self.0 - } -} - #[derive(Clone, Debug)] #[wasm_bindgen] pub struct PlutusMap(cml_chain::plutus::PlutusMap); impl_wasm_conversions!(cml_chain::plutus::PlutusMap, PlutusMap); +impl_wasm_cbor_json_api!(PlutusMap); + #[wasm_bindgen] impl PlutusMap { pub fn new() -> Self { @@ -88,6 +50,10 @@ impl PlutusMap { self.0.len() } + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + /// Replaces all datums of a given key, if any exist. pub fn set(&mut self, key: &PlutusData, value: &PlutusData) { self.0.set(key.clone().into(), value.clone().into()) @@ -102,13 +68,9 @@ impl PlutusMap { /// In the extremely unlikely situation there are duplicate keys, this gets all of a single key pub fn get_all(&self, key: &PlutusData) -> Option { - self.0.get_all(key.as_ref()).map(|datums| { - datums - .into_iter() - .map(|d| d.clone().into()) - .collect::>() - .into() - }) + self.0 + .get_all(key.as_ref()) + .map(|datums| datums.into_iter().cloned().collect::>().into()) } pub fn keys(&self) -> PlutusDataList { diff --git a/chain/wasm/src/transaction/utils.rs b/chain/wasm/src/transaction/utils.rs index 76aab1e1..5a460801 100644 --- a/chain/wasm/src/transaction/utils.rs +++ b/chain/wasm/src/transaction/utils.rs @@ -36,7 +36,7 @@ impl TransactionOutput { } pub fn datum(&self) -> Option { - self.0.datum().clone().map(Into::into) + self.0.datum().map(Into::into) } /// Get the datum hash from a tx output if present as a hash. diff --git a/chain/wasm/src/utils.rs b/chain/wasm/src/utils.rs index 291f548c..df9de13d 100644 --- a/chain/wasm/src/utils.rs +++ b/chain/wasm/src/utils.rs @@ -1,41 +1,23 @@ use super::Int; use wasm_bindgen::prelude::{wasm_bindgen, JsError, JsValue}; + +use cml_core_wasm::{impl_wasm_cbor_json_api, impl_wasm_conversions}; + #[wasm_bindgen] #[derive(Clone, Debug)] pub struct BigInt(cml_chain::utils::BigInt); -#[wasm_bindgen] -impl BigInt { - pub fn to_cbor_bytes(&self) -> Vec { - cml_chain::serialization::Serialize::to_cbor_bytes(&self.0) - } +impl_wasm_conversions!(cml_chain::utils::BigInt, BigInt); - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_chain::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_js_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } - - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_cbor_json_api!(BigInt); +#[wasm_bindgen] +impl BigInt { pub fn from_int(x: &Int) -> Self { Self(cml_chain::utils::BigInt::from_int(x.as_ref())) } + #[allow(clippy::should_implement_trait)] pub fn from_str(s: &str) -> Result { use std::str::FromStr; cml_chain::utils::BigInt::from_str(s) @@ -60,21 +42,3 @@ impl BigInt { self.0.as_int().map(Into::into) } } - -impl From for BigInt { - fn from(native: cml_chain::utils::BigInt) -> Self { - Self(native) - } -} - -impl From for cml_chain::utils::BigInt { - fn from(wasm: BigInt) -> Self { - wasm.0 - } -} - -impl AsRef for BigInt { - fn as_ref(&self) -> &cml_chain::utils::BigInt { - &self.0 - } -} diff --git a/cip25/rust/src/lib.rs b/cip25/rust/src/lib.rs index c0373931..b60150ed 100644 --- a/cip25/rust/src/lib.rs +++ b/cip25/rust/src/lib.rs @@ -8,7 +8,6 @@ pub mod utils; pub use utils::{CIP25Version, LabelMetadata}; -use cbor_event; use cbor_event::de::Deserializer; use cbor_event::se::Serializer; use cbor_event::Special as CBORSpecial; diff --git a/cip25/rust/src/serialization.rs b/cip25/rust/src/serialization.rs index c33e2a48..a9f39dab 100644 --- a/cip25/rust/src/serialization.rs +++ b/cip25/rust/src/serialization.rs @@ -2,7 +2,7 @@ use crate::utils::LabelMetadata; use super::*; pub use cml_core::{error::*, serialization::*}; -use std::io::{Seek, SeekFrom}; +use std::io::Seek; impl cbor_event::se::Serialize for FilesDetails { fn serialize<'se, W: Write>( @@ -10,11 +10,11 @@ impl cbor_event::se::Serialize for FilesDetails { serializer: &'se mut Serializer, ) -> cbor_event::Result<&'se mut Serializer> { serializer.write_map(cbor_event::Len::Len(3))?; - serializer.write_text(&"src")?; + serializer.write_text("src")?; self.src.serialize(serializer)?; - serializer.write_text(&"name")?; + serializer.write_text("name")?; self.name.serialize(serializer)?; - serializer.write_text(&"mediaType")?; + serializer.write_text("mediaType")?; self.media_type.serialize(serializer)?; Ok(serializer) } @@ -47,10 +47,8 @@ impl Deserialize for FilesDetails { .into()); } src = Some( - (|| -> Result<_, DeserializeError> { - Ok(ChunkableString::deserialize(raw)?) - })() - .map_err(|e| e.annotate("src"))?, + { ChunkableString::deserialize(raw) } + .map_err(|e| e.annotate("src"))?, ); } "name" => { @@ -61,10 +59,7 @@ impl Deserialize for FilesDetails { .into()); } name = Some( - (|| -> Result<_, DeserializeError> { - Ok(String64::deserialize(raw)?) - })() - .map_err(|e| e.annotate("name"))?, + { String64::deserialize(raw) }.map_err(|e| e.annotate("name"))?, ); } "mediaType" => { @@ -75,10 +70,8 @@ impl Deserialize for FilesDetails { .into()); } media_type = Some( - (|| -> Result<_, DeserializeError> { - Ok(String64::deserialize(raw)?) - })() - .map_err(|e| e.annotate("media_type"))?, + { String64::deserialize(raw) } + .map_err(|e| e.annotate("media_type"))?, ); } _unknown_key => { @@ -138,7 +131,6 @@ impl Deserialize for FilesDetails { ) } }; - (); Ok(Self { name, media_type, @@ -183,10 +175,8 @@ impl Deserialize for CIP25Metadata { return Err(DeserializeFailure::DuplicateKey(Key::Uint(721)).into()); } key_721 = Some( - (|| -> Result<_, DeserializeError> { - Ok(LabelMetadata::deserialize(raw)?) - })() - .map_err(|e| e.annotate("key_721"))?, + { LabelMetadata::deserialize(raw) } + .map_err(|e| e.annotate("key_721"))?, ); } _unknown_key => { @@ -218,7 +208,6 @@ impl Deserialize for CIP25Metadata { return Err(DeserializeFailure::MandatoryFieldMissing(Key::Uint(721)).into()) } }; - (); Ok(Self { key_721 }) })() .map_err(|e| e.annotate("CIP25Metadata")) @@ -242,23 +231,23 @@ impl cbor_event::se::Serialize for MetadataDetails { None => 0, }, ))?; - serializer.write_text(&"name")?; + serializer.write_text("name")?; self.name.serialize(serializer)?; if let Some(field) = &self.files { - serializer.write_text(&"files")?; + serializer.write_text("files")?; serializer.write_array(cbor_event::Len::Len(field.len() as u64))?; for element in field.iter() { element.serialize(serializer)?; } } - serializer.write_text(&"image")?; + serializer.write_text("image")?; self.image.serialize(serializer)?; if let Some(field) = &self.media_type { - serializer.write_text(&"mediaType")?; + serializer.write_text("mediaType")?; field.serialize(serializer)?; } if let Some(field) = &self.description { - serializer.write_text(&"description")?; + serializer.write_text("description")?; field.serialize(serializer)?; } Ok(serializer) @@ -294,10 +283,7 @@ impl Deserialize for MetadataDetails { .into()); } name = Some( - (|| -> Result<_, DeserializeError> { - Ok(String64::deserialize(raw)?) - })() - .map_err(|e| e.annotate("name"))?, + { String64::deserialize(raw) }.map_err(|e| e.annotate("name"))?, ); } "files" => { @@ -335,10 +321,8 @@ impl Deserialize for MetadataDetails { .into()); } image = Some( - (|| -> Result<_, DeserializeError> { - Ok(ChunkableString::deserialize(raw)?) - })() - .map_err(|e| e.annotate("image"))?, + { ChunkableString::deserialize(raw) } + .map_err(|e| e.annotate("image"))?, ); } "mediaType" => { @@ -351,7 +335,7 @@ impl Deserialize for MetadataDetails { media_type = Some( (|| -> Result<_, DeserializeError> { read_len.read_elems(1)?; - Ok(String64::deserialize(raw)?) + String64::deserialize(raw) })() .map_err(|e| e.annotate("media_type"))?, ); @@ -366,7 +350,7 @@ impl Deserialize for MetadataDetails { description = Some( (|| -> Result<_, DeserializeError> { read_len.read_elems(1)?; - Ok(ChunkableString::deserialize(raw)?) + ChunkableString::deserialize(raw) })() .map_err(|e| e.annotate("description"))?, ); @@ -478,43 +462,28 @@ impl cbor_event::se::Serialize for ChunkableString { impl Deserialize for ChunkableString { fn deserialize(raw: &mut Deserializer) -> Result { (|| -> Result<_, DeserializeError> { - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); - match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> { - Ok(String64::deserialize(raw)?) - })(raw) - { - Ok(string64) => return Ok(Self::Single(string64)), - Err(_) => raw - .as_mut_ref() - .seek(SeekFrom::Start(initial_position)) - .unwrap(), - }; - match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> { - let mut arr_string64_arr = Vec::new(); - let len = raw.array()?; - while match len { - cbor_event::Len::Len(n) => arr_string64_arr.len() < n as usize, - cbor_event::Len::Indefinite => true, - } { - if raw.cbor_type()? == CBORType::Special { - assert_eq!(raw.special()?, CBORSpecial::Break); - break; + match raw.cbor_type()? { + cbor_event::Type::Text => String64::deserialize(raw).map(Self::Single), + cbor_event::Type::Array => { + let mut arr_string64_arr = Vec::new(); + let len = raw.array()?; + while match len { + cbor_event::Len::Len(n) => arr_string64_arr.len() < n as usize, + cbor_event::Len::Indefinite => true, + } { + if raw.cbor_type()? == CBORType::Special { + assert_eq!(raw.special()?, CBORSpecial::Break); + break; + } + arr_string64_arr.push(String64::deserialize(raw)?); } - arr_string64_arr.push(String64::deserialize(raw)?); + Ok(Self::Chunked(arr_string64_arr)) } - Ok(arr_string64_arr) - })(raw) - { - Ok(arr_string64) => return Ok(Self::Chunked(arr_string64)), - Err(_) => raw - .as_mut_ref() - .seek(SeekFrom::Start(initial_position)) - .unwrap(), - }; - Err(DeserializeError::new( - "ChunkableString", - DeserializeFailure::NoVariantMatched.into(), - )) + _ => Err(DeserializeError::new( + "ChunkableString", + DeserializeFailure::NoVariantMatched, + )), + } })() .map_err(|e| e.annotate("ChunkableString")) } diff --git a/cip25/rust/src/utils.rs b/cip25/rust/src/utils.rs index b250173f..b14bd567 100644 --- a/cip25/rust/src/utils.rs +++ b/cip25/rust/src/utils.rs @@ -145,17 +145,16 @@ impl MiniMetadataDetails { .or_else(|| map.get(&TransactionMetadatum::new_text("title".to_owned()))) // for some reason, 0.3% of NFTs use "id" instead of name .or_else(|| map.get(&TransactionMetadatum::new_text("id".to_owned()))) - .map(|result| match result { - TransactionMetadatum::Text { text, .. } => String64::new_str(&text).ok(), + .and_then(|result| match result { + TransactionMetadatum::Text { text, .. } => String64::new_str(text).ok(), _ => None, - }) - .flatten(); + }); let image_base = map.get(&TransactionMetadatum::new_text("image".to_owned())); let image = match image_base { None => None, Some(base) => match base { - TransactionMetadatum::Text { text, .. } => match String64::new_str(&text) { + TransactionMetadatum::Text { text, .. } => match String64::new_str(text) { Ok(str64) => Some(ChunkableString::Single(str64)), Err(_) => None, }, @@ -164,7 +163,7 @@ impl MiniMetadataDetails { for i in 0..elements.len() { match elements.get(i) { Some(TransactionMetadatum::Text { text, .. }) => { - match String64::new_str(&text) { + match String64::new_str(text) { Ok(str64) => chunks.push(str64), Err(_) => return None, } @@ -293,7 +292,7 @@ impl cbor_event::se::Serialize for LabelMetadata { } CIP25Version::V2 => { serializer.write_map(cbor_event::Len::Len(2))?; - serializer.write_text(&"data")?; + serializer.write_text("data")?; serializer.write_map(cbor_event::Len::Len(self.nfts.len() as u64))?; for (policy_id, assets) in self.nfts.iter() { // hand-edit: write bytes @@ -307,7 +306,7 @@ impl cbor_event::se::Serialize for LabelMetadata { details.serialize(serializer)?; } } - serializer.write_text(&"version")?; + serializer.write_text("version")?; serializer.write_unsigned_integer(2u64)?; } } @@ -320,7 +319,7 @@ impl Deserialize for LabelMetadata { (|| -> Result<_, DeserializeError> { // largely taken from result of generating the original CDDL then modifying to merge v1/v2 // this has to be modified anyway to allow for permissive parsing in the first place. - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); + let initial_position = raw.as_mut_ref().stream_position().unwrap(); // Try parsing V1 match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> { @@ -618,7 +617,7 @@ impl Deserialize for LabelMetadata { // Neither worked Err(DeserializeError::new( "LabelMetadata", - DeserializeFailure::NoVariantMatched.into(), + DeserializeFailure::NoVariantMatched, )) })() .map_err(|e| e.annotate("LabelMetadata")) @@ -627,10 +626,6 @@ impl Deserialize for LabelMetadata { #[cfg(test)] mod tests { - use std::collections::BTreeMap; - - use cml_chain::OrderedHashMap; - use crate::{FilesDetails, MetadataDetails}; use super::*; @@ -664,7 +659,8 @@ mod tests { PolicyId::from_raw_bytes(&policy_id_bytes).unwrap(), AssetName::new(vec![0xCA, 0xFE, 0xD0, 0x0D]).unwrap(), details, - ); + ) + .unwrap(); let metadata = CIP25Metadata::new(v2); let metadata_bytes = metadata.to_bytes(); let roundtrip = CIP25Metadata::from_cbor_bytes(&metadata_bytes).unwrap(); diff --git a/cip25/wasm/src/lib.rs b/cip25/wasm/src/lib.rs index 77a821a0..05ec80fc 100644 --- a/cip25/wasm/src/lib.rs +++ b/cip25/wasm/src/lib.rs @@ -6,6 +6,10 @@ pub mod utils; +use cml_core_wasm::{ + impl_wasm_cbor_json_api_cbor_event_serialize, impl_wasm_conversions, impl_wasm_json_api, + impl_wasm_list, +}; pub use utils::LabelMetadata; pub use core::CIP25Version; @@ -18,7 +22,13 @@ use wasm_bindgen::prelude::{wasm_bindgen, JsValue}; /// Parsing from CBOR bytes should be marginally faster. #[derive(Clone, Debug)] #[wasm_bindgen] -pub struct CIP25Metadata(pub(crate) core::CIP25Metadata); +pub struct CIP25Metadata(core::CIP25Metadata); + +impl_wasm_conversions!(core::CIP25Metadata, CIP25Metadata); + +// we manually write to_cbor_bytes/from_cbor_bytes so we can add the comments + +impl_wasm_json_api!(CIP25Metadata); #[wasm_bindgen] impl CIP25Metadata { @@ -26,7 +36,7 @@ impl CIP25Metadata { /// Does not guarantee any specific type of CBOR format and should NOT /// be used with round-tripping. It will ignore all non-CIP25 keys. /// Use core::metadate crate for round-tripping metadata. - pub fn to_bytes(&self) -> Vec { + pub fn to_cbor_bytes(&self) -> Vec { use core::serialization::ToBytes; ToBytes::to_bytes(&self.0) } @@ -35,27 +45,11 @@ impl CIP25Metadata { /// Does not guarantee any specific type of CBOR format and should NOT /// be used with round-tripping. It will ignore all non-CIP25 keys. /// Use core::metadate crate for round-tripping metadata. - pub fn from_bytes(data: Vec) -> Result { + pub fn from_cbor_bytes(data: Vec) -> Result { use core::serialization::FromBytes; FromBytes::from_bytes(data) .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } - - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) + .map_err(|e| JsValue::from_str(&format!("from_cbor_bytes: {e}"))) } /// The core details of the CIP25 spec @@ -68,18 +62,6 @@ impl CIP25Metadata { } } -impl From for CIP25Metadata { - fn from(native: core::CIP25Metadata) -> Self { - Self(native) - } -} - -impl From for core::CIP25Metadata { - fn from(wasm: CIP25Metadata) -> Self { - wasm.0 - } -} - /// A String that may or may not be chunked into 64-byte chunks to be able /// to conform to Cardano TX Metadata limitations. /// Most users should simply use ChunkableString::from_string() and ChunkableString::to_string() @@ -89,43 +71,19 @@ impl From for core::CIP25Metadata { /// ``` #[derive(Clone, Debug)] #[wasm_bindgen] -pub struct ChunkableString(pub(crate) core::ChunkableString); - -#[wasm_bindgen] -impl ChunkableString { - pub fn to_bytes(&self) -> Vec { - use core::serialization::ToBytes; - ToBytes::to_bytes(&self.0) - } - - pub fn from_bytes(data: Vec) -> Result { - use core::serialization::FromBytes; - FromBytes::from_bytes(data) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } +pub struct ChunkableString(core::ChunkableString); - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } +impl_wasm_conversions!(core::ChunkableString, ChunkableString); - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_cbor_json_api_cbor_event_serialize!(ChunkableString); +#[wasm_bindgen] +impl ChunkableString { pub fn new_single(single: &String64) -> Self { Self(core::ChunkableString::new_single(single.clone().into())) } - pub fn new_chunked(chunked: &String64s) -> Self { + pub fn new_chunked(chunked: &String64List) -> Self { Self(core::ChunkableString::new_chunked(chunked.clone().into())) } @@ -143,7 +101,7 @@ impl ChunkableString { } } - pub fn as_chunked(&self) -> Option { + pub fn as_chunked(&self) -> Option { match &self.0 { core::ChunkableString::Chunked(chunked) => Some(chunked.clone().into()), _ => None, @@ -151,18 +109,6 @@ impl ChunkableString { } } -impl From for ChunkableString { - fn from(native: core::ChunkableString) -> Self { - Self(native) - } -} - -impl From for core::ChunkableString { - fn from(wasm: ChunkableString) -> Self { - wasm.0 - } -} - #[wasm_bindgen] pub enum ChunkableStringKind { Single, @@ -171,38 +117,14 @@ pub enum ChunkableStringKind { #[derive(Clone, Debug)] #[wasm_bindgen] -pub struct FilesDetails(pub(crate) core::FilesDetails); - -#[wasm_bindgen] -impl FilesDetails { - pub fn to_bytes(&self) -> Vec { - use core::serialization::ToBytes; - ToBytes::to_bytes(&self.0) - } +pub struct FilesDetails(core::FilesDetails); - pub fn from_bytes(data: Vec) -> Result { - use core::serialization::FromBytes; - FromBytes::from_bytes(data) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } +impl_wasm_conversions!(core::FilesDetails, FilesDetails); - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_cbor_json_api_cbor_event_serialize!(FilesDetails); +#[wasm_bindgen] +impl FilesDetails { pub fn name(&self) -> String64 { self.0.name.clone().into() } @@ -224,87 +146,18 @@ impl FilesDetails { } } -impl From for FilesDetails { - fn from(native: core::FilesDetails) -> Self { - Self(native) - } -} - -impl From for core::FilesDetails { - fn from(wasm: FilesDetails) -> Self { - wasm.0 - } -} +impl_wasm_list!(core::FilesDetails, FilesDetails, FilesDetailsList); #[derive(Clone, Debug)] #[wasm_bindgen] -pub struct FilesDetailss(pub(crate) Vec); - -#[wasm_bindgen] -impl FilesDetailss { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> FilesDetails { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &FilesDetails) { - self.0.push(elem.clone().into()); - } -} +pub struct MetadataDetails(core::MetadataDetails); -impl From> for FilesDetailss { - fn from(native: Vec) -> Self { - Self(native) - } -} +impl_wasm_conversions!(core::MetadataDetails, MetadataDetails); -impl From for Vec { - fn from(wrapper: FilesDetailss) -> Self { - wrapper.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct MetadataDetails(pub(crate) core::MetadataDetails); +impl_wasm_cbor_json_api_cbor_event_serialize!(MetadataDetails); #[wasm_bindgen] impl MetadataDetails { - pub fn to_bytes(&self) -> Vec { - use core::serialization::ToBytes; - ToBytes::to_bytes(&self.0) - } - - pub fn from_bytes(data: Vec) -> Result { - use core::serialization::FromBytes; - FromBytes::from_bytes(data) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } - - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } - pub fn name(&self) -> String64 { self.0.name.clone().into() } @@ -329,11 +182,11 @@ impl MetadataDetails { self.0.description.clone().map(std::convert::Into::into) } - pub fn set_files(&mut self, files: &FilesDetailss) { + pub fn set_files(&mut self, files: &FilesDetailsList) { self.0.files = Some(files.clone().into()) } - pub fn files(&self) -> Option { + pub fn files(&self) -> Option { self.0.files.clone().map(std::convert::Into::into) } @@ -345,102 +198,21 @@ impl MetadataDetails { } } -impl From for MetadataDetails { - fn from(native: core::MetadataDetails) -> Self { - Self(native) - } -} - -impl From for core::MetadataDetails { - fn from(wasm: MetadataDetails) -> Self { - wasm.0 - } -} - /// A String of at most 64 bytes. /// This is to conform with Cardano metadata restrictions. #[derive(Clone, Debug)] #[wasm_bindgen] -pub struct String64(pub(crate) core::String64); - -#[wasm_bindgen] -impl String64 { - pub fn to_bytes(&self) -> Vec { - use core::serialization::ToBytes; - ToBytes::to_bytes(&self.0) - } +pub struct String64(core::String64); - pub fn from_bytes(data: Vec) -> Result { - use core::serialization::FromBytes; - FromBytes::from_bytes(data) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } +impl_wasm_conversions!(core::String64, String64); - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } - - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_cbor_json_api_cbor_event_serialize!(String64); +#[wasm_bindgen] +impl String64 { pub fn get(&self) -> String { self.0.get().clone() } } -impl From for String64 { - fn from(native: core::String64) -> Self { - Self(native) - } -} - -impl From for core::String64 { - fn from(wasm: String64) -> Self { - wasm.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct String64s(pub(crate) Vec); - -#[wasm_bindgen] -impl String64s { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> String64 { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &String64) { - self.0.push(elem.clone().into()); - } -} - -impl From> for String64s { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wrapper: String64s) -> Self { - wrapper.0 - } -} +impl_wasm_list!(core::String64, String64, String64List); diff --git a/cip25/wasm/src/utils.rs b/cip25/wasm/src/utils.rs index 2b4e1e95..9413b833 100644 --- a/cip25/wasm/src/utils.rs +++ b/cip25/wasm/src/utils.rs @@ -4,7 +4,10 @@ use crate::*; use wasm_bindgen::prelude::JsError; -use cml_core_wasm::metadata::{Metadata, TransactionMetadatum}; +use cml_core_wasm::{ + impl_wasm_json_api, + metadata::{Metadata, TransactionMetadatum}, +}; #[wasm_bindgen] impl CIP25Metadata { @@ -51,6 +54,7 @@ impl ChunkableString { Self(core::ChunkableString::from(str)) } + #[allow(clippy::inherent_to_string)] pub fn to_string(&self) -> String { String::from(&self.0) } @@ -58,7 +62,11 @@ impl ChunkableString { #[derive(Clone, Debug)] #[wasm_bindgen] -pub struct MiniMetadataDetails(pub(crate) core::utils::MiniMetadataDetails); +pub struct MiniMetadataDetails(core::utils::MiniMetadataDetails); + +impl_wasm_conversions!(core::utils::MiniMetadataDetails, MiniMetadataDetails); + +impl_wasm_json_api!(MiniMetadataDetails); #[wasm_bindgen] impl MiniMetadataDetails { @@ -69,22 +77,6 @@ impl MiniMetadataDetails { }) } - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } - - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } - pub fn set_name(&mut self, name: &String64) { self.0.name = Some(name.clone().into()) } @@ -105,57 +97,21 @@ impl MiniMetadataDetails { /// `metadatum` should represent the data where the `MetadataDetails` is in the cip25 structure pub fn loose_parse(metadatum: &TransactionMetadatum) -> Result { let parsed_data = core::utils::MiniMetadataDetails::loose_parse(&metadatum.clone().into()) - .map_err(|e| JsValue::from_str(&format!("loose_parse: {}", e)))?; + .map_err(|e| JsValue::from_str(&format!("loose_parse: {e}")))?; Ok(MiniMetadataDetails(parsed_data)) } } -impl From for MiniMetadataDetails { - fn from(native: core::utils::MiniMetadataDetails) -> Self { - Self(native) - } -} - -impl From for core::utils::MiniMetadataDetails { - fn from(wasm: MiniMetadataDetails) -> Self { - wasm.0 - } -} - #[derive(Clone, Debug)] #[wasm_bindgen] pub struct LabelMetadata(core::LabelMetadata); -#[wasm_bindgen] -impl LabelMetadata { - pub fn to_bytes(&self) -> Vec { - use core::serialization::ToBytes; - ToBytes::to_bytes(&self.0) - } +impl_wasm_conversions!(core::LabelMetadata, LabelMetadata); - pub fn from_bytes(data: Vec) -> Result { - use core::serialization::FromBytes; - FromBytes::from_bytes(data) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } - - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_cbor_json_api_cbor_event_serialize!(LabelMetadata); +#[wasm_bindgen] +impl LabelMetadata { /// Note that Version 1 can only support utf8 string asset names. /// Version 2 can support any asset name. pub fn new(version: CIP25Version) -> Self { @@ -192,15 +148,3 @@ impl LabelMetadata { self.0.version() } } - -impl From for LabelMetadata { - fn from(native: core::LabelMetadata) -> Self { - Self(native) - } -} - -impl From for core::LabelMetadata { - fn from(wasm: LabelMetadata) -> Self { - wasm.0 - } -} diff --git a/cip36/rust/src/lib.rs b/cip36/rust/src/lib.rs index 9160ad0c..68b6376d 100644 --- a/cip36/rust/src/lib.rs +++ b/cip36/rust/src/lib.rs @@ -187,12 +187,10 @@ mod tests { // .derive(0) // .derive(0); // let catalyst_prv_key = hex::decode("4820f7ce221e177c8eae2b2ee5c1f1581a0d88ca5c14329d8f2389e77a465655c27662621bfb99cb9445bf8114cc2a630afd2dd53bc88c08c5f2aed8e9c7cb89").unwrap(); - let stake_cred = StakeCredential::from( - PublicKey::from_raw_hex( - "86870efc99c453a873a16492ce87738ec79a0ebd064379a62e2c9cf4e119219e", - ) - .unwrap(), - ); + let stake_cred = PublicKey::from_raw_hex( + "86870efc99c453a873a16492ce87738ec79a0ebd064379a62e2c9cf4e119219e", + ) + .unwrap(); // let stake_cred = StakeCredential::from(staking_derived_prv.to_public().to_raw_key()); let reward_address = RewardAddress::from_address( &Address::from_bech32( @@ -243,7 +241,7 @@ mod tests { reward_address, nonce, ); - let weighted_sign_data_hash = weighted_reg.hash_to_sign(false).unwrap(); + let _weighted_sign_data_hash = weighted_reg.hash_to_sign(false).unwrap(); // There are some issues with the CIP-36 test vector here. TODO: figure out whether it's the vector or the spec or us that's wrong. //assert_eq!("5bc0681f173efd76e1989037a3694b8a7abea22053f5940cbb5cfcdf721007d7", hex::encode(weighted_sign_data_hash)); diff --git a/cip36/rust/src/serialization.rs b/cip36/rust/src/serialization.rs index 326a18cb..7d72f893 100644 --- a/cip36/rust/src/serialization.rs +++ b/cip36/rust/src/serialization.rs @@ -29,7 +29,7 @@ impl Serialize for Delegation { .to_len_sz(2, force_canonical), )?; serializer.write_bytes_sz( - &self.voting_pub_key.to_raw_bytes(), + self.voting_pub_key.to_raw_bytes(), self.encodings .as_ref() .map(|encs| encs.voting_pub_key_encoding.clone()) @@ -123,7 +123,7 @@ impl Serialize for DelegationDistribution { legacy, legacy_encoding, } => serializer.write_bytes_sz( - &legacy.to_raw_bytes(), + legacy.to_raw_bytes(), legacy_encoding.to_str_len_sz(legacy.to_raw_bytes().len() as u64, force_canonical), ), } @@ -133,7 +133,7 @@ impl Serialize for DelegationDistribution { impl Deserialize for DelegationDistribution { fn deserialize(raw: &mut Deserializer) -> Result { (|| -> Result<_, DeserializeError> { - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); + let initial_position = raw.as_mut_ref().stream_position().unwrap(); match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> { let mut weighted_arr = Vec::new(); let len = raw.array_sz()?; @@ -225,7 +225,7 @@ impl Serialize for DeregistrationWitness { ), )?; serializer.write_bytes_sz( - &self.stake_witness.to_raw_bytes(), + self.stake_witness.to_raw_bytes(), self.encodings .as_ref() .map(|encs| encs.stake_witness_encoding.clone()) @@ -313,7 +313,6 @@ impl Deserialize for DeregistrationWitness { Some(x) => x, None => return Err(DeserializeFailure::MandatoryFieldMissing(Key::Uint(1)).into()), }; - (); Ok(Self { stake_witness, encodings: Some(DeregistrationWitnessEncoding { @@ -389,7 +388,7 @@ impl Serialize for KeyDeregistration { ), )?; serializer.write_bytes_sz( - &self.stake_credential.to_raw_bytes(), + self.stake_credential.to_raw_bytes(), self.encodings .as_ref() .map(|encs| encs.stake_credential_encoding.clone()) @@ -676,7 +675,7 @@ impl Serialize for KeyRegistration { ), )?; serializer.write_bytes_sz( - &self.stake_credential.to_raw_bytes(), + self.stake_credential.to_raw_bytes(), self.encodings .as_ref() .map(|encs| encs.stake_credential_encoding.clone()) @@ -966,7 +965,7 @@ impl Serialize for RegistrationWitness { ), )?; serializer.write_bytes_sz( - &self.stake_witness.to_raw_bytes(), + self.stake_witness.to_raw_bytes(), self.encodings .as_ref() .map(|encs| encs.stake_witness_encoding.clone()) @@ -1054,7 +1053,6 @@ impl Deserialize for RegistrationWitness { Some(x) => x, None => return Err(DeserializeFailure::MandatoryFieldMissing(Key::Uint(1)).into()), }; - (); Ok(Self { stake_witness, encodings: Some(RegistrationWitnessEncoding { diff --git a/cip36/wasm/Cargo.toml b/cip36/wasm/Cargo.toml index fe5cd9ee..638fb33e 100644 --- a/cip36/wasm/Cargo.toml +++ b/cip36/wasm/Cargo.toml @@ -13,6 +13,7 @@ cml-crypto = { path = "../../crypto/rust" } cml-crypto-wasm = { path = "../../crypto/wasm" } cml-chain-wasm = { path = "../../chain/wasm" } cml-core = { path = "../../core/rust" } +cml-core-wasm = { path = "../../core/wasm" } cbor_event = "2.2.0" wasm-bindgen = { version = "=0.2.83", features = ["serde-serialize"] } linked-hash-map = "0.5.3" diff --git a/cip36/wasm/src/lib.rs b/cip36/wasm/src/lib.rs index 5d8822cb..e92d4936 100644 --- a/cip36/wasm/src/lib.rs +++ b/cip36/wasm/src/lib.rs @@ -8,6 +8,8 @@ use wasm_bindgen::prelude::{wasm_bindgen, JsValue}; +use cml_core_wasm::{impl_wasm_cbor_json_api, impl_wasm_conversions, impl_wasm_json_api}; + use cml_chain_wasm::address::RewardAddress; pub mod utils; @@ -15,34 +17,12 @@ pub mod utils; #[wasm_bindgen] pub struct Delegation(cml_cip36::Delegation); -#[wasm_bindgen] -impl Delegation { - pub fn to_cbor_bytes(&self) -> Vec { - cml_core::serialization::Serialize::to_cbor_bytes(&self.0) - } - - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } +impl_wasm_cbor_json_api!(Delegation); - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_conversions!(cml_cip36::Delegation, Delegation); +#[wasm_bindgen] +impl Delegation { pub fn voting_pub_key(&self) -> VotingPubKey { self.0.voting_pub_key.clone().into() } @@ -59,56 +39,16 @@ impl Delegation { } } -impl From for Delegation { - fn from(native: cml_cip36::Delegation) -> Self { - Self(native) - } -} - -impl From for cml_cip36::Delegation { - fn from(wasm: Delegation) -> Self { - wasm.0 - } -} - -impl AsRef for Delegation { - fn as_ref(&self) -> &cml_cip36::Delegation { - &self.0 - } -} - #[derive(Clone, Debug)] #[wasm_bindgen] pub struct DelegationDistribution(cml_cip36::DelegationDistribution); -#[wasm_bindgen] -impl DelegationDistribution { - pub fn to_cbor_bytes(&self) -> Vec { - cml_core::serialization::Serialize::to_cbor_bytes(&self.0) - } - - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } +impl_wasm_cbor_json_api!(DelegationDistribution); - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_conversions!(cml_cip36::DelegationDistribution, DelegationDistribution); +#[wasm_bindgen] +impl DelegationDistribution { pub fn new_weighted(delegations: &DelegationList) -> Self { Self(cml_cip36::DelegationDistribution::new_weighted( delegations.clone().into(), @@ -147,24 +87,6 @@ impl DelegationDistribution { } } -impl From for DelegationDistribution { - fn from(native: cml_cip36::DelegationDistribution) -> Self { - Self(native) - } -} - -impl From for cml_cip36::DelegationDistribution { - fn from(wasm: DelegationDistribution) -> Self { - wasm.0 - } -} - -impl AsRef for DelegationDistribution { - fn as_ref(&self) -> &cml_cip36::DelegationDistribution { - &self.0 - } -} - #[wasm_bindgen] pub enum DelegationDistributionKind { Weighted, @@ -216,24 +138,13 @@ impl AsRef> for DelegationList { #[wasm_bindgen] pub struct DeregistrationCbor(cml_cip36::DeregistrationCbor); -#[wasm_bindgen] -impl DeregistrationCbor { - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } +// DeregistrationCbor does not implement Serialize as it may be a subset of metadata +impl_wasm_json_api!(DeregistrationCbor); - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_conversions!(cml_cip36::DeregistrationCbor, DeregistrationCbor); +#[wasm_bindgen] +impl DeregistrationCbor { pub fn key_deregistration(&self) -> KeyDeregistration { self.0.key_deregistration.clone().into() } @@ -253,56 +164,16 @@ impl DeregistrationCbor { } } -impl From for DeregistrationCbor { - fn from(native: cml_cip36::DeregistrationCbor) -> Self { - Self(native) - } -} - -impl From for cml_cip36::DeregistrationCbor { - fn from(wasm: DeregistrationCbor) -> Self { - wasm.0 - } -} - -impl AsRef for DeregistrationCbor { - fn as_ref(&self) -> &cml_cip36::DeregistrationCbor { - &self.0 - } -} - #[derive(Clone, Debug)] #[wasm_bindgen] pub struct DeregistrationWitness(cml_cip36::DeregistrationWitness); -#[wasm_bindgen] -impl DeregistrationWitness { - pub fn to_cbor_bytes(&self) -> Vec { - cml_core::serialization::Serialize::to_cbor_bytes(&self.0) - } - - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } +impl_wasm_cbor_json_api!(DeregistrationWitness); - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_conversions!(cml_cip36::DeregistrationWitness, DeregistrationWitness); +#[wasm_bindgen] +impl DeregistrationWitness { pub fn stake_witness(&self) -> StakeWitness { self.0.stake_witness.clone().into() } @@ -314,56 +185,16 @@ impl DeregistrationWitness { } } -impl From for DeregistrationWitness { - fn from(native: cml_cip36::DeregistrationWitness) -> Self { - Self(native) - } -} - -impl From for cml_cip36::DeregistrationWitness { - fn from(wasm: DeregistrationWitness) -> Self { - wasm.0 - } -} - -impl AsRef for DeregistrationWitness { - fn as_ref(&self) -> &cml_cip36::DeregistrationWitness { - &self.0 - } -} - #[derive(Clone, Debug)] #[wasm_bindgen] pub struct KeyDeregistration(cml_cip36::KeyDeregistration); -#[wasm_bindgen] -impl KeyDeregistration { - pub fn to_cbor_bytes(&self) -> Vec { - cml_core::serialization::Serialize::to_cbor_bytes(&self.0) - } - - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } +impl_wasm_cbor_json_api!(KeyDeregistration); - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_conversions!(cml_cip36::KeyDeregistration, KeyDeregistration); +#[wasm_bindgen] +impl KeyDeregistration { pub fn stake_credential(&self) -> StakeCredential { self.0.stake_credential.clone().into() } @@ -388,56 +219,16 @@ impl KeyDeregistration { } } -impl From for KeyDeregistration { - fn from(native: cml_cip36::KeyDeregistration) -> Self { - Self(native) - } -} - -impl From for cml_cip36::KeyDeregistration { - fn from(wasm: KeyDeregistration) -> Self { - wasm.0 - } -} - -impl AsRef for KeyDeregistration { - fn as_ref(&self) -> &cml_cip36::KeyDeregistration { - &self.0 - } -} - #[derive(Clone, Debug)] #[wasm_bindgen] pub struct KeyRegistration(cml_cip36::KeyRegistration); -#[wasm_bindgen] -impl KeyRegistration { - pub fn to_cbor_bytes(&self) -> Vec { - cml_core::serialization::Serialize::to_cbor_bytes(&self.0) - } - - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } +impl_wasm_cbor_json_api!(KeyRegistration); - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_conversions!(cml_cip36::KeyRegistration, KeyRegistration); +#[wasm_bindgen] +impl KeyRegistration { pub fn delegation(&self) -> DelegationDistribution { self.0.delegation.clone().into() } @@ -477,24 +268,6 @@ impl KeyRegistration { } } -impl From for KeyRegistration { - fn from(native: cml_cip36::KeyRegistration) -> Self { - Self(native) - } -} - -impl From for cml_cip36::KeyRegistration { - fn from(wasm: KeyRegistration) -> Self { - wasm.0 - } -} - -impl AsRef for KeyRegistration { - fn as_ref(&self) -> &cml_cip36::KeyRegistration { - &self.0 - } -} - pub type LegacyKeyRegistration = cml_crypto_wasm::PublicKey; pub type Nonce = u64; @@ -503,24 +276,13 @@ pub type Nonce = u64; #[wasm_bindgen] pub struct RegistrationCbor(cml_cip36::RegistrationCbor); -#[wasm_bindgen] -impl RegistrationCbor { - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } +// not implemented since RegistrationCbor doesn't implement Serialize as it's a subset of metadata +impl_wasm_json_api!(RegistrationCbor); - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_conversions!(cml_cip36::RegistrationCbor, RegistrationCbor); +#[wasm_bindgen] +impl RegistrationCbor { pub fn key_registration(&self) -> KeyRegistration { self.0.key_registration.clone().into() } @@ -540,56 +302,16 @@ impl RegistrationCbor { } } -impl From for RegistrationCbor { - fn from(native: cml_cip36::RegistrationCbor) -> Self { - Self(native) - } -} - -impl From for cml_cip36::RegistrationCbor { - fn from(wasm: RegistrationCbor) -> Self { - wasm.0 - } -} - -impl AsRef for RegistrationCbor { - fn as_ref(&self) -> &cml_cip36::RegistrationCbor { - &self.0 - } -} - #[derive(Clone, Debug)] #[wasm_bindgen] pub struct RegistrationWitness(cml_cip36::RegistrationWitness); -#[wasm_bindgen] -impl RegistrationWitness { - pub fn to_cbor_bytes(&self) -> Vec { - cml_core::serialization::Serialize::to_cbor_bytes(&self.0) - } - - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } +impl_wasm_cbor_json_api!(RegistrationWitness); - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } +impl_wasm_conversions!(cml_cip36::RegistrationWitness, RegistrationWitness); +#[wasm_bindgen] +impl RegistrationWitness { pub fn stake_witness(&self) -> StakeWitness { self.0.stake_witness.clone().into() } @@ -601,24 +323,6 @@ impl RegistrationWitness { } } -impl From for RegistrationWitness { - fn from(native: cml_cip36::RegistrationWitness) -> Self { - Self(native) - } -} - -impl From for cml_cip36::RegistrationWitness { - fn from(wasm: RegistrationWitness) -> Self { - wasm.0 - } -} - -impl AsRef for RegistrationWitness { - fn as_ref(&self) -> &cml_cip36::RegistrationWitness { - &self.0 - } -} - pub type StakeCredential = cml_crypto_wasm::PublicKey; pub type StakeWitness = cml_crypto_wasm::Ed25519Signature; diff --git a/core/rust/src/metadata.rs b/core/rust/src/metadata.rs index 9b9ab1e8..39a7bc50 100644 --- a/core/rust/src/metadata.rs +++ b/core/rust/src/metadata.rs @@ -28,6 +28,10 @@ impl Metadata { self.entries.len() } + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + /// Replaces all metadatums of a given label, if any exist. pub fn set(&mut self, label: TransactionMetadatumLabel, datum: TransactionMetadatum) { self.entries.retain(|(l, _)| *l != label); @@ -168,6 +172,10 @@ impl MetadatumMap { self.entries.len() } + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + /// Replaces all metadatums of a given key, if any exist. pub fn set(&mut self, key: TransactionMetadatum, datum: TransactionMetadatum) { self.entries.retain(|(k, _)| *k != key); diff --git a/core/rust/src/ordered_hash_map.rs b/core/rust/src/ordered_hash_map.rs index fac8ff00..c3008308 100644 --- a/core/rust/src/ordered_hash_map.rs +++ b/core/rust/src/ordered_hash_map.rs @@ -1,5 +1,7 @@ use core::hash::{Hash, Hasher}; +// allowing this since PartialEq equality here still implies hash equality +#[allow(clippy::derive_hash_xor_eq)] #[derive(Clone, Debug, Ord, Eq, PartialEq, PartialOrd)] pub struct OrderedHashMap(linked_hash_map::LinkedHashMap) where @@ -47,6 +49,7 @@ where } } +#[allow(clippy::derive_hash_xor_eq)] impl Hash for OrderedHashMap where K: Hash + Eq + Ord, diff --git a/core/wasm/src/wasm_wrappers.rs b/core/wasm/src/wasm_wrappers.rs index aaf3dc89..ff61be01 100644 --- a/core/wasm/src/wasm_wrappers.rs +++ b/core/wasm/src/wasm_wrappers.rs @@ -12,6 +12,7 @@ macro_rules! impl_wasm_conversions { } } + #[allow(clippy::from_over_into)] impl Into<$rust> for $wasm { fn into(self) -> $rust { self.0 @@ -26,6 +27,35 @@ macro_rules! impl_wasm_conversions { }; } +/// This shouldn't be explicitly called - only via impl_wasm_list!() +/// We use this to get around restrictions in outer macros evaluating before inner macros +/// which breaks wasm_bindgen's parameter parsing resulting in FromWasmAbi on &T instead +/// See comment for impl_wasm_map_insert_get! for more context +#[macro_export] +macro_rules! impl_wasm_list_add { + ($rust_elem_name:ty, $wasm_elem_name:ty, $wasm_list_name:ident, false) => { + #[wasm_bindgen::prelude::wasm_bindgen] + impl $wasm_list_name { + pub fn add(&mut self, elem: &$wasm_elem_name) { + self.0.push(elem.clone().into()); + } + } + }; + ($rust_elem_name:ty, $wasm_elem_name:ty, $wasm_list_name:ident, true) => { + #[wasm_bindgen::prelude::wasm_bindgen] + impl $wasm_list_name { + pub fn add(&mut self, elem: $wasm_elem_name) { + self.0.push(elem); + } + } + }; +} + +// TODO: when/if concat_idents! leaves nightly/experimental +// make the default case for impl_wasm_list! / impl_wasm_map! +// not take in the name and instead derive it by appending List +// since that is what we do in virtually all cases anyway. + /// Convenience creator for generic WASM-exposable list /// This is exactly as the ones created by cddl-codegen /// so it is useful for utility functionality where those @@ -33,6 +63,15 @@ macro_rules! impl_wasm_conversions { #[macro_export] macro_rules! impl_wasm_list { ($rust_elem_name:ty, $wasm_elem_name:ty, $wasm_list_name:ident) => { + impl_wasm_list!( + $rust_elem_name, + $wasm_elem_name, + $wasm_list_name, + false, + false + ); + }; + ($rust_elem_name:ty, $wasm_elem_name:ty, $wasm_list_name:ident, $elem_wasm_abi:tt, $elem_copy:tt) => { #[wasm_bindgen::prelude::wasm_bindgen] #[derive(Debug, Clone)] pub struct $wasm_list_name(Vec<$rust_elem_name>); @@ -48,34 +87,225 @@ macro_rules! impl_wasm_list { } pub fn get(&self, index: usize) -> $wasm_elem_name { - self.0[index].clone().into() + $crate::wasm_val_into!( + $crate::wasm_val_clone!(self.0[index], $elem_copy), + $elem_wasm_abi + ) } + } - pub fn add(&mut self, elem: &$wasm_elem_name) { - self.0.push(elem.clone().into()); + $crate::impl_wasm_list_add!( + $rust_elem_name, + $wasm_elem_name, + $wasm_list_name, + $elem_wasm_abi + ); + + $crate::impl_wasm_conversions!(Vec<$rust_elem_name>, $wasm_list_name); + }; +} + +/// This shouldn't be explicitly called - only via impl_wasm_* macros here +/// expression, e is Copy +#[macro_export] +macro_rules! wasm_val_clone { + ($e:expr, true) => { + $e + }; + ($e:expr, false) => { + $e.clone() + }; +} + +/// This shouldn't be explicitly called - only via impl_wasm_* macros here +/// expression, e is wasm-exposable +#[macro_export] +macro_rules! wasm_val_into { + ($e:expr, true) => { + $e + }; + ($e:expr, false) => { + $e.into() + }; +} + +/// This shouldn't be explicitly called - only via impl_wasm_* macros here +/// expression, e is wasm-exposable +#[macro_export] +macro_rules! wasm_val_map_into { + ($e:expr, true) => { + $e + }; + ($e:expr, false) => { + $e.map(Into::into) + }; +} + +/// This shouldn't be explicitly called - only via impl_wasm_* macros here +/// expression, e is Copy +#[macro_export] +macro_rules! wasm_copied_or_cloned { + ($e:expr, true) => { + $e.copied() + }; + ($e:expr, false) => { + $e.cloned() + }; +} + +/// This shouldn't be explicitly called - only via impl_wasm_* macros here +/// This is here due to problems with AsRef vs & in impl_wasm_get +/// expression, e is wasm-exposable +#[macro_export] +macro_rules! wasm_as_ref { + ($e:expr, false) => { + $e.as_ref() + }; + ($e:expr, true) => { + &$e + }; +} + +/// This shouldn't be explicitly called - only via impl_wasm_* macros here +#[macro_export] +macro_rules! impl_wasm_map_get { + ($self:ident, $key:ident, $key_wasm_abi:tt, $val_wasm_abi:tt, $val_copy:tt, $rust_key:ty) => { + $crate::wasm_val_map_into!( + $crate::wasm_copied_or_cloned!( + $self + .0 + .get::<$rust_key>($crate::wasm_as_ref!($key, $key_wasm_abi)), + $val_copy + ), + $val_wasm_abi + ) + }; +} + +/// This shouldn't be explicitly called - only via impl_wasm_* macros here +#[macro_export] +macro_rules! impl_wasm_map_insert { + ($self:ident, $key:ident, $value:ident, $key_wasm_abi:tt, $val_wasm_abi:tt) => { + $crate::wasm_val_map_into!( + $self.0.insert( + $crate::wasm_val_into!($crate::wasm_val_clone!($key, $key_wasm_abi), $key_wasm_abi), + $crate::wasm_val_into!( + $crate::wasm_val_clone!($value, $val_wasm_abi), + $val_wasm_abi + ) + ), + $val_wasm_abi + ) + }; +} + +/// This shouldn't be explicitly called - only via impl_wasm_map!() +/// We use this to get around restrictions in outer macros evaluating before inner macros +/// which breaks wasm_bindgen's parameter parsing resulting in FromWasmAbi on &T instead +/// of RefFromWasmAbi on T being used. +/// This happened when these were inlined directly in impl_wasm_map!() e.g.: +/// +/// #[macro_export] +/// macro_rules! wasm_type_param { +/// ($wasm_type:ty, true) => { +/// $wasm_type +/// }; +/// ($wasm_type:ty, false) => { +/// &$wasm_type +/// }; +/// } +/// +/// Then used within the impl of the wasm_bindgen map: +/// +/// pub fn get(&self, key: $crate::wasm_type_param!($wasm_key, $key_wasm_abi)) -> Option<$wasm_value> { +/// $crate::wasm_option_return!( +/// self.0.get(key.as_ref()), +/// $val_wasm_abi) +/// } +/// pub fn insert( +/// &mut self, +/// key: $crate::wasm_type_param!($wasm_key, $key_wasm_abi), +/// value: $crate::wasm_type_param!($wasm_value, $val_wasm_abi) +/// ) -> Option<$wasm_value> { +/// self.0.insert( +/// $crate::wasm_val_clone!(key, $key_wasm_abi), +/// $crate::wasm_val_clone!(value, $val_wasm_abi)) +/// } +#[macro_export] +macro_rules! impl_wasm_map_insert_get { + ($rust_key:ty, $wasm_key:ty, $wasm_value:ty, $wasm_map_name:ident, false, false, $key_copy:tt, $val_copy:tt) => { + #[wasm_bindgen::prelude::wasm_bindgen] + impl $wasm_map_name { + pub fn get(&self, key: &$wasm_key) -> Option<$wasm_value> { + $crate::impl_wasm_map_get!(self, key, false, false, $val_copy, $rust_key) + } + + pub fn insert(&mut self, key: &$wasm_key, value: &$wasm_value) -> Option<$wasm_value> { + $crate::impl_wasm_map_insert!(self, key, value, false, false) } } + }; + ($rust_key:ty, $wasm_key:ty, $wasm_value:ty, $wasm_map_name:ident, false, true, $key_copy:tt, $val_copy:tt) => { + #[wasm_bindgen::prelude::wasm_bindgen] + impl $wasm_map_name { + pub fn get(&self, key: &$wasm_key) -> Option<$wasm_value> { + $crate::impl_wasm_map_get!(self, key, false, true, $val_copy, $rust_key) + } - impl From> for $wasm_list_name { - fn from(native: Vec<$rust_elem_name>) -> Self { - Self(native) + pub fn insert(&mut self, key: &$wasm_key, value: $wasm_value) -> Option<$wasm_value> { + $crate::impl_wasm_map_insert!(self, key, value, false, true) } } + }; + ($rust_key:ty, $wasm_key:ty, $wasm_value:ty, $wasm_map_name:ident, true, false, $key_copy:tt, $val_copy:tt) => { + #[wasm_bindgen::prelude::wasm_bindgen] + impl $wasm_map_name { + pub fn get(&self, key: $wasm_key) -> Option<$wasm_value> { + $crate::impl_wasm_map_get!(self, key, true, false, $val_copy, $rust_key) + } - impl From<$wasm_list_name> for Vec<$rust_elem_name> { - fn from(wasm: $wasm_list_name) -> Self { - wasm.0 + pub fn insert(&mut self, key: $wasm_key, value: &$wasm_value) -> Option<$wasm_value> { + $crate::impl_wasm_map_insert!(self, key, value, true, false) } } + }; + ($rust_key:ty, $wasm_key:ty, $wasm_value:ty, $wasm_map_name:ident, true, true, $key_copy:tt, $val_copy:tt) => { + #[wasm_bindgen::prelude::wasm_bindgen] + impl $wasm_map_name { + pub fn get(&self, key: $wasm_key) -> Option<$wasm_value> { + $crate::impl_wasm_map_get!(self, key, true, true, $val_copy, $rust_key) + } - impl AsRef> for $wasm_list_name { - fn as_ref(&self) -> &Vec<$rust_elem_name> { - &self.0 + pub fn insert(&mut self, key: $wasm_key, value: $wasm_value) -> Option<$wasm_value> { + $crate::impl_wasm_map_insert!(self, key, value, true, true) } } }; } +/// Useful for Byron/cip25/etc where we don't use OrderedHashMap +#[macro_export] +macro_rules! impl_wasm_map_btree { + ($rust_key:ty, $rust_value:ty, $wasm_key:ty, $wasm_value:ty, $wasm_key_list:ty, $wasm_map_name:ident) => { + impl_wasm_map_btree!($rust_key, $rust_value, $wasm_key, $wasm_value, $wasm_key_list, $wasm_map_name, false, false, false, false); + }; + ($rust_key:ty, $rust_value:ty, $wasm_key:ty, $wasm_value:ty, $wasm_key_list:ty, $wasm_map_name:ident, $key_wasm_abi:tt, $val_wasm_abi:tt, $key_copy:tt, $val_copy:tt) => { + $crate::impl_wasm_map!( + $rust_key, + $rust_value, + $wasm_key, + $wasm_value, + $wasm_key_list, + $wasm_map_name, + $key_wasm_abi, + $val_wasm_abi, + $key_copy, + $val_copy, + std::collections::BTreeMap<$rust_key, $rust_value> + ); + }; +} + /// Convenience creator for generic WASM-exposable map /// This is exactly as the ones created by cddl-codegen /// so it is useful for utility functionality where those @@ -83,89 +313,144 @@ macro_rules! impl_wasm_list { #[macro_export] macro_rules! impl_wasm_map { ($rust_key:ty, $rust_value:ty, $wasm_key:ty, $wasm_value:ty, $wasm_key_list:ty, $wasm_map_name:ident) => { + impl_wasm_map!($rust_key, $rust_value, $wasm_key, $wasm_value, $wasm_key_list, $wasm_map_name, false, false, false, false); + }; + ($rust_key:ty, $rust_value:ty, $wasm_key:ty, $wasm_value:ty, $wasm_key_list:ty, $wasm_map_name:ident, $key_wasm_abi:tt, $val_wasm_abi:tt, $key_copy:tt, $val_copy:tt) => { + impl_wasm_map!( + $rust_key, + $rust_value, + $wasm_key, + $wasm_value, + $wasm_key_list, + $wasm_map_name, + $key_wasm_abi, + $val_wasm_abi, + $key_copy, + $val_copy, + cml_core::ordered_hash_map::OrderedHashMap<$rust_key, $rust_value> + ); + }; + ($rust_key:ty, $rust_value:ty, $wasm_key:ty, $wasm_value:ty, $wasm_key_list:ty, $wasm_map_name:ident, $key_wasm_abi:tt, $val_wasm_abi:tt, $key_copy:tt, $val_copy:tt, $map_type:ty) => { #[wasm_bindgen::prelude::wasm_bindgen] #[derive(Debug, Clone)] - pub struct $wasm_map_name( - cml_core::ordered_hash_map::OrderedHashMap<$rust_key, $rust_value>, + pub struct $wasm_map_name($map_type); + + $crate::impl_wasm_map_insert_get!( + $rust_key, + $wasm_key, + $wasm_value, + $wasm_map_name, + $key_wasm_abi, + $val_wasm_abi, + $key_copy, + $val_copy ); #[wasm_bindgen::prelude::wasm_bindgen] impl $wasm_map_name { pub fn new() -> Self { - Self(cml_core::ordered_hash_map::OrderedHashMap::new()) + Self(<$map_type>::new()) } pub fn len(&self) -> usize { self.0.len() } - pub fn insert(&mut self, key: &$wasm_key, value: $wasm_value) -> Option<$wasm_value> { - self.0.insert(key.clone().into(), value) - } - - pub fn get(&self, key: &$wasm_key) -> Option<$wasm_value> { - self.0.get(key.as_ref()).cloned() + pub fn is_empty(&self) -> bool { + self.0.is_empty() } pub fn keys(&self) -> $wasm_key_list { - self.0 - .iter() - .map(|(k, _v)| k.clone()) + $crate::wasm_copied_or_cloned!( + self.0.keys(), + $key_copy) .collect::>() .into() } } - impl From> - for $wasm_map_name - { - fn from( - native: cml_core::ordered_hash_map::OrderedHashMap<$rust_key, $rust_value>, - ) -> Self { - Self(native) - } - } + $crate::impl_wasm_conversions!( + $map_type, + $wasm_map_name + ); + }; +} - impl From<$wasm_map_name> - for cml_core::ordered_hash_map::OrderedHashMap<$rust_key, $rust_value> - { - fn from(wasm: $wasm_map_name) -> Self { - wasm.0 +#[macro_export] +macro_rules! impl_wasm_cbor_json_api { + ($wasm_name:ident) => { + $crate::impl_wasm_cbor_api!($wasm_name); + $crate::impl_wasm_json_api!($wasm_name); + }; +} + +/// We use this instead of cml_core::impl_wasm_cbor_json_api for types that do not implement +/// cml's Serialize. e.g. CIP25/Byron just do cbor_event's due to not supporting preserve-encodings=true +/// All other methods are identical to impl_wasm_cbor_json_api though. +#[macro_export] +macro_rules! impl_wasm_cbor_json_api_cbor_event_serialize { + ($wasm_name:ident) => { + $crate::impl_wasm_cbor_event_serialize_api!($wasm_name); + $crate::impl_wasm_json_api!($wasm_name); + }; +} + +/// Implements to/from CBOR bytes API for WASM wrappers using CML's Serialize +/// i.e. it remembers encodings +#[macro_export] +macro_rules! impl_wasm_cbor_api { + ($wasm_name:ident) => { + #[wasm_bindgen::prelude::wasm_bindgen] + impl $wasm_name { + pub fn to_cbor_bytes(&self) -> Vec { + cml_core::serialization::Serialize::to_cbor_bytes(&self.0) } - } - impl AsRef> - for $wasm_map_name - { - fn as_ref( - &self, - ) -> &cml_core::ordered_hash_map::OrderedHashMap<$rust_key, $rust_value> { - &self.0 + pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result<$wasm_name, JsValue> { + cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) + .map(Self) + .map_err(|e| { + JsValue::from_str(&format!( + concat!(stringify!($wasm_name), "::from_bytes: {}"), + e + )) + }) } } }; } +/// Implements to/from CBOR bytes API for WASM wrappers using cbor_event's Serialize +/// i.e. it does not remember encodings #[macro_export] -macro_rules! impl_wasm_cbor_json_api { +macro_rules! impl_wasm_cbor_event_serialize_api { ($wasm_name:ident) => { #[wasm_bindgen::prelude::wasm_bindgen] impl $wasm_name { pub fn to_cbor_bytes(&self) -> Vec { - cml_chain::serialization::Serialize::to_cbor_bytes(&self.0) + cml_core::serialization::ToBytes::to_bytes(&self.0) } pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result<$wasm_name, JsValue> { - cml_chain::serialization::Deserialize::from_cbor_bytes(cbor_bytes) + cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) .map(Self) .map_err(|e| { JsValue::from_str(&format!( - concat!(stringify!($wasm_name), "::from_bytes: {}"), + concat!(stringify!($wasm_name), "::from_cbor_bytes: {}"), e )) }) } + } + }; +} +/// Implements the to/from JSON + JS object API for WASM wrappers +#[macro_export] +macro_rules! impl_wasm_json_api { + ($wasm_name:ident) => { + #[wasm_bindgen::prelude::wasm_bindgen] + impl $wasm_name { pub fn to_json(&self) -> Result { serde_json::to_string_pretty(&self.0).map_err(|e| { JsValue::from_str(&format!( diff --git a/crypto/rust/src/chain_core/abor.rs b/crypto/rust/src/chain_core/abor.rs index 550a75e4..b2b80b97 100644 --- a/crypto/rust/src/chain_core/abor.rs +++ b/crypto/rust/src/chain_core/abor.rs @@ -148,6 +148,12 @@ impl Encoder { } } +impl Default for Encoder { + fn default() -> Self { + Self::new() + } +} + /// Create a decoder on some data pub struct Decoder<'a> { slice: &'a [u8], @@ -170,7 +176,6 @@ impl<'a> Decoder<'a> { Decoder { slice: data } } - #[must_use] fn pop(&mut self) -> Result { if !self.slice.is_empty() { let v = self.slice[0]; @@ -181,7 +186,6 @@ impl<'a> Decoder<'a> { } } - #[must_use] fn expect_tag(&mut self, tag: Tag) -> Result<(), DecodeError> { let t = self.pop()?; match Tag::from_u8(t) { @@ -191,7 +195,6 @@ impl<'a> Decoder<'a> { } } - #[must_use] fn expect_size(&self, nb_bytes: usize) -> Result<(), DecodeError> { if nb_bytes <= self.slice.len() { Ok(()) @@ -203,27 +206,23 @@ impl<'a> Decoder<'a> { } } - #[must_use] fn expect_tag_size(&mut self, tag: Tag, nb_bytes: usize) -> Result<(), DecodeError> { self.expect_tag(tag)?; self.expect_size(nb_bytes) } - #[must_use] pub fn array(&mut self) -> Result { self.expect_tag_size(Tag::Array, 1)?; let len = self.pop()?; Ok(len as usize) } - #[must_use] pub fn u8(&mut self) -> Result { self.expect_tag_size(Tag::U8, 1)?; let len = self.pop()?; Ok(len) } - #[must_use] pub fn u16(&mut self) -> Result { self.expect_tag_size(Tag::U16, 2)?; let v = { @@ -235,7 +234,6 @@ impl<'a> Decoder<'a> { Ok(v) } - #[must_use] pub fn u32(&mut self) -> Result { self.expect_tag_size(Tag::U32, 2)?; let v = { @@ -247,7 +245,6 @@ impl<'a> Decoder<'a> { Ok(v) } - #[must_use] pub fn u64(&mut self) -> Result { self.expect_tag_size(Tag::U64, 8)?; let v = { @@ -259,7 +256,6 @@ impl<'a> Decoder<'a> { Ok(v) } - #[must_use] pub fn u128(&mut self) -> Result { self.expect_tag_size(Tag::U128, 16)?; let v = { @@ -271,7 +267,6 @@ impl<'a> Decoder<'a> { Ok(v) } - #[must_use] pub fn bytes(&mut self) -> Result, DecodeError> { self.expect_tag_size(Tag::Bytes, 1)?; let len = self.pop()? as usize; @@ -282,7 +277,6 @@ impl<'a> Decoder<'a> { Ok(v.into()) } - #[must_use] pub fn end(self) -> Result<(), DecodeError> { if self.slice.is_empty() { Ok(()) @@ -300,7 +294,7 @@ mod tests { #[test] pub fn serialize_unit1() { - let v = 0xf1235_fc; + let v = 0xf12_35fc; let e = Encoder::new().u32(v).finalize(); let mut d = Decoder::new(&e); let ev = d.u32().unwrap(); diff --git a/crypto/rust/src/chain_core/mempack.rs b/crypto/rust/src/chain_core/mempack.rs index 896f2bbf..89102b96 100644 --- a/crypto/rust/src/chain_core/mempack.rs +++ b/crypto/rust/src/chain_core/mempack.rs @@ -30,6 +30,12 @@ impl WriteBuf { } } +impl Default for WriteBuf { + fn default() -> Self { + Self::new() + } +} + #[derive(Debug, Clone, PartialEq, Eq)] pub enum ReadError { /// Return the number of bytes left and the number of bytes demanded @@ -225,18 +231,18 @@ impl<'a> ReadBuf<'a> { } pub trait Readable: Sized { - fn read<'a>(buf: &mut ReadBuf<'a>) -> Result; + fn read(buf: &mut ReadBuf) -> Result; - fn read_validate<'a>(buf: &mut ReadBuf<'a>) -> Result<(), ReadError> { + fn read_validate(buf: &mut ReadBuf) -> Result<(), ReadError> { Self::read(buf).map(|_| ()) } } impl Readable for () { - fn read<'a>(_: &mut ReadBuf<'a>) -> Result<(), ReadError> { + fn read(_: &mut ReadBuf) -> Result<(), ReadError> { Ok(()) } - fn read_validate<'a>(buf: &mut ReadBuf<'a>) -> Result<(), ReadError> { + fn read_validate(buf: &mut ReadBuf) -> Result<(), ReadError> { Self::read(buf) } } @@ -244,7 +250,7 @@ impl Readable for () { macro_rules! read_prim_impl { ($Ty: ty, $meth: ident) => { impl Readable for $Ty { - fn read<'a>(buf: &mut ReadBuf<'a>) -> Result { + fn read(buf: &mut ReadBuf) -> Result { buf.$meth() } } @@ -261,7 +267,7 @@ macro_rules! read_array_impls { ($($N: expr)+) => { $( impl Readable for [u8; $N] { - fn read<'a>(readbuf: &mut ReadBuf<'a>) -> Result { + fn read(readbuf: &mut ReadBuf) -> Result { let mut buf = [0u8; $N]; buf.copy_from_slice(readbuf.get_slice($N)?); Ok(buf) @@ -276,7 +282,7 @@ read_array_impls! { } /// read N times for a T elements in sequences -pub fn read_vec<'a, T: Readable>(readbuf: &mut ReadBuf<'a>, n: usize) -> Result, ReadError> { +pub fn read_vec(readbuf: &mut ReadBuf, n: usize) -> Result, ReadError> { let mut v = Vec::with_capacity(n); for _ in 0..n { let t = T::read(readbuf)?; @@ -286,13 +292,10 @@ pub fn read_vec<'a, T: Readable>(readbuf: &mut ReadBuf<'a>, n: usize) -> Result< } /// Fill a mutable slice with as many T as filling requires -pub fn read_mut_slice<'a, T: Readable>( - readbuf: &mut ReadBuf<'a>, - v: &mut [T], -) -> Result<(), ReadError> { - for i in 0..v.len() { +pub fn read_mut_slice(readbuf: &mut ReadBuf, v: &mut [T]) -> Result<(), ReadError> { + for elem in v.iter_mut() { let t = T::read(readbuf)?; - v[i] = t + *elem = t } Ok(()) } @@ -301,19 +304,15 @@ pub fn read_mut_slice<'a, T: Readable>( pub fn read_from_raw(raw: &[u8]) -> Result { let mut rbuf = ReadBuf::from(raw); match T::read(&mut rbuf) { - Err(e) => { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("invalid data {e:?} {raw:?}"), - )); - } + Err(e) => Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("invalid data {e:?} {raw:?}"), + )), Ok(h) => match rbuf.expect_end() { - Err(e) => { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("end of data {e:?}"), - )); - } + Err(e) => Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("end of data {e:?}"), + )), Ok(()) => Ok(h), }, } diff --git a/crypto/rust/src/chain_core/property.rs b/crypto/rust/src/chain_core/property.rs index 33870653..2ab0fc18 100644 --- a/crypto/rust/src/chain_core/property.rs +++ b/crypto/rust/src/chain_core/property.rs @@ -226,10 +226,10 @@ pub trait Ledger: Sized { /// Ledger's errors type Error: std::error::Error; - fn input<'a, I>( - &'a self, + fn input( + &self, input: ::Input, - ) -> Result<&'a ::Output, Self::Error>; + ) -> Result<&::Output, Self::Error>; } /// Trait identifying the leader identifier type. diff --git a/crypto/rust/src/chain_crypto/digest.rs b/crypto/rust/src/chain_crypto/digest.rs index c04e3fbd..ab111f39 100644 --- a/crypto/rust/src/chain_crypto/digest.rs +++ b/crypto/rust/src/chain_crypto/digest.rs @@ -164,6 +164,12 @@ impl Context { } } +impl Default for Context { + fn default() -> Self { + Self::new() + } +} + pub struct Digest(H::DigestData); impl Clone for Digest { @@ -279,6 +285,7 @@ impl fmt::Debug for Digest { impl Digest { /// Get the digest of a slice of data + #[allow(clippy::self_named_constructors)] pub fn digest(slice: &[u8]) -> Self { let mut ctx = Context::new(); ctx.append_data(slice); @@ -386,7 +393,7 @@ impl DigestOf { } } - pub fn digest_byteslice<'a>(byteslice: &ByteSlice<'a, T>) -> Self { + pub fn digest_byteslice(byteslice: &ByteSlice) -> Self { let mut ctx = Context::new(); ctx.append_data(byteslice.as_slice()); DigestOf { diff --git a/crypto/rust/src/chain_crypto/hash.rs b/crypto/rust/src/chain_crypto/hash.rs index ca1b0767..51416587 100644 --- a/crypto/rust/src/chain_crypto/hash.rs +++ b/crypto/rust/src/chain_crypto/hash.rs @@ -100,6 +100,8 @@ macro_rules! define_hash_object { $constructor(bytes) } } + // allow since both act on the raw bytes + #[allow(clippy::derive_hash_xor_eq)] impl Hash for $hash_ty { fn hash(&self, state: &mut H) { self.0.hash(state) diff --git a/crypto/rust/src/impl_mockchain/key.rs b/crypto/rust/src/impl_mockchain/key.rs index dd87116a..042b2145 100644 --- a/crypto/rust/src/impl_mockchain/key.rs +++ b/crypto/rust/src/impl_mockchain/key.rs @@ -83,9 +83,7 @@ pub fn serialize_signature( writer.write_all(signature.as_ref()) } #[inline] -pub fn deserialize_public_key<'a, A>( - buf: &mut ReadBuf<'a>, -) -> Result, ReadError> +pub fn deserialize_public_key(buf: &mut ReadBuf) -> Result, ReadError> where A: AsymmetricPublicKey, { @@ -94,9 +92,7 @@ where crypto::PublicKey::from_binary(&bytes).map_err(chain_crypto_pub_err) } #[inline] -pub fn deserialize_signature<'a, A, T>( - buf: &mut ReadBuf<'a>, -) -> Result, ReadError> +pub fn deserialize_signature(buf: &mut ReadBuf) -> Result, ReadError> where A: VerificationAlgorithm, { @@ -165,7 +161,7 @@ where } impl Readable for Signed { - fn read<'a>(buf: &mut ReadBuf<'a>) -> Result { + fn read(buf: &mut ReadBuf) -> Result { Ok(Signed { data: T::read(buf)?, sig: deserialize_signature(buf)?, diff --git a/crypto/rust/src/lib.rs b/crypto/rust/src/lib.rs index d2960445..0ce9d5fb 100644 --- a/crypto/rust/src/lib.rs +++ b/crypto/rust/src/lib.rs @@ -482,6 +482,8 @@ macro_rules! impl_signature { } } + // allow since both act on the raw bytes + #[allow(clippy::derive_hash_xor_eq)] impl std::hash::Hash for $name { fn hash(&self, state: &mut H) { self.0.as_ref().hash(state) diff --git a/crypto/rust/src/typed_bytes/builder.rs b/crypto/rust/src/typed_bytes/builder.rs index 594fa9ed..898ecc90 100644 --- a/crypto/rust/src/typed_bytes/builder.rs +++ b/crypto/rust/src/typed_bytes/builder.rs @@ -93,6 +93,7 @@ impl ByteBuilder { l.fold(bb, f) } + #[allow(clippy::should_implement_trait)] pub fn sub(self, f: F) -> Self where F: Fn(ByteBuilder) -> ByteBuilder, @@ -152,3 +153,9 @@ impl ByteBuilder { self.buffer } } + +impl Default for ByteBuilder { + fn default() -> Self { + Self::new() + } +} diff --git a/multi-era/rust/src/allegra/serialization.rs b/multi-era/rust/src/allegra/serialization.rs index 4ba6d6ac..673a12ac 100644 --- a/multi-era/rust/src/allegra/serialization.rs +++ b/multi-era/rust/src/allegra/serialization.rs @@ -32,7 +32,7 @@ impl Serialize for AllegraAuxiliaryData { impl Deserialize for AllegraAuxiliaryData { fn deserialize(raw: &mut Deserializer) -> Result { (|| -> Result<_, DeserializeError> { - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); + let initial_position = raw.as_mut_ref().stream_position().unwrap(); let deser_variant: Result<_, DeserializeError> = ShelleyAuxData::deserialize(raw); match deser_variant { Ok(shelley_aux_data) => return Ok(Self::ShelleyAuxData(shelley_aux_data)), @@ -590,7 +590,7 @@ impl Serialize for AllegraTransactionBody { ), )?; serializer.write_bytes_sz( - &field.to_raw_bytes(), + field.to_raw_bytes(), self.encodings .as_ref() .map(|encs| encs.auxiliary_data_hash_encoding.clone()) diff --git a/multi-era/rust/src/alonzo/serialization.rs b/multi-era/rust/src/alonzo/serialization.rs index 532e41df..dd75f47d 100644 --- a/multi-era/rust/src/alonzo/serialization.rs +++ b/multi-era/rust/src/alonzo/serialization.rs @@ -34,7 +34,7 @@ impl Serialize for AlonzoAuxiliaryData { impl Deserialize for AlonzoAuxiliaryData { fn deserialize(raw: &mut Deserializer) -> Result { (|| -> Result<_, DeserializeError> { - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); + let initial_position = raw.as_mut_ref().stream_position().unwrap(); let deser_variant: Result<_, DeserializeError> = ShelleyAuxData::deserialize(raw); match deser_variant { Ok(shelley) => return Ok(Self::Shelley(shelley)), @@ -423,7 +423,6 @@ impl Deserialize for AlonzoCostmdls { Some(x) => x, None => return Err(DeserializeFailure::MandatoryFieldMissing(Key::Uint(0)).into()), }; - (); Ok(Self { plutus_v1, encodings: Some(AlonzoCostmdlsEncoding { @@ -2384,7 +2383,7 @@ impl Serialize for AlonzoTransactionBody { ), )?; serializer.write_bytes_sz( - &field.to_raw_bytes(), + field.to_raw_bytes(), self.encodings .as_ref() .map(|encs| encs.auxiliary_data_hash_encoding.clone()) @@ -2450,7 +2449,7 @@ impl Serialize for AlonzoTransactionBody { .cloned() .unwrap_or_default(); buf.write_bytes_sz( - &k.to_raw_bytes(), + k.to_raw_bytes(), mint_key_encoding.to_str_len_sz( k.to_raw_bytes().len() as u64, force_canonical, @@ -2516,7 +2515,7 @@ impl Serialize for AlonzoTransactionBody { serializer.write_negative_integer_sz( *value as i128, fit_sz( - (*value + 1).abs() as u64, + (*value + 1).unsigned_abs(), mint_value_value_encoding, force_canonical, ), @@ -2546,7 +2545,7 @@ impl Serialize for AlonzoTransactionBody { ), )?; serializer.write_bytes_sz( - &field.to_raw_bytes(), + field.to_raw_bytes(), self.encodings .as_ref() .map(|encs| encs.script_data_hash_encoding.clone()) @@ -2613,7 +2612,7 @@ impl Serialize for AlonzoTransactionBody { .cloned() .unwrap_or_default(); serializer.write_bytes_sz( - &element.to_raw_bytes(), + element.to_raw_bytes(), required_signers_elem_encoding.to_str_len_sz( element.to_raw_bytes().len() as u64, force_canonical, @@ -3115,7 +3114,7 @@ impl Serialize for AlonzoTransactionOutput { impl Deserialize for AlonzoTransactionOutput { fn deserialize(raw: &mut Deserializer) -> Result { (|| -> Result<_, DeserializeError> { - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); + let initial_position = raw.as_mut_ref().stream_position().unwrap(); let deser_variant: Result<_, DeserializeError> = ShelleyTxOut::deserialize(raw); match deser_variant { Ok(shelley_tx_out) => return Ok(Self::ShelleyTxOut(shelley_tx_out)), @@ -3702,7 +3701,7 @@ impl Serialize for AlonzoUpdate { .cloned() .unwrap_or_default(); buf.write_bytes_sz( - &k.to_raw_bytes(), + k.to_raw_bytes(), proposed_protocol_parameter_updates_key_encoding .to_str_len_sz(k.to_raw_bytes().len() as u64, force_canonical), )?; diff --git a/multi-era/rust/src/byron/block/serialization.rs b/multi-era/rust/src/byron/block/serialization.rs index 68ba6245..71411916 100644 --- a/multi-era/rust/src/byron/block/serialization.rs +++ b/multi-era/rust/src/byron/block/serialization.rs @@ -25,7 +25,7 @@ impl cbor_event::se::Serialize for BlockHeaderExtraData { key.serialize(serializer)?; value.serialize(serializer)?; } - serializer.write_bytes(&self.extra_proof.to_raw_bytes())?; + serializer.write_bytes(self.extra_proof.to_raw_bytes())?; Ok(serializer) } } @@ -108,7 +108,7 @@ impl cbor_event::se::Serialize for ByronBlock { impl Deserialize for ByronBlock { fn deserialize(raw: &mut Deserializer) -> Result { (|| -> Result<_, DeserializeError> { - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); + let initial_position = raw.as_mut_ref().stream_position().unwrap(); let mut errs = Vec::new(); let deser_variant: Result<_, DeserializeError> = ByronEbBlock::deserialize(raw); match deser_variant { @@ -278,7 +278,7 @@ impl cbor_event::se::Serialize for ByronBlockHeader { ) -> cbor_event::Result<&'se mut Serializer> { serializer.write_array(cbor_event::Len::Len(5))?; serializer.write_unsigned_integer(self.protocol_magic as u64)?; - serializer.write_bytes(&self.prev_block.to_raw_bytes())?; + serializer.write_bytes(self.prev_block.to_raw_bytes())?; self.body_proof.serialize(serializer)?; self.consensus_data.serialize(serializer)?; self.extra_data.serialize(serializer)?; @@ -344,7 +344,7 @@ impl cbor_event::se::Serialize for ByronBlockSignature { impl Deserialize for ByronBlockSignature { fn deserialize(raw: &mut Deserializer) -> Result { (|| -> Result<_, DeserializeError> { - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); + let initial_position = raw.as_mut_ref().stream_position().unwrap(); let mut errs = Vec::new(); let deser_variant: Result<_, DeserializeError> = ByronBlockSignatureNormal::deserialize(raw); @@ -534,8 +534,8 @@ impl cbor_event::se::Serialize for ByronBodyProof { serializer.write_array(cbor_event::Len::Len(4))?; self.tx_proof.serialize(serializer)?; self.ssc_proof.serialize(serializer)?; - serializer.write_bytes(&self.dlg_proof.to_raw_bytes())?; - serializer.write_bytes(&self.upd_proof.to_raw_bytes())?; + serializer.write_bytes(self.dlg_proof.to_raw_bytes())?; + serializer.write_bytes(self.upd_proof.to_raw_bytes())?; Ok(serializer) } } @@ -603,8 +603,8 @@ impl Deserialize for ByronDifficulty { read_len.read_elems(1)?; read_len.finish()?; (|| -> Result<_, DeserializeError> { - let u64 = Ok(raw.unsigned_integer()? as u64) - .map_err(|e: DeserializeError| e.annotate("u64"))?; + let u64 = + Ok(raw.unsigned_integer()?).map_err(|e: DeserializeError| e.annotate("u64"))?; match len { cbor_event::Len::Len(_) => (), cbor_event::Len::Indefinite => match raw.special()? { @@ -628,7 +628,7 @@ impl cbor_event::se::Serialize for ByronEbBlock { //serializer.write_array(cbor_event::Len::Len(self.body.len() as u64))?; serializer.write_array(cbor_event::Len::Indefinite)?; for element in self.body.iter() { - serializer.write_bytes(&element.to_raw_bytes())?; + serializer.write_bytes(element.to_raw_bytes())?; } serializer.write_special(cbor_event::Special::Break)?; serializer.write_array(cbor_event::Len::Len(self.extra.len() as u64))?; @@ -836,7 +836,7 @@ impl Deserialize for EbbConsensusData { read_len.read_elems(2)?; read_len.finish()?; (|| -> Result<_, DeserializeError> { - let epoch_id = Ok(raw.unsigned_integer()? as u64) + let epoch_id = Ok(raw.unsigned_integer()?) .map_err(|e: DeserializeError| e.annotate("epoch_id"))?; let byron_difficulty = ByronDifficulty::deserialize(raw) .map_err(|e: DeserializeError| e.annotate("byron_difficulty"))?; @@ -863,8 +863,8 @@ impl cbor_event::se::Serialize for EbbHead { ) -> cbor_event::Result<&'se mut Serializer> { serializer.write_array(cbor_event::Len::Len(5))?; serializer.write_unsigned_integer(self.protocol_magic as u64)?; - serializer.write_bytes(&self.prev_block.to_raw_bytes())?; - serializer.write_bytes(&self.body_proof.to_raw_bytes())?; + serializer.write_bytes(self.prev_block.to_raw_bytes())?; + serializer.write_bytes(self.body_proof.to_raw_bytes())?; self.consensus_data.serialize(serializer)?; serializer.write_array(cbor_event::Len::Len(self.extra_data.len() as u64))?; for element in self.extra_data.iter() { diff --git a/multi-era/rust/src/byron/delegation/serialization.rs b/multi-era/rust/src/byron/delegation/serialization.rs index 8d283d18..f6655dd1 100644 --- a/multi-era/rust/src/byron/delegation/serialization.rs +++ b/multi-era/rust/src/byron/delegation/serialization.rs @@ -30,8 +30,8 @@ impl Deserialize for ByronDelegation { read_len.read_elems(4)?; read_len.finish()?; (|| -> Result<_, DeserializeError> { - let epoch = Ok(raw.unsigned_integer()? as u64) - .map_err(|e: DeserializeError| e.annotate("epoch"))?; + let epoch = + Ok(raw.unsigned_integer()?).map_err(|e: DeserializeError| e.annotate("epoch"))?; let issuer = Ok(raw.bytes()? as Vec).map_err(|e: DeserializeError| e.annotate("issuer"))?; let delegate = Ok(raw.bytes()? as Vec) @@ -114,9 +114,9 @@ impl Deserialize for EpochRange { read_len.read_elems(2)?; read_len.finish()?; (|| -> Result<_, DeserializeError> { - let epoch_id = Ok(raw.unsigned_integer()? as u64) + let epoch_id = Ok(raw.unsigned_integer()?) .map_err(|e: DeserializeError| e.annotate("epoch_id"))?; - let epoch_id2 = Ok(raw.unsigned_integer()? as u64) + let epoch_id2 = Ok(raw.unsigned_integer()?) .map_err(|e: DeserializeError| e.annotate("epoch_id2"))?; match len { cbor_event::Len::Len(_) => (), diff --git a/multi-era/rust/src/byron/mpc/serialization.rs b/multi-era/rust/src/byron/mpc/serialization.rs index 91f6209a..88bd4556 100644 --- a/multi-era/rust/src/byron/mpc/serialization.rs +++ b/multi-era/rust/src/byron/mpc/serialization.rs @@ -33,7 +33,7 @@ impl cbor_event::se::Serialize for Ssc { impl Deserialize for Ssc { fn deserialize(raw: &mut Deserializer) -> Result { (|| -> Result<_, DeserializeError> { - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); + let initial_position = raw.as_mut_ref().stream_position().unwrap(); let mut errs = Vec::new(); let deser_variant: Result<_, DeserializeError> = SscCommitmentsPayload::deserialize(raw); @@ -115,7 +115,7 @@ impl Deserialize for SscCert { (|| -> Result<_, DeserializeError> { let vss_pub_key = Ok(raw.bytes()? as Vec) .map_err(|e: DeserializeError| e.annotate("vss_pub_key"))?; - let epoch_id = Ok(raw.unsigned_integer()? as u64) + let epoch_id = Ok(raw.unsigned_integer()?) .map_err(|e: DeserializeError| e.annotate("epoch_id"))?; let byron_pub_key = Ok(raw.bytes()? as Vec) .map_err(|e: DeserializeError| e.annotate("byron_pub_key"))?; @@ -219,7 +219,7 @@ impl cbor_event::se::Serialize for SscCertificatesProof { ) -> cbor_event::Result<&'se mut Serializer> { serializer.write_array(cbor_event::Len::Len(2))?; serializer.write_unsigned_integer(3u64)?; - serializer.write_bytes(&self.blake2b256.to_raw_bytes())?; + serializer.write_bytes(self.blake2b256.to_raw_bytes())?; Ok(serializer) } } @@ -272,7 +272,7 @@ impl cbor_event::se::Serialize for SscCommitment { serializer.write_array(cbor_event::Len::Len(2))?; serializer.write_map(cbor_event::Len::Len(self.vss_shares.len() as u64))?; for (key, value) in self.vss_shares.iter() { - serializer.write_bytes(&key)?; + serializer.write_bytes(key)?; value.serialize(serializer)?; } self.vss_proof.serialize(serializer)?; @@ -448,8 +448,8 @@ impl cbor_event::se::Serialize for SscCommitmentsProof { ) -> cbor_event::Result<&'se mut Serializer> { serializer.write_array(cbor_event::Len::Len(3))?; serializer.write_unsigned_integer(0u64)?; - serializer.write_bytes(&self.blake2b256.to_raw_bytes())?; - serializer.write_bytes(&self.blake2b2562.to_raw_bytes())?; + serializer.write_bytes(self.blake2b256.to_raw_bytes())?; + serializer.write_bytes(self.blake2b2562.to_raw_bytes())?; Ok(serializer) } } @@ -514,8 +514,8 @@ impl cbor_event::se::Serialize for SscOpeningsPayload { serializer.write_unsigned_integer(1u64)?; serializer.write_map(cbor_event::Len::Len(self.ssc_opens.len() as u64))?; for (key, value) in self.ssc_opens.iter() { - serializer.write_bytes(&key.to_raw_bytes())?; - serializer.write_bytes(&value)?; + serializer.write_bytes(key.to_raw_bytes())?; + serializer.write_bytes(value)?; } serializer.write_tag(258u64)?; serializer.write_array(cbor_event::Len::Len(self.ssc_certs.len() as u64))?; @@ -626,8 +626,8 @@ impl cbor_event::se::Serialize for SscOpeningsProof { ) -> cbor_event::Result<&'se mut Serializer> { serializer.write_array(cbor_event::Len::Len(3))?; serializer.write_unsigned_integer(1u64)?; - serializer.write_bytes(&self.blake2b256.to_raw_bytes())?; - serializer.write_bytes(&self.blake2b2562.to_raw_bytes())?; + serializer.write_bytes(self.blake2b256.to_raw_bytes())?; + serializer.write_bytes(self.blake2b2562.to_raw_bytes())?; Ok(serializer) } } @@ -706,7 +706,7 @@ impl cbor_event::se::Serialize for SscProof { impl Deserialize for SscProof { fn deserialize(raw: &mut Deserializer) -> Result { (|| -> Result<_, DeserializeError> { - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); + let initial_position = raw.as_mut_ref().stream_position().unwrap(); let mut errs = Vec::new(); let deser_variant: Result<_, DeserializeError> = SscCommitmentsProof::deserialize(raw); match deser_variant { @@ -770,13 +770,13 @@ impl cbor_event::se::Serialize for SscSharesPayload { serializer.write_unsigned_integer(2u64)?; serializer.write_map(cbor_event::Len::Len(self.ssc_shares.len() as u64))?; for (key, value) in self.ssc_shares.iter() { - serializer.write_bytes(&key.to_raw_bytes())?; + serializer.write_bytes(key.to_raw_bytes())?; serializer.write_map(cbor_event::Len::Len(value.len() as u64))?; for (key, value) in value.iter() { - serializer.write_bytes(&key.to_raw_bytes())?; + serializer.write_bytes(key.to_raw_bytes())?; serializer.write_array(cbor_event::Len::Indefinite)?; for element in value.iter() { - serializer.write_bytes(&element)?; + serializer.write_bytes(element)?; } serializer.write_special(cbor_event::Special::Break)?; } @@ -933,8 +933,8 @@ impl cbor_event::se::Serialize for SscSharesProof { ) -> cbor_event::Result<&'se mut Serializer> { serializer.write_array(cbor_event::Len::Len(3))?; serializer.write_unsigned_integer(2u64)?; - serializer.write_bytes(&self.blake2b256.to_raw_bytes())?; - serializer.write_bytes(&self.blake2b2562.to_raw_bytes())?; + serializer.write_bytes(self.blake2b256.to_raw_bytes())?; + serializer.write_bytes(self.blake2b2562.to_raw_bytes())?; Ok(serializer) } } @@ -1080,7 +1080,7 @@ impl cbor_event::se::Serialize for VssProof { //serializer.write_array(cbor_event::Len::Len(self.bytess.len() as u64))?; serializer.write_array(cbor_event::Len::Indefinite)?; for element in self.bytess.iter() { - serializer.write_bytes(&element)?; + serializer.write_bytes(element)?; } serializer.write_special(cbor_event::Special::Break)?; Ok(serializer) diff --git a/multi-era/rust/src/byron/serialization.rs b/multi-era/rust/src/byron/serialization.rs index 4f27d048..5b87ce9d 100644 --- a/multi-era/rust/src/byron/serialization.rs +++ b/multi-era/rust/src/byron/serialization.rs @@ -28,10 +28,10 @@ impl Deserialize for ByronSlotId { read_len.read_elems(2)?; read_len.finish()?; (|| -> Result<_, DeserializeError> { - let epoch = Ok(raw.unsigned_integer()? as u64) - .map_err(|e: DeserializeError| e.annotate("epoch"))?; - let slot = Ok(raw.unsigned_integer()? as u64) - .map_err(|e: DeserializeError| e.annotate("slot"))?; + let epoch = + Ok(raw.unsigned_integer()?).map_err(|e: DeserializeError| e.annotate("epoch"))?; + let slot = + Ok(raw.unsigned_integer()?).map_err(|e: DeserializeError| e.annotate("slot"))?; match len { cbor_event::Len::Len(_) => (), cbor_event::Len::Indefinite => match raw.special()? { diff --git a/multi-era/rust/src/byron/transaction/serialization.rs b/multi-era/rust/src/byron/transaction/serialization.rs index aac3b4ea..6daeed68 100644 --- a/multi-era/rust/src/byron/transaction/serialization.rs +++ b/multi-era/rust/src/byron/transaction/serialization.rs @@ -540,7 +540,7 @@ impl cbor_event::se::Serialize for ByronTxIn { impl Deserialize for ByronTxIn { fn deserialize(raw: &mut Deserializer) -> Result { (|| -> Result<_, DeserializeError> { - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); + let initial_position = raw.as_mut_ref().stream_position().unwrap(); let mut errs = Vec::new(); let deser_variant: Result<_, DeserializeError> = ByronTxInRegular::deserialize(raw); match deser_variant { @@ -686,7 +686,7 @@ impl cbor_event::se::Serialize for ByronTxOutPtr { serializer: &'se mut Serializer, ) -> cbor_event::Result<&'se mut Serializer> { serializer.write_array(cbor_event::Len::Len(2))?; - serializer.write_bytes(&self.byron_tx_id.to_raw_bytes())?; + serializer.write_bytes(self.byron_tx_id.to_raw_bytes())?; serializer.write_unsigned_integer(self.u32 as u64)?; Ok(serializer) } @@ -729,8 +729,8 @@ impl cbor_event::se::Serialize for ByronTxProof { ) -> cbor_event::Result<&'se mut Serializer> { serializer.write_array(cbor_event::Len::Len(3))?; serializer.write_unsigned_integer(self.u32 as u64)?; - serializer.write_bytes(&self.blake2b256.to_raw_bytes())?; - serializer.write_bytes(&self.blake2b2562.to_raw_bytes())?; + serializer.write_bytes(self.blake2b256.to_raw_bytes())?; + serializer.write_bytes(self.blake2b2562.to_raw_bytes())?; Ok(serializer) } } @@ -801,7 +801,7 @@ impl Deserialize for ByronTxWitness { (|| -> Result<_, DeserializeError> { let len = raw.array()?; let mut read_len = CBORReadLen::from(len); - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); + let initial_position = raw.as_mut_ref().stream_position().unwrap(); let mut errs = Vec::new(); let deser_variant: Result<_, DeserializeError> = ByronPkWitness::deserialize_as_embedded_group( diff --git a/multi-era/rust/src/byron/update/serialization.rs b/multi-era/rust/src/byron/update/serialization.rs index 163d9fcf..d16686c6 100644 --- a/multi-era/rust/src/byron/update/serialization.rs +++ b/multi-era/rust/src/byron/update/serialization.rs @@ -198,7 +198,7 @@ impl Deserialize for Bvermod { assert_eq!(raw.special()?, cbor_event::Special::Break); break; } - mpc_thd_arr.push(raw.unsigned_integer()? as u64); + mpc_thd_arr.push(raw.unsigned_integer()?); } Ok(mpc_thd_arr) })() @@ -214,7 +214,7 @@ impl Deserialize for Bvermod { assert_eq!(raw.special()?, cbor_event::Special::Break); break; } - heavy_del_thd_arr.push(raw.unsigned_integer()? as u64); + heavy_del_thd_arr.push(raw.unsigned_integer()?); } Ok(heavy_del_thd_arr) })() @@ -230,7 +230,7 @@ impl Deserialize for Bvermod { assert_eq!(raw.special()?, cbor_event::Special::Break); break; } - update_vote_thd_arr.push(raw.unsigned_integer()? as u64); + update_vote_thd_arr.push(raw.unsigned_integer()?); } Ok(update_vote_thd_arr) })() @@ -246,7 +246,7 @@ impl Deserialize for Bvermod { assert_eq!(raw.special()?, cbor_event::Special::Break); break; } - update_proposal_thd_arr.push(raw.unsigned_integer()? as u64); + update_proposal_thd_arr.push(raw.unsigned_integer()?); } Ok(update_proposal_thd_arr) })() @@ -262,7 +262,7 @@ impl Deserialize for Bvermod { assert_eq!(raw.special()?, cbor_event::Special::Break); break; } - update_implicit_arr.push(raw.unsigned_integer()? as u64); + update_implicit_arr.push(raw.unsigned_integer()?); } Ok(update_implicit_arr) })() @@ -310,7 +310,7 @@ impl Deserialize for Bvermod { assert_eq!(raw.special()?, cbor_event::Special::Break); break; } - unlock_stake_epoch_arr.push(raw.unsigned_integer()? as u64); + unlock_stake_epoch_arr.push(raw.unsigned_integer()?); } Ok(unlock_stake_epoch_arr) })() @@ -562,10 +562,10 @@ impl cbor_event::se::Serialize for ByronUpdateData { serializer: &'se mut Serializer, ) -> cbor_event::Result<&'se mut Serializer> { serializer.write_array(cbor_event::Len::Len(4))?; - serializer.write_bytes(&self.blake2b256.to_raw_bytes())?; - serializer.write_bytes(&self.blake2b2562.to_raw_bytes())?; - serializer.write_bytes(&self.blake2b2563.to_raw_bytes())?; - serializer.write_bytes(&self.blake2b2564.to_raw_bytes())?; + serializer.write_bytes(self.blake2b256.to_raw_bytes())?; + serializer.write_bytes(self.blake2b2562.to_raw_bytes())?; + serializer.write_bytes(self.blake2b2563.to_raw_bytes())?; + serializer.write_bytes(self.blake2b2564.to_raw_bytes())?; Ok(serializer) } } @@ -638,7 +638,7 @@ impl cbor_event::se::Serialize for ByronUpdateProposal { self.software_version.serialize(serializer)?; serializer.write_map(cbor_event::Len::Len(self.data.len() as u64))?; for (key, value) in self.data.iter() { - serializer.write_text(&key)?; + serializer.write_text(key)?; value.serialize(serializer)?; } serializer.write_map(cbor_event::Len::Len(self.byron_attributes.len() as u64))?; @@ -746,7 +746,7 @@ impl cbor_event::se::Serialize for ByronUpdateVote { ) -> cbor_event::Result<&'se mut Serializer> { serializer.write_array(cbor_event::Len::Len(4))?; serializer.write_bytes(&self.voter)?; - serializer.write_bytes(&self.proposal_id.to_raw_bytes())?; + serializer.write_bytes(self.proposal_id.to_raw_bytes())?; serializer.write_special(cbor_event::Special::Bool(self.vote))?; serializer.write_bytes(&self.signature)?; Ok(serializer) @@ -814,11 +814,11 @@ impl Deserialize for SoftForkRule { read_len.read_elems(3)?; read_len.finish()?; (|| -> Result<_, DeserializeError> { - let coin_portion = Ok(raw.unsigned_integer()? as u64) + let coin_portion = Ok(raw.unsigned_integer()?) .map_err(|e: DeserializeError| e.annotate("coin_portion"))?; - let coin_portion2 = Ok(raw.unsigned_integer()? as u64) + let coin_portion2 = Ok(raw.unsigned_integer()?) .map_err(|e: DeserializeError| e.annotate("coin_portion2"))?; - let coin_portion3 = Ok(raw.unsigned_integer()? as u64) + let coin_portion3 = Ok(raw.unsigned_integer()?) .map_err(|e: DeserializeError| e.annotate("coin_portion3"))?; match len { cbor_event::Len::Len(_) => (), diff --git a/multi-era/rust/src/mary/serialization.rs b/multi-era/rust/src/mary/serialization.rs index 12c7dabe..02a99aff 100644 --- a/multi-era/rust/src/mary/serialization.rs +++ b/multi-era/rust/src/mary/serialization.rs @@ -550,7 +550,7 @@ impl Serialize for MaryTransactionBody { ), )?; serializer.write_bytes_sz( - &field.to_raw_bytes(), + field.to_raw_bytes(), self.encodings .as_ref() .map(|encs| encs.auxiliary_data_hash_encoding.clone()) @@ -616,7 +616,7 @@ impl Serialize for MaryTransactionBody { .cloned() .unwrap_or_default(); buf.write_bytes_sz( - &k.to_raw_bytes(), + k.to_raw_bytes(), mint_key_encoding.to_str_len_sz( k.to_raw_bytes().len() as u64, force_canonical, @@ -682,7 +682,7 @@ impl Serialize for MaryTransactionBody { serializer.write_negative_integer_sz( *value as i128, fit_sz( - (*value + 1).abs() as u64, + (*value + 1).unsigned_abs(), mint_value_value_encoding, force_canonical, ), diff --git a/multi-era/rust/src/serialization.rs b/multi-era/rust/src/serialization.rs index 80a238d7..76c5bdc2 100644 --- a/multi-era/rust/src/serialization.rs +++ b/multi-era/rust/src/serialization.rs @@ -25,7 +25,7 @@ impl Serialize for MultiEraBlock { impl Deserialize for MultiEraBlock { fn deserialize(raw: &mut Deserializer) -> Result { (|| -> Result<_, DeserializeError> { - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); + let initial_position = raw.as_mut_ref().stream_position().unwrap(); let deser_variant: Result<_, DeserializeError> = ByronBlock::deserialize(raw); match deser_variant { Ok(byron) => return Ok(Self::Byron(byron)), diff --git a/multi-era/rust/src/shelley/mod.rs b/multi-era/rust/src/shelley/mod.rs index a4c39d66..09a35811 100644 --- a/multi-era/rust/src/shelley/mod.rs +++ b/multi-era/rust/src/shelley/mod.rs @@ -151,6 +151,7 @@ impl ShelleyBlock { } } +#[allow(clippy::large_enum_variant)] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)] pub enum ShelleyCertificate { StakeRegistration(StakeRegistration), diff --git a/multi-era/rust/src/shelley/serialization.rs b/multi-era/rust/src/shelley/serialization.rs index 566a5cde..269d1d12 100644 --- a/multi-era/rust/src/shelley/serialization.rs +++ b/multi-era/rust/src/shelley/serialization.rs @@ -443,7 +443,7 @@ impl SerializeEmbeddedGroup for MultisigPubkey { ), )?; serializer.write_bytes_sz( - &self.ed25519_key_hash.to_raw_bytes(), + self.ed25519_key_hash.to_raw_bytes(), self.encodings .as_ref() .map(|encs| encs.ed25519_key_hash_encoding.clone()) @@ -549,7 +549,7 @@ impl Deserialize for MultisigScript { (|| -> Result<_, DeserializeError> { let len = raw.array_sz()?; let mut read_len = CBORReadLen::new(len); - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); + let initial_position = raw.as_mut_ref().stream_position().unwrap(); let mut errs = Vec::new(); let deser_variant: Result<_, DeserializeError> = MultisigPubkey::deserialize_as_embedded_group(raw, &mut read_len, len); @@ -777,7 +777,7 @@ impl Serialize for ShelleyCertificate { impl Deserialize for ShelleyCertificate { fn deserialize(raw: &mut Deserializer) -> Result { (|| -> Result<_, DeserializeError> { - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); + let initial_position = raw.as_mut_ref().stream_position().unwrap(); let mut errs = Vec::new(); let deser_variant: Result<_, DeserializeError> = StakeRegistration::deserialize(raw); match deser_variant { @@ -956,7 +956,7 @@ impl Serialize for ShelleyHeaderBody { )?; match &self.prev_hash { Some(x) => serializer.write_bytes_sz( - &x.to_raw_bytes(), + x.to_raw_bytes(), self.encodings .as_ref() .map(|encs| encs.prev_hash_encoding.clone()) @@ -966,7 +966,7 @@ impl Serialize for ShelleyHeaderBody { None => serializer.write_special(cbor_event::Special::Null), }?; serializer.write_bytes_sz( - &self.issuer_vkey.to_raw_bytes(), + self.issuer_vkey.to_raw_bytes(), self.encodings .as_ref() .map(|encs| encs.issuer_vkey_encoding.clone()) @@ -977,7 +977,7 @@ impl Serialize for ShelleyHeaderBody { ), )?; serializer.write_bytes_sz( - &self.v_r_f_vkey.to_raw_bytes(), + self.v_r_f_vkey.to_raw_bytes(), self.encodings .as_ref() .map(|encs| encs.v_r_f_vkey_encoding.clone()) @@ -998,7 +998,7 @@ impl Serialize for ShelleyHeaderBody { ), )?; serializer.write_bytes_sz( - &self.block_body_hash.to_raw_bytes(), + self.block_body_hash.to_raw_bytes(), self.encodings .as_ref() .map(|encs| encs.block_body_hash_encoding.clone()) @@ -1234,7 +1234,7 @@ impl Deserialize for ShelleyMoveInstantaneousReward { read_len.finish()?; (|| -> Result<_, DeserializeError> { let (pot, pot_encoding) = (|| -> Result<_, DeserializeError> { - let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap(); + let initial_position = raw.as_mut_ref().stream_position().unwrap(); match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> { let (reserve_value, reserve_encoding) = raw.unsigned_integer_sz()?; if reserve_value != 0 { @@ -2635,7 +2635,7 @@ impl Serialize for ShelleyTransactionBody { ), )?; serializer.write_bytes_sz( - &field.to_raw_bytes(), + field.to_raw_bytes(), self.encodings .as_ref() .map(|encs| encs.auxiliary_data_hash_encoding.clone()) @@ -3390,7 +3390,7 @@ impl Serialize for ShelleyUpdate { .cloned() .unwrap_or_default(); buf.write_bytes_sz( - &k.to_raw_bytes(), + k.to_raw_bytes(), shelley_proposed_protocol_parameter_updates_key_encoding .to_str_len_sz(k.to_raw_bytes().len() as u64, force_canonical), )?; diff --git a/multi-era/wasm/src/byron/block/mod.rs b/multi-era/wasm/src/byron/block/mod.rs index 8d9013ba..1410e5b5 100644 --- a/multi-era/wasm/src/byron/block/mod.rs +++ b/multi-era/wasm/src/byron/block/mod.rs @@ -9,15 +9,16 @@ use crate::byron::{Blake2b256, ByronBlockId, ByronPubKey, ByronSignature, ByronS use crate::byron::{ ByronAttributesList, ByronDelegationList, ByronTxWitnessList, StakeholderIdList, }; -use crate::impl_wasm_cbor_json_api_byron; -use cml_core_wasm::impl_wasm_conversions; +use cml_core_wasm::{ + impl_wasm_cbor_json_api_cbor_event_serialize, impl_wasm_conversions, impl_wasm_list, +}; use wasm_bindgen::prelude::{wasm_bindgen, JsValue}; #[derive(Clone, Debug)] #[wasm_bindgen] pub struct BlockHeaderExtraData(cml_multi_era::byron::block::BlockHeaderExtraData); -impl_wasm_cbor_json_api_byron!(BlockHeaderExtraData); +impl_wasm_cbor_json_api_cbor_event_serialize!(BlockHeaderExtraData); impl_wasm_conversions!( cml_multi_era::byron::block::BlockHeaderExtraData, @@ -61,7 +62,7 @@ impl BlockHeaderExtraData { #[wasm_bindgen] pub struct ByronBlock(cml_multi_era::byron::block::ByronBlock); -impl_wasm_cbor_json_api_byron!(ByronBlock); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronBlock); impl_wasm_conversions!(cml_multi_era::byron::block::ByronBlock, ByronBlock); @@ -109,7 +110,7 @@ impl ByronBlock { #[wasm_bindgen] pub struct ByronBlockBody(cml_multi_era::byron::block::ByronBlockBody); -impl_wasm_cbor_json_api_byron!(ByronBlockBody); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronBlockBody); impl_wasm_conversions!(cml_multi_era::byron::block::ByronBlockBody, ByronBlockBody); @@ -150,7 +151,7 @@ impl ByronBlockBody { #[wasm_bindgen] pub struct ByronBlockConsensusData(cml_multi_era::byron::block::ByronBlockConsensusData); -impl_wasm_cbor_json_api_byron!(ByronBlockConsensusData); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronBlockConsensusData); impl_wasm_conversions!( cml_multi_era::byron::block::ByronBlockConsensusData, @@ -194,7 +195,7 @@ impl ByronBlockConsensusData { #[wasm_bindgen] pub struct ByronBlockHeader(cml_multi_era::byron::block::ByronBlockHeader); -impl_wasm_cbor_json_api_byron!(ByronBlockHeader); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronBlockHeader); impl_wasm_conversions!( cml_multi_era::byron::block::ByronBlockHeader, @@ -250,7 +251,7 @@ pub enum ByronBlockKind { #[wasm_bindgen] pub struct ByronBlockSignature(cml_multi_era::byron::block::ByronBlockSignature); -impl_wasm_cbor_json_api_byron!(ByronBlockSignature); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronBlockSignature); impl_wasm_conversions!( cml_multi_era::byron::block::ByronBlockSignature, @@ -336,7 +337,7 @@ pub enum ByronBlockSignatureKind { #[wasm_bindgen] pub struct ByronBlockSignatureNormal(cml_multi_era::byron::block::ByronBlockSignatureNormal); -impl_wasm_cbor_json_api_byron!(ByronBlockSignatureNormal); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronBlockSignatureNormal); impl_wasm_conversions!( cml_multi_era::byron::block::ByronBlockSignatureNormal, @@ -362,7 +363,7 @@ pub struct ByronBlockSignatureProxyHeavy( cml_multi_era::byron::block::ByronBlockSignatureProxyHeavy, ); -impl_wasm_cbor_json_api_byron!(ByronBlockSignatureProxyHeavy); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronBlockSignatureProxyHeavy); impl_wasm_conversions!( cml_multi_era::byron::block::ByronBlockSignatureProxyHeavy, @@ -390,7 +391,7 @@ pub struct ByronBlockSignatureProxyLight( cml_multi_era::byron::block::ByronBlockSignatureProxyLight, ); -impl_wasm_cbor_json_api_byron!(ByronBlockSignatureProxyLight); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronBlockSignatureProxyLight); impl_wasm_conversions!( cml_multi_era::byron::block::ByronBlockSignatureProxyLight, @@ -416,7 +417,7 @@ impl ByronBlockSignatureProxyLight { #[wasm_bindgen] pub struct ByronBodyProof(cml_multi_era::byron::block::ByronBodyProof); -impl_wasm_cbor_json_api_byron!(ByronBodyProof); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronBodyProof); impl_wasm_conversions!(cml_multi_era::byron::block::ByronBodyProof, ByronBodyProof); @@ -457,7 +458,7 @@ impl ByronBodyProof { #[wasm_bindgen] pub struct ByronDifficulty(cml_multi_era::byron::block::ByronDifficulty); -impl_wasm_cbor_json_api_byron!(ByronDifficulty); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronDifficulty); impl_wasm_conversions!( cml_multi_era::byron::block::ByronDifficulty, @@ -479,7 +480,7 @@ impl ByronDifficulty { #[wasm_bindgen] pub struct ByronEbBlock(cml_multi_era::byron::block::ByronEbBlock); -impl_wasm_cbor_json_api_byron!(ByronEbBlock); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronEbBlock); impl_wasm_conversions!(cml_multi_era::byron::block::ByronEbBlock, ByronEbBlock); @@ -510,7 +511,7 @@ impl ByronEbBlock { #[wasm_bindgen] pub struct ByronMainBlock(cml_multi_era::byron::block::ByronMainBlock); -impl_wasm_cbor_json_api_byron!(ByronMainBlock); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronMainBlock); impl_wasm_conversions!(cml_multi_era::byron::block::ByronMainBlock, ByronMainBlock); @@ -545,7 +546,7 @@ impl ByronMainBlock { #[wasm_bindgen] pub struct EbbConsensusData(cml_multi_era::byron::block::EbbConsensusData); -impl_wasm_cbor_json_api_byron!(EbbConsensusData); +impl_wasm_cbor_json_api_cbor_event_serialize!(EbbConsensusData); impl_wasm_conversions!( cml_multi_era::byron::block::EbbConsensusData, @@ -574,7 +575,7 @@ impl EbbConsensusData { #[wasm_bindgen] pub struct EbbHead(cml_multi_era::byron::block::EbbHead); -impl_wasm_cbor_json_api_byron!(EbbHead); +impl_wasm_cbor_json_api_cbor_event_serialize!(EbbHead); impl_wasm_conversions!(cml_multi_era::byron::block::EbbHead, EbbHead); @@ -621,7 +622,7 @@ impl EbbHead { #[wasm_bindgen] pub struct TxAux(cml_multi_era::byron::block::TxAux); -impl_wasm_cbor_json_api_byron!(TxAux); +impl_wasm_cbor_json_api_cbor_event_serialize!(TxAux); impl_wasm_conversions!(cml_multi_era::byron::block::TxAux, TxAux); @@ -643,27 +644,4 @@ impl TxAux { } } -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct TxPayload(Vec); - -impl_wasm_conversions!(Vec, TxPayload); - -#[wasm_bindgen] -impl TxPayload { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> TxAux { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &TxAux) { - self.0.push(elem.clone().into()); - } -} +impl_wasm_list!(cml_multi_era::byron::block::TxAux, TxAux, TxPayload); diff --git a/multi-era/wasm/src/byron/delegation/mod.rs b/multi-era/wasm/src/byron/delegation/mod.rs index 0a265ded..1e5fc23f 100644 --- a/multi-era/wasm/src/byron/delegation/mod.rs +++ b/multi-era/wasm/src/byron/delegation/mod.rs @@ -2,15 +2,14 @@ // https://github.com/dcSpark/cddl-codegen use crate::byron::{ByronPubKey, ByronSignature, EpochId}; -use crate::impl_wasm_cbor_json_api_byron; -use cml_core_wasm::impl_wasm_conversions; +use cml_core_wasm::{impl_wasm_cbor_json_api_cbor_event_serialize, impl_wasm_conversions}; use wasm_bindgen::prelude::{wasm_bindgen, JsValue}; #[derive(Clone, Debug)] #[wasm_bindgen] pub struct ByronDelegation(cml_multi_era::byron::delegation::ByronDelegation); -impl_wasm_cbor_json_api_byron!(ByronDelegation); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronDelegation); impl_wasm_conversions!( cml_multi_era::byron::delegation::ByronDelegation, @@ -54,7 +53,7 @@ impl ByronDelegation { #[wasm_bindgen] pub struct ByronDelegationSignature(cml_multi_era::byron::delegation::ByronDelegationSignature); -impl_wasm_cbor_json_api_byron!(ByronDelegationSignature); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronDelegationSignature); impl_wasm_conversions!( cml_multi_era::byron::delegation::ByronDelegationSignature, @@ -85,7 +84,7 @@ impl ByronDelegationSignature { #[wasm_bindgen] pub struct EpochRange(cml_multi_era::byron::delegation::EpochRange); -impl_wasm_cbor_json_api_byron!(EpochRange); +impl_wasm_cbor_json_api_cbor_event_serialize!(EpochRange); impl_wasm_conversions!(cml_multi_era::byron::delegation::EpochRange, EpochRange); @@ -112,7 +111,7 @@ pub struct LightWeightDelegationSignature( cml_multi_era::byron::delegation::LightWeightDelegationSignature, ); -impl_wasm_cbor_json_api_byron!(LightWeightDelegationSignature); +impl_wasm_cbor_json_api_cbor_event_serialize!(LightWeightDelegationSignature); impl_wasm_conversions!( cml_multi_era::byron::delegation::LightWeightDelegationSignature, @@ -143,7 +142,7 @@ impl LightWeightDelegationSignature { #[wasm_bindgen] pub struct LightWeightDlg(cml_multi_era::byron::delegation::LightWeightDlg); -impl_wasm_cbor_json_api_byron!(LightWeightDlg); +impl_wasm_cbor_json_api_cbor_event_serialize!(LightWeightDlg); impl_wasm_conversions!( cml_multi_era::byron::delegation::LightWeightDlg, diff --git a/multi-era/wasm/src/byron/mod.rs b/multi-era/wasm/src/byron/mod.rs index 2ecf7abc..e90ee40e 100644 --- a/multi-era/wasm/src/byron/mod.rs +++ b/multi-era/wasm/src/byron/mod.rs @@ -9,12 +9,13 @@ pub mod update; #[macro_use] pub mod utils; -use crate::impl_wasm_cbor_json_api_byron; use ::wasm_bindgen::prelude::{wasm_bindgen, JsValue}; use cml_chain_wasm::byron::ByronTxOut; use cml_chain_wasm::utils::BigInt; -use cml_core_wasm::impl_wasm_conversions; -use std::collections::BTreeMap; +use cml_core_wasm::{ + impl_wasm_cbor_json_api_cbor_event_serialize, impl_wasm_conversions, impl_wasm_list, + impl_wasm_map_btree, +}; pub use utils::{Blake2b224, Blake2b256, ByronAny}; pub type SystemTag = String; @@ -29,7 +30,7 @@ pub type ByronSignature = Vec; #[wasm_bindgen] pub struct ByronSlotId(cml_multi_era::byron::ByronSlotId); -impl_wasm_cbor_json_api_byron!(ByronSlotId); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronSlotId); impl_wasm_conversions!(cml_multi_era::byron::ByronSlotId, ByronSlotId); @@ -57,789 +58,94 @@ pub type EpochId = u64; // this is pasted from lib.rs due to the export structure being at cml-multi-era-wasm root: use cml_chain_wasm::byron::{AddressId, StakeholderId}; -use mpc::VssPubKey; use crate::byron::{ delegation::ByronDelegation, - mpc::VssDecryptedShare, transaction::{ByronAttributes, ByronTxIn, ByronTxWitness}, update::{ ByronTxFeePolicy, ByronUpdateData, ByronUpdateProposal, ByronUpdateVote, SoftForkRule, }, }; -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct AddressIdList(Vec); - -#[wasm_bindgen] -impl AddressIdList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> AddressId { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &AddressId) { - self.0.push(elem.clone().into()); - } -} - -impl From> for AddressIdList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: AddressIdList) -> Self { - wasm.0 - } -} - -impl AsRef> for AddressIdList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct BigIntList(Vec); - -#[wasm_bindgen] -impl BigIntList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> BigInt { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &BigInt) { - self.0.push(elem.clone().into()); - } -} - -impl From> for BigIntList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: BigIntList) -> Self { - wasm.0 - } -} - -impl AsRef> for BigIntList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct ByronAnyList(Vec); - -#[wasm_bindgen] -impl ByronAnyList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> ByronAny { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &ByronAny) { - self.0.push(elem.clone().into()); - } -} - -impl From> for ByronAnyList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: ByronAnyList) -> Self { - wasm.0 - } -} - -impl AsRef> for ByronAnyList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct ByronAttributesList(Vec); - -#[wasm_bindgen] -impl ByronAttributesList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> ByronAttributes { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &ByronAttributes) { - self.0.push(elem.clone().into()); - } -} - -impl From> for ByronAttributesList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: ByronAttributesList) -> Self { - wasm.0 - } -} - -impl AsRef> for ByronAttributesList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct ByronDelegationList(Vec); - -#[wasm_bindgen] -impl ByronDelegationList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> ByronDelegation { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &ByronDelegation) { - self.0.push(elem.clone().into()); - } -} - -impl From> for ByronDelegationList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: ByronDelegationList) -> Self { - wasm.0 - } -} - -impl AsRef> for ByronDelegationList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct ByronTxFeePolicyList(Vec); - -#[wasm_bindgen] -impl ByronTxFeePolicyList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> ByronTxFeePolicy { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &ByronTxFeePolicy) { - self.0.push(elem.clone().into()); - } -} - -impl From> for ByronTxFeePolicyList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: ByronTxFeePolicyList) -> Self { - wasm.0 - } -} - -impl AsRef> for ByronTxFeePolicyList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct ByronTxInList(Vec); - -#[wasm_bindgen] -impl ByronTxInList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> ByronTxIn { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &ByronTxIn) { - self.0.push(elem.clone().into()); - } -} - -impl From> for ByronTxInList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: ByronTxInList) -> Self { - wasm.0 - } -} - -impl AsRef> for ByronTxInList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct ByronTxOutList(Vec); - -#[wasm_bindgen] -impl ByronTxOutList { - pub fn new() -> Self { - Self(Vec::new()) - } +impl_wasm_list!(cml_chain::byron::AddressId, AddressId, AddressIdList); - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> ByronTxOut { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &ByronTxOut) { - self.0.push(elem.clone().into()); - } -} - -impl From> for ByronTxOutList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: ByronTxOutList) -> Self { - wasm.0 - } -} +impl_wasm_list!(cml_chain::utils::BigInt, BigInt, BigIntList); -impl AsRef> for ByronTxOutList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct ByronTxWitnessList(Vec); - -#[wasm_bindgen] -impl ByronTxWitnessList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> ByronTxWitness { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &ByronTxWitness) { - self.0.push(elem.clone().into()); - } -} - -impl From> for ByronTxWitnessList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: ByronTxWitnessList) -> Self { - wasm.0 - } -} - -impl AsRef> for ByronTxWitnessList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} +impl_wasm_list!(cml_multi_era::byron::ByronAny, ByronAny, ByronAnyList); -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct ByronUpdateProposalList(Vec); - -#[wasm_bindgen] -impl ByronUpdateProposalList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> ByronUpdateProposal { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &ByronUpdateProposal) { - self.0.push(elem.clone().into()); - } -} - -impl From> for ByronUpdateProposalList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: ByronUpdateProposalList) -> Self { - wasm.0 - } -} - -impl AsRef> for ByronUpdateProposalList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct ByronUpdateVoteList(Vec); - -#[wasm_bindgen] -impl ByronUpdateVoteList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> ByronUpdateVote { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &ByronUpdateVote) { - self.0.push(elem.clone().into()); - } -} - -impl From> for ByronUpdateVoteList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: ByronUpdateVoteList) -> Self { - wasm.0 - } -} - -impl AsRef> for ByronUpdateVoteList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct BytesList(Vec>); - -#[wasm_bindgen] -impl BytesList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> Vec { - self.0[index].clone() - } - - pub fn add(&mut self, elem: Vec) { - self.0.push(elem); - } -} - -impl From>> for BytesList { - fn from(native: Vec>) -> Self { - Self(native) - } -} - -impl From for Vec> { - fn from(wasm: BytesList) -> Self { - wasm.0 - } -} - -impl AsRef>> for BytesList { - fn as_ref(&self) -> &Vec> { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct MapSystemTagToByronUpdateData( - BTreeMap< - cml_multi_era::byron::update::SystemTag, - cml_multi_era::byron::update::ByronUpdateData, - >, +impl_wasm_list!( + cml_multi_era::byron::transaction::ByronAttributes, + ByronAttributes, + ByronAttributesList ); -#[wasm_bindgen] -impl MapSystemTagToByronUpdateData { - pub fn new() -> Self { - Self(BTreeMap::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn insert(&mut self, key: SystemTag, value: &ByronUpdateData) -> Option { - self.0.insert(key, value.clone().into()).map(Into::into) - } - - pub fn get(&self, key: SystemTag) -> Option { - self.0.get(&key).map(|v| v.clone().into()) - } - - pub fn keys(&self) -> SystemTagList { - SystemTagList(self.0.iter().map(|(k, _v)| k.clone()).collect::>()) - } -} - -impl - From< - BTreeMap< - cml_multi_era::byron::update::SystemTag, - cml_multi_era::byron::update::ByronUpdateData, - >, - > for MapSystemTagToByronUpdateData -{ - fn from( - native: BTreeMap< - cml_multi_era::byron::update::SystemTag, - cml_multi_era::byron::update::ByronUpdateData, - >, - ) -> Self { - Self(native) - } -} - -impl From - for BTreeMap< - cml_multi_era::byron::update::SystemTag, - cml_multi_era::byron::update::ByronUpdateData, - > -{ - fn from(wasm: MapSystemTagToByronUpdateData) -> Self { - wasm.0 - } -} - -impl - AsRef< - BTreeMap< - cml_multi_era::byron::update::SystemTag, - cml_multi_era::byron::update::ByronUpdateData, - >, - > for MapSystemTagToByronUpdateData -{ - fn as_ref( - &self, - ) -> &BTreeMap< - cml_multi_era::byron::update::SystemTag, - cml_multi_era::byron::update::ByronUpdateData, - > { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct SoftForkRuleList(Vec); - -#[wasm_bindgen] -impl SoftForkRuleList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> SoftForkRule { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &SoftForkRule) { - self.0.push(elem.clone().into()); - } -} - -impl From> for SoftForkRuleList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: SoftForkRuleList) -> Self { - wasm.0 - } -} - -impl AsRef> for SoftForkRuleList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct StakeholderIdList(Vec); - -#[wasm_bindgen] -impl StakeholderIdList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> StakeholderId { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &StakeholderId) { - self.0.push(elem.clone().into()); - } -} - -impl From> for StakeholderIdList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: StakeholderIdList) -> Self { - wasm.0 - } -} - -impl AsRef> for StakeholderIdList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct SystemTagList(Vec); - -#[wasm_bindgen] -impl SystemTagList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> SystemTag { - self.0[index].clone() - } - - pub fn add(&mut self, elem: SystemTag) { - self.0.push(elem); - } -} - -impl From> for SystemTagList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: SystemTagList) -> Self { - wasm.0 - } -} - -impl AsRef> for SystemTagList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct VssDecryptedShareList(Vec); - -#[wasm_bindgen] -impl VssDecryptedShareList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> VssDecryptedShare { - self.0[index].clone() - } +impl_wasm_list!( + cml_multi_era::byron::delegation::ByronDelegation, + ByronDelegation, + ByronDelegationList +); - pub fn add(&mut self, elem: VssDecryptedShare) { - self.0.push(elem); - } -} +impl_wasm_list!( + cml_multi_era::byron::update::ByronTxFeePolicy, + ByronTxFeePolicy, + ByronTxFeePolicyList +); -impl From> for VssDecryptedShareList { - fn from(native: Vec) -> Self { - Self(native) - } -} +impl_wasm_list!( + cml_multi_era::byron::transaction::ByronTxIn, + ByronTxIn, + ByronTxInList +); -impl From for Vec { - fn from(wasm: VssDecryptedShareList) -> Self { - wasm.0 - } -} +impl_wasm_list!(cml_chain::byron::ByronTxOut, ByronTxOut, ByronTxOutList); -impl AsRef> for VssDecryptedShareList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} +impl_wasm_list!( + cml_multi_era::byron::transaction::ByronTxWitness, + ByronTxWitness, + ByronTxWitnessList +); -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct VssPubKeyList(Vec); +impl_wasm_list!( + cml_multi_era::byron::update::ByronUpdateProposal, + ByronUpdateProposal, + ByronUpdateProposalList +); -#[wasm_bindgen] -impl VssPubKeyList { - pub fn new() -> Self { - Self(Vec::new()) - } +impl_wasm_list!( + cml_multi_era::byron::update::ByronUpdateVote, + ByronUpdateVote, + ByronUpdateVoteList +); - pub fn len(&self) -> usize { - self.0.len() - } +impl_wasm_list!(Vec, Vec, BytesList, true, false); + +impl_wasm_map_btree!( + cml_multi_era::byron::update::SystemTag, + cml_multi_era::byron::update::ByronUpdateData, + SystemTag, + ByronUpdateData, + SystemTagList, + MapSystemTagToByronUpdateData, + true, + false, + false, + false +); - pub fn get(&self, index: usize) -> VssPubKey { - self.0[index].clone() - } +impl_wasm_list!( + cml_multi_era::byron::update::SoftForkRule, + SoftForkRule, + SoftForkRuleList +); - pub fn add(&mut self, elem: VssPubKey) { - self.0.push(elem); - } -} +impl_wasm_list!( + cml_chain::byron::StakeholderId, + StakeholderId, + StakeholderIdList +); -impl From> for VssPubKeyList { - fn from(native: Vec) -> Self { - Self(native) - } -} +impl_wasm_list!(String, String, SystemTagList, true, false); -impl From for Vec { - fn from(wasm: VssPubKeyList) -> Self { - wasm.0 - } -} +pub type VssDecryptedShareList = BytesList; -impl AsRef> for VssPubKeyList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} +pub type VssPubKeyList = BytesList; diff --git a/multi-era/wasm/src/byron/mpc/mod.rs b/multi-era/wasm/src/byron/mpc/mod.rs index fa31ed3d..d351cf6b 100644 --- a/multi-era/wasm/src/byron/mpc/mod.rs +++ b/multi-era/wasm/src/byron/mpc/mod.rs @@ -5,17 +5,18 @@ use crate::byron::{ AddressIdList, Blake2b256, ByronPubKey, ByronSignature, BytesList, EpochId, StakeholderIdList, VssDecryptedShareList, VssPubKeyList, }; -use crate::impl_wasm_cbor_json_api_byron; use cml_chain_wasm::byron::{AddressId, StakeholderId}; -use cml_core_wasm::impl_wasm_conversions; -use std::collections::BTreeMap; +use cml_core_wasm::{ + impl_wasm_cbor_json_api_cbor_event_serialize, impl_wasm_conversions, impl_wasm_list, + impl_wasm_map_btree, +}; use wasm_bindgen::prelude::{wasm_bindgen, JsValue}; #[derive(Clone, Debug)] #[wasm_bindgen] pub struct Ssc(cml_multi_era::byron::mpc::Ssc); -impl_wasm_cbor_json_api_byron!(Ssc); +impl_wasm_cbor_json_api_cbor_event_serialize!(Ssc); impl_wasm_conversions!(cml_multi_era::byron::mpc::Ssc, Ssc); @@ -101,7 +102,7 @@ impl Ssc { #[wasm_bindgen] pub struct SscCert(cml_multi_era::byron::mpc::SscCert); -impl_wasm_cbor_json_api_byron!(SscCert); +impl_wasm_cbor_json_api_cbor_event_serialize!(SscCert); impl_wasm_conversions!(cml_multi_era::byron::mpc::SscCert, SscCert); @@ -142,7 +143,7 @@ impl SscCert { #[wasm_bindgen] pub struct SscCertificatesPayload(cml_multi_era::byron::mpc::SscCertificatesPayload); -impl_wasm_cbor_json_api_byron!(SscCertificatesPayload); +impl_wasm_cbor_json_api_cbor_event_serialize!(SscCertificatesPayload); impl_wasm_conversions!( cml_multi_era::byron::mpc::SscCertificatesPayload, @@ -166,7 +167,7 @@ impl SscCertificatesPayload { #[wasm_bindgen] pub struct SscCertificatesProof(cml_multi_era::byron::mpc::SscCertificatesProof); -impl_wasm_cbor_json_api_byron!(SscCertificatesProof); +impl_wasm_cbor_json_api_cbor_event_serialize!(SscCertificatesProof); impl_wasm_conversions!( cml_multi_era::byron::mpc::SscCertificatesProof, @@ -186,36 +187,13 @@ impl SscCertificatesProof { } } -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct SscCerts(Vec); - -impl_wasm_conversions!(Vec, SscCerts); - -#[wasm_bindgen] -impl SscCerts { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> SscCert { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &SscCert) { - self.0.push(elem.clone().into()); - } -} +impl_wasm_list!(cml_multi_era::byron::mpc::SscCert, SscCert, SscCerts); #[derive(Clone, Debug)] #[wasm_bindgen] pub struct SscCommitment(cml_multi_era::byron::mpc::SscCommitment); -impl_wasm_cbor_json_api_byron!(SscCommitment); +impl_wasm_cbor_json_api_cbor_event_serialize!(SscCommitment); impl_wasm_conversions!(cml_multi_era::byron::mpc::SscCommitment, SscCommitment); @@ -241,7 +219,7 @@ impl SscCommitment { #[wasm_bindgen] pub struct SscCommitmentsPayload(cml_multi_era::byron::mpc::SscCommitmentsPayload); -impl_wasm_cbor_json_api_byron!(SscCommitmentsPayload); +impl_wasm_cbor_json_api_cbor_event_serialize!(SscCommitmentsPayload); impl_wasm_conversions!( cml_multi_era::byron::mpc::SscCommitmentsPayload, @@ -270,7 +248,7 @@ impl SscCommitmentsPayload { #[wasm_bindgen] pub struct SscCommitmentsProof(cml_multi_era::byron::mpc::SscCommitmentsProof); -impl_wasm_cbor_json_api_byron!(SscCommitmentsProof); +impl_wasm_cbor_json_api_cbor_event_serialize!(SscCommitmentsProof); impl_wasm_conversions!( cml_multi_era::byron::mpc::SscCommitmentsProof, @@ -307,7 +285,7 @@ pub enum SscKind { #[wasm_bindgen] pub struct SscOpeningsPayload(cml_multi_era::byron::mpc::SscOpeningsPayload); -impl_wasm_cbor_json_api_byron!(SscOpeningsPayload); +impl_wasm_cbor_json_api_cbor_event_serialize!(SscOpeningsPayload); impl_wasm_conversions!( cml_multi_era::byron::mpc::SscOpeningsPayload, @@ -336,7 +314,7 @@ impl SscOpeningsPayload { #[wasm_bindgen] pub struct SscOpeningsProof(cml_multi_era::byron::mpc::SscOpeningsProof); -impl_wasm_cbor_json_api_byron!(SscOpeningsProof); +impl_wasm_cbor_json_api_cbor_event_serialize!(SscOpeningsProof); impl_wasm_conversions!( cml_multi_era::byron::mpc::SscOpeningsProof, @@ -361,40 +339,24 @@ impl SscOpeningsProof { } } -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct SscOpens(cml_multi_era::byron::mpc::SscOpens); - -impl_wasm_conversions!(cml_multi_era::byron::mpc::SscOpens, SscOpens); - -#[wasm_bindgen] -impl SscOpens { - pub fn new() -> Self { - Self(BTreeMap::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn insert(&mut self, key: &StakeholderId, value: Vsssec) -> Option { - self.0.insert(key.clone().into(), value) - } - - pub fn get(&self, key: &StakeholderId) -> Option { - self.0.get(key.as_ref()).map(|v| v.clone()) - } - - pub fn keys(&self) -> StakeholderIdList { - StakeholderIdList(self.0.iter().map(|(k, _v)| k.clone()).collect::>()) - } -} +impl_wasm_map_btree!( + cml_chain::byron::StakeholderId, + cml_multi_era::byron::mpc::Vsssec, + StakeholderId, + Vsssec, + StakeholderIdList, + SscOpens, + false, + true, + false, + false +); #[derive(Clone, Debug)] #[wasm_bindgen] pub struct SscProof(cml_multi_era::byron::mpc::SscProof); -impl_wasm_cbor_json_api_byron!(SscProof); +impl_wasm_cbor_json_api_cbor_event_serialize!(SscProof); impl_wasm_conversions!(cml_multi_era::byron::mpc::SscProof, SscProof); @@ -488,42 +450,20 @@ pub enum SscProofKind { SscCertificatesProof, } -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct SscShares(cml_multi_era::byron::mpc::SscShares); - -impl_wasm_conversions!(cml_multi_era::byron::mpc::SscShares, SscShares); - -#[wasm_bindgen] -impl SscShares { - pub fn new() -> Self { - Self(BTreeMap::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn insert(&mut self, key: &AddressId, value: &SscSharesSubmap) -> Option { - self.0 - .insert(key.clone().into(), value.clone().into()) - .map(Into::into) - } - - pub fn get(&self, key: &AddressId) -> Option { - self.0.get(key.as_ref()).map(|v| v.clone().into()) - } - - pub fn keys(&self) -> AddressIdList { - AddressIdList(self.0.iter().map(|(k, _v)| k.clone()).collect::>()) - } -} +impl_wasm_map_btree!( + cml_chain::byron::AddressId, + cml_multi_era::byron::mpc::SscSharesSubmap, + AddressId, + SscSharesSubmap, + AddressIdList, + SscShares +); #[derive(Clone, Debug)] #[wasm_bindgen] pub struct SscSharesPayload(cml_multi_era::byron::mpc::SscSharesPayload); -impl_wasm_cbor_json_api_byron!(SscSharesPayload); +impl_wasm_cbor_json_api_cbor_event_serialize!(SscSharesPayload); impl_wasm_conversions!( cml_multi_era::byron::mpc::SscSharesPayload, @@ -552,7 +492,7 @@ impl SscSharesPayload { #[wasm_bindgen] pub struct SscSharesProof(cml_multi_era::byron::mpc::SscSharesProof); -impl_wasm_cbor_json_api_byron!(SscSharesProof); +impl_wasm_cbor_json_api_cbor_event_serialize!(SscSharesProof); impl_wasm_conversions!(cml_multi_era::byron::mpc::SscSharesProof, SscSharesProof); @@ -574,46 +514,20 @@ impl SscSharesProof { } } -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct SscSharesSubmap(cml_multi_era::byron::mpc::SscSharesSubmap); - -impl_wasm_conversions!(cml_multi_era::byron::mpc::SscSharesSubmap, SscSharesSubmap); - -#[wasm_bindgen] -impl SscSharesSubmap { - pub fn new() -> Self { - Self(BTreeMap::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn insert( - &mut self, - key: &AddressId, - value: &VssDecryptedShareList, - ) -> Option { - self.0 - .insert(key.clone().into(), value.clone().into()) - .map(Into::into) - } - - pub fn get(&self, key: &AddressId) -> Option { - self.0.get(key.as_ref()).map(|v| v.clone().into()) - } - - pub fn keys(&self) -> AddressIdList { - AddressIdList(self.0.iter().map(|(k, _v)| k.clone()).collect::>()) - } -} +impl_wasm_map_btree!( + cml_chain::byron::AddressId, + Vec>, + AddressId, + VssDecryptedShareList, + AddressIdList, + SscSharesSubmap +); #[derive(Clone, Debug)] #[wasm_bindgen] pub struct SscSignedCommitment(cml_multi_era::byron::mpc::SscSignedCommitment); -impl_wasm_cbor_json_api_byron!(SscSignedCommitment); +impl_wasm_cbor_json_api_cbor_event_serialize!(SscSignedCommitment); impl_wasm_conversions!( cml_multi_era::byron::mpc::SscSignedCommitment, @@ -647,41 +561,19 @@ impl SscSignedCommitment { } } -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct SscSignedCommitments(Vec); - -impl_wasm_conversions!( - Vec, +impl_wasm_list!( + cml_multi_era::byron::mpc::SscSignedCommitment, + SscSignedCommitment, SscSignedCommitments ); -#[wasm_bindgen] -impl SscSignedCommitments { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> SscSignedCommitment { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &SscSignedCommitment) { - self.0.push(elem.clone().into()); - } -} - pub type VssDecryptedShare = Vec; #[derive(Clone, Debug)] #[wasm_bindgen] pub struct VssEncryptedShare(cml_multi_era::byron::mpc::VssEncryptedShare); -impl_wasm_cbor_json_api_byron!(VssEncryptedShare); +impl_wasm_cbor_json_api_cbor_event_serialize!(VssEncryptedShare); impl_wasm_conversions!( cml_multi_era::byron::mpc::VssEncryptedShare, @@ -703,7 +595,7 @@ impl VssEncryptedShare { #[wasm_bindgen] pub struct VssProof(cml_multi_era::byron::mpc::VssProof); -impl_wasm_cbor_json_api_byron!(VssProof); +impl_wasm_cbor_json_api_cbor_event_serialize!(VssProof); impl_wasm_conversions!(cml_multi_era::byron::mpc::VssProof, VssProof); @@ -742,37 +634,17 @@ impl VssProof { pub type VssPubKey = Vec; -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct VssShares(cml_multi_era::byron::mpc::VssShares); - -impl_wasm_conversions!(cml_multi_era::byron::mpc::VssShares, VssShares); - -#[wasm_bindgen] -impl VssShares { - pub fn new() -> Self { - Self(BTreeMap::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn insert( - &mut self, - key: VssPubKey, - value: &VssEncryptedShare, - ) -> Option { - self.0.insert(key, value.clone().into()).map(Into::into) - } - - pub fn get(&self, key: VssPubKey) -> Option { - self.0.get(&key).map(|v| v.clone().into()) - } - - pub fn keys(&self) -> VssPubKeyList { - VssPubKeyList(self.0.iter().map(|(k, _v)| k.clone()).collect::>()) - } -} +impl_wasm_map_btree!( + cml_multi_era::byron::mpc::VssPubKey, + cml_multi_era::byron::mpc::VssEncryptedShare, + VssPubKey, + VssEncryptedShare, + VssPubKeyList, + VssShares, + true, + false, + false, + false +); pub type Vsssec = Vec; diff --git a/multi-era/wasm/src/byron/transaction/mod.rs b/multi-era/wasm/src/byron/transaction/mod.rs index 4baa2ccc..df46517a 100644 --- a/multi-era/wasm/src/byron/transaction/mod.rs +++ b/multi-era/wasm/src/byron/transaction/mod.rs @@ -5,50 +5,25 @@ use crate::byron::{ Blake2b256, ByronAny, ByronAnyList, ByronPubKey, ByronSignature, ByronTxId, ByronTxInList, ByronTxOutList, }; -use crate::impl_wasm_cbor_json_api_byron; -use cml_core_wasm::impl_wasm_conversions; -use std::collections::BTreeMap; +use cml_core_wasm::{ + impl_wasm_cbor_json_api_cbor_event_serialize, impl_wasm_conversions, impl_wasm_map_btree, +}; use wasm_bindgen::prelude::{wasm_bindgen, JsValue}; -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct ByronAttributes(cml_multi_era::byron::transaction::ByronAttributes); - -impl_wasm_conversions!( - cml_multi_era::byron::transaction::ByronAttributes, +impl_wasm_map_btree!( + cml_multi_era::byron::ByronAny, + cml_multi_era::byron::ByronAny, + ByronAny, + ByronAny, + ByronAnyList, ByronAttributes ); -#[wasm_bindgen] -impl ByronAttributes { - pub fn new() -> Self { - Self(BTreeMap::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn insert(&mut self, key: &ByronAny, value: &ByronAny) -> Option { - self.0 - .insert(key.clone().into(), value.clone().into()) - .map(Into::into) - } - - pub fn get(&self, key: &ByronAny) -> Option { - self.0.get(key.as_ref()).map(|v| v.clone().into()) - } - - pub fn keys(&self) -> ByronAnyList { - ByronAnyList(self.0.iter().map(|(k, _v)| k.clone()).collect::>()) - } -} - #[derive(Clone, Debug)] #[wasm_bindgen] pub struct ByronPkWitness(cml_multi_era::byron::transaction::ByronPkWitness); -impl_wasm_cbor_json_api_byron!(ByronPkWitness); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronPkWitness); impl_wasm_conversions!( cml_multi_era::byron::transaction::ByronPkWitness, @@ -72,7 +47,7 @@ impl ByronPkWitness { #[wasm_bindgen] pub struct ByronPkWitnessEntry(cml_multi_era::byron::transaction::ByronPkWitnessEntry); -impl_wasm_cbor_json_api_byron!(ByronPkWitnessEntry); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronPkWitnessEntry); impl_wasm_conversions!( cml_multi_era::byron::transaction::ByronPkWitnessEntry, @@ -101,7 +76,7 @@ impl ByronPkWitnessEntry { #[wasm_bindgen] pub struct ByronRedeemWitness(cml_multi_era::byron::transaction::ByronRedeemWitness); -impl_wasm_cbor_json_api_byron!(ByronRedeemWitness); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronRedeemWitness); impl_wasm_conversions!( cml_multi_era::byron::transaction::ByronRedeemWitness, @@ -125,7 +100,7 @@ impl ByronRedeemWitness { #[wasm_bindgen] pub struct ByronRedeemerScript(cml_multi_era::byron::transaction::ByronRedeemerScript); -impl_wasm_cbor_json_api_byron!(ByronRedeemerScript); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronRedeemerScript); impl_wasm_conversions!( cml_multi_era::byron::transaction::ByronRedeemerScript, @@ -153,7 +128,7 @@ impl ByronRedeemerScript { #[wasm_bindgen] pub struct ByronRedeemerWitnessEntry(cml_multi_era::byron::transaction::ByronRedeemerWitnessEntry); -impl_wasm_cbor_json_api_byron!(ByronRedeemerWitnessEntry); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronRedeemerWitnessEntry); impl_wasm_conversions!( cml_multi_era::byron::transaction::ByronRedeemerWitnessEntry, @@ -184,7 +159,7 @@ impl ByronRedeemerWitnessEntry { #[wasm_bindgen] pub struct ByronScriptWitness(cml_multi_era::byron::transaction::ByronScriptWitness); -impl_wasm_cbor_json_api_byron!(ByronScriptWitness); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronScriptWitness); impl_wasm_conversions!( cml_multi_era::byron::transaction::ByronScriptWitness, @@ -208,7 +183,7 @@ impl ByronScriptWitness { #[wasm_bindgen] pub struct ByronScriptWitnessEntry(cml_multi_era::byron::transaction::ByronScriptWitnessEntry); -impl_wasm_cbor_json_api_byron!(ByronScriptWitnessEntry); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronScriptWitnessEntry); impl_wasm_conversions!( cml_multi_era::byron::transaction::ByronScriptWitnessEntry, @@ -242,7 +217,7 @@ impl ByronScriptWitnessEntry { #[wasm_bindgen] pub struct ByronTx(cml_multi_era::byron::transaction::ByronTx); -impl_wasm_cbor_json_api_byron!(ByronTx); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronTx); impl_wasm_conversions!(cml_multi_era::byron::transaction::ByronTx, ByronTx); @@ -273,7 +248,7 @@ impl ByronTx { #[wasm_bindgen] pub struct ByronTxIn(cml_multi_era::byron::transaction::ByronTxIn); -impl_wasm_cbor_json_api_byron!(ByronTxIn); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronTxIn); impl_wasm_conversions!(cml_multi_era::byron::transaction::ByronTxIn, ByronTxIn); @@ -329,7 +304,7 @@ impl ByronTxIn { #[wasm_bindgen] pub struct ByronTxInGenesis(cml_multi_era::byron::transaction::ByronTxInGenesis); -impl_wasm_cbor_json_api_byron!(ByronTxInGenesis); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronTxInGenesis); impl_wasm_conversions!( cml_multi_era::byron::transaction::ByronTxInGenesis, @@ -363,7 +338,7 @@ pub enum ByronTxInKind { #[wasm_bindgen] pub struct ByronTxInRegular(cml_multi_era::byron::transaction::ByronTxInRegular); -impl_wasm_cbor_json_api_byron!(ByronTxInRegular); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronTxInRegular); impl_wasm_conversions!( cml_multi_era::byron::transaction::ByronTxInRegular, @@ -387,7 +362,7 @@ impl ByronTxInRegular { #[wasm_bindgen] pub struct ByronTxOutPtr(cml_multi_era::byron::transaction::ByronTxOutPtr); -impl_wasm_cbor_json_api_byron!(ByronTxOutPtr); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronTxOutPtr); impl_wasm_conversions!( cml_multi_era::byron::transaction::ByronTxOutPtr, @@ -416,7 +391,7 @@ impl ByronTxOutPtr { #[wasm_bindgen] pub struct ByronTxProof(cml_multi_era::byron::transaction::ByronTxProof); -impl_wasm_cbor_json_api_byron!(ByronTxProof); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronTxProof); impl_wasm_conversions!( cml_multi_era::byron::transaction::ByronTxProof, @@ -450,7 +425,7 @@ impl ByronTxProof { #[wasm_bindgen] pub struct ByronTxWitness(cml_multi_era::byron::transaction::ByronTxWitness); -impl_wasm_cbor_json_api_byron!(ByronTxWitness); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronTxWitness); impl_wasm_conversions!( cml_multi_era::byron::transaction::ByronTxWitness, @@ -536,7 +511,7 @@ pub enum ByronTxWitnessKind { #[wasm_bindgen] pub struct ByronValidatorScript(cml_multi_era::byron::transaction::ByronValidatorScript); -impl_wasm_cbor_json_api_byron!(ByronValidatorScript); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronValidatorScript); impl_wasm_conversions!( cml_multi_era::byron::transaction::ByronValidatorScript, diff --git a/multi-era/wasm/src/byron/update/mod.rs b/multi-era/wasm/src/byron/update/mod.rs index a12154c7..d95e0aa5 100644 --- a/multi-era/wasm/src/byron/update/mod.rs +++ b/multi-era/wasm/src/byron/update/mod.rs @@ -7,16 +7,15 @@ use crate::byron::{ MapSystemTagToByronUpdateData, SoftForkRuleList, }; use crate::byron::{Blake2b256, ByronPubKey, ByronSignature, ByronUpdateId, EpochId}; -use crate::impl_wasm_cbor_json_api_byron; use cml_chain_wasm::utils::BigInt; -use cml_core_wasm::impl_wasm_conversions; +use cml_core_wasm::{impl_wasm_cbor_json_api_cbor_event_serialize, impl_wasm_conversions}; use wasm_bindgen::prelude::{wasm_bindgen, JsValue}; #[derive(Clone, Debug)] #[wasm_bindgen] pub struct Bvermod(cml_multi_era::byron::update::Bvermod); -impl_wasm_cbor_json_api_byron!(Bvermod); +impl_wasm_cbor_json_api_cbor_event_serialize!(Bvermod); impl_wasm_conversions!(cml_multi_era::byron::update::Bvermod, Bvermod); @@ -117,7 +116,7 @@ impl Bvermod { #[wasm_bindgen] pub struct ByronBlockVersion(cml_multi_era::byron::update::ByronBlockVersion); -impl_wasm_cbor_json_api_byron!(ByronBlockVersion); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronBlockVersion); impl_wasm_conversions!( cml_multi_era::byron::update::ByronBlockVersion, @@ -149,7 +148,7 @@ impl ByronBlockVersion { #[wasm_bindgen] pub struct ByronSoftwareVersion(cml_multi_era::byron::update::ByronSoftwareVersion); -impl_wasm_cbor_json_api_byron!(ByronSoftwareVersion); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronSoftwareVersion); impl_wasm_conversions!( cml_multi_era::byron::update::ByronSoftwareVersion, @@ -178,7 +177,7 @@ impl ByronSoftwareVersion { #[wasm_bindgen] pub struct ByronTxFeePolicy(cml_multi_era::byron::update::ByronTxFeePolicy); -impl_wasm_cbor_json_api_byron!(ByronTxFeePolicy); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronTxFeePolicy); impl_wasm_conversions!( cml_multi_era::byron::update::ByronTxFeePolicy, @@ -202,7 +201,7 @@ impl ByronTxFeePolicy { #[wasm_bindgen] pub struct ByronUpdate(cml_multi_era::byron::update::ByronUpdate); -impl_wasm_cbor_json_api_byron!(ByronUpdate); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronUpdate); impl_wasm_conversions!(cml_multi_era::byron::update::ByronUpdate, ByronUpdate); @@ -228,7 +227,7 @@ impl ByronUpdate { #[wasm_bindgen] pub struct ByronUpdateData(cml_multi_era::byron::update::ByronUpdateData); -impl_wasm_cbor_json_api_byron!(ByronUpdateData); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronUpdateData); impl_wasm_conversions!( cml_multi_era::byron::update::ByronUpdateData, @@ -272,7 +271,7 @@ impl ByronUpdateData { #[wasm_bindgen] pub struct ByronUpdateProposal(cml_multi_era::byron::update::ByronUpdateProposal); -impl_wasm_cbor_json_api_byron!(ByronUpdateProposal); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronUpdateProposal); impl_wasm_conversions!( cml_multi_era::byron::update::ByronUpdateProposal, @@ -334,7 +333,7 @@ impl ByronUpdateProposal { #[wasm_bindgen] pub struct ByronUpdateVote(cml_multi_era::byron::update::ByronUpdateVote); -impl_wasm_cbor_json_api_byron!(ByronUpdateVote); +impl_wasm_cbor_json_api_cbor_event_serialize!(ByronUpdateVote); impl_wasm_conversions!( cml_multi_era::byron::update::ByronUpdateVote, @@ -380,7 +379,7 @@ pub type CoinPortion = u64; #[wasm_bindgen] pub struct SoftForkRule(cml_multi_era::byron::update::SoftForkRule); -impl_wasm_cbor_json_api_byron!(SoftForkRule); +impl_wasm_cbor_json_api_cbor_event_serialize!(SoftForkRule); impl_wasm_conversions!(cml_multi_era::byron::update::SoftForkRule, SoftForkRule); @@ -415,7 +414,7 @@ impl SoftForkRule { #[wasm_bindgen] pub struct StdFeePolicy(cml_multi_era::byron::update::StdFeePolicy); -impl_wasm_cbor_json_api_byron!(StdFeePolicy); +impl_wasm_cbor_json_api_cbor_event_serialize!(StdFeePolicy); impl_wasm_conversions!(cml_multi_era::byron::update::StdFeePolicy, StdFeePolicy); diff --git a/multi-era/wasm/src/byron/utils.rs b/multi-era/wasm/src/byron/utils.rs index 16a1e9fb..a7b53669 100644 --- a/multi-era/wasm/src/byron/utils.rs +++ b/multi-era/wasm/src/byron/utils.rs @@ -20,56 +20,3 @@ pub struct ByronAny(cml_multi_era::byron::ByronAny); // useful on-chain for this. It's either not present or is an empty array impl_wasm_conversions!(cml_multi_era::byron::ByronAny, ByronAny); - -/// We use this instead of cml_core::impl_wasm_cbor_json_api due to not implementing -/// cml's Serialize. Byron just does cbor_event's due to not supporting preserve-encodings=true -/// All other methods are identical to cml_core's macro though. -#[macro_export] -macro_rules! impl_wasm_cbor_json_api_byron { - ($wasm_name:ident) => { - #[wasm_bindgen::prelude::wasm_bindgen] - impl $wasm_name { - pub fn to_cbor_bytes(&self) -> Vec { - cml_core::serialization::ToBytes::to_bytes(&self.0) - } - - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result<$wasm_name, JsValue> { - cml_chain::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| { - JsValue::from_str(&format!( - concat!(stringify!($wasm_name), "::from_cbor_bytes: {}"), - e - )) - }) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0).map_err(|e| { - JsValue::from_str(&format!( - concat!(stringify!($wasm_name), "::to_json: {}"), - e - )) - }) - } - - pub fn to_js_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0).map_err(|e| { - JsValue::from_str(&format!( - concat!(stringify!($wasm_name), "::to_js_value: {}"), - e - )) - }) - } - - pub fn from_json(json: &str) -> Result<$wasm_name, JsValue> { - serde_json::from_str(json).map(Self).map_err(|e| { - JsValue::from_str(&format!( - concat!(stringify!($wasm_name), "::from_json: {}"), - e - )) - }) - } - } - }; -} diff --git a/multi-era/wasm/src/lib.rs b/multi-era/wasm/src/lib.rs index c292258c..f8f6d337 100644 --- a/multi-era/wasm/src/lib.rs +++ b/multi-era/wasm/src/lib.rs @@ -30,534 +30,102 @@ use cml_chain_wasm::{ block::Block, certs::StakeCredential, transaction::ShelleyTxOut, Coin, StakeCredentialList, TransactionIndex, }; -use cml_core::ordered_hash_map::OrderedHashMap; +use cml_core_wasm::{ + impl_wasm_cbor_json_api, impl_wasm_conversions, impl_wasm_list, impl_wasm_map, +}; use wasm_bindgen::prelude::{wasm_bindgen, JsValue}; -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct AllegraTransactionBodyList(Vec); - -#[wasm_bindgen] -impl AllegraTransactionBodyList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> AllegraTransactionBody { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &AllegraTransactionBody) { - self.0.push(elem.clone().into()); - } -} - -impl From> for AllegraTransactionBodyList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: AllegraTransactionBodyList) -> Self { - wasm.0 - } -} - -impl AsRef> for AllegraTransactionBodyList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct AllegraTransactionWitnessSetList( - Vec, +impl_wasm_list!( + cml_multi_era::allegra::AllegraTransactionBody, + AllegraTransactionBody, + AllegraTransactionBodyList ); -#[wasm_bindgen] -impl AllegraTransactionWitnessSetList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> AllegraTransactionWitnessSet { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &AllegraTransactionWitnessSet) { - self.0.push(elem.clone().into()); - } -} - -impl From> - for AllegraTransactionWitnessSetList -{ - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From - for Vec -{ - fn from(wasm: AllegraTransactionWitnessSetList) -> Self { - wasm.0 - } -} - -impl AsRef> - for AllegraTransactionWitnessSetList -{ - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct AlonzoTransactionBodyList(Vec); - -#[wasm_bindgen] -impl AlonzoTransactionBodyList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> AlonzoTransactionBody { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &AlonzoTransactionBody) { - self.0.push(elem.clone().into()); - } -} - -impl From> for AlonzoTransactionBodyList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: AlonzoTransactionBodyList) -> Self { - wasm.0 - } -} - -impl AsRef> for AlonzoTransactionBodyList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct AlonzoTransactionWitnessSetList(Vec); - -#[wasm_bindgen] -impl AlonzoTransactionWitnessSetList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> AlonzoTransactionWitnessSet { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &AlonzoTransactionWitnessSet) { - self.0.push(elem.clone().into()); - } -} - -impl From> - for AlonzoTransactionWitnessSetList -{ - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From - for Vec -{ - fn from(wasm: AlonzoTransactionWitnessSetList) -> Self { - wasm.0 - } -} - -impl AsRef> - for AlonzoTransactionWitnessSetList -{ - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct AlonzoTransactionOutputList(Vec); - -#[wasm_bindgen] -impl AlonzoTransactionOutputList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> AlonzoTransactionOutput { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &AlonzoTransactionOutput) { - self.0.push(elem.clone().into()); - } -} - -impl From> for AlonzoTransactionOutputList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: AlonzoTransactionOutputList) -> Self { - wasm.0 - } -} - -impl AsRef> for AlonzoTransactionOutputList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct MapStakeCredentialToCoin( - OrderedHashMap, +impl_wasm_list!( + cml_multi_era::allegra::AllegraTransactionWitnessSet, + AllegraTransactionWitnessSet, + AllegraTransactionWitnessSetList ); -#[wasm_bindgen] -impl MapStakeCredentialToCoin { - pub fn new() -> Self { - Self(OrderedHashMap::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn insert(&mut self, key: &StakeCredential, value: Coin) -> Option { - self.0.insert(key.clone().into(), value) - } - - pub fn get(&self, key: &StakeCredential) -> Option { - self.0.get(key.as_ref()).copied() - } - - pub fn keys(&self) -> StakeCredentialList { - self.0 - .iter() - .map(|(k, _v)| k.clone()) - .collect::>() - .into() - } -} - -impl From> - for MapStakeCredentialToCoin -{ - fn from( - native: OrderedHashMap, - ) -> Self { - Self(native) - } -} - -impl From - for OrderedHashMap -{ - fn from(wasm: MapStakeCredentialToCoin) -> Self { - wasm.0 - } -} - -impl AsRef> - for MapStakeCredentialToCoin -{ - fn as_ref( - &self, - ) -> &OrderedHashMap { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct MapTransactionIndexToAllegraAuxiliaryData( - OrderedHashMap, +impl_wasm_list!( + cml_multi_era::alonzo::AlonzoTransactionBody, + AlonzoTransactionBody, + AlonzoTransactionBodyList ); -#[wasm_bindgen] -impl MapTransactionIndexToAllegraAuxiliaryData { - pub fn new() -> Self { - Self(OrderedHashMap::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn insert( - &mut self, - key: TransactionIndex, - value: &AllegraAuxiliaryData, - ) -> Option { - self.0.insert(key, value.clone().into()).map(Into::into) - } - - pub fn get(&self, key: TransactionIndex) -> Option { - self.0.get(&key).map(|v| v.clone().into()) - } - - pub fn keys(&self) -> Vec { - self.0.keys().copied().collect::>() - } -} - -impl From> - for MapTransactionIndexToAllegraAuxiliaryData -{ - fn from( - native: OrderedHashMap< - cml_chain::TransactionIndex, - cml_multi_era::allegra::AllegraAuxiliaryData, - >, - ) -> Self { - Self(native) - } -} - -impl From - for OrderedHashMap -{ - fn from(wasm: MapTransactionIndexToAllegraAuxiliaryData) -> Self { - wasm.0 - } -} - -impl - AsRef> - for MapTransactionIndexToAllegraAuxiliaryData -{ - fn as_ref( - &self, - ) -> &OrderedHashMap - { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct MapTransactionIndexToAlonzoAuxiliaryData( - OrderedHashMap, +impl_wasm_list!( + cml_multi_era::alonzo::AlonzoTransactionWitnessSet, + AlonzoTransactionWitnessSet, + AlonzoTransactionWitnessSetList ); -#[wasm_bindgen] -impl MapTransactionIndexToAlonzoAuxiliaryData { - pub fn new() -> Self { - Self(OrderedHashMap::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn insert( - &mut self, - key: TransactionIndex, - value: &AlonzoAuxiliaryData, - ) -> Option { - self.0.insert(key, value.clone().into()).map(Into::into) - } - - pub fn get(&self, key: TransactionIndex) -> Option { - self.0.get(&key).map(|v| v.clone().into()) - } - - pub fn keys(&self) -> Vec { - self.0.keys().copied().collect::>() - } -} - -impl From> - for MapTransactionIndexToAlonzoAuxiliaryData -{ - fn from( - native: OrderedHashMap< - cml_chain::TransactionIndex, - cml_multi_era::alonzo::AlonzoAuxiliaryData, - >, - ) -> Self { - Self(native) - } -} - -impl From - for OrderedHashMap -{ - fn from(wasm: MapTransactionIndexToAlonzoAuxiliaryData) -> Self { - wasm.0 - } -} - -impl AsRef> - for MapTransactionIndexToAlonzoAuxiliaryData -{ - fn as_ref( - &self, - ) -> &OrderedHashMap - { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct MaryTransactionBodyList(Vec); - -#[wasm_bindgen] -impl MaryTransactionBodyList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } +impl_wasm_list!( + cml_multi_era::alonzo::AlonzoTransactionOutput, + AlonzoTransactionOutput, + AlonzoTransactionOutputList +); - pub fn get(&self, index: usize) -> MaryTransactionBody { - self.0[index].clone().into() - } +impl_wasm_map!( + cml_chain::certs::StakeCredential, + cml_chain::assets::Coin, + StakeCredential, + Coin, + StakeCredentialList, + MapStakeCredentialToCoin, + false, + true, + false, + true +); - pub fn add(&mut self, elem: &MaryTransactionBody) { - self.0.push(elem.clone().into()); - } -} +impl_wasm_map!( + cml_chain::TransactionIndex, + cml_multi_era::allegra::AllegraAuxiliaryData, + TransactionIndex, + AllegraAuxiliaryData, + Vec, + MapTransactionIndexToAllegraAuxiliaryData, + true, + false, + true, + false +); -impl From> for MaryTransactionBodyList { - fn from(native: Vec) -> Self { - Self(native) - } -} +impl_wasm_map!( + cml_chain::TransactionIndex, + cml_multi_era::alonzo::AlonzoAuxiliaryData, + TransactionIndex, + AlonzoAuxiliaryData, + Vec, + MapTransactionIndexToAlonzoAuxiliaryData, + true, + false, + true, + false +); -impl From for Vec { - fn from(wasm: MaryTransactionBodyList) -> Self { - wasm.0 - } -} +impl_wasm_list!( + cml_multi_era::mary::MaryTransactionBody, + MaryTransactionBody, + MaryTransactionBodyList +); -impl AsRef> for MaryTransactionBodyList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} +impl_wasm_list!( + cml_multi_era::shelley::MultisigScript, + MultisigScript, + MultisigScriptList +); #[derive(Clone, Debug)] #[wasm_bindgen] -pub struct MultisigScriptList(Vec); - -#[wasm_bindgen] -impl MultisigScriptList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> MultisigScript { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &MultisigScript) { - self.0.push(elem.clone().into()); - } -} - -impl From> for MultisigScriptList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: MultisigScriptList) -> Self { - wasm.0 - } -} +pub struct MultiEraBlock(cml_multi_era::MultiEraBlock); -impl AsRef> for MultisigScriptList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} +impl_wasm_cbor_json_api!(MultiEraBlock); -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct MultiEraBlock(cml_multi_era::MultiEraBlock); +impl_wasm_conversions!(cml_multi_era::MultiEraBlock, MultiEraBlock); #[wasm_bindgen] impl MultiEraBlock { - pub fn to_cbor_bytes(&self) -> Vec { - cml_core::serialization::Serialize::to_cbor_bytes(&self.0) - } - - pub fn from_cbor_bytes(cbor_bytes: &[u8]) -> Result { - cml_core::serialization::Deserialize::from_cbor_bytes(cbor_bytes) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_bytes: {}", e))) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_json: {}", e))) - } - - pub fn to_json_value(&self) -> Result { - serde_wasm_bindgen::to_value(&self.0) - .map_err(|e| JsValue::from_str(&format!("to_js_value: {}", e))) - } - - pub fn from_json(json: &str) -> Result { - serde_json::from_str(json) - .map(Self) - .map_err(|e| JsValue::from_str(&format!("from_json: {}", e))) - } - pub fn new_byron(byron: &ByronBlock) -> Self { Self(cml_multi_era::MultiEraBlock::new_byron( byron.clone().into(), @@ -646,24 +214,6 @@ impl MultiEraBlock { } } -impl From for MultiEraBlock { - fn from(native: cml_multi_era::MultiEraBlock) -> Self { - Self(native) - } -} - -impl From for cml_multi_era::MultiEraBlock { - fn from(wasm: MultiEraBlock) -> Self { - wasm.0 - } -} - -impl AsRef for MultiEraBlock { - fn as_ref(&self) -> &cml_multi_era::MultiEraBlock { - &self.0 - } -} - #[wasm_bindgen] pub enum MultiEraBlockKind { Byron, @@ -674,174 +224,26 @@ pub enum MultiEraBlockKind { Babbage, } -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct ShelleyTransactionBodyList(Vec); - -#[wasm_bindgen] -impl ShelleyTransactionBodyList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> ShelleyTransactionBody { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &ShelleyTransactionBody) { - self.0.push(elem.clone().into()); - } -} - -impl From> for ShelleyTransactionBodyList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: ShelleyTransactionBodyList) -> Self { - wasm.0 - } -} - -impl AsRef> for ShelleyTransactionBodyList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct ShelleyTransactionOutputList(Vec); - -#[wasm_bindgen] -impl ShelleyTransactionOutputList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> ShelleyTransactionOutput { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &ShelleyTransactionOutput) { - self.0.push(elem.clone().into()); - } -} - -impl From> for ShelleyTransactionOutputList { - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From for Vec { - fn from(wasm: ShelleyTransactionOutputList) -> Self { - wasm.0 - } -} - -impl AsRef> for ShelleyTransactionOutputList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct ShelleyTransactionWitnessSetList( - Vec, +impl_wasm_list!( + cml_multi_era::shelley::ShelleyTransactionBody, + ShelleyTransactionBody, + ShelleyTransactionBodyList ); -#[wasm_bindgen] -impl ShelleyTransactionWitnessSetList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> ShelleyTransactionWitnessSet { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &ShelleyTransactionWitnessSet) { - self.0.push(elem.clone().into()); - } -} - -impl From> - for ShelleyTransactionWitnessSetList -{ - fn from(native: Vec) -> Self { - Self(native) - } -} - -impl From - for Vec -{ - fn from(wasm: ShelleyTransactionWitnessSetList) -> Self { - wasm.0 - } -} - -impl AsRef> - for ShelleyTransactionWitnessSetList -{ - fn as_ref(&self) -> &Vec { - &self.0 - } -} - -#[derive(Clone, Debug)] -#[wasm_bindgen] -pub struct ShelleyTxOutList(Vec); - -#[wasm_bindgen] -impl ShelleyTxOutList { - pub fn new() -> Self { - Self(Vec::new()) - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn get(&self, index: usize) -> ShelleyTxOut { - self.0[index].clone().into() - } - - pub fn add(&mut self, elem: &ShelleyTxOut) { - self.0.push(elem.clone().into()); - } -} - -impl From> for ShelleyTxOutList { - fn from(native: Vec) -> Self { - Self(native) - } -} +impl_wasm_list!( + cml_multi_era::shelley::ShelleyTransactionOutput, + ShelleyTransactionOutput, + ShelleyTransactionOutputList +); -impl From for Vec { - fn from(wasm: ShelleyTxOutList) -> Self { - wasm.0 - } -} +impl_wasm_list!( + cml_multi_era::shelley::ShelleyTransactionWitnessSet, + ShelleyTransactionWitnessSet, + ShelleyTransactionWitnessSetList +); -impl AsRef> for ShelleyTxOutList { - fn as_ref(&self) -> &Vec { - &self.0 - } -} +impl_wasm_list!( + cml_chain::transaction::ShelleyTxOut, + ShelleyTxOut, + ShelleyTxOutList +); diff --git a/multi-era/wasm/src/shelley/mod.rs b/multi-era/wasm/src/shelley/mod.rs index 9d33494f..2acd0793 100644 --- a/multi-era/wasm/src/shelley/mod.rs +++ b/multi-era/wasm/src/shelley/mod.rs @@ -563,7 +563,7 @@ impl ShelleyMoveInstantaneousReward { pub fn new(pot: MIRPot, to_stake_credentials: &MapStakeCredentialToCoin) -> Self { Self(cml_multi_era::shelley::ShelleyMoveInstantaneousReward::new( - pot.into(), + pot, to_stake_credentials.clone().into(), )) }