From 5705cb799ecc5ac2a2c51daaa3305cc584c457cd Mon Sep 17 00:00:00 2001 From: Alex Coats Date: Wed, 7 Jun 2023 16:38:09 -0400 Subject: [PATCH 1/8] Use owned data over refs for dto conversions --- bindings/core/src/lib.rs | 8 +- bindings/core/src/method_handler/account.rs | 62 ++++++--------- bindings/core/src/method_handler/client.rs | 16 ++-- .../core/src/method_handler/secret_manager.rs | 2 +- bindings/core/src/method_handler/utils.rs | 10 +-- bindings/nodejs/src/secret_manager.rs | 2 +- bindings/python/src/secret_manager.rs | 2 +- bindings/wasm/src/secret_manager.rs | 2 +- .../offline_signing/2_transaction_signing.rs | 2 +- .../client/offline_signing/3_send_block.rs | 2 +- .../offline_signing/2_sign_transaction.rs | 2 +- .../offline_signing/3_send_transaction.rs | 2 +- .../input_selection/core/burn.rs | 23 ++---- sdk/src/client/api/block_builder/mod.rs | 4 +- sdk/src/client/api/types.rs | 40 +++++----- sdk/src/client/node_api/core/routes.rs | 12 +-- sdk/src/client/secret/mod.rs | 25 ++++--- sdk/src/client/secret/types.rs | 31 +++++--- sdk/src/types/block/address/alias.rs | 4 +- sdk/src/types/block/address/ed25519.rs | 4 +- sdk/src/types/block/address/mod.rs | 4 +- sdk/src/types/block/address/nft.rs | 4 +- sdk/src/types/block/block.rs | 30 ++++---- sdk/src/types/block/input/mod.rs | 4 +- sdk/src/types/block/input/treasury.rs | 4 +- sdk/src/types/block/input/utxo.rs | 4 +- sdk/src/types/block/output/alias.rs | 60 ++++++++++----- sdk/src/types/block/output/basic.rs | 39 +++++----- sdk/src/types/block/output/feature/mod.rs | 8 +- sdk/src/types/block/output/foundry.rs | 56 ++++++++------ sdk/src/types/block/output/metadata.rs | 4 +- sdk/src/types/block/output/mod.rs | 4 +- sdk/src/types/block/output/native_token.rs | 4 +- sdk/src/types/block/output/nft.rs | 49 +++++++----- .../types/block/output/token_scheme/mod.rs | 4 +- .../types/block/output/token_scheme/simple.rs | 10 +-- sdk/src/types/block/output/treasury.rs | 4 +- .../block/output/unlock_condition/address.rs | 6 +- .../output/unlock_condition/expiration.rs | 6 +- .../unlock_condition/governor_address.rs | 7 +- .../immutable_alias_address.rs | 11 +-- .../block/output/unlock_condition/mod.rs | 4 +- .../state_controller_address.rs | 6 +- .../storage_deposit_return.rs | 8 +- .../block/output/unlock_condition/timelock.rs | 4 +- sdk/src/types/block/payload/milestone/mod.rs | 16 ++-- .../block/payload/milestone/option/mod.rs | 4 +- .../payload/milestone/option/parameters.rs | 4 +- .../option/receipt/migrated_funds_entry.rs | 8 +- .../payload/milestone/option/receipt/mod.rs | 16 ++-- sdk/src/types/block/payload/mod.rs | 24 +++--- .../types/block/payload/tagged_data/mod.rs | 4 +- .../block/payload/transaction/essence/mod.rs | 4 +- .../payload/transaction/essence/regular.rs | 63 +++++++++------- .../types/block/payload/transaction/mod.rs | 40 +++++----- .../block/payload/treasury_transaction/mod.rs | 38 +++++----- sdk/src/types/block/signature/ed25519.rs | 4 +- sdk/src/types/block/signature/mod.rs | 4 +- sdk/src/types/block/unlock/mod.rs | 6 +- .../transaction/high_level/create_alias.rs | 10 +-- .../high_level/minting/mint_native_token.rs | 21 +++--- .../high_level/minting/mint_nfts.rs | 32 ++++---- .../account/operations/transaction/options.rs | 18 ++--- .../operations/transaction/prepare_output.rs | 25 +++---- sdk/src/wallet/account/update.rs | 2 +- .../message_interface/message_handler.rs | 75 +++++++------------ sdk/src/wallet/message_interface/mod.rs | 2 +- sdk/src/wallet/storage/manager.rs | 2 +- .../operations/stronghold_backup/mod.rs | 4 +- sdk/tests/client/input_signing_data.rs | 4 +- sdk/tests/types/address/alias.rs | 6 +- sdk/tests/types/address/ed25519.rs | 6 +- sdk/tests/types/address/nft.rs | 6 +- sdk/tests/types/input/treasury.rs | 6 +- sdk/tests/types/input/utxo.rs | 8 +- 75 files changed, 535 insertions(+), 526 deletions(-) diff --git a/bindings/core/src/lib.rs b/bindings/core/src/lib.rs index dea7c45401..9bf83839c7 100644 --- a/bindings/core/src/lib.rs +++ b/bindings/core/src/lib.rs @@ -49,7 +49,7 @@ pub struct WalletOptions { } impl WalletOptions { - pub async fn build_manager(&self) -> iota_sdk::wallet::Result { + pub async fn build_manager(self) -> iota_sdk::wallet::Result { log::debug!("build_manager {self:?}"); let mut builder = Wallet::builder(); @@ -58,12 +58,12 @@ impl WalletOptions { builder = builder.with_storage_path(storage_path); } - if let Some(secret_manager) = &self.secret_manager { + if let Some(secret_manager) = self.secret_manager { builder = builder.with_secret_manager(SecretManager::try_from(secret_manager)?); } - if let Some(client_options) = &self.client_options { - builder = builder.with_client_options(client_options.clone()); + if let Some(client_options) = self.client_options { + builder = builder.with_client_options(client_options); } if let Some(coin_type) = self.coin_type { diff --git a/bindings/core/src/method_handler/account.rs b/bindings/core/src/method_handler/account.rs index 5cdd358621..17a8357a4c 100644 --- a/bindings/core/src/method_handler/account.rs +++ b/bindings/core/src/method_handler/account.rs @@ -111,7 +111,7 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco Response::Transactions(transactions.iter().map(TransactionDto::from).collect()) } AccountMethod::MinimumRequiredStorageDeposit { output } => { - let output = Output::try_from_dto(&output, account.client().get_token_supply().await?)?; + let output = Output::try_from_dto(output, account.client().get_token_supply().await?)?; let rent_structure = account.client().get_rent_structure().await?; let minimum_storage_deposit = output.rent_cost(&rent_structure); @@ -129,8 +129,8 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco AccountMethod::PrepareBurn { burn, options } => { let data = account .prepare_burn( - Burn::try_from(&burn)?, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + Burn::try_from(burn)?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Response::PreparedTransaction(PreparedTransactionDataDto::from(&data)) @@ -145,15 +145,10 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco Response::PreparedTransaction(PreparedTransactionDataDto::from(&data)) } AccountMethod::PrepareCreateAliasOutput { params, options } => { - let params = params - .map(|options| CreateAliasParams::try_from(&options)) - .transpose()?; + let params = params.map(CreateAliasParams::try_from).transpose()?; let data = account - .prepare_create_alias_output( - params, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, - ) + .prepare_create_alias_output(params, options.map(TransactionOptions::try_from_dto).transpose()?) .await?; Response::PreparedTransaction(PreparedTransactionDataDto::from(&data)) } @@ -166,7 +161,7 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco .prepare_decrease_native_token_supply( token_id, U256::try_from(&melt_amount).map_err(|_| Error::InvalidField("melt_amount"))?, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Response::PreparedTransaction(PreparedTransactionDataDto::from(&data)) @@ -189,7 +184,7 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco .prepare_increase_native_token_supply( token_id, U256::try_from(&mint_amount).map_err(|_| Error::InvalidField("mint_amount"))?, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Response::PreparedMintTokenTransaction(PreparedMintTokenTransactionDto::from(&data)) @@ -207,10 +202,10 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco let data = account .prepare_mint_nfts( params - .iter() + .into_iter() .map(MintNftParams::try_from) .collect::>>()?, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Response::PreparedTransaction(PreparedTransactionDataDto::from(&data)) @@ -218,8 +213,8 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco AccountMethod::PrepareMintNativeToken { params, options } => { let data = account .prepare_mint_native_token( - MintNativeTokenParams::try_from(¶ms)?, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + MintNativeTokenParams::try_from(params)?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Response::PreparedMintTokenTransaction(PreparedMintTokenTransactionDto::from(&data)) @@ -230,21 +225,15 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco } => { let output = account .prepare_output( - OutputParams::try_from(options.as_ref())?, - transaction_options - .as_ref() - .map(TransactionOptions::try_from_dto) - .transpose()?, + OutputParams::try_from(*options)?, + transaction_options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Response::Output(OutputDto::from(&output)) } AccountMethod::PrepareSendAmount { params, options } => { let data = account - .prepare_send_amount( - params, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, - ) + .prepare_send_amount(params, options.map(TransactionOptions::try_from_dto).transpose()?) .await?; Response::PreparedTransaction(PreparedTransactionDataDto::from(&data)) } @@ -252,7 +241,7 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco let data = account .prepare_send_native_tokens( params.clone(), - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Response::PreparedTransaction(PreparedTransactionDataDto::from(&data)) @@ -261,7 +250,7 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco let data = account .prepare_send_nft( params.clone(), - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Response::PreparedTransaction(PreparedTransactionDataDto::from(&data)) @@ -276,10 +265,10 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco let data = account .prepare_transaction( outputs - .iter() + .into_iter() .map(|o| Ok(Output::try_from_dto(o, token_supply)?)) .collect::>>()?, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Response::PreparedTransaction(PreparedTransactionDataDto::from(&data)) @@ -306,10 +295,7 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco } AccountMethod::SendAmount { params, options } => { let transaction = account - .send_amount( - params, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, - ) + .send_amount(params, options.map(TransactionOptions::try_from_dto).transpose()?) .await?; Response::SentTransaction(TransactionDto::from(&transaction)) } @@ -318,10 +304,10 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco let transaction = account .send( outputs - .iter() + .into_iter() .map(|o| Ok(Output::try_from_dto(o, token_supply)?)) .collect::>>()?, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Response::SentTransaction(TransactionDto::from(&transaction)) @@ -339,7 +325,7 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco } => { let transaction = account .sign_and_submit_transaction(PreparedTransactionData::try_from_dto( - &prepared_transaction_data, + prepared_transaction_data, &account.client().get_protocol_parameters().await?, )?) .await?; @@ -350,7 +336,7 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco } => { let signed_transaction_data = account .sign_transaction_essence(&PreparedTransactionData::try_from_dto( - &prepared_transaction_data, + prepared_transaction_data, &account.client().get_protocol_parameters().await?, )?) .await?; @@ -360,7 +346,7 @@ pub(crate) async fn call_account_method_internal(account: &Account, method: Acco signed_transaction_data, } => { let signed_transaction_data = SignedTransactionData::try_from_dto( - &signed_transaction_data, + signed_transaction_data, &account.client().get_protocol_parameters().await?, )?; let transaction = account.submit_and_store_transaction(signed_transaction_data).await?; diff --git a/bindings/core/src/method_handler/client.rs b/bindings/core/src/method_handler/client.rs index c154f75ad3..0f6c5cc615 100644 --- a/bindings/core/src/method_handler/client.rs +++ b/bindings/core/src/method_handler/client.rs @@ -137,7 +137,7 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM }, native_tokens, serial_number, - &token_scheme, + token_scheme, unlock_conditions, features, immutable_features, @@ -178,7 +178,7 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM let mut block_builder = client.block(); let secret_manager = match secret_manager { - Some(secret_manager) => Some((&secret_manager).try_into()?), + Some(secret_manager) => Some(secret_manager.try_into()?), None => None, }; @@ -232,7 +232,7 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM let mut block_builder = client.block(); let secret_manager = match secret_manager { - Some(secret_manager) => Some((&secret_manager).try_into()?), + Some(secret_manager) => Some(secret_manager.try_into()?), None => None, }; @@ -254,14 +254,14 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM } => { let mut block_builder = client.block(); - let secret_manager = (&secret_manager).try_into()?; + let secret_manager = secret_manager.try_into()?; block_builder = block_builder.with_secret_manager(&secret_manager); Response::SignedTransaction(PayloadDto::from( &block_builder .sign_transaction(PreparedTransactionData::try_from_dto_unverified( - &prepared_transaction_data, + prepared_transaction_data, )?) .await?, )) @@ -271,7 +271,7 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM let block = block_builder .finish_block(Some(Payload::try_from_dto( - &payload, + payload, &client.get_protocol_parameters().await?, )?)) .await?; @@ -297,7 +297,7 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM ), ClientMethod::PostBlock { block } => Response::BlockId( client - .post_block(&Block::try_from_dto(&block, &client.get_protocol_parameters().await?)?) + .post_block(&Block::try_from_dto(block, &client.get_protocol_parameters().await?)?) .await?, ), ClientMethod::GetBlock { block_id } => Response::Block(BlockDto::from(&client.get_block(&block_id).await?)), @@ -404,7 +404,7 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM secret_manager, generate_addresses_options, } => { - let secret_manager = (&secret_manager).try_into()?; + let secret_manager = secret_manager.try_into()?; Response::ConsolidatedFunds( client .consolidate_funds(&secret_manager, generate_addresses_options) diff --git a/bindings/core/src/method_handler/secret_manager.rs b/bindings/core/src/method_handler/secret_manager.rs index 1a04c58b05..3a24f6bfdc 100644 --- a/bindings/core/src/method_handler/secret_manager.rs +++ b/bindings/core/src/method_handler/secret_manager.rs @@ -41,7 +41,7 @@ pub(crate) async fn call_secret_manager_method_internal( } => { let payload = &secret_manager .sign_transaction(PreparedTransactionData::try_from_dto_unverified( - &prepared_transaction_data, + prepared_transaction_data, )?) .await?; Response::SignedTransaction(PayloadDto::from(payload)) diff --git a/bindings/core/src/method_handler/utils.rs b/bindings/core/src/method_handler/utils.rs index 039f08f939..ad326286af 100644 --- a/bindings/core/src/method_handler/utils.rs +++ b/bindings/core/src/method_handler/utils.rs @@ -36,11 +36,11 @@ pub(crate) fn call_utils_method_internal(method: UtilsMethod) -> Result { - let block = Block::try_from_dto_unverified(&block)?; + let block = Block::try_from_dto_unverified(block)?; Response::BlockId(block.id()) } UtilsMethod::TransactionId { payload } => { - let payload = TransactionPayload::try_from_dto_unverified(&payload)?; + let payload = TransactionPayload::try_from_dto_unverified(payload)?; Response::TransactionId(payload.id()) } UtilsMethod::ComputeAliasId { output_id } => Response::AliasId(AliasId::from(&output_id)), @@ -51,16 +51,16 @@ pub(crate) fn call_utils_method_internal(method: UtilsMethod) -> Result Response::FoundryId(FoundryId::build(&alias_address, serial_number, token_scheme_kind)), UtilsMethod::HashTransactionEssence { essence } => Response::TransactionEssenceHash(prefix_hex::encode( - TransactionEssence::try_from_dto_unverified(&essence)?.hash(), + TransactionEssence::try_from_dto_unverified(essence)?.hash(), )), UtilsMethod::VerifyEd25519Signature { signature, message, address, } => { - let signature = Ed25519Signature::try_from(&signature)?; + let signature = Ed25519Signature::try_from(signature)?; let msg: Vec = prefix_hex::decode(message)?; - let address = Ed25519Address::try_from(&address)?; + let address = Ed25519Address::try_from(address)?; Response::Bool(signature.is_valid(&msg, &address).is_ok()) } UtilsMethod::VerifyMnemonic { mut mnemonic } => { diff --git a/bindings/nodejs/src/secret_manager.rs b/bindings/nodejs/src/secret_manager.rs index e527fc8e7b..0b21b5fbcb 100644 --- a/bindings/nodejs/src/secret_manager.rs +++ b/bindings/nodejs/src/secret_manager.rs @@ -22,7 +22,7 @@ impl SecretManagerMethodHandler { fn new(channel: Channel, options: String) -> Arc { let secret_manager_dto = serde_json::from_str::(&options).expect("error initializing secret manager"); - let secret_manager = SecretManager::try_from(&secret_manager_dto).expect("error initializing secret manager"); + let secret_manager = SecretManager::try_from(secret_manager_dto).expect("error initializing secret manager"); Arc::new(Self { channel, diff --git a/bindings/python/src/secret_manager.rs b/bindings/python/src/secret_manager.rs index 297788621a..a1bbadf1a2 100644 --- a/bindings/python/src/secret_manager.rs +++ b/bindings/python/src/secret_manager.rs @@ -22,7 +22,7 @@ pub struct SecretManager { #[pyfunction] pub fn create_secret_manager(options: String) -> Result { let secret_manager_dto = serde_json::from_str::(&options)?; - let secret_manager = RustSecretManager::try_from(&secret_manager_dto)?; + let secret_manager = RustSecretManager::try_from(secret_manager_dto)?; Ok(SecretManager { secret_manager: Arc::new(RwLock::new(secret_manager)), }) diff --git a/bindings/wasm/src/secret_manager.rs b/bindings/wasm/src/secret_manager.rs index 62aff13680..1a6de917ff 100644 --- a/bindings/wasm/src/secret_manager.rs +++ b/bindings/wasm/src/secret_manager.rs @@ -25,7 +25,7 @@ pub struct SecretManagerMethodHandler { #[allow(non_snake_case)] pub fn create_secret_manager(options: String) -> Result { let secret_manager_dto = serde_json::from_str::(&options).map_err(|err| err.to_string())?; - let secret_manager = SecretManager::try_from(&secret_manager_dto).map_err(|err| err.to_string())?; + let secret_manager = SecretManager::try_from(secret_manager_dto).map_err(|err| err.to_string())?; Ok(SecretManagerMethodHandler { secret_manager: Arc::new(RwLock::new(secret_manager)), diff --git a/sdk/examples/client/offline_signing/2_transaction_signing.rs b/sdk/examples/client/offline_signing/2_transaction_signing.rs index 04590b4096..aac5b93fd2 100644 --- a/sdk/examples/client/offline_signing/2_transaction_signing.rs +++ b/sdk/examples/client/offline_signing/2_transaction_signing.rs @@ -57,7 +57,7 @@ fn read_prepared_transaction_from_file>(path: P) -> Result(&json)?, + serde_json::from_str::(&json)?, )?) } diff --git a/sdk/examples/client/offline_signing/3_send_block.rs b/sdk/examples/client/offline_signing/3_send_block.rs index 7b46009a82..c80a1b8e75 100644 --- a/sdk/examples/client/offline_signing/3_send_block.rs +++ b/sdk/examples/client/offline_signing/3_send_block.rs @@ -69,5 +69,5 @@ fn read_signed_transaction_from_file>(path: P) -> Result(&json)?; - Ok(SignedTransactionData::try_from_dto_unverified(&dto)?) + Ok(SignedTransactionData::try_from_dto_unverified(dto)?) } diff --git a/sdk/examples/wallet/offline_signing/2_sign_transaction.rs b/sdk/examples/wallet/offline_signing/2_sign_transaction.rs index 34fd7fa8dc..7ec015da95 100644 --- a/sdk/examples/wallet/offline_signing/2_sign_transaction.rs +++ b/sdk/examples/wallet/offline_signing/2_sign_transaction.rs @@ -88,7 +88,7 @@ fn read_prepared_transaction_from_file>( file.read_to_string(&mut json)?; Ok(PreparedTransactionData::try_from_dto( - &serde_json::from_str::(&json)?, + serde_json::from_str::(&json)?, protocol_parameters, )?) } diff --git a/sdk/examples/wallet/offline_signing/3_send_transaction.rs b/sdk/examples/wallet/offline_signing/3_send_transaction.rs index 33a2a62536..a4999157da 100644 --- a/sdk/examples/wallet/offline_signing/3_send_transaction.rs +++ b/sdk/examples/wallet/offline_signing/3_send_transaction.rs @@ -58,7 +58,7 @@ async fn read_signed_transaction_from_file + Send>( let dto = serde_json::from_str::(&json)?; Ok(SignedTransactionData::try_from_dto( - &dto, + dto, &client.get_protocol_parameters().await?, )?) } diff --git a/sdk/src/client/api/block_builder/input_selection/core/burn.rs b/sdk/src/client/api/block_builder/input_selection/core/burn.rs index cffac3d249..a43bf324e8 100644 --- a/sdk/src/client/api/block_builder/input_selection/core/burn.rs +++ b/sdk/src/client/api/block_builder/input_selection/core/burn.rs @@ -163,26 +163,15 @@ impl From<&Burn> for BurnDto { } } -impl TryFrom<&BurnDto> for Burn { +impl TryFrom for Burn { type Error = Error; - fn try_from(value: &BurnDto) -> Result { + fn try_from(value: BurnDto) -> Result { Ok(Self { - aliases: value.aliases.clone().unwrap_or_default(), - nfts: value.nfts.clone().unwrap_or_default(), - foundries: value.foundries.clone().unwrap_or_default(), - native_tokens: value - .native_tokens - .as_ref() - .map(|native_tokens| { - native_tokens - .iter() - .map(|(token_id, amount)| U256::try_from(amount).map(|amount| (*token_id, amount))) - .collect::, _>>() - }) - .transpose() - .map_err(|_| Error::InvalidField("native_tokens"))? - .unwrap_or_default(), + aliases: value.aliases.unwrap_or_default(), + nfts: value.nfts.unwrap_or_default(), + foundries: value.foundries.unwrap_or_default(), + native_tokens: value.native_tokens.unwrap_or_default(), }) } } diff --git a/sdk/src/client/api/block_builder/mod.rs b/sdk/src/client/api/block_builder/mod.rs index 354456b461..72910b2f57 100644 --- a/sdk/src/client/api/block_builder/mod.rs +++ b/sdk/src/client/api/block_builder/mod.rs @@ -244,7 +244,7 @@ impl<'a> ClientBlockBuilder<'a> { if let Some(inputs) = options.inputs { for input in inputs { - self = self.with_input(UtxoInput::try_from(&input)?)?; + self = self.with_input(UtxoInput::try_from(input)?)?; } } @@ -281,7 +281,7 @@ impl<'a> ClientBlockBuilder<'a> { self = self.with_outputs( outputs - .iter() + .into_iter() .map(|o| Ok(Output::try_from_dto(o, token_supply)?)) .collect::>>()?, )?; diff --git a/sdk/src/client/api/types.rs b/sdk/src/client/api/types.rs index 2e74232de2..cd94d907d5 100644 --- a/sdk/src/client/api/types.rs +++ b/sdk/src/client/api/types.rs @@ -58,19 +58,19 @@ impl From<&PreparedTransactionData> for PreparedTransactionDataDto { impl PreparedTransactionData { /// Conversion from [`PreparedTransactionDataDto`] to [`PreparedTransactionData`]. pub fn try_from_dto( - value: &PreparedTransactionDataDto, + value: PreparedTransactionDataDto, protocol_parameters: &ProtocolParameters, ) -> Result { Ok(Self { - essence: TransactionEssence::try_from_dto(&value.essence, protocol_parameters) + essence: TransactionEssence::try_from_dto(value.essence, protocol_parameters) .map_err(|_| Error::InvalidField("essence"))?, inputs_data: value .inputs_data - .iter() + .into_iter() .map(|i| InputSigningData::try_from_dto(i, protocol_parameters.token_supply())) .collect::>>() .map_err(|_| Error::InvalidField("input_data"))?, - remainder: match &value.remainder { + remainder: match value.remainder { Some(remainder) => Some( RemainderData::try_from_dto(remainder, protocol_parameters.token_supply()) .map_err(|_| Error::InvalidField("remainder"))?, @@ -81,17 +81,17 @@ impl PreparedTransactionData { } /// Unverified conversion from [`PreparedTransactionDataDto`] to [`PreparedTransactionData`]. - pub fn try_from_dto_unverified(value: &PreparedTransactionDataDto) -> Result { + pub fn try_from_dto_unverified(value: PreparedTransactionDataDto) -> Result { Ok(Self { - essence: TransactionEssence::try_from_dto_unverified(&value.essence) + essence: TransactionEssence::try_from_dto_unverified(value.essence) .map_err(|_| Error::InvalidField("essence"))?, inputs_data: value .inputs_data - .iter() + .into_iter() .map(InputSigningData::try_from_dto_unverified) .collect::>>() .map_err(|_| Error::InvalidField("inputs_data"))?, - remainder: match &value.remainder { + remainder: match value.remainder { Some(remainder) => Some( RemainderData::try_from_dto_unverified(remainder).map_err(|_| Error::InvalidField("remainder"))?, ), @@ -133,15 +133,15 @@ impl From<&SignedTransactionData> for SignedTransactionDataDto { impl SignedTransactionData { /// Conversion from [`SignedTransactionDataDto`] to [`SignedTransactionData`]. pub fn try_from_dto( - value: &SignedTransactionDataDto, + value: SignedTransactionDataDto, protocol_parameters: &ProtocolParameters, ) -> Result { Ok(Self { - transaction_payload: TransactionPayload::try_from_dto(&value.transaction_payload, protocol_parameters) + transaction_payload: TransactionPayload::try_from_dto(value.transaction_payload, protocol_parameters) .map_err(|_| Error::InvalidField("transaction_payload"))?, inputs_data: value .inputs_data - .iter() + .into_iter() .map(|i| InputSigningData::try_from_dto(i, protocol_parameters.token_supply())) .collect::>>() .map_err(|_| Error::InvalidField("input_data"))?, @@ -149,13 +149,13 @@ impl SignedTransactionData { } /// Unverified conversion from [`SignedTransactionDataDto`] to [`SignedTransactionData`]. - pub fn try_from_dto_unverified(value: &SignedTransactionDataDto) -> Result { + pub fn try_from_dto_unverified(value: SignedTransactionDataDto) -> Result { Ok(Self { - transaction_payload: TransactionPayload::try_from_dto_unverified(&value.transaction_payload) + transaction_payload: TransactionPayload::try_from_dto_unverified(value.transaction_payload) .map_err(|_| Error::InvalidField("transaction_payload"))?, inputs_data: value .inputs_data - .iter() + .into_iter() .map(InputSigningData::try_from_dto_unverified) .collect::>>() .map_err(|_| Error::InvalidField("inputs_data"))?, @@ -186,19 +186,19 @@ pub struct RemainderDataDto { } impl RemainderData { - pub(crate) fn try_from_dto(remainder: &RemainderDataDto, token_supply: u64) -> crate::client::Result { + pub(crate) fn try_from_dto(remainder: RemainderDataDto, token_supply: u64) -> crate::client::Result { Ok(Self { - output: Output::try_from_dto(&remainder.output, token_supply)?, + output: Output::try_from_dto(remainder.output, token_supply)?, chain: remainder.chain.clone(), - address: Address::try_from(&remainder.address)?, + address: Address::try_from(remainder.address)?, }) } - pub(crate) fn try_from_dto_unverified(remainder: &RemainderDataDto) -> crate::client::Result { + pub(crate) fn try_from_dto_unverified(remainder: RemainderDataDto) -> crate::client::Result { Ok(Self { - output: Output::try_from_dto_unverified(&remainder.output)?, + output: Output::try_from_dto_unverified(remainder.output)?, chain: remainder.chain.clone(), - address: Address::try_from(&remainder.address)?, + address: Address::try_from(remainder.address)?, }) } } diff --git a/sdk/src/client/node_api/core/routes.rs b/sdk/src/client/node_api/core/routes.rs index 50cf5e7907..9b7a5fcb7d 100644 --- a/sdk/src/client/node_api/core/routes.rs +++ b/sdk/src/client/node_api/core/routes.rs @@ -240,7 +240,7 @@ impl ClientInner { .await?; match resp { - BlockResponse::Json(dto) => Ok(Block::try_from_dto(&dto, &self.get_protocol_parameters().await?)?), + BlockResponse::Json(dto) => Ok(Block::try_from_dto(dto, &self.get_protocol_parameters().await?)?), BlockResponse::Raw(_) => Err(crate::client::Error::UnexpectedApiResponse), } } @@ -284,8 +284,8 @@ impl ClientInner { .await?; let token_supply = self.get_token_supply().await?; - let output = Output::try_from_dto(&response.output, token_supply)?; - let metadata = OutputMetadata::try_from(&response.metadata)?; + let output = Output::try_from_dto(response.output, token_supply)?; + let metadata = OutputMetadata::try_from(response.metadata)?; Ok(OutputWithMetadata::new(output, metadata)) } @@ -370,7 +370,7 @@ impl ClientInner { .await?; match resp { - BlockResponse::Json(dto) => Ok(Block::try_from_dto(&dto, &self.get_protocol_parameters().await?)?), + BlockResponse::Json(dto) => Ok(Block::try_from_dto(dto, &self.get_protocol_parameters().await?)?), BlockResponse::Raw(_) => Err(crate::client::Error::UnexpectedApiResponse), } } @@ -415,7 +415,7 @@ impl ClientInner { match resp { MilestoneResponse::Json(dto) => Ok(MilestonePayload::try_from_dto( - &dto, + dto, &self.get_protocol_parameters().await?, )?), MilestoneResponse::Raw(_) => Err(crate::client::Error::UnexpectedApiResponse), @@ -460,7 +460,7 @@ impl ClientInner { match resp { MilestoneResponse::Json(dto) => Ok(MilestonePayload::try_from_dto( - &dto, + dto, &self.get_protocol_parameters().await?, )?), MilestoneResponse::Raw(_) => Err(crate::client::Error::UnexpectedApiResponse), diff --git a/sdk/src/client/secret/mod.rs b/sdk/src/client/secret/mod.rs index 6cbfbaa004..0338a37668 100644 --- a/sdk/src/client/secret/mod.rs +++ b/sdk/src/client/secret/mod.rs @@ -27,7 +27,6 @@ use crypto::{ signatures::secp256k1_ecdsa::{self, EvmAddress}, }; use serde::{Deserialize, Serialize}; -use zeroize::ZeroizeOnDrop; #[cfg(feature = "ledger_nano")] use self::ledger_nano::LedgerSecretManager; @@ -154,12 +153,12 @@ impl FromStr for SecretManager { type Err = Error; fn from_str(s: &str) -> crate::client::Result { - Self::try_from(&serde_json::from_str::(s)?) + Self::try_from(serde_json::from_str::(s)?) } } /// DTO for secret manager types with required data. -#[derive(Debug, Clone, Serialize, Deserialize, ZeroizeOnDrop)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub enum SecretManagerDto { /// Stronghold #[cfg(feature = "stronghold")] @@ -182,35 +181,37 @@ pub enum SecretManagerDto { Placeholder, } -impl TryFrom<&SecretManagerDto> for SecretManager { +impl TryFrom for SecretManager { type Error = Error; - fn try_from(value: &SecretManagerDto) -> crate::client::Result { + fn try_from(value: SecretManagerDto) -> crate::client::Result { Ok(match value { #[cfg(feature = "stronghold")] SecretManagerDto::Stronghold(stronghold_dto) => { let mut builder = StrongholdSecretManager::builder(); - if let Some(password) = &stronghold_dto.password { + if let Some(password) = stronghold_dto.password { // `SecretManagerDto` is `ZeroizeOnDrop` so it will take care of zeroizing the original. - builder = builder.password(password.clone()); + builder = builder.password(password); } - if let Some(timeout) = &stronghold_dto.timeout { - builder = builder.timeout(Duration::from_secs(*timeout)); + if let Some(timeout) = stronghold_dto.timeout { + builder = builder.timeout(Duration::from_secs(timeout)); } Self::Stronghold(builder.build(&stronghold_dto.snapshot_path)?) } #[cfg(feature = "ledger_nano")] - SecretManagerDto::LedgerNano(is_simulator) => Self::LedgerNano(LedgerSecretManager::new(*is_simulator)), + SecretManagerDto::LedgerNano(is_simulator) => Self::LedgerNano(LedgerSecretManager::new(is_simulator)), - SecretManagerDto::Mnemonic(mnemonic) => Self::Mnemonic(MnemonicSecretManager::try_from_mnemonic(mnemonic)?), + SecretManagerDto::Mnemonic(mnemonic) => { + Self::Mnemonic(MnemonicSecretManager::try_from_mnemonic(&mnemonic)?) + } SecretManagerDto::HexSeed(hex_seed) => { // `SecretManagerDto` is `ZeroizeOnDrop` so it will take care of zeroizing the original. - Self::Mnemonic(MnemonicSecretManager::try_from_hex_seed(hex_seed.clone())?) + Self::Mnemonic(MnemonicSecretManager::try_from_hex_seed(hex_seed)?) } SecretManagerDto::Placeholder => Self::Placeholder(PlaceholderSecretManager), diff --git a/sdk/src/client/secret/types.rs b/sdk/src/client/secret/types.rs index 4029288b65..8c56b7e479 100644 --- a/sdk/src/client/secret/types.rs +++ b/sdk/src/client/secret/types.rs @@ -7,7 +7,7 @@ use crypto::keys::slip10::{Chain, Segment}; use serde::{Deserialize, Serialize}; use crate::{ - client::Result, + client::{Password, Result}, types::block::{ address::Address, output::{ @@ -20,17 +20,26 @@ use crate::{ /// Stronghold DTO to allow the creation of a Stronghold secret manager from bindings #[cfg(feature = "stronghold")] #[cfg_attr(docsrs, doc(cfg(feature = "stronghold")))] -#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, zeroize::ZeroizeOnDrop)] +#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct StrongholdDto { /// The Stronghold password - pub password: Option, + pub password: Option, /// The timeout for auto key clearing, in seconds pub timeout: Option, /// The path for the Stronghold file pub snapshot_path: String, } +impl core::fmt::Debug for StrongholdDto { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("StrongholdDto") + .field("timeout", &self.timeout) + .field("snapshot_path", &self.snapshot_path) + .finish() + } +} + /// An account address. #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -173,19 +182,19 @@ pub struct InputSigningDataDto { #[allow(missing_docs)] impl InputSigningData { - pub fn try_from_dto(input: &InputSigningDataDto, token_supply: u64) -> Result { + pub fn try_from_dto(input: InputSigningDataDto, token_supply: u64) -> Result { Ok(Self { - output: Output::try_from_dto(&input.output, token_supply)?, - output_metadata: OutputMetadata::try_from(&input.output_metadata)?, - chain: input.chain.clone().map(Chain::from_u32_hardened), + output: Output::try_from_dto(input.output, token_supply)?, + output_metadata: OutputMetadata::try_from(input.output_metadata)?, + chain: input.chain.map(Chain::from_u32_hardened), }) } - pub fn try_from_dto_unverified(input: &InputSigningDataDto) -> Result { + pub fn try_from_dto_unverified(input: InputSigningDataDto) -> Result { Ok(Self { - output: Output::try_from_dto_unverified(&input.output)?, - output_metadata: OutputMetadata::try_from(&input.output_metadata)?, - chain: input.chain.clone().map(Chain::from_u32_hardened), + output: Output::try_from_dto_unverified(input.output)?, + output_metadata: OutputMetadata::try_from(input.output_metadata)?, + chain: input.chain.map(Chain::from_u32_hardened), }) } } diff --git a/sdk/src/types/block/address/alias.rs b/sdk/src/types/block/address/alias.rs index f2d13978dd..74e331bb37 100644 --- a/sdk/src/types/block/address/alias.rs +++ b/sdk/src/types/block/address/alias.rs @@ -87,10 +87,10 @@ pub mod dto { } } - impl TryFrom<&AliasAddressDto> for AliasAddress { + impl TryFrom for AliasAddress { type Error = Error; - fn try_from(value: &AliasAddressDto) -> Result { + fn try_from(value: AliasAddressDto) -> Result { value .alias_id .parse::() diff --git a/sdk/src/types/block/address/ed25519.rs b/sdk/src/types/block/address/ed25519.rs index 976c945f55..1fc135b2f2 100644 --- a/sdk/src/types/block/address/ed25519.rs +++ b/sdk/src/types/block/address/ed25519.rs @@ -76,10 +76,10 @@ pub mod dto { } } - impl TryFrom<&Ed25519AddressDto> for Ed25519Address { + impl TryFrom for Ed25519Address { type Error = Error; - fn try_from(value: &Ed25519AddressDto) -> Result { + fn try_from(value: Ed25519AddressDto) -> Result { value .pub_key_hash .parse::() diff --git a/sdk/src/types/block/address/mod.rs b/sdk/src/types/block/address/mod.rs index 5546020196..9f8a07fd46 100644 --- a/sdk/src/types/block/address/mod.rs +++ b/sdk/src/types/block/address/mod.rs @@ -246,10 +246,10 @@ pub mod dto { } } - impl TryFrom<&AddressDto> for Address { + impl TryFrom for Address { type Error = Error; - fn try_from(value: &AddressDto) -> Result { + fn try_from(value: AddressDto) -> Result { match value { AddressDto::Ed25519(a) => Ok(Self::Ed25519(a.try_into()?)), AddressDto::Alias(a) => Ok(Self::Alias(a.try_into()?)), diff --git a/sdk/src/types/block/address/nft.rs b/sdk/src/types/block/address/nft.rs index f7735a8e2c..341d8547c7 100644 --- a/sdk/src/types/block/address/nft.rs +++ b/sdk/src/types/block/address/nft.rs @@ -87,10 +87,10 @@ pub mod dto { } } - impl TryFrom<&NftAddressDto> for NftAddress { + impl TryFrom for NftAddress { type Error = Error; - fn try_from(value: &NftAddressDto) -> Result { + fn try_from(value: NftAddressDto) -> Result { value.nft_id.parse::().map_err(|_| Error::InvalidField("nftId")) } } diff --git a/sdk/src/types/block/block.rs b/sdk/src/types/block/block.rs index e2ed8c28d7..3f05fe0ff6 100644 --- a/sdk/src/types/block/block.rs +++ b/sdk/src/types/block/block.rs @@ -287,36 +287,40 @@ pub mod dto { } impl Block { - fn _try_from_dto(value: &BlockDto) -> Result { + pub fn try_from_dto(value: BlockDto, protocol_parameters: &ProtocolParameters) -> Result { let parents = Parents::from_vec( value .parents - .iter() + .into_iter() .map(|m| m.parse::().map_err(|_| Error::InvalidField("parents"))) .collect::, Error>>()?, )?; - let builder = BlockBuilder::new(parents) + let mut builder = BlockBuilder::new(parents) .with_protocol_version(value.protocol_version) .with_nonce(value.nonce.parse::().map_err(|_| Error::InvalidField("nonce"))?); - Ok(builder) - } - - pub fn try_from_dto(value: &BlockDto, protocol_parameters: &ProtocolParameters) -> Result { - let mut builder = Self::_try_from_dto(value)?; - - if let Some(p) = value.payload.as_ref() { + if let Some(p) = value.payload { builder = builder.with_payload(Payload::try_from_dto(p, protocol_parameters)?); } builder.finish() } - pub fn try_from_dto_unverified(value: &BlockDto) -> Result { - let mut builder = Self::_try_from_dto(value)?; + pub fn try_from_dto_unverified(value: BlockDto) -> Result { + let parents = Parents::from_vec( + value + .parents + .into_iter() + .map(|m| m.parse::().map_err(|_| Error::InvalidField("parents"))) + .collect::, Error>>()?, + )?; + + let mut builder = BlockBuilder::new(parents) + .with_protocol_version(value.protocol_version) + .with_nonce(value.nonce.parse::().map_err(|_| Error::InvalidField("nonce"))?); - if let Some(p) = value.payload.as_ref() { + if let Some(p) = value.payload { builder = builder.with_payload(Payload::try_from_dto_unverified(p)?); } diff --git a/sdk/src/types/block/input/mod.rs b/sdk/src/types/block/input/mod.rs index 030ec23746..5dfbb3388d 100644 --- a/sdk/src/types/block/input/mod.rs +++ b/sdk/src/types/block/input/mod.rs @@ -112,10 +112,10 @@ pub mod dto { } } - impl TryFrom<&InputDto> for Input { + impl TryFrom for Input { type Error = Error; - fn try_from(value: &InputDto) -> Result { + fn try_from(value: InputDto) -> Result { match value { InputDto::Utxo(u) => Ok(Self::Utxo(u.try_into()?)), InputDto::Treasury(t) => Ok(Self::Treasury(t.try_into()?)), diff --git a/sdk/src/types/block/input/treasury.rs b/sdk/src/types/block/input/treasury.rs index d7bda0b8f3..c42a0b2e7f 100644 --- a/sdk/src/types/block/input/treasury.rs +++ b/sdk/src/types/block/input/treasury.rs @@ -77,10 +77,10 @@ pub mod dto { } } - impl TryFrom<&TreasuryInputDto> for TreasuryInput { + impl TryFrom for TreasuryInput { type Error = Error; - fn try_from(value: &TreasuryInputDto) -> Result { + fn try_from(value: TreasuryInputDto) -> Result { Ok(Self::new( value .milestone_id diff --git a/sdk/src/types/block/input/utxo.rs b/sdk/src/types/block/input/utxo.rs index 01579089c3..3a1ff9260f 100644 --- a/sdk/src/types/block/input/utxo.rs +++ b/sdk/src/types/block/input/utxo.rs @@ -78,10 +78,10 @@ pub mod dto { } } - impl TryFrom<&UtxoInputDto> for UtxoInput { + impl TryFrom for UtxoInput { type Error = Error; - fn try_from(value: &UtxoInputDto) -> Result { + fn try_from(value: UtxoInputDto) -> Result { Self::new( value .transaction_id diff --git a/sdk/src/types/block/output/alias.rs b/sdk/src/types/block/output/alias.rs index 47473cadbe..d416d6dba1 100644 --- a/sdk/src/types/block/output/alias.rs +++ b/sdk/src/types/block/output/alias.rs @@ -762,7 +762,7 @@ pub mod dto { } impl AliasOutput { - fn _try_from_dto(value: &AliasOutputDto) -> Result { + pub fn try_from_dto(value: AliasOutputDto, token_supply: u64) -> Result { let mut builder = AliasOutputBuilder::new_with_amount( value.amount.parse::().map_err(|_| Error::InvalidField("amount"))?, value.alias_id, @@ -779,35 +779,55 @@ pub mod dto { builder = builder.with_foundry_counter(value.foundry_counter); - for t in &value.native_tokens { + for t in value.native_tokens { builder = builder.add_native_token(t.try_into()?); } - for b in &value.features { + for b in value.features { builder = builder.add_feature(Feature::try_from(b)?); } - for b in &value.immutable_features { + for b in value.immutable_features { builder = builder.add_immutable_feature(Feature::try_from(b)?); } - Ok(builder) - } - - pub fn try_from_dto(value: &AliasOutputDto, token_supply: u64) -> Result { - let mut builder = Self::_try_from_dto(value)?; - - for u in &value.unlock_conditions { + for u in value.unlock_conditions { builder = builder.add_unlock_condition(UnlockCondition::try_from_dto(u, token_supply)?); } builder.finish(token_supply) } - pub fn try_from_dto_unverified(value: &AliasOutputDto) -> Result { - let mut builder = Self::_try_from_dto(value)?; + pub fn try_from_dto_unverified(value: AliasOutputDto) -> Result { + let mut builder = AliasOutputBuilder::new_with_amount( + value.amount.parse::().map_err(|_| Error::InvalidField("amount"))?, + value.alias_id, + ); + + builder = builder.with_state_index(value.state_index); + + if !value.state_metadata.is_empty() { + builder = builder.with_state_metadata( + prefix_hex::decode::>(&value.state_metadata) + .map_err(|_| Error::InvalidField("state_metadata"))?, + ); + } + + builder = builder.with_foundry_counter(value.foundry_counter); + + for t in value.native_tokens { + builder = builder.add_native_token(t.try_into()?); + } + + for b in value.features { + builder = builder.add_feature(Feature::try_from(b)?); + } + + for b in value.immutable_features { + builder = builder.add_immutable_feature(Feature::try_from(b)?); + } - for u in &value.unlock_conditions { + for u in value.unlock_conditions { builder = builder.add_unlock_condition(UnlockCondition::try_from_dto_unverified(u)?); } @@ -839,7 +859,7 @@ pub mod dto { if let Some(native_tokens) = native_tokens { let native_tokens = native_tokens - .iter() + .into_iter() .map(NativeToken::try_from) .collect::, Error>>()?; builder = builder.with_native_tokens(native_tokens); @@ -858,14 +878,14 @@ pub mod dto { } let unlock_conditions = unlock_conditions - .iter() + .into_iter() .map(|u| UnlockCondition::try_from_dto(u, token_supply)) .collect::, Error>>()?; builder = builder.with_unlock_conditions(unlock_conditions); if let Some(features) = features { let features = features - .iter() + .into_iter() .map(Feature::try_from) .collect::, Error>>()?; builder = builder.with_features(features); @@ -873,7 +893,7 @@ pub mod dto { if let Some(immutable_features) = immutable_features { let immutable_features = immutable_features - .iter() + .into_iter() .map(Feature::try_from) .collect::, Error>>()?; builder = builder.with_immutable_features(immutable_features); @@ -991,9 +1011,9 @@ mod tests { let protocol_parameters = protocol_parameters(); let output = rand_alias_output(protocol_parameters.token_supply()); let dto = OutputDto::Alias((&output).into()); - let output_unver = Output::try_from_dto_unverified(&dto).unwrap(); + let output_unver = Output::try_from_dto_unverified(dto.clone()).unwrap(); assert_eq!(&output, output_unver.as_alias()); - let output_ver = Output::try_from_dto(&dto, protocol_parameters.token_supply()).unwrap(); + let output_ver = Output::try_from_dto(dto, protocol_parameters.token_supply()).unwrap(); assert_eq!(&output, output_ver.as_alias()); let output_split = AliasOutput::try_from_dtos( diff --git a/sdk/src/types/block/output/basic.rs b/sdk/src/types/block/output/basic.rs index a7ba8a1f16..4a1a100144 100644 --- a/sdk/src/types/block/output/basic.rs +++ b/sdk/src/types/block/output/basic.rs @@ -370,35 +370,38 @@ pub mod dto { } impl BasicOutput { - fn _try_from_dto(value: &BasicOutputDto) -> Result { + pub fn try_from_dto(value: BasicOutputDto, token_supply: u64) -> Result { let mut builder = BasicOutputBuilder::new_with_amount(value.amount.parse().map_err(|_| Error::InvalidField("amount"))?); - for t in &value.native_tokens { + for t in value.native_tokens { builder = builder.add_native_token(t.try_into()?); } - for b in &value.features { + for b in value.features { builder = builder.add_feature(Feature::try_from(b)?); } - Ok(builder) - } - - pub fn try_from_dto(value: &BasicOutputDto, token_supply: u64) -> Result { - let mut builder = Self::_try_from_dto(value)?; - - for u in &value.unlock_conditions { + for u in value.unlock_conditions { builder = builder.add_unlock_condition(UnlockCondition::try_from_dto(u, token_supply)?); } builder.finish(token_supply) } - pub fn try_from_dto_unverified(value: &BasicOutputDto) -> Result { - let mut builder = Self::_try_from_dto(value)?; + pub fn try_from_dto_unverified(value: BasicOutputDto) -> Result { + let mut builder = + BasicOutputBuilder::new_with_amount(value.amount.parse().map_err(|_| Error::InvalidField("amount"))?); + + for t in value.native_tokens { + builder = builder.add_native_token(t.try_into()?); + } + + for b in value.features { + builder = builder.add_feature(Feature::try_from(b)?); + } - for u in &value.unlock_conditions { + for u in value.unlock_conditions { builder = builder.add_unlock_condition(UnlockCondition::try_from_dto_unverified(u)?); } @@ -423,21 +426,21 @@ pub mod dto { if let Some(native_tokens) = native_tokens { let native_tokens = native_tokens - .iter() + .into_iter() .map(NativeToken::try_from) .collect::, Error>>()?; builder = builder.with_native_tokens(native_tokens); } let unlock_conditions = unlock_conditions - .iter() + .into_iter() .map(|u| UnlockCondition::try_from_dto(u, token_supply)) .collect::, Error>>()?; builder = builder.with_unlock_conditions(unlock_conditions); if let Some(features) = features { let features = features - .iter() + .into_iter() .map(Feature::try_from) .collect::, Error>>()?; builder = builder.with_features(features); @@ -527,9 +530,9 @@ mod tests { let protocol_parameters = protocol_parameters(); let output = rand_basic_output(protocol_parameters.token_supply()); let dto = OutputDto::Basic((&output).into()); - let output_unver = Output::try_from_dto_unverified(&dto).unwrap(); + let output_unver = Output::try_from_dto_unverified(dto.clone()).unwrap(); assert_eq!(&output, output_unver.as_basic()); - let output_ver = Output::try_from_dto(&dto, protocol_parameters.token_supply()).unwrap(); + let output_ver = Output::try_from_dto(dto, protocol_parameters.token_supply()).unwrap(); assert_eq!(&output, output_ver.as_basic()); let output_split = BasicOutput::try_from_dtos( diff --git a/sdk/src/types/block/output/feature/mod.rs b/sdk/src/types/block/output/feature/mod.rs index e79a8feaaf..e55307273d 100644 --- a/sdk/src/types/block/output/feature/mod.rs +++ b/sdk/src/types/block/output/feature/mod.rs @@ -423,13 +423,13 @@ pub mod dto { } } - impl TryFrom<&FeatureDto> for Feature { + impl TryFrom for Feature { type Error = Error; - fn try_from(value: &FeatureDto) -> Result { + fn try_from(value: FeatureDto) -> Result { Ok(match value { - FeatureDto::Sender(v) => Self::Sender(SenderFeature::new(Address::try_from(&v.address)?)), - FeatureDto::Issuer(v) => Self::Issuer(IssuerFeature::new(Address::try_from(&v.address)?)), + FeatureDto::Sender(v) => Self::Sender(SenderFeature::new(Address::try_from(v.address)?)), + FeatureDto::Issuer(v) => Self::Issuer(IssuerFeature::new(Address::try_from(v.address)?)), FeatureDto::Metadata(v) => Self::Metadata(MetadataFeature::new( prefix_hex::decode::>(&v.data).map_err(|_e| Error::InvalidField("MetadataFeature"))?, )?), diff --git a/sdk/src/types/block/output/foundry.rs b/sdk/src/types/block/output/foundry.rs index 58d9aa44e7..1126c11248 100644 --- a/sdk/src/types/block/output/foundry.rs +++ b/sdk/src/types/block/output/foundry.rs @@ -655,42 +655,52 @@ pub mod dto { } impl FoundryOutput { - fn _try_from_dto(value: &FoundryOutputDto) -> Result { + pub fn try_from_dto(value: FoundryOutputDto, token_supply: u64) -> Result { let mut builder = FoundryOutputBuilder::new_with_amount( value.amount.parse::().map_err(|_| Error::InvalidField("amount"))?, value.serial_number, - (&value.token_scheme).try_into()?, + value.token_scheme.try_into()?, ); - for t in &value.native_tokens { + for t in value.native_tokens { builder = builder.add_native_token(t.try_into()?); } - for b in &value.features { + for b in value.features { builder = builder.add_feature(Feature::try_from(b)?); } - for b in &value.immutable_features { + for b in value.immutable_features { builder = builder.add_immutable_feature(Feature::try_from(b)?); } - Ok(builder) - } - - pub fn try_from_dto(value: &FoundryOutputDto, token_supply: u64) -> Result { - let mut builder = Self::_try_from_dto(value)?; - - for u in &value.unlock_conditions { + for u in value.unlock_conditions { builder = builder.add_unlock_condition(UnlockCondition::try_from_dto(u, token_supply)?); } builder.finish(token_supply) } - pub fn try_from_dto_unverified(value: &FoundryOutputDto) -> Result { - let mut builder = Self::_try_from_dto(value)?; + pub fn try_from_dto_unverified(value: FoundryOutputDto) -> Result { + let mut builder = FoundryOutputBuilder::new_with_amount( + value.amount.parse::().map_err(|_| Error::InvalidField("amount"))?, + value.serial_number, + value.token_scheme.try_into()?, + ); + + for t in value.native_tokens { + builder = builder.add_native_token(t.try_into()?); + } + + for b in value.features { + builder = builder.add_feature(Feature::try_from(b)?); + } + + for b in value.immutable_features { + builder = builder.add_immutable_feature(Feature::try_from(b)?); + } - for u in &value.unlock_conditions { + for u in value.unlock_conditions { builder = builder.add_unlock_condition(UnlockCondition::try_from_dto_unverified(u)?); } @@ -702,7 +712,7 @@ pub mod dto { amount: OutputBuilderAmountDto, native_tokens: Option>, serial_number: u32, - token_scheme: &TokenSchemeDto, + token_scheme: TokenSchemeDto, unlock_conditions: Vec, features: Option>, immutable_features: Option>, @@ -723,21 +733,21 @@ pub mod dto { if let Some(native_tokens) = native_tokens { let native_tokens = native_tokens - .iter() + .into_iter() .map(NativeToken::try_from) .collect::, Error>>()?; builder = builder.with_native_tokens(native_tokens); } let unlock_conditions = unlock_conditions - .iter() + .into_iter() .map(|u| UnlockCondition::try_from_dto(u, token_supply)) .collect::, Error>>()?; builder = builder.with_unlock_conditions(unlock_conditions); if let Some(features) = features { let features = features - .iter() + .into_iter() .map(Feature::try_from) .collect::, Error>>()?; builder = builder.with_features(features); @@ -745,7 +755,7 @@ pub mod dto { if let Some(immutable_features) = immutable_features { let immutable_features = immutable_features - .iter() + .into_iter() .map(Feature::try_from) .collect::, Error>>()?; builder = builder.with_immutable_features(immutable_features); @@ -836,9 +846,9 @@ mod tests { let protocol_parameters = protocol_parameters(); let output = rand_foundry_output(protocol_parameters.token_supply()); let dto = OutputDto::Foundry((&output).into()); - let output_unver = Output::try_from_dto_unverified(&dto).unwrap(); + let output_unver = Output::try_from_dto_unverified(dto.clone()).unwrap(); assert_eq!(&output, output_unver.as_foundry()); - let output_ver = Output::try_from_dto(&dto, protocol_parameters.token_supply()).unwrap(); + let output_ver = Output::try_from_dto(dto, protocol_parameters.token_supply()).unwrap(); assert_eq!(&output, output_ver.as_foundry()); let foundry_id = FoundryId::build(&rand_alias_address(), 0, SimpleTokenScheme::KIND); @@ -848,7 +858,7 @@ mod tests { (&builder.amount).into(), Some(builder.native_tokens.iter().map(Into::into).collect()), builder.serial_number, - &(&builder.token_scheme).into(), + (&builder.token_scheme).into(), builder.unlock_conditions.iter().map(Into::into).collect(), Some(builder.features.iter().map(Into::into).collect()), Some(builder.immutable_features.iter().map(Into::into).collect()), diff --git a/sdk/src/types/block/output/metadata.rs b/sdk/src/types/block/output/metadata.rs index 5055e7abb2..5475006aea 100644 --- a/sdk/src/types/block/output/metadata.rs +++ b/sdk/src/types/block/output/metadata.rs @@ -158,10 +158,10 @@ pub mod dto { } } - impl TryFrom<&OutputMetadataDto> for OutputMetadata { + impl TryFrom for OutputMetadata { type Error = Error; - fn try_from(response: &OutputMetadataDto) -> Result { + fn try_from(response: OutputMetadataDto) -> Result { Ok(Self { block_id: BlockId::from_str(&response.block_id)?, output_id: OutputId::new( diff --git a/sdk/src/types/block/output/mod.rs b/sdk/src/types/block/output/mod.rs index fd7645f1cb..0bf37ca1fb 100644 --- a/sdk/src/types/block/output/mod.rs +++ b/sdk/src/types/block/output/mod.rs @@ -560,7 +560,7 @@ pub mod dto { } impl Output { - pub fn try_from_dto(value: &OutputDto, token_supply: u64) -> Result { + pub fn try_from_dto(value: OutputDto, token_supply: u64) -> Result { Ok(match value { OutputDto::Treasury(o) => Self::Treasury(TreasuryOutput::try_from_dto(o, token_supply)?), OutputDto::Basic(o) => Self::Basic(BasicOutput::try_from_dto(o, token_supply)?), @@ -570,7 +570,7 @@ pub mod dto { }) } - pub fn try_from_dto_unverified(value: &OutputDto) -> Result { + pub fn try_from_dto_unverified(value: OutputDto) -> Result { Ok(match value { OutputDto::Treasury(o) => Self::Treasury(TreasuryOutput::try_from_dto_unverified(o)?), OutputDto::Basic(o) => Self::Basic(BasicOutput::try_from_dto_unverified(o)?), diff --git a/sdk/src/types/block/output/native_token.rs b/sdk/src/types/block/output/native_token.rs index 470139b29c..cbace6d6f5 100644 --- a/sdk/src/types/block/output/native_token.rs +++ b/sdk/src/types/block/output/native_token.rs @@ -270,10 +270,10 @@ pub mod dto { } } - impl TryFrom<&NativeTokenDto> for NativeToken { + impl TryFrom for NativeToken { type Error = Error; - fn try_from(value: &NativeTokenDto) -> Result { + fn try_from(value: NativeTokenDto) -> Result { Self::new( value.token_id, U256::try_from(&value.amount).map_err(|_| Error::InvalidField("amount"))?, diff --git a/sdk/src/types/block/output/nft.rs b/sdk/src/types/block/output/nft.rs index b431e02dea..292081a93c 100644 --- a/sdk/src/types/block/output/nft.rs +++ b/sdk/src/types/block/output/nft.rs @@ -526,41 +526,50 @@ pub mod dto { } impl NftOutput { - fn _try_from_dto(value: &NftOutputDto) -> Result { + pub fn try_from_dto(value: NftOutputDto, token_supply: u64) -> Result { let mut builder = NftOutputBuilder::new_with_amount( value.amount.parse::().map_err(|_| Error::InvalidField("amount"))?, value.nft_id, ); - for t in &value.native_tokens { + for t in value.native_tokens { builder = builder.add_native_token(t.try_into()?); } - for b in &value.features { + for b in value.features { builder = builder.add_feature(Feature::try_from(b)?); } - for b in &value.immutable_features { + for b in value.immutable_features { builder = builder.add_immutable_feature(Feature::try_from(b)?); } - Ok(builder) - } - - pub fn try_from_dto(value: &NftOutputDto, token_supply: u64) -> Result { - let mut builder = Self::_try_from_dto(value)?; - - for u in &value.unlock_conditions { + for u in value.unlock_conditions { builder = builder.add_unlock_condition(UnlockCondition::try_from_dto(u, token_supply)?); } builder.finish(token_supply) } - pub fn try_from_dto_unverified(value: &NftOutputDto) -> Result { - let mut builder = Self::_try_from_dto(value)?; + pub fn try_from_dto_unverified(value: NftOutputDto) -> Result { + let mut builder = NftOutputBuilder::new_with_amount( + value.amount.parse::().map_err(|_| Error::InvalidField("amount"))?, + value.nft_id, + ); + + for t in value.native_tokens { + builder = builder.add_native_token(t.try_into()?); + } + + for b in value.features { + builder = builder.add_feature(Feature::try_from(b)?); + } + + for b in value.immutable_features { + builder = builder.add_immutable_feature(Feature::try_from(b)?); + } - for u in &value.unlock_conditions { + for u in value.unlock_conditions { builder = builder.add_unlock_condition(UnlockCondition::try_from_dto_unverified(u)?); } @@ -588,21 +597,21 @@ pub mod dto { if let Some(native_tokens) = native_tokens { let native_tokens = native_tokens - .iter() + .into_iter() .map(NativeToken::try_from) .collect::, Error>>()?; builder = builder.with_native_tokens(native_tokens); } let unlock_conditions = unlock_conditions - .iter() + .into_iter() .map(|u| UnlockCondition::try_from_dto(u, token_supply)) .collect::, Error>>()?; builder = builder.with_unlock_conditions(unlock_conditions); if let Some(features) = features { let features = features - .iter() + .into_iter() .map(Feature::try_from) .collect::, Error>>()?; builder = builder.with_features(features); @@ -610,7 +619,7 @@ pub mod dto { if let Some(immutable_features) = immutable_features { let immutable_features = immutable_features - .iter() + .into_iter() .map(Feature::try_from) .collect::, Error>>()?; builder = builder.with_immutable_features(immutable_features); @@ -702,9 +711,9 @@ mod tests { let protocol_parameters = protocol_parameters(); let output = rand_nft_output(protocol_parameters.token_supply()); let dto = OutputDto::Nft((&output).into()); - let output_unver = Output::try_from_dto_unverified(&dto).unwrap(); + let output_unver = Output::try_from_dto_unverified(dto.clone()).unwrap(); assert_eq!(&output, output_unver.as_nft()); - let output_ver = Output::try_from_dto(&dto, protocol_parameters.token_supply()).unwrap(); + let output_ver = Output::try_from_dto(dto, protocol_parameters.token_supply()).unwrap(); assert_eq!(&output, output_ver.as_nft()); let foundry_id = FoundryId::build(&rand_alias_address(), 0, SimpleTokenScheme::KIND); diff --git a/sdk/src/types/block/output/token_scheme/mod.rs b/sdk/src/types/block/output/token_scheme/mod.rs index 819ea3d0d3..b11818943e 100644 --- a/sdk/src/types/block/output/token_scheme/mod.rs +++ b/sdk/src/types/block/output/token_scheme/mod.rs @@ -58,10 +58,10 @@ pub mod dto { } } - impl TryFrom<&TokenSchemeDto> for TokenScheme { + impl TryFrom for TokenScheme { type Error = Error; - fn try_from(value: &TokenSchemeDto) -> Result { + fn try_from(value: TokenSchemeDto) -> Result { Ok(match value { TokenSchemeDto::Simple(v) => Self::Simple(v.try_into()?), }) diff --git a/sdk/src/types/block/output/token_scheme/simple.rs b/sdk/src/types/block/output/token_scheme/simple.rs index b48bc1a467..99ba912e56 100644 --- a/sdk/src/types/block/output/token_scheme/simple.rs +++ b/sdk/src/types/block/output/token_scheme/simple.rs @@ -141,15 +141,11 @@ pub mod dto { } } - impl TryFrom<&SimpleTokenSchemeDto> for SimpleTokenScheme { + impl TryFrom for SimpleTokenScheme { type Error = Error; - fn try_from(value: &SimpleTokenSchemeDto) -> Result { - Self::new( - U256::try_from(&value.minted_tokens).map_err(|_| Error::InvalidField("mintedTokens"))?, - U256::try_from(&value.melted_tokens).map_err(|_| Error::InvalidField("meltedTokens"))?, - U256::try_from(&value.maximum_supply).map_err(|_| Error::InvalidField("maximumSupply"))?, - ) + fn try_from(value: SimpleTokenSchemeDto) -> Result { + Self::new(value.minted_tokens, value.melted_tokens, value.maximum_supply) } } } diff --git a/sdk/src/types/block/output/treasury.rs b/sdk/src/types/block/output/treasury.rs index 0037a3eaec..0a877a8642 100644 --- a/sdk/src/types/block/output/treasury.rs +++ b/sdk/src/types/block/output/treasury.rs @@ -73,14 +73,14 @@ pub mod dto { } impl TreasuryOutput { - pub fn try_from_dto(value: &TreasuryOutputDto, token_supply: u64) -> Result { + pub fn try_from_dto(value: TreasuryOutputDto, token_supply: u64) -> Result { Self::new( value.amount.parse::().map_err(|_| Error::InvalidField("amount"))?, token_supply, ) } - pub fn try_from_dto_unverified(value: &TreasuryOutputDto) -> Result { + pub fn try_from_dto_unverified(value: TreasuryOutputDto) -> Result { Ok(Self { amount: value.amount.parse::().map_err(|_| Error::InvalidField("amount"))?, }) diff --git a/sdk/src/types/block/output/unlock_condition/address.rs b/sdk/src/types/block/output/unlock_condition/address.rs index 0f0cd88fcd..919b4d59e7 100644 --- a/sdk/src/types/block/output/unlock_condition/address.rs +++ b/sdk/src/types/block/output/unlock_condition/address.rs @@ -50,12 +50,12 @@ pub mod dto { } } - impl TryFrom<&AddressUnlockConditionDto> for AddressUnlockCondition { + impl TryFrom for AddressUnlockCondition { type Error = Error; - fn try_from(value: &AddressUnlockConditionDto) -> Result { + fn try_from(value: AddressUnlockConditionDto) -> Result { Ok(Self::new( - Address::try_from(&value.address).map_err(|_e| Error::InvalidField("addressUnlockCondition"))?, + Address::try_from(value.address).map_err(|_e| Error::InvalidField("addressUnlockCondition"))?, )) } } diff --git a/sdk/src/types/block/output/unlock_condition/expiration.rs b/sdk/src/types/block/output/unlock_condition/expiration.rs index 752c098ff0..d5b8bb7a64 100644 --- a/sdk/src/types/block/output/unlock_condition/expiration.rs +++ b/sdk/src/types/block/output/unlock_condition/expiration.rs @@ -92,12 +92,12 @@ pub mod dto { } } - impl TryFrom<&ExpirationUnlockConditionDto> for ExpirationUnlockCondition { + impl TryFrom for ExpirationUnlockCondition { type Error = Error; - fn try_from(value: &ExpirationUnlockConditionDto) -> Result { + fn try_from(value: ExpirationUnlockConditionDto) -> Result { Self::new( - Address::try_from(&value.return_address) + Address::try_from(value.return_address) .map_err(|_e| Error::InvalidField("expirationUnlockCondition"))?, value.timestamp, ) diff --git a/sdk/src/types/block/output/unlock_condition/governor_address.rs b/sdk/src/types/block/output/unlock_condition/governor_address.rs index cce4365260..f84162a0fa 100644 --- a/sdk/src/types/block/output/unlock_condition/governor_address.rs +++ b/sdk/src/types/block/output/unlock_condition/governor_address.rs @@ -52,13 +52,12 @@ pub mod dto { } } - impl TryFrom<&GovernorAddressUnlockConditionDto> for GovernorAddressUnlockCondition { + impl TryFrom for GovernorAddressUnlockCondition { type Error = Error; - fn try_from(value: &GovernorAddressUnlockConditionDto) -> Result { + fn try_from(value: GovernorAddressUnlockConditionDto) -> Result { Ok(Self::new( - Address::try_from(&value.address) - .map_err(|_e| Error::InvalidField("governorAddressUnlockCondition"))?, + Address::try_from(value.address).map_err(|_e| Error::InvalidField("governorAddressUnlockCondition"))?, )) } } diff --git a/sdk/src/types/block/output/unlock_condition/immutable_alias_address.rs b/sdk/src/types/block/output/unlock_condition/immutable_alias_address.rs index 93e29a9589..4b8296b316 100644 --- a/sdk/src/types/block/output/unlock_condition/immutable_alias_address.rs +++ b/sdk/src/types/block/output/unlock_condition/immutable_alias_address.rs @@ -71,17 +71,18 @@ pub mod dto { } } - impl TryFrom<&ImmutableAliasAddressUnlockConditionDto> for ImmutableAliasAddressUnlockCondition { + impl TryFrom for ImmutableAliasAddressUnlockCondition { type Error = Error; - fn try_from(value: &ImmutableAliasAddressUnlockConditionDto) -> Result { - let address: Address = (&value.address) + fn try_from(value: ImmutableAliasAddressUnlockConditionDto) -> Result { + let address: Address = value + .address .try_into() .map_err(|_e| Error::InvalidField("immutableAliasAddressUnlockCondition"))?; // An ImmutableAliasAddressUnlockCondition must have an AliasAddress. - if let Address::Alias(alias_address) = &address { - Ok(Self::new(*alias_address)) + if let Address::Alias(alias_address) = address { + Ok(Self::new(alias_address)) } else { Err(Error::InvalidField("immutableAliasAddressUnlockCondition")) } diff --git a/sdk/src/types/block/output/unlock_condition/mod.rs b/sdk/src/types/block/output/unlock_condition/mod.rs index cf4248fd5e..4081f24910 100644 --- a/sdk/src/types/block/output/unlock_condition/mod.rs +++ b/sdk/src/types/block/output/unlock_condition/mod.rs @@ -586,7 +586,7 @@ pub mod dto { } impl UnlockCondition { - pub fn try_from_dto(value: &UnlockConditionDto, token_supply: u64) -> Result { + pub fn try_from_dto(value: UnlockConditionDto, token_supply: u64) -> Result { Ok(match value { UnlockConditionDto::Address(v) => Self::Address(AddressUnlockCondition::try_from(v)?), UnlockConditionDto::StorageDepositReturn(v) => { @@ -606,7 +606,7 @@ pub mod dto { }) } - pub fn try_from_dto_unverified(value: &UnlockConditionDto) -> Result { + pub fn try_from_dto_unverified(value: UnlockConditionDto) -> Result { Ok(match value { UnlockConditionDto::Address(v) => Self::Address(AddressUnlockCondition::try_from(v)?), UnlockConditionDto::StorageDepositReturn(v) => { diff --git a/sdk/src/types/block/output/unlock_condition/state_controller_address.rs b/sdk/src/types/block/output/unlock_condition/state_controller_address.rs index a18ed82ea7..ccc6579bd0 100644 --- a/sdk/src/types/block/output/unlock_condition/state_controller_address.rs +++ b/sdk/src/types/block/output/unlock_condition/state_controller_address.rs @@ -52,11 +52,11 @@ pub mod dto { } } - impl TryFrom<&StateControllerAddressUnlockConditionDto> for StateControllerAddressUnlockCondition { + impl TryFrom for StateControllerAddressUnlockCondition { type Error = Error; - fn try_from(value: &StateControllerAddressUnlockConditionDto) -> Result { - Ok(Self::new(Address::try_from(&value.address).map_err(|_e| { + fn try_from(value: StateControllerAddressUnlockConditionDto) -> Result { + Ok(Self::new(Address::try_from(value.address).map_err(|_e| { Error::InvalidField("stateControllerAddressUnlockCondition") })?)) } diff --git a/sdk/src/types/block/output/unlock_condition/storage_deposit_return.rs b/sdk/src/types/block/output/unlock_condition/storage_deposit_return.rs index dfce67ecdd..68f79836d7 100644 --- a/sdk/src/types/block/output/unlock_condition/storage_deposit_return.rs +++ b/sdk/src/types/block/output/unlock_condition/storage_deposit_return.rs @@ -89,17 +89,17 @@ pub mod dto { } impl StorageDepositReturnUnlockCondition { - pub fn try_from_dto(value: &StorageDepositReturnUnlockConditionDto, token_supply: u64) -> Result { + pub fn try_from_dto(value: StorageDepositReturnUnlockConditionDto, token_supply: u64) -> Result { Self::new( - Address::try_from(&value.return_address)?, + Address::try_from(value.return_address)?, value.amount.parse::().map_err(|_| Error::InvalidField("amount"))?, token_supply, ) } - pub fn try_from_dto_unverified(value: &StorageDepositReturnUnlockConditionDto) -> Result { + pub fn try_from_dto_unverified(value: StorageDepositReturnUnlockConditionDto) -> Result { Ok(Self { - return_address: Address::try_from(&value.return_address)?, + return_address: Address::try_from(value.return_address)?, amount: value.amount.parse::().map_err(|_| Error::InvalidField("amount"))?, }) } diff --git a/sdk/src/types/block/output/unlock_condition/timelock.rs b/sdk/src/types/block/output/unlock_condition/timelock.rs index d6b7d8cf15..dce526c199 100644 --- a/sdk/src/types/block/output/unlock_condition/timelock.rs +++ b/sdk/src/types/block/output/unlock_condition/timelock.rs @@ -63,10 +63,10 @@ pub mod dto { } } - impl TryFrom<&TimelockUnlockConditionDto> for TimelockUnlockCondition { + impl TryFrom for TimelockUnlockCondition { type Error = Error; - fn try_from(value: &TimelockUnlockConditionDto) -> Result { + fn try_from(value: TimelockUnlockConditionDto) -> Result { Self::new(value.timestamp).map_err(|_| Error::InvalidField("timelockUnlockCondition")) } } diff --git a/sdk/src/types/block/payload/milestone/mod.rs b/sdk/src/types/block/payload/milestone/mod.rs index a4504ebe77..c008ff213c 100644 --- a/sdk/src/types/block/payload/milestone/mod.rs +++ b/sdk/src/types/block/payload/milestone/mod.rs @@ -217,7 +217,7 @@ pub mod dto { impl MilestonePayload { // TODO: find a solution to factorize. pub fn try_from_dto( - value: &MilestonePayloadDto, + value: MilestonePayloadDto, protocol_parameters: &ProtocolParameters, ) -> Result { let essence = { @@ -227,7 +227,7 @@ pub mod dto { .map_err(|_| Error::InvalidField("previousMilestoneId"))?; let parent_ids = value .parents - .iter() + .into_iter() .map(|block_id| block_id.parse::().map_err(|_| Error::InvalidField("parents"))) .collect::>()?; @@ -238,7 +238,7 @@ pub mod dto { let options = MilestoneOptions::try_from( value .options - .iter() + .into_iter() .map(|o| MilestoneOption::try_from_dto(o, protocol_parameters.token_supply())) .collect::, _>>()?, )?; @@ -263,14 +263,14 @@ pub mod dto { let signatures = value .signatures - .iter() + .into_iter() .map(|v| v.try_into().map_err(|_| Error::InvalidField("signatures"))) .collect::, _>>()?; Self::new(essence, signatures) } - pub fn try_from_dto_unverified(value: &MilestonePayloadDto) -> Result { + pub fn try_from_dto_unverified(value: MilestonePayloadDto) -> Result { let essence = { let index = value.index; let timestamp = value.timestamp; @@ -280,7 +280,7 @@ pub mod dto { let parent_ids = value .parents - .iter() + .into_iter() .map(|block_id| block_id.parse::().map_err(|_| Error::InvalidField("parents"))) .collect::>()?; @@ -291,7 +291,7 @@ pub mod dto { let options = MilestoneOptions::try_from( value .options - .iter() + .into_iter() .map(MilestoneOption::try_from_dto_unverified) .collect::, _>>()?, )?; @@ -315,7 +315,7 @@ pub mod dto { }; let mut signatures = Vec::new(); - for v in &value.signatures { + for v in value.signatures { signatures.push(v.try_into().map_err(|_| Error::InvalidField("signatures"))?) } diff --git a/sdk/src/types/block/payload/milestone/option/mod.rs b/sdk/src/types/block/payload/milestone/option/mod.rs index 28e753e96d..e8903ec633 100644 --- a/sdk/src/types/block/payload/milestone/option/mod.rs +++ b/sdk/src/types/block/payload/milestone/option/mod.rs @@ -255,14 +255,14 @@ pub mod dto { } impl MilestoneOption { - pub fn try_from_dto(value: &MilestoneOptionDto, token_supply: u64) -> Result { + pub fn try_from_dto(value: MilestoneOptionDto, token_supply: u64) -> Result { Ok(match value { MilestoneOptionDto::Receipt(v) => Self::Receipt(ReceiptMilestoneOption::try_from_dto(v, token_supply)?), MilestoneOptionDto::Parameters(v) => Self::Parameters(v.try_into()?), }) } - pub fn try_from_dto_unverified(value: &MilestoneOptionDto) -> Result { + pub fn try_from_dto_unverified(value: MilestoneOptionDto) -> Result { Ok(match value { MilestoneOptionDto::Receipt(v) => Self::Receipt(ReceiptMilestoneOption::try_from_dto_unverified(v)?), MilestoneOptionDto::Parameters(v) => Self::Parameters(v.try_into()?), diff --git a/sdk/src/types/block/payload/milestone/option/parameters.rs b/sdk/src/types/block/payload/milestone/option/parameters.rs index c5e9dabae6..311d9d6cf3 100644 --- a/sdk/src/types/block/payload/milestone/option/parameters.rs +++ b/sdk/src/types/block/payload/milestone/option/parameters.rs @@ -99,10 +99,10 @@ pub mod dto { } } - impl TryFrom<&ParametersMilestoneOptionDto> for ParametersMilestoneOption { + impl TryFrom for ParametersMilestoneOption { type Error = Error; - fn try_from(value: &ParametersMilestoneOptionDto) -> Result { + fn try_from(value: ParametersMilestoneOptionDto) -> Result { Self::new( value.target_milestone_index.into(), value.protocol_version, diff --git a/sdk/src/types/block/payload/milestone/option/receipt/migrated_funds_entry.rs b/sdk/src/types/block/payload/milestone/option/receipt/migrated_funds_entry.rs index a9f40aed7e..0e6912552b 100644 --- a/sdk/src/types/block/payload/milestone/option/receipt/migrated_funds_entry.rs +++ b/sdk/src/types/block/payload/milestone/option/receipt/migrated_funds_entry.rs @@ -102,26 +102,26 @@ pub mod dto { } impl MigratedFundsEntry { - pub fn try_from_dto(value: &MigratedFundsEntryDto, token_supply: u64) -> Result { + pub fn try_from_dto(value: MigratedFundsEntryDto, token_supply: u64) -> Result { let tail_transaction_hash = prefix_hex::decode(&value.tail_transaction_hash) .map_err(|_| Error::InvalidField("tailTransactionHash"))?; Self::new( TailTransactionHash::new(tail_transaction_hash)?, - (&value.address).try_into()?, + value.address.try_into()?, value.deposit, token_supply, ) } - pub fn try_from_dto_unverified(value: &MigratedFundsEntryDto) -> Result { + pub fn try_from_dto_unverified(value: MigratedFundsEntryDto) -> Result { let tail_transaction_hash = prefix_hex::decode(&value.tail_transaction_hash) .map_err(|_| Error::InvalidField("tailTransactionHash"))?; Ok(Self { tail_transaction_hash: TailTransactionHash::new(tail_transaction_hash)?, amount: value.deposit, - address: (&value.address).try_into()?, + address: value.address.try_into()?, }) } } diff --git a/sdk/src/types/block/payload/milestone/option/receipt/mod.rs b/sdk/src/types/block/payload/milestone/option/receipt/mod.rs index fc50bcd4b4..21752778d4 100644 --- a/sdk/src/types/block/payload/milestone/option/receipt/mod.rs +++ b/sdk/src/types/block/payload/milestone/option/receipt/mod.rs @@ -188,17 +188,17 @@ pub mod dto { } impl ReceiptMilestoneOption { - pub fn try_from_dto(value: &ReceiptMilestoneOptionDto, token_supply: u64) -> Result { + pub fn try_from_dto(value: ReceiptMilestoneOptionDto, token_supply: u64) -> Result { Self::new( MilestoneIndex(value.migrated_at), value.last, value .funds - .iter() + .into_iter() .map(|f| MigratedFundsEntry::try_from_dto(f, token_supply)) .collect::, _>>()?, - if let PayloadDto::TreasuryTransaction(ref transaction) = value.transaction { - TreasuryTransactionPayload::try_from_dto(transaction.as_ref(), token_supply)? + if let PayloadDto::TreasuryTransaction(transaction) = value.transaction { + TreasuryTransactionPayload::try_from_dto(*transaction, token_supply)? } else { return Err(Error::InvalidField("transaction")); }, @@ -206,10 +206,10 @@ pub mod dto { ) } - pub fn try_from_dto_unverified(value: &ReceiptMilestoneOptionDto) -> Result { + pub fn try_from_dto_unverified(value: ReceiptMilestoneOptionDto) -> Result { let funds = value .funds - .iter() + .into_iter() .map(MigratedFundsEntry::try_from_dto_unverified) .collect::, _>>()?; @@ -218,8 +218,8 @@ pub mod dto { last: value.last, funds: VecPrefix::::try_from(funds) .map_err(Error::InvalidReceiptFundsCount)?, - transaction: if let PayloadDto::TreasuryTransaction(ref transaction) = value.transaction { - TreasuryTransactionPayload::try_from_dto_unverified(transaction.as_ref())?.into() + transaction: if let PayloadDto::TreasuryTransaction(transaction) = value.transaction { + TreasuryTransactionPayload::try_from_dto_unverified(*transaction)?.into() } else { return Err(Error::InvalidField("transaction")); }, diff --git a/sdk/src/types/block/payload/mod.rs b/sdk/src/types/block/payload/mod.rs index 5f9bc76ae9..a1e9e5849f 100644 --- a/sdk/src/types/block/payload/mod.rs +++ b/sdk/src/types/block/payload/mod.rs @@ -277,30 +277,26 @@ pub mod dto { } impl Payload { - pub fn try_from_dto(value: &PayloadDto, protocol_parameters: &ProtocolParameters) -> Result { + pub fn try_from_dto(value: PayloadDto, protocol_parameters: &ProtocolParameters) -> Result { Ok(match value { - PayloadDto::Transaction(p) => { - Self::from(TransactionPayload::try_from_dto(p.as_ref(), protocol_parameters)?) - } - PayloadDto::Milestone(p) => { - Self::from(MilestonePayload::try_from_dto(p.as_ref(), protocol_parameters)?) - } + PayloadDto::Transaction(p) => Self::from(TransactionPayload::try_from_dto(*p, protocol_parameters)?), + PayloadDto::Milestone(p) => Self::from(MilestonePayload::try_from_dto(*p, protocol_parameters)?), PayloadDto::TreasuryTransaction(p) => Self::from(TreasuryTransactionPayload::try_from_dto( - p.as_ref(), + *p, protocol_parameters.token_supply(), )?), - PayloadDto::TaggedData(p) => Self::from(TaggedDataPayload::try_from(p.as_ref())?), + PayloadDto::TaggedData(p) => Self::from(TaggedDataPayload::try_from(*p)?), }) } - pub fn try_from_dto_unverified(value: &PayloadDto) -> Result { + pub fn try_from_dto_unverified(value: PayloadDto) -> Result { Ok(match value { - PayloadDto::Transaction(p) => Self::from(TransactionPayload::try_from_dto_unverified(p.as_ref())?), - PayloadDto::Milestone(p) => Self::from(MilestonePayload::try_from_dto_unverified(p.as_ref())?), + PayloadDto::Transaction(p) => Self::from(TransactionPayload::try_from_dto_unverified(*p)?), + PayloadDto::Milestone(p) => Self::from(MilestonePayload::try_from_dto_unverified(*p)?), PayloadDto::TreasuryTransaction(p) => { - Self::from(TreasuryTransactionPayload::try_from_dto_unverified(p.as_ref())?) + Self::from(TreasuryTransactionPayload::try_from_dto_unverified(*p)?) } - PayloadDto::TaggedData(p) => Self::from(TaggedDataPayload::try_from(p.as_ref())?), + PayloadDto::TaggedData(p) => Self::from(TaggedDataPayload::try_from(*p)?), }) } } diff --git a/sdk/src/types/block/payload/tagged_data/mod.rs b/sdk/src/types/block/payload/tagged_data/mod.rs index 13b1499038..57394c2d65 100644 --- a/sdk/src/types/block/payload/tagged_data/mod.rs +++ b/sdk/src/types/block/payload/tagged_data/mod.rs @@ -98,10 +98,10 @@ pub mod dto { } } - impl TryFrom<&TaggedDataPayloadDto> for TaggedDataPayload { + impl TryFrom for TaggedDataPayload { type Error = Error; - fn try_from(value: &TaggedDataPayloadDto) -> Result { + fn try_from(value: TaggedDataPayloadDto) -> Result { Self::new( if !value.tag.is_empty() { prefix_hex::decode(&value.tag).map_err(|_| Error::InvalidField("tag"))? diff --git a/sdk/src/types/block/payload/transaction/essence/mod.rs b/sdk/src/types/block/payload/transaction/essence/mod.rs index 55680c502e..3484c1f217 100644 --- a/sdk/src/types/block/payload/transaction/essence/mod.rs +++ b/sdk/src/types/block/payload/transaction/essence/mod.rs @@ -65,7 +65,7 @@ pub mod dto { impl TransactionEssence { pub fn try_from_dto( - value: &TransactionEssenceDto, + value: TransactionEssenceDto, protocol_parameters: &ProtocolParameters, ) -> Result { match value { @@ -76,7 +76,7 @@ pub mod dto { } } - pub fn try_from_dto_unverified(value: &TransactionEssenceDto) -> Result { + pub fn try_from_dto_unverified(value: TransactionEssenceDto) -> Result { match value { TransactionEssenceDto::Regular(r) => { Ok(Self::Regular(RegularTransactionEssence::try_from_dto_unverified(r)?)) diff --git a/sdk/src/types/block/payload/transaction/essence/regular.rs b/sdk/src/types/block/payload/transaction/essence/regular.rs index adbb73844e..ff9f2ab42a 100644 --- a/sdk/src/types/block/payload/transaction/essence/regular.rs +++ b/sdk/src/types/block/payload/transaction/essence/regular.rs @@ -377,17 +377,23 @@ pub mod dto { } impl RegularTransactionEssence { - fn _try_from_dto( - value: &RegularTransactionEssenceDto, - outputs: Vec, - ) -> Result { + pub fn try_from_dto( + value: RegularTransactionEssenceDto, + protocol_parameters: &ProtocolParameters, + ) -> Result { + let outputs = value + .outputs + .into_iter() + .map(|o| Output::try_from_dto(o, protocol_parameters.token_supply())) + .collect::, Error>>()?; + let network_id = value .network_id .parse::() .map_err(|_| Error::InvalidField("network_id"))?; let inputs = value .inputs - .iter() + .into_iter() .map(TryInto::try_into) .collect::, Error>>()?; @@ -395,9 +401,9 @@ pub mod dto { .with_inputs(inputs) .with_outputs(outputs); - builder = if let Some(p) = &value.payload { + builder = if let Some(p) = value.payload { if let PayloadDto::TaggedData(i) = p { - builder.with_payload(Payload::TaggedData(Box::new((i.as_ref()).try_into()?))) + builder.with_payload(Payload::TaggedData(Box::new((*i).try_into()?))) } else { return Err(Error::InvalidField("payload")); } @@ -405,32 +411,39 @@ pub mod dto { builder }; - Ok(builder) - } - - pub fn try_from_dto( - value: &RegularTransactionEssenceDto, - protocol_parameters: &ProtocolParameters, - ) -> Result { - let outputs = value - .outputs - .iter() - .map(|o| Output::try_from_dto(o, protocol_parameters.token_supply())) - .collect::, Error>>()?; - - let builder = Self::_try_from_dto(value, outputs)?; - builder.finish(protocol_parameters).map_err(Into::into) } - pub fn try_from_dto_unverified(value: &RegularTransactionEssenceDto) -> Result { + pub fn try_from_dto_unverified(value: RegularTransactionEssenceDto) -> Result { let outputs = value .outputs - .iter() + .into_iter() .map(Output::try_from_dto_unverified) .collect::, Error>>()?; - let builder = Self::_try_from_dto(value, outputs)?; + let network_id = value + .network_id + .parse::() + .map_err(|_| Error::InvalidField("network_id"))?; + let inputs = value + .inputs + .into_iter() + .map(TryInto::try_into) + .collect::, Error>>()?; + + let mut builder = Self::builder(network_id, InputsCommitment::from_str(&value.inputs_commitment)?) + .with_inputs(inputs) + .with_outputs(outputs); + + builder = if let Some(p) = value.payload { + if let PayloadDto::TaggedData(i) = p { + builder.with_payload(Payload::TaggedData(Box::new((*i).try_into()?))) + } else { + return Err(Error::InvalidField("payload")); + } + } else { + builder + }; builder.finish_unverified().map_err(Into::into) } diff --git a/sdk/src/types/block/payload/transaction/mod.rs b/sdk/src/types/block/payload/transaction/mod.rs index 58f10c0991..9277bd0b80 100644 --- a/sdk/src/types/block/payload/transaction/mod.rs +++ b/sdk/src/types/block/payload/transaction/mod.rs @@ -127,31 +127,33 @@ pub mod dto { } impl TransactionPayload { - fn _try_from_dto( - value: &TransactionPayloadDto, - transaction_essence: TransactionEssence, - ) -> Result { - let mut unlocks = Vec::new(); - - for b in &value.unlocks { - unlocks.push(b.try_into()?); - } - - Self::new(transaction_essence, Unlocks::new(unlocks)?) - } - pub fn try_from_dto( - value: &TransactionPayloadDto, + value: TransactionPayloadDto, protocol_parameters: &ProtocolParameters, ) -> Result { - Self::_try_from_dto( - value, - TransactionEssence::try_from_dto(&value.essence, protocol_parameters)?, + Self::new( + TransactionEssence::try_from_dto(value.essence, protocol_parameters)?, + Unlocks::new( + value + .unlocks + .into_iter() + .map(TryInto::try_into) + .collect::, _>>()?, + )?, ) } - pub fn try_from_dto_unverified(value: &TransactionPayloadDto) -> Result { - Self::_try_from_dto(value, TransactionEssence::try_from_dto_unverified(&value.essence)?) + pub fn try_from_dto_unverified(value: TransactionPayloadDto) -> Result { + Self::new( + TransactionEssence::try_from_dto_unverified(value.essence)?, + Unlocks::new( + value + .unlocks + .into_iter() + .map(TryInto::try_into) + .collect::, _>>()?, + )?, + ) } } } diff --git a/sdk/src/types/block/payload/treasury_transaction/mod.rs b/sdk/src/types/block/payload/treasury_transaction/mod.rs index 4fa03cda3a..d4cac27ab0 100644 --- a/sdk/src/types/block/payload/treasury_transaction/mod.rs +++ b/sdk/src/types/block/payload/treasury_transaction/mod.rs @@ -97,9 +97,9 @@ pub mod dto { } impl TreasuryTransactionPayload { - fn _try_from_dto(value: &TreasuryTransactionPayloadDto, output: TreasuryOutput) -> Result { + fn _try_from_dto(value: TreasuryTransactionPayloadDto, output: TreasuryOutput) -> Result { Self::new( - if let InputDto::Treasury(ref input) = value.input { + if let InputDto::Treasury(input) = value.input { input.try_into()? } else { return Err(Error::InvalidField("input")); @@ -108,26 +108,28 @@ pub mod dto { ) } - pub fn try_from_dto(value: &TreasuryTransactionPayloadDto, token_supply: u64) -> Result { - Self::_try_from_dto( - value, - if let OutputDto::Treasury(ref output) = value.output { - TreasuryOutput::try_from_dto(output, token_supply)? + pub fn try_from_dto(value: TreasuryTransactionPayloadDto, token_supply: u64) -> Result { + if let OutputDto::Treasury(output) = value.output { + if let InputDto::Treasury(input) = value.input { + Self::new(input.try_into()?, TreasuryOutput::try_from_dto(output, token_supply)?) } else { - return Err(Error::InvalidField("output")); - }, - ) + Err(Error::InvalidField("input")) + } + } else { + Err(Error::InvalidField("output")) + } } - pub fn try_from_dto_unverified(value: &TreasuryTransactionPayloadDto) -> Result { - Self::_try_from_dto( - value, - if let OutputDto::Treasury(ref output) = value.output { - TreasuryOutput::try_from_dto_unverified(output)? + pub fn try_from_dto_unverified(value: TreasuryTransactionPayloadDto) -> Result { + if let OutputDto::Treasury(output) = value.output { + if let InputDto::Treasury(input) = value.input { + Self::new(input.try_into()?, TreasuryOutput::try_from_dto_unverified(output)?) } else { - return Err(Error::InvalidField("output")); - }, - ) + Err(Error::InvalidField("input")) + } + } else { + Err(Error::InvalidField("output")) + } } } } diff --git a/sdk/src/types/block/signature/ed25519.rs b/sdk/src/types/block/signature/ed25519.rs index 03cca18a70..a0d1f11eff 100644 --- a/sdk/src/types/block/signature/ed25519.rs +++ b/sdk/src/types/block/signature/ed25519.rs @@ -108,10 +108,10 @@ pub mod dto { } } - impl TryFrom<&Ed25519SignatureDto> for Ed25519Signature { + impl TryFrom for Ed25519Signature { type Error = Error; - fn try_from(value: &Ed25519SignatureDto) -> Result { + fn try_from(value: Ed25519SignatureDto) -> Result { Ok(Self::new( prefix_hex::decode(&value.public_key).map_err(|_| Error::InvalidField("publicKey"))?, prefix_hex::decode(&value.signature).map_err(|_| Error::InvalidField("signature"))?, diff --git a/sdk/src/types/block/signature/mod.rs b/sdk/src/types/block/signature/mod.rs index 80cd9a015b..8082dc5eb6 100644 --- a/sdk/src/types/block/signature/mod.rs +++ b/sdk/src/types/block/signature/mod.rs @@ -67,10 +67,10 @@ pub mod dto { } } - impl TryFrom<&SignatureDto> for Signature { + impl TryFrom for Signature { type Error = Error; - fn try_from(value: &SignatureDto) -> Result { + fn try_from(value: SignatureDto) -> Result { match value { SignatureDto::Ed25519(s) => Ok(Self::Ed25519(s.try_into()?)), } diff --git a/sdk/src/types/block/unlock/mod.rs b/sdk/src/types/block/unlock/mod.rs index 1c49d29c56..1167742a1d 100644 --- a/sdk/src/types/block/unlock/mod.rs +++ b/sdk/src/types/block/unlock/mod.rs @@ -201,12 +201,12 @@ pub mod dto { } } - impl TryFrom<&UnlockDto> for Unlock { + impl TryFrom for Unlock { type Error = Error; - fn try_from(value: &UnlockDto) -> Result { + fn try_from(value: UnlockDto) -> Result { match value { - UnlockDto::Signature(s) => match &s.signature { + UnlockDto::Signature(s) => match s.signature { SignatureDto::Ed25519(ed) => { let public_key = prefix_hex::decode(&ed.public_key).map_err(|_| Error::InvalidField("publicKey"))?; diff --git a/sdk/src/wallet/account/operations/transaction/high_level/create_alias.rs b/sdk/src/wallet/account/operations/transaction/high_level/create_alias.rs index 122e5b6bf9..dd55f18cee 100644 --- a/sdk/src/wallet/account/operations/transaction/high_level/create_alias.rs +++ b/sdk/src/wallet/account/operations/transaction/high_level/create_alias.rs @@ -47,23 +47,23 @@ pub struct CreateAliasParamsDto { pub state_metadata: Option, } -impl TryFrom<&CreateAliasParamsDto> for CreateAliasParams { +impl TryFrom for CreateAliasParams { type Error = crate::wallet::Error; - fn try_from(value: &CreateAliasParamsDto) -> crate::wallet::Result { + fn try_from(value: CreateAliasParamsDto) -> crate::wallet::Result { Ok(Self { address: value.address, - immutable_metadata: match &value.immutable_metadata { + immutable_metadata: match value.immutable_metadata { Some(metadata) => { Some(prefix_hex::decode(metadata).map_err(|_| Error::InvalidField("immutable_metadata"))?) } None => None, }, - metadata: match &value.metadata { + metadata: match value.metadata { Some(metadata) => Some(prefix_hex::decode(metadata).map_err(|_| Error::InvalidField("metadata"))?), None => None, }, - state_metadata: match &value.state_metadata { + state_metadata: match value.state_metadata { Some(metadata) => { Some(prefix_hex::decode(metadata).map_err(|_| Error::InvalidField("state_metadata"))?) } diff --git a/sdk/src/wallet/account/operations/transaction/high_level/minting/mint_native_token.rs b/sdk/src/wallet/account/operations/transaction/high_level/minting/mint_native_token.rs index 736ff45b04..6398bd3a27 100644 --- a/sdk/src/wallet/account/operations/transaction/high_level/minting/mint_native_token.rs +++ b/sdk/src/wallet/account/operations/transaction/high_level/minting/mint_native_token.rs @@ -48,21 +48,18 @@ pub struct MintNativeTokenParamsDto { pub foundry_metadata: Option, } -impl TryFrom<&MintNativeTokenParamsDto> for MintNativeTokenParams { +impl TryFrom for MintNativeTokenParams { type Error = crate::wallet::Error; - fn try_from(value: &MintNativeTokenParamsDto) -> crate::wallet::Result { + fn try_from(value: MintNativeTokenParamsDto) -> crate::wallet::Result { Ok(Self { - alias_id: value.alias_id.as_ref().copied(), - circulating_supply: U256::try_from(&value.circulating_supply) - .map_err(|_| Error::InvalidField("circulating_supply"))?, - maximum_supply: U256::try_from(&value.maximum_supply).map_err(|_| Error::InvalidField("maximum_supply"))?, - foundry_metadata: match &value.foundry_metadata { - Some(metadata) => { - Some(prefix_hex::decode(metadata).map_err(|_| Error::InvalidField("foundry_metadata"))?) - } - None => None, - }, + alias_id: value.alias_id, + circulating_supply: value.circulating_supply, + maximum_supply: value.maximum_supply, + foundry_metadata: value + .foundry_metadata + .map(|metadata| prefix_hex::decode(metadata).map_err(|_| Error::InvalidField("foundry_metadata"))) + .transpose()?, }) } } diff --git a/sdk/src/wallet/account/operations/transaction/high_level/minting/mint_nfts.rs b/sdk/src/wallet/account/operations/transaction/high_level/minting/mint_nfts.rs index f065bb0714..0ba0a1e565 100644 --- a/sdk/src/wallet/account/operations/transaction/high_level/minting/mint_nfts.rs +++ b/sdk/src/wallet/account/operations/transaction/high_level/minting/mint_nfts.rs @@ -125,28 +125,28 @@ pub struct MintNftParamsDto { pub immutable_metadata: Option, } -impl TryFrom<&MintNftParamsDto> for MintNftParams { +impl TryFrom for MintNftParams { type Error = crate::wallet::Error; - fn try_from(value: &MintNftParamsDto) -> crate::wallet::Result { + fn try_from(value: MintNftParamsDto) -> crate::wallet::Result { Ok(Self { address: value.address, sender: value.sender, - metadata: match &value.metadata { - Some(metadata) => Some(prefix_hex::decode(metadata).map_err(|_| BlockError::InvalidField("metadata"))?), - None => None, - }, - tag: match &value.tag { - Some(tag) => Some(prefix_hex::decode(tag).map_err(|_| BlockError::InvalidField("tag"))?), - None => None, - }, + metadata: value + .metadata + .map(|metadata| prefix_hex::decode(metadata).map_err(|_| BlockError::InvalidField("metadata"))) + .transpose()?, + tag: value + .tag + .map(|tag| prefix_hex::decode(tag).map_err(|_| BlockError::InvalidField("tag"))) + .transpose()?, issuer: value.issuer, - immutable_metadata: match &value.immutable_metadata { - Some(metadata) => { - Some(prefix_hex::decode(metadata).map_err(|_| BlockError::InvalidField("immutable_metadata"))?) - } - None => None, - }, + immutable_metadata: value + .immutable_metadata + .map(|metadata| { + prefix_hex::decode(metadata).map_err(|_| BlockError::InvalidField("immutable_metadata")) + }) + .transpose()?, }) } } diff --git a/sdk/src/wallet/account/operations/transaction/options.rs b/sdk/src/wallet/account/operations/transaction/options.rs index 97f407a1b4..572fc48ee1 100644 --- a/sdk/src/wallet/account/operations/transaction/options.rs +++ b/sdk/src/wallet/account/operations/transaction/options.rs @@ -35,18 +35,14 @@ pub struct TransactionOptions { impl TransactionOptions { /// Conversion from TransactionOptionsDto to TransactionOptions. - pub fn try_from_dto(value: &TransactionOptionsDto) -> Result { + pub fn try_from_dto(value: TransactionOptionsDto) -> Result { Ok(Self { - remainder_value_strategy: value.remainder_value_strategy.clone(), - tagged_data_payload: value - .tagged_data_payload - .as_ref() - .map(TaggedDataPayload::try_from) - .transpose()?, - custom_inputs: value.custom_inputs.clone(), - mandatory_inputs: value.mandatory_inputs.clone(), - burn: value.burn.as_ref().map(Burn::try_from).transpose()?, - note: value.note.clone(), + remainder_value_strategy: value.remainder_value_strategy, + tagged_data_payload: value.tagged_data_payload.map(TaggedDataPayload::try_from).transpose()?, + custom_inputs: value.custom_inputs, + mandatory_inputs: value.mandatory_inputs, + burn: value.burn.map(Burn::try_from).transpose()?, + note: value.note, allow_micro_amount: value.allow_micro_amount, }) } diff --git a/sdk/src/wallet/account/operations/transaction/prepare_output.rs b/sdk/src/wallet/account/operations/transaction/prepare_output.rs index cbbddbe4b3..796b1a55b6 100644 --- a/sdk/src/wallet/account/operations/transaction/prepare_output.rs +++ b/sdk/src/wallet/account/operations/transaction/prepare_output.rs @@ -454,21 +454,20 @@ pub struct OutputParamsDto { storage_deposit: Option, } -impl TryFrom<&OutputParamsDto> for OutputParams { +impl TryFrom for OutputParams { type Error = crate::wallet::Error; - fn try_from(value: &OutputParamsDto) -> crate::wallet::Result { + fn try_from(value: OutputParamsDto) -> crate::wallet::Result { Ok(Self { recipient_address: value.recipient_address, - amount: u64::from_str(&value.amount) - .map_err(|_| crate::client::Error::InvalidAmount(value.amount.clone()))?, - assets: match &value.assets { + amount: u64::from_str(&value.amount).map_err(|_| crate::client::Error::InvalidAmount(value.amount))?, + assets: match value.assets { Some(r) => Some(Assets::try_from(r)?), None => None, }, - features: value.features.clone(), - unlocks: value.unlocks.clone(), - storage_deposit: value.storage_deposit.clone(), + features: value.features, + unlocks: value.unlocks, + storage_deposit: value.storage_deposit, }) } } @@ -480,16 +479,16 @@ pub struct AssetsDto { nft_id: Option, } -impl TryFrom<&AssetsDto> for Assets { +impl TryFrom for Assets { type Error = crate::wallet::Error; - fn try_from(value: &AssetsDto) -> crate::wallet::Result { + fn try_from(value: AssetsDto) -> crate::wallet::Result { Ok(Self { - native_tokens: match &value.native_tokens { + native_tokens: match value.native_tokens { Some(r) => Some( - r.iter() + r.into_iter() .map(|r| Ok(NativeToken::try_from(r)?)) - .collect::>>()?, + .collect::>()?, ), None => None, }, diff --git a/sdk/src/wallet/account/update.rs b/sdk/src/wallet/account/update.rs index bccd5dafb4..53bb506057 100644 --- a/sdk/src/wallet/account/update.rs +++ b/sdk/src/wallet/account/update.rs @@ -100,7 +100,7 @@ impl Account { if output_metadata_response.is_spent { account_details.unspent_outputs.remove(&output_id); if let Some(output_data) = account_details.outputs.get_mut(&output_id) { - output_data.metadata = (&output_metadata_response).try_into()?; + output_data.metadata = output_metadata_response.try_into()?; } } else { // not spent, just not synced, skip diff --git a/sdk/src/wallet/message_interface/message_handler.rs b/sdk/src/wallet/message_interface/message_handler.rs index cc729d76eb..992bda50b0 100644 --- a/sdk/src/wallet/message_interface/message_handler.rs +++ b/sdk/src/wallet/message_interface/message_handler.rs @@ -461,7 +461,7 @@ impl WalletMessageHandler { }, native_tokens, serial_number, - &token_scheme, + token_scheme, unlock_conditions, features, immutable_features, @@ -503,7 +503,7 @@ impl WalletMessageHandler { let transaction = account .burn( NativeToken::new(token_id, burn_amount)?, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Ok(Response::SentTransaction(TransactionDto::from(&transaction))) @@ -513,10 +513,7 @@ impl WalletMessageHandler { AccountMethod::BurnNft { nft_id, options } => { convert_async_panics(|| async { let transaction = account - .burn( - nft_id, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, - ) + .burn(nft_id, options.map(TransactionOptions::try_from_dto).transpose()?) .await?; Ok(Response::SentTransaction(TransactionDto::from(&transaction))) }) @@ -536,15 +533,10 @@ impl WalletMessageHandler { } AccountMethod::CreateAliasOutput { params, options } => { convert_async_panics(|| async { - let params = params - .map(|options| CreateAliasParams::try_from(&options)) - .transpose()?; + let params = params.map(CreateAliasParams::try_from).transpose()?; let transaction = account - .create_alias_output( - params, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, - ) + .create_alias_output(params, options.map(TransactionOptions::try_from_dto).transpose()?) .await?; Ok(Response::SentTransaction(TransactionDto::from(&transaction))) }) @@ -553,10 +545,7 @@ impl WalletMessageHandler { AccountMethod::DestroyAlias { alias_id, options } => { convert_async_panics(|| async { let transaction = account - .burn( - alias_id, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, - ) + .burn(alias_id, options.map(TransactionOptions::try_from_dto).transpose()?) .await?; Ok(Response::SentTransaction(TransactionDto::from(&transaction))) }) @@ -565,10 +554,7 @@ impl WalletMessageHandler { AccountMethod::DestroyFoundry { foundry_id, options } => { convert_async_panics(|| async { let transaction = account - .burn( - foundry_id, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, - ) + .burn(foundry_id, options.map(TransactionOptions::try_from_dto).transpose()?) .await?; Ok(Response::SentTransaction(TransactionDto::from(&transaction))) }) @@ -680,7 +666,7 @@ impl WalletMessageHandler { .decrease_native_token_supply( token_id, U256::try_from(&melt_amount).map_err(|_| Error::InvalidField("melt_amount"))?, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Ok(Response::SentTransaction(TransactionDto::from(&transaction))) @@ -697,7 +683,7 @@ impl WalletMessageHandler { .increase_native_token_supply( token_id, U256::try_from(&mint_amount).map_err(|_| Error::InvalidField("mint_amount"))?, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Ok(Response::MintTokenTransaction(MintTokenTransactionDto::from( @@ -710,8 +696,8 @@ impl WalletMessageHandler { convert_async_panics(|| async { let transaction = account .mint_native_token( - MintNativeTokenParams::try_from(¶ms)?, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + MintNativeTokenParams::try_from(params)?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Ok(Response::MintTokenTransaction(MintTokenTransactionDto::from( @@ -722,7 +708,7 @@ impl WalletMessageHandler { } AccountMethod::MinimumRequiredStorageDeposit { output } => { convert_async_panics(|| async { - let output = Output::try_from_dto(&output, account.client().get_token_supply().await?)?; + let output = Output::try_from_dto(output, account.client().get_token_supply().await?)?; let rent_structure = account.client().get_rent_structure().await?; let minimum_storage_deposit = output.rent_cost(&rent_structure); @@ -738,10 +724,10 @@ impl WalletMessageHandler { let transaction = account .mint_nfts( params - .iter() + .into_iter() .map(MintNftParams::try_from) .collect::>>()?, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Ok(Response::SentTransaction(TransactionDto::from(&transaction))) @@ -756,11 +742,8 @@ impl WalletMessageHandler { convert_async_panics(|| async { let output = account .prepare_output( - OutputParams::try_from(options.as_ref())?, - transaction_options - .as_ref() - .map(TransactionOptions::try_from_dto) - .transpose()?, + OutputParams::try_from(*options)?, + transaction_options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Ok(Response::Output(OutputDto::from(&output))) @@ -770,10 +753,7 @@ impl WalletMessageHandler { AccountMethod::PrepareSendAmount { params, options } => { convert_async_panics(|| async { let data = account - .prepare_send_amount( - params, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, - ) + .prepare_send_amount(params, options.map(TransactionOptions::try_from_dto).transpose()?) .await?; Ok(Response::PreparedTransaction(PreparedTransactionDataDto::from(&data))) }) @@ -785,10 +765,10 @@ impl WalletMessageHandler { let data = account .prepare_transaction( outputs - .iter() + .into_iter() .map(|o| Ok(Output::try_from_dto(o, token_supply)?)) .collect::>>()?, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Ok(Response::PreparedTransaction(PreparedTransactionDataDto::from(&data))) @@ -814,10 +794,7 @@ impl WalletMessageHandler { AccountMethod::SendAmount { params, options } => { convert_async_panics(|| async { let transaction = account - .send_amount( - params, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, - ) + .send_amount(params, options.map(TransactionOptions::try_from_dto).transpose()?) .await?; Ok(Response::SentTransaction(TransactionDto::from(&transaction))) }) @@ -828,7 +805,7 @@ impl WalletMessageHandler { let transaction = account .send_native_tokens( params.clone(), - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Ok(Response::SentTransaction(TransactionDto::from(&transaction))) @@ -840,7 +817,7 @@ impl WalletMessageHandler { let transaction = account .send_nft( params.clone(), - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Ok(Response::SentTransaction(TransactionDto::from(&transaction))) @@ -867,10 +844,10 @@ impl WalletMessageHandler { let transaction = account .send( outputs - .iter() + .into_iter() .map(|o| Ok(Output::try_from_dto(o, token_supply)?)) .collect::>>()?, - options.as_ref().map(TransactionOptions::try_from_dto).transpose()?, + options.map(TransactionOptions::try_from_dto).transpose()?, ) .await?; Ok(Response::SentTransaction(TransactionDto::from(&transaction))) @@ -883,7 +860,7 @@ impl WalletMessageHandler { convert_async_panics(|| async { let signed_transaction_data = account .sign_transaction_essence(&PreparedTransactionData::try_from_dto( - &prepared_transaction_data, + prepared_transaction_data, &account.client().get_protocol_parameters().await?, )?) .await?; @@ -898,7 +875,7 @@ impl WalletMessageHandler { } => { convert_async_panics(|| async { let signed_transaction_data = SignedTransactionData::try_from_dto( - &signed_transaction_data, + signed_transaction_data, &account.client().get_protocol_parameters().await?, )?; let transaction = account.submit_and_store_transaction(signed_transaction_data).await?; diff --git a/sdk/src/wallet/message_interface/mod.rs b/sdk/src/wallet/message_interface/mod.rs index ff069dbf18..7721a6f95c 100644 --- a/sdk/src/wallet/message_interface/mod.rs +++ b/sdk/src/wallet/message_interface/mod.rs @@ -73,7 +73,7 @@ pub async fn create_message_handler(options: Option) -> crate::w } if let Some(secret_manager) = options.secret_manager { - builder = builder.with_secret_manager(SecretManager::try_from(&secret_manager)?); + builder = builder.with_secret_manager(SecretManager::try_from(secret_manager)?); } if let Some(client_options) = options.client_options { diff --git a/sdk/src/wallet/storage/manager.rs b/sdk/src/wallet/storage/manager.rs index cb6c8008b7..c7fed9526e 100644 --- a/sdk/src/wallet/storage/manager.rs +++ b/sdk/src/wallet/storage/manager.rs @@ -122,7 +122,7 @@ impl StorageManager { match secret_manager_dto { SecretManagerDto::Mnemonic(_) => {} _ => { - let secret_manager = SecretManager::try_from(&secret_manager_dto)?; + let secret_manager = SecretManager::try_from(secret_manager_dto)?; builder.secret_manager = Some(Arc::new(RwLock::new(secret_manager))); } } diff --git a/sdk/src/wallet/wallet/operations/stronghold_backup/mod.rs b/sdk/src/wallet/wallet/operations/stronghold_backup/mod.rs index bf804fe76d..0b88e62c96 100644 --- a/sdk/src/wallet/wallet/operations/stronghold_backup/mod.rs +++ b/sdk/src/wallet/wallet/operations/stronghold_backup/mod.rs @@ -130,10 +130,10 @@ impl Wallet { if let Some(mut read_secret_manager) = read_secret_manager { // We have to replace the snapshot path with the current one, when building stronghold if let SecretManagerDto::Stronghold(stronghold_dto) = &mut read_secret_manager { - stronghold_dto.snapshot_path = new_snapshot_path.clone().into_os_string().to_string_lossy().into(); + stronghold_dto.snapshot_path = new_snapshot_path.clone().to_string_lossy().into_owned(); } - let mut restored_secret_manager = SecretManager::try_from(&read_secret_manager) + let mut restored_secret_manager = SecretManager::try_from(read_secret_manager) .map_err(|_| crate::wallet::Error::Backup("invalid secret_manager"))?; if let SecretManager::Stronghold(stronghold) = &mut restored_secret_manager { diff --git a/sdk/tests/client/input_signing_data.rs b/sdk/tests/client/input_signing_data.rs index 269ca21275..255b368a2e 100644 --- a/sdk/tests/client/input_signing_data.rs +++ b/sdk/tests/client/input_signing_data.rs @@ -50,7 +50,7 @@ fn input_signing_data_conversion() { assert_eq!(input_signing_data_dto.chain.as_deref(), Some(&bip32_chain[..])); let restored_input_signing_data = - InputSigningData::try_from_dto(&input_signing_data_dto, protocol_parameters.token_supply()).unwrap(); + InputSigningData::try_from_dto(input_signing_data_dto.clone(), protocol_parameters.token_supply()).unwrap(); assert_eq!(input_signing_data, restored_input_signing_data); let input_signing_data_dto_str = r#"{"output":{"type":3,"amount":"1000000","unlockConditions":[{"type":0,"address":{"type":0,"pubKeyHash":"0x7ffec9e1233204d9c6dce6812b1539ee96af691ca2e4d9065daa85907d33e5d3"}}]},"outputMetadata":{"blockId":"0xedf5f572c58ddf4b4f9567d82bf96689cc68b730df796d822b4b9fb643f5efda","transactionId":"0xbce525324af12eda02bf7927e92cea3a8e8322d0f41966271443e6c3b245a440","outputIndex":0,"isSpent":false,"milestoneIndexBooked":0,"milestoneTimestampBooked":0,"ledgerIndex":0},"chain":[44,4219,0,0,0]}"#; @@ -64,7 +64,7 @@ fn input_signing_data_conversion() { assert_eq!(restored_input_signing_data_dto.chain.as_deref(), Some(&bip32_chain[..])); let restored_input_signing_data = - InputSigningData::try_from_dto(&restored_input_signing_data_dto, protocol_parameters.token_supply()).unwrap(); + InputSigningData::try_from_dto(restored_input_signing_data_dto, protocol_parameters.token_supply()).unwrap(); assert!(restored_input_signing_data.output.is_basic()); assert_eq!( restored_input_signing_data.chain, diff --git a/sdk/tests/types/address/alias.rs b/sdk/tests/types/address/alias.rs index cd65a136ca..237b7c9824 100644 --- a/sdk/tests/types/address/alias.rs +++ b/sdk/tests/types/address/alias.rs @@ -120,12 +120,12 @@ fn dto_roundtrip() { let alias_address = AliasAddress::from_str(ALIAS_ID).unwrap(); let alias_dto = AliasAddressDto::from(&alias_address); - assert_eq!(AliasAddress::try_from(&alias_dto).unwrap(), alias_address); + assert_eq!(AliasAddress::try_from(alias_dto).unwrap(), alias_address); let address = Address::from(alias_address); let dto = AddressDto::from(&address); - assert_eq!(Address::try_from(&dto).unwrap(), address); + assert_eq!(Address::try_from(dto).unwrap(), address); } #[test] @@ -136,7 +136,7 @@ fn dto_invalid_alias_id() { }; assert!(matches!( - AliasAddress::try_from(&dto), + AliasAddress::try_from(dto), Err(Error::InvalidField("aliasId")) )); } diff --git a/sdk/tests/types/address/ed25519.rs b/sdk/tests/types/address/ed25519.rs index 91645663f7..4fd3ec357e 100644 --- a/sdk/tests/types/address/ed25519.rs +++ b/sdk/tests/types/address/ed25519.rs @@ -110,12 +110,12 @@ fn dto_roundtrip() { let ed25519_address = Ed25519Address::from_str(ED25519_ADDRESS).unwrap(); let ed25519_dto = Ed25519AddressDto::from(&ed25519_address); - assert_eq!(Ed25519Address::try_from(&ed25519_dto).unwrap(), ed25519_address); + assert_eq!(Ed25519Address::try_from(ed25519_dto).unwrap(), ed25519_address); let address = Address::from(ed25519_address); let dto = AddressDto::from(&address); - assert_eq!(Address::try_from(&dto).unwrap(), address); + assert_eq!(Address::try_from(dto).unwrap(), address); } #[test] @@ -126,7 +126,7 @@ fn dto_invalid_pub_key_hash() { }; assert!(matches!( - Ed25519Address::try_from(&dto), + Ed25519Address::try_from(dto), Err(Error::InvalidField("pubKeyHash")) )); } diff --git a/sdk/tests/types/address/nft.rs b/sdk/tests/types/address/nft.rs index cc3975e9f8..3255203d2f 100644 --- a/sdk/tests/types/address/nft.rs +++ b/sdk/tests/types/address/nft.rs @@ -120,12 +120,12 @@ fn dto_roundtrip() { let nft_address = NftAddress::from_str(NFT_ID).unwrap(); let nft_dto = NftAddressDto::from(&nft_address); - assert_eq!(NftAddress::try_from(&nft_dto).unwrap(), nft_address); + assert_eq!(NftAddress::try_from(nft_dto).unwrap(), nft_address); let address = Address::from(nft_address); let dto = AddressDto::from(&address); - assert_eq!(Address::try_from(&dto).unwrap(), address); + assert_eq!(Address::try_from(dto).unwrap(), address); } #[test] @@ -135,7 +135,7 @@ fn dto_invalid_nft_id() { nft_id: NFT_ID_INVALID.to_string(), }; - assert!(matches!(NftAddress::try_from(&dto), Err(Error::InvalidField("nftId")))); + assert!(matches!(NftAddress::try_from(dto), Err(Error::InvalidField("nftId")))); } #[test] diff --git a/sdk/tests/types/input/treasury.rs b/sdk/tests/types/input/treasury.rs index e9c9a729af..488c059942 100644 --- a/sdk/tests/types/input/treasury.rs +++ b/sdk/tests/types/input/treasury.rs @@ -101,12 +101,12 @@ fn dto_roundtrip() { let treasury_input = TreasuryInput::from_str(MILESTONE_ID).unwrap(); let treasury_dto = TreasuryInputDto::from(&treasury_input); - assert_eq!(TreasuryInput::try_from(&treasury_dto).unwrap(), treasury_input); + assert_eq!(TreasuryInput::try_from(treasury_dto).unwrap(), treasury_input); let input = Input::from(treasury_input); let dto = InputDto::from(&input); - assert_eq!(Input::try_from(&dto).unwrap(), input); + assert_eq!(Input::try_from(dto).unwrap(), input); } #[test] @@ -117,7 +117,7 @@ fn dto_invalid() { }; assert!(matches!( - TreasuryInput::try_from(&dto), + TreasuryInput::try_from(dto), Err(Error::InvalidField("milestoneId")) )); } diff --git a/sdk/tests/types/input/utxo.rs b/sdk/tests/types/input/utxo.rs index 6999439803..83f918752e 100644 --- a/sdk/tests/types/input/utxo.rs +++ b/sdk/tests/types/input/utxo.rs @@ -101,12 +101,12 @@ fn dto_roundtrip() { let utxo_input = UtxoInput::from_str(OUTPUT_ID).unwrap(); let utxo_dto = UtxoInputDto::from(&utxo_input); - assert_eq!(UtxoInput::try_from(&utxo_dto).unwrap(), utxo_input); + assert_eq!(UtxoInput::try_from(utxo_dto).unwrap(), utxo_input); let input = Input::from(utxo_input); let dto = InputDto::from(&input); - assert_eq!(Input::try_from(&dto).unwrap(), input); + assert_eq!(Input::try_from(dto).unwrap(), input); } #[test] @@ -118,7 +118,7 @@ fn dto_invalid() { }; assert!(matches!( - UtxoInput::try_from(&dto), + UtxoInput::try_from(dto), Err(Error::InvalidField("transactionId")) )); @@ -129,7 +129,7 @@ fn dto_invalid() { }; assert!(matches!( - UtxoInput::try_from(&dto), + UtxoInput::try_from(dto), Err(Error::InvalidInputOutputIndex(InvalidBoundedU16(1000))) )); } From 9843cb4d2173ef5703ef7d30439c52be5bfa337c Mon Sep 17 00:00:00 2001 From: Alex Coats Date: Wed, 7 Jun 2023 16:40:56 -0400 Subject: [PATCH 2/8] changelog --- sdk/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/CHANGELOG.md b/sdk/CHANGELOG.md index b6ad5d612d..803f37ecc4 100644 --- a/sdk/CHANGELOG.md +++ b/sdk/CHANGELOG.md @@ -94,6 +94,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `LedgerNanoStatus::locked` is now optional since it's an IOTA/Shimmer specific API; - `StorageManager` and wallet dynamic `StorageAdapter` are now private; - All public password-related methods now claim ownership over provided passwords and take care of zeroing the memory on drop; +- Dto type conversion to represented type now always takes owned data; ### Removed From 81ffe5a03eb67bd7ebbe9352e7e07100b6375759 Mon Sep 17 00:00:00 2001 From: Alex Coats Date: Wed, 7 Jun 2023 16:43:04 -0400 Subject: [PATCH 3/8] fix no_std and wasm --- sdk/src/client/secret/types.rs | 5 +++-- sdk/src/types/block/payload/transaction/mod.rs | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/sdk/src/client/secret/types.rs b/sdk/src/client/secret/types.rs index 8c56b7e479..dd47a12e9b 100644 --- a/sdk/src/client/secret/types.rs +++ b/sdk/src/client/secret/types.rs @@ -7,7 +7,7 @@ use crypto::keys::slip10::{Chain, Segment}; use serde::{Deserialize, Serialize}; use crate::{ - client::{Password, Result}, + client::Result, types::block::{ address::Address, output::{ @@ -24,13 +24,14 @@ use crate::{ #[serde(rename_all = "camelCase")] pub struct StrongholdDto { /// The Stronghold password - pub password: Option, + pub password: Option, /// The timeout for auto key clearing, in seconds pub timeout: Option, /// The path for the Stronghold file pub snapshot_path: String, } +#[cfg(feature = "stronghold")] impl core::fmt::Debug for StrongholdDto { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("StrongholdDto") diff --git a/sdk/src/types/block/payload/transaction/mod.rs b/sdk/src/types/block/payload/transaction/mod.rs index 9277bd0b80..490751ab36 100644 --- a/sdk/src/types/block/payload/transaction/mod.rs +++ b/sdk/src/types/block/payload/transaction/mod.rs @@ -99,7 +99,7 @@ fn verify_essence_unlocks(essence: &TransactionEssence, unlocks: &Unlocks) -> Re #[allow(missing_docs)] pub mod dto { - use alloc::vec::Vec; + use alloc::{boxed::Box, vec::Vec}; use serde::{Deserialize, Serialize}; From 28f622d7e3bc3ce6eb301582fb4c8730b94055d1 Mon Sep 17 00:00:00 2001 From: Alex Coats Date: Wed, 7 Jun 2023 17:19:12 -0400 Subject: [PATCH 4/8] PR suggestion --- bindings/core/src/lib.rs | 4 ++-- bindings/core/tests/combined.rs | 6 +++--- bindings/nodejs/src/wallet.rs | 2 +- bindings/python/src/wallet.rs | 2 +- bindings/wasm/src/wallet.rs | 2 +- sdk/CHANGELOG.md | 1 + 6 files changed, 9 insertions(+), 8 deletions(-) diff --git a/bindings/core/src/lib.rs b/bindings/core/src/lib.rs index 9bf83839c7..d2aed1f268 100644 --- a/bindings/core/src/lib.rs +++ b/bindings/core/src/lib.rs @@ -49,8 +49,8 @@ pub struct WalletOptions { } impl WalletOptions { - pub async fn build_manager(self) -> iota_sdk::wallet::Result { - log::debug!("build_manager {self:?}"); + pub async fn build(self) -> iota_sdk::wallet::Result { + log::debug!("wallet options: {self:?}"); let mut builder = Wallet::builder(); #[cfg(feature = "storage")] diff --git a/bindings/core/tests/combined.rs b/bindings/core/tests/combined.rs index 06ef0ed8ca..fe12eefa2d 100644 --- a/bindings/core/tests/combined.rs +++ b/bindings/core/tests/combined.rs @@ -32,7 +32,7 @@ async fn create_account() -> Result<()> { secret_manager: Some(serde_json::from_str(secret_manager).unwrap()), }; - let wallet = options.build_manager().await?; + let wallet = options.build().await?; // create an account let response = wallet @@ -90,7 +90,7 @@ async fn verify_accounts() -> Result<()> { secret_manager: Some(serde_json::from_str(secret_manager).unwrap()), }; - let wallet = options.build_manager().await?; + let wallet = options.build().await?; let mut account_details = BTreeMap::new(); let mut handle_response = |response| match response { @@ -198,7 +198,7 @@ async fn client_from_wallet() -> Result<()> { secret_manager: Some(serde_json::from_str(secret_manager).unwrap()), }; - let wallet = options.build_manager().await?; + let wallet = options.build().await?; // create an account let response = wallet diff --git a/bindings/nodejs/src/wallet.rs b/bindings/nodejs/src/wallet.rs index 05ae0d3f5d..2cdf3e3c48 100644 --- a/bindings/nodejs/src/wallet.rs +++ b/bindings/nodejs/src/wallet.rs @@ -34,7 +34,7 @@ impl WalletMethodHandler { let wallet_options = serde_json::from_str::(&options)?; let wallet = crate::RUNTIME - .block_on(async move { wallet_options.build_manager().await }) + .block_on(async move { wallet_options.build().await }) .expect("error initializing wallet"); Ok(Self { channel, wallet }) diff --git a/bindings/python/src/wallet.rs b/bindings/python/src/wallet.rs index f8fe7507e7..6401e08484 100644 --- a/bindings/python/src/wallet.rs +++ b/bindings/python/src/wallet.rs @@ -35,7 +35,7 @@ pub fn destroy_wallet(wallet: &Wallet) -> PyResult<()> { #[pyfunction] pub fn create_wallet(options: String) -> Result { let wallet_options = serde_json::from_str::(&options)?; - let wallet = crate::block_on(async { wallet_options.build_manager().await })?; + let wallet = crate::block_on(async { wallet_options.build().await })?; Ok(Wallet { wallet: Arc::new(RwLock::new(Some(wallet))), diff --git a/bindings/wasm/src/wallet.rs b/bindings/wasm/src/wallet.rs index eb505e29d1..580ead2b51 100644 --- a/bindings/wasm/src/wallet.rs +++ b/bindings/wasm/src/wallet.rs @@ -31,7 +31,7 @@ pub fn create_wallet(options: String) -> Result { let wallet_method_handler = tokio::runtime::Builder::new_current_thread() .build() .unwrap() - .block_on(async move { wallet_options.build_manager().await }) + .block_on(async move { wallet_options.build().await }) .map_err(|e| e.to_string())?; Ok(WalletMethodHandler { diff --git a/sdk/CHANGELOG.md b/sdk/CHANGELOG.md index 803f37ecc4..e658c0e2f8 100644 --- a/sdk/CHANGELOG.md +++ b/sdk/CHANGELOG.md @@ -95,6 +95,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `StorageManager` and wallet dynamic `StorageAdapter` are now private; - All public password-related methods now claim ownership over provided passwords and take care of zeroing the memory on drop; - Dto type conversion to represented type now always takes owned data; +- Rename `WalletOptions::build_manager` to `build`; ### Removed From 7655287ed6fd51cb7f4691647be5ea79f896df9b Mon Sep 17 00:00:00 2001 From: Alex Coats Date: Thu, 8 Jun 2023 08:46:14 -0400 Subject: [PATCH 5/8] cleanup --- sdk/src/types/block/output/basic.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/sdk/src/types/block/output/basic.rs b/sdk/src/types/block/output/basic.rs index 7a6fb25549..ab561b1c59 100644 --- a/sdk/src/types/block/output/basic.rs +++ b/sdk/src/types/block/output/basic.rs @@ -371,9 +371,7 @@ pub mod dto { let mut builder = BasicOutputBuilder::new_with_amount(value.amount.parse().map_err(|_| Error::InvalidField("amount"))?); - for t in value.native_tokens { - builder = builder.add_native_token(t); - } + builder = builder.with_native_tokens(value.native_tokens); for b in value.features { builder = builder.add_feature(Feature::try_from(b)?); @@ -390,9 +388,7 @@ pub mod dto { let mut builder = BasicOutputBuilder::new_with_amount(value.amount.parse().map_err(|_| Error::InvalidField("amount"))?); - for t in value.native_tokens { - builder = builder.add_native_token(t); - } + builder = builder.with_native_tokens(value.native_tokens); for b in value.features { builder = builder.add_feature(Feature::try_from(b)?); From e88356867cd66b23804ad2e84929341cdfc3cec9 Mon Sep 17 00:00:00 2001 From: Alex Coats Date: Thu, 8 Jun 2023 09:23:53 -0400 Subject: [PATCH 6/8] comment --- sdk/src/client/secret/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/src/client/secret/mod.rs b/sdk/src/client/secret/mod.rs index 0338a37668..b492ee735d 100644 --- a/sdk/src/client/secret/mod.rs +++ b/sdk/src/client/secret/mod.rs @@ -191,7 +191,6 @@ impl TryFrom for SecretManager { let mut builder = StrongholdSecretManager::builder(); if let Some(password) = stronghold_dto.password { - // `SecretManagerDto` is `ZeroizeOnDrop` so it will take care of zeroizing the original. builder = builder.password(password); } From 00df44893a4e0914d510eff11b4c2b0f361f5923 Mon Sep 17 00:00:00 2001 From: Alex Coats Date: Thu, 8 Jun 2023 10:18:25 -0400 Subject: [PATCH 7/8] zeroize more sensitive data --- bindings/core/tests/secrets_manager.rs | 4 ++-- sdk/examples/client/01_generate_addresses.rs | 2 +- sdk/examples/client/02_get_address_balance.rs | 2 +- sdk/examples/client/block/output.rs | 2 +- sdk/examples/client/block/transaction.rs | 2 +- .../client/high_level/search_address.rs | 4 ++-- .../offline_signing/0_address_generation.rs | 2 +- .../offline_signing/2_transaction_signing.rs | 2 +- sdk/examples/client/output/alias.rs | 2 +- sdk/examples/client/output/all.rs | 2 +- .../output/all_automatic_input_selection.rs | 2 +- sdk/examples/client/output/basic.rs | 2 +- sdk/examples/client/output/expiration.rs | 2 +- sdk/examples/client/output/foundry.rs | 2 +- sdk/examples/client/output/micro_transaction.rs | 2 +- sdk/examples/client/output/native_tokens.rs | 2 +- sdk/examples/client/output/nft.rs | 2 +- sdk/examples/client/output/recursive_alias.rs | 2 +- sdk/examples/client/participation.rs | 4 ++-- sdk/examples/client/quorum.rs | 2 +- sdk/examples/client/send_all.rs | 2 +- sdk/examples/client/split_funds.rs | 2 +- sdk/examples/wallet/accounts.rs | 2 +- sdk/examples/wallet/background_syncing.rs | 2 +- sdk/examples/wallet/events.rs | 2 +- sdk/examples/wallet/logger.rs | 2 +- sdk/examples/wallet/output_consolidation.rs | 2 +- sdk/examples/wallet/participation.rs | 2 +- sdk/examples/wallet/ping.rs | 2 +- sdk/examples/wallet/pong.rs | 2 +- sdk/examples/wallet/recover_accounts.rs | 2 +- sdk/examples/wallet/split_funds.rs | 2 +- sdk/examples/wallet/storage.rs | 2 +- sdk/examples/wallet/threads.rs | 2 +- sdk/examples/wallet/wallet.rs | 2 +- sdk/src/client/secret/mnemonic.rs | 17 ++++++++--------- sdk/src/client/secret/mod.rs | 17 ++++++++--------- sdk/src/client/utils.rs | 12 ++++++------ sdk/tests/client/addresses.rs | 6 +++--- sdk/tests/client/common/mod.rs | 4 ++-- sdk/tests/client/signing/alias.rs | 6 +++--- sdk/tests/client/signing/basic.rs | 6 +++--- sdk/tests/client/signing/mod.rs | 2 +- sdk/tests/client/signing/nft.rs | 2 +- sdk/tests/wallet/account_recovery.rs | 4 ++-- sdk/tests/wallet/backup_restore.rs | 4 ++-- sdk/tests/wallet/common/mod.rs | 4 ++-- sdk/tests/wallet/wallet.rs | 14 ++++++++------ 48 files changed, 87 insertions(+), 87 deletions(-) diff --git a/bindings/core/tests/secrets_manager.rs b/bindings/core/tests/secrets_manager.rs index 06ebff06cc..7ff91e891f 100644 --- a/bindings/core/tests/secrets_manager.rs +++ b/bindings/core/tests/secrets_manager.rs @@ -10,7 +10,7 @@ use tokio::sync::RwLock; #[tokio::test] async fn generate_ed25519_addresses() -> Result<()> { let secret_manager = Arc::new(RwLock::new(SecretManager::try_from_mnemonic( - "endorse answer radar about source reunion marriage tag sausage weekend frost daring base attack because joke dream slender leisure group reason prepare broken river", + "endorse answer radar about source reunion marriage tag sausage weekend frost daring base attack because joke dream slender leisure group reason prepare broken river".to_owned(), )?)); let method = SecretManagerMethod::GenerateEd25519Addresses { @@ -32,7 +32,7 @@ async fn generate_ed25519_addresses() -> Result<()> { #[tokio::test] async fn generate_evm_addresses() -> Result<()> { let secret_manager = Arc::new(RwLock::new(SecretManager::try_from_mnemonic( - "endorse answer radar about source reunion marriage tag sausage weekend frost daring base attack because joke dream slender leisure group reason prepare broken river", + "endorse answer radar about source reunion marriage tag sausage weekend frost daring base attack because joke dream slender leisure group reason prepare broken river".to_owned(), )?)); let method = SecretManagerMethod::GenerateEvmAddresses { diff --git a/sdk/examples/client/01_generate_addresses.rs b/sdk/examples/client/01_generate_addresses.rs index ba873cb218..183eb46723 100644 --- a/sdk/examples/client/01_generate_addresses.rs +++ b/sdk/examples/client/01_generate_addresses.rs @@ -28,7 +28,7 @@ async fn main() -> Result<()> { .await?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; // Generate addresses with default account index and range let addresses = secret_manager diff --git a/sdk/examples/client/02_get_address_balance.rs b/sdk/examples/client/02_get_address_balance.rs index 9f4eece8d5..51c82002ad 100644 --- a/sdk/examples/client/02_get_address_balance.rs +++ b/sdk/examples/client/02_get_address_balance.rs @@ -27,7 +27,7 @@ async fn main() -> Result<()> { .await?; let secret_manager = - MnemonicSecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + MnemonicSecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let token_supply = client.get_token_supply().await?; diff --git a/sdk/examples/client/block/output.rs b/sdk/examples/client/block/output.rs index ee573417f4..359c648e24 100644 --- a/sdk/examples/client/block/output.rs +++ b/sdk/examples/client/block/output.rs @@ -23,7 +23,7 @@ async fn main() -> Result<()> { let client = Client::builder().with_node(&node_url)?.finish().await?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let token_supply = client.get_token_supply().await?; diff --git a/sdk/examples/client/block/transaction.rs b/sdk/examples/client/block/transaction.rs index 58cb03608e..99e4c16c43 100644 --- a/sdk/examples/client/block/transaction.rs +++ b/sdk/examples/client/block/transaction.rs @@ -19,7 +19,7 @@ async fn main() -> Result<()> { let client = Client::builder().with_node(&node_url)?.finish().await?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let block = client .block() diff --git a/sdk/examples/client/high_level/search_address.rs b/sdk/examples/client/high_level/search_address.rs index 71ffad018c..64a7140518 100644 --- a/sdk/examples/client/high_level/search_address.rs +++ b/sdk/examples/client/high_level/search_address.rs @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 //! In this example we will try to find the index and address type of an address. -//! +//! //! `cargo run --example search_address --release` use iota_sdk::client::{ @@ -25,7 +25,7 @@ async fn main() -> Result<()> { .finish()?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let addresses = client .get_addresses(&secret_manager) diff --git a/sdk/examples/client/offline_signing/0_address_generation.rs b/sdk/examples/client/offline_signing/0_address_generation.rs index e7bc85fff1..1f58054062 100644 --- a/sdk/examples/client/offline_signing/0_address_generation.rs +++ b/sdk/examples/client/offline_signing/0_address_generation.rs @@ -24,7 +24,7 @@ async fn main() -> Result<()> { dotenvy::dotenv().ok(); let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; // Generates an address offline. let address = secret_manager diff --git a/sdk/examples/client/offline_signing/2_transaction_signing.rs b/sdk/examples/client/offline_signing/2_transaction_signing.rs index aac5b93fd2..e02af2c101 100644 --- a/sdk/examples/client/offline_signing/2_transaction_signing.rs +++ b/sdk/examples/client/offline_signing/2_transaction_signing.rs @@ -29,7 +29,7 @@ async fn main() -> Result<()> { dotenvy::dotenv().ok(); let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let prepared_transaction_data = read_prepared_transaction_from_file(PREPARED_TRANSACTION_FILE_NAME)?; diff --git a/sdk/examples/client/output/alias.rs b/sdk/examples/client/output/alias.rs index daf823ba8c..15eac15b87 100644 --- a/sdk/examples/client/output/alias.rs +++ b/sdk/examples/client/output/alias.rs @@ -31,7 +31,7 @@ async fn main() -> Result<()> { let client = Client::builder().with_node(&node_url)?.finish().await?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let token_supply = client.get_token_supply().await?; diff --git a/sdk/examples/client/output/all.rs b/sdk/examples/client/output/all.rs index fd65662665..7edba792cd 100644 --- a/sdk/examples/client/output/all.rs +++ b/sdk/examples/client/output/all.rs @@ -42,7 +42,7 @@ async fn main() -> Result<()> { let client = Client::builder().with_node(&node_url)?.finish().await?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let token_supply = client.get_token_supply().await?; diff --git a/sdk/examples/client/output/all_automatic_input_selection.rs b/sdk/examples/client/output/all_automatic_input_selection.rs index dc0929bc10..b0e7729bb0 100644 --- a/sdk/examples/client/output/all_automatic_input_selection.rs +++ b/sdk/examples/client/output/all_automatic_input_selection.rs @@ -39,7 +39,7 @@ async fn main() -> Result<()> { let client = Client::builder().with_node(&node_url)?.finish().await?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let token_supply = client.get_token_supply().await?; diff --git a/sdk/examples/client/output/basic.rs b/sdk/examples/client/output/basic.rs index 43ab415527..414c1338c9 100644 --- a/sdk/examples/client/output/basic.rs +++ b/sdk/examples/client/output/basic.rs @@ -32,7 +32,7 @@ async fn main() -> Result<()> { let client = Client::builder().with_node(&node_url)?.finish().await?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let token_supply = client.get_token_supply().await?; diff --git a/sdk/examples/client/output/expiration.rs b/sdk/examples/client/output/expiration.rs index 67f683ca7e..afdbb0560f 100644 --- a/sdk/examples/client/output/expiration.rs +++ b/sdk/examples/client/output/expiration.rs @@ -33,7 +33,7 @@ async fn main() -> Result<()> { let client = Client::builder().with_node(&node_url)?.finish().await?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let addresses = secret_manager .generate_ed25519_addresses(GetAddressesOptions::from_client(&client).await?.with_range(0..2)) diff --git a/sdk/examples/client/output/foundry.rs b/sdk/examples/client/output/foundry.rs index c93e7fbc75..56f298e4f5 100644 --- a/sdk/examples/client/output/foundry.rs +++ b/sdk/examples/client/output/foundry.rs @@ -44,7 +44,7 @@ async fn main() -> Result<()> { let client = Client::builder().with_node(&node_url)?.finish().await?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let token_supply = client.get_token_supply().await?; diff --git a/sdk/examples/client/output/micro_transaction.rs b/sdk/examples/client/output/micro_transaction.rs index 1433a6dbd7..a7b3a14e2f 100644 --- a/sdk/examples/client/output/micro_transaction.rs +++ b/sdk/examples/client/output/micro_transaction.rs @@ -34,7 +34,7 @@ async fn main() -> Result<()> { let client = Client::builder().with_node(&node_url)?.finish().await?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let addresses = secret_manager .generate_ed25519_addresses(GetAddressesOptions::from_client(&client).await?.with_range(0..2)) diff --git a/sdk/examples/client/output/native_tokens.rs b/sdk/examples/client/output/native_tokens.rs index 75c9c0a1d5..3957f1bb0f 100644 --- a/sdk/examples/client/output/native_tokens.rs +++ b/sdk/examples/client/output/native_tokens.rs @@ -33,7 +33,7 @@ async fn main() -> Result<()> { let client = Client::builder().with_node(&node_url)?.finish().await?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let addresses = secret_manager .generate_ed25519_addresses(GetAddressesOptions::from_client(&client).await?.with_range(0..2)) diff --git a/sdk/examples/client/output/nft.rs b/sdk/examples/client/output/nft.rs index 32721575b3..e0be1ab460 100644 --- a/sdk/examples/client/output/nft.rs +++ b/sdk/examples/client/output/nft.rs @@ -34,7 +34,7 @@ async fn main() -> Result<()> { let client = Client::builder().with_node(&node_url)?.finish().await?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let token_supply = client.get_token_supply().await?; diff --git a/sdk/examples/client/output/recursive_alias.rs b/sdk/examples/client/output/recursive_alias.rs index bc32df77f9..1bef96694a 100644 --- a/sdk/examples/client/output/recursive_alias.rs +++ b/sdk/examples/client/output/recursive_alias.rs @@ -33,7 +33,7 @@ async fn main() -> Result<()> { let client = Client::builder().with_node(&node_url)?.finish().await?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let address = secret_manager .generate_ed25519_addresses(GetAddressesOptions::from_client(&client).await?.with_range(0..1)) diff --git a/sdk/examples/client/participation.rs b/sdk/examples/client/participation.rs index 7104f639bf..d1201a6a66 100644 --- a/sdk/examples/client/participation.rs +++ b/sdk/examples/client/participation.rs @@ -46,7 +46,7 @@ async fn main() -> Result<()> { } let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let address = secret_manager .generate_ed25519_addresses(GetAddressesOptions::from_client(&client).await?.with_range(0..1)) .await?[0]; @@ -92,7 +92,7 @@ async fn main() -> Result<()> { async fn participate(client: &Client, event_id: ParticipationEventId) -> Result<()> { let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let token_supply = client.get_token_supply().await?; let rent_structure = client.get_rent_structure().await?; diff --git a/sdk/examples/client/quorum.rs b/sdk/examples/client/quorum.rs index fb0545bf94..5fcfba1e38 100644 --- a/sdk/examples/client/quorum.rs +++ b/sdk/examples/client/quorum.rs @@ -24,7 +24,7 @@ async fn main() -> Result<()> { .finish()?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; // Generate the first address let addresses = client diff --git a/sdk/examples/client/send_all.rs b/sdk/examples/client/send_all.rs index cc8a606915..9071c63af4 100644 --- a/sdk/examples/client/send_all.rs +++ b/sdk/examples/client/send_all.rs @@ -30,7 +30,7 @@ async fn main() -> Result<()> { .finish()?; let secret_manager_1 = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let secret_manager_2 = SecretManager::try_from_hex_seed(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_SEED_2").unwrap())?; diff --git a/sdk/examples/client/split_funds.rs b/sdk/examples/client/split_funds.rs index dde7dbdaee..3f161830ed 100644 --- a/sdk/examples/client/split_funds.rs +++ b/sdk/examples/client/split_funds.rs @@ -20,7 +20,7 @@ async fn main() -> Result<()> { let client = Client::builder().with_node(&node_url)?.finish().await?; let secret_manager = - SecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + SecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let address = client.get_addresses(&secret_manager).with_range(0..1).get_raw().await?[0]; println!( diff --git a/sdk/examples/wallet/accounts.rs b/sdk/examples/wallet/accounts.rs index 075e77fa73..6c9993a51f 100644 --- a/sdk/examples/wallet/accounts.rs +++ b/sdk/examples/wallet/accounts.rs @@ -24,7 +24,7 @@ async fn main() -> Result<()> { let client_options = ClientOptions::new().with_node(&std::env::var("NODE_URL").unwrap())?; let secret_manager = - MnemonicSecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + MnemonicSecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let wallet = Wallet::builder() .with_secret_manager(SecretManager::Mnemonic(secret_manager)) diff --git a/sdk/examples/wallet/background_syncing.rs b/sdk/examples/wallet/background_syncing.rs index a4b6bcd5af..c948270103 100644 --- a/sdk/examples/wallet/background_syncing.rs +++ b/sdk/examples/wallet/background_syncing.rs @@ -22,7 +22,7 @@ async fn main() -> Result<()> { let client_options = ClientOptions::new().with_node(&std::env::var("NODE_URL").unwrap())?; let secret_manager = - MnemonicSecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + MnemonicSecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let wallet = Wallet::builder() .with_secret_manager(SecretManager::Mnemonic(secret_manager)) diff --git a/sdk/examples/wallet/events.rs b/sdk/examples/wallet/events.rs index 04cfbe8af9..a6db3b006a 100644 --- a/sdk/examples/wallet/events.rs +++ b/sdk/examples/wallet/events.rs @@ -25,7 +25,7 @@ async fn main() -> Result<()> { let client_options = ClientOptions::new().with_node(&std::env::var("NODE_URL").unwrap())?; let secret_manager = - MnemonicSecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + MnemonicSecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let wallet = Wallet::builder() .with_secret_manager(SecretManager::Mnemonic(secret_manager)) diff --git a/sdk/examples/wallet/logger.rs b/sdk/examples/wallet/logger.rs index f6be6d5150..3a1398ac76 100644 --- a/sdk/examples/wallet/logger.rs +++ b/sdk/examples/wallet/logger.rs @@ -30,7 +30,7 @@ async fn main() -> Result<()> { let client_options = ClientOptions::new().with_node(&std::env::var("NODE_URL").unwrap())?; let secret_manager = - MnemonicSecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + MnemonicSecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let wallet = Wallet::builder() .with_secret_manager(SecretManager::Mnemonic(secret_manager)) diff --git a/sdk/examples/wallet/output_consolidation.rs b/sdk/examples/wallet/output_consolidation.rs index 9001cecfb8..aa33795f95 100644 --- a/sdk/examples/wallet/output_consolidation.rs +++ b/sdk/examples/wallet/output_consolidation.rs @@ -21,7 +21,7 @@ async fn main() -> Result<()> { // This example uses secrets in environment variables for simplicity which should not be done in production. dotenvy::dotenv().ok(); - let mnemonic: &str = &std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap(); + let mnemonic = std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap(); let mnemonic_secret_manager = MnemonicSecretManager::try_from_mnemonic(mnemonic).unwrap(); let secret_manager = SecretManager::Mnemonic(mnemonic_secret_manager); diff --git a/sdk/examples/wallet/participation.rs b/sdk/examples/wallet/participation.rs index eb4ea80ad4..ffb350fc8f 100644 --- a/sdk/examples/wallet/participation.rs +++ b/sdk/examples/wallet/participation.rs @@ -39,7 +39,7 @@ async fn main() -> Result<()> { .with_ignore_node_health(); let secret_manager = - MnemonicSecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + MnemonicSecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let wallet = Wallet::builder() .with_secret_manager(SecretManager::Mnemonic(secret_manager)) diff --git a/sdk/examples/wallet/ping.rs b/sdk/examples/wallet/ping.rs index 0dc25a0883..7ac9d32be6 100644 --- a/sdk/examples/wallet/ping.rs +++ b/sdk/examples/wallet/ping.rs @@ -24,7 +24,7 @@ async fn main() -> Result<()> { let client_options = ClientOptions::new().with_node(&std::env::var("NODE_URL").unwrap())?; let secret_manager = - MnemonicSecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + MnemonicSecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let wallet = Wallet::builder() .with_secret_manager(SecretManager::Mnemonic(secret_manager)) diff --git a/sdk/examples/wallet/pong.rs b/sdk/examples/wallet/pong.rs index 3c3ead53e2..123ff6c851 100644 --- a/sdk/examples/wallet/pong.rs +++ b/sdk/examples/wallet/pong.rs @@ -24,7 +24,7 @@ async fn main() -> Result<()> { let client_options = ClientOptions::new().with_node(&std::env::var("NODE_URL").unwrap())?; let secret_manager = - MnemonicSecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + MnemonicSecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let wallet = Wallet::builder() .with_secret_manager(SecretManager::Mnemonic(secret_manager)) diff --git a/sdk/examples/wallet/recover_accounts.rs b/sdk/examples/wallet/recover_accounts.rs index e199afccf6..acd5db3bd8 100644 --- a/sdk/examples/wallet/recover_accounts.rs +++ b/sdk/examples/wallet/recover_accounts.rs @@ -23,7 +23,7 @@ async fn main() -> Result<()> { let client_options = ClientOptions::new().with_node(&std::env::var("NODE_URL").unwrap())?; let secret_manager = - MnemonicSecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + MnemonicSecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let wallet = Wallet::builder() .with_secret_manager(SecretManager::Mnemonic(secret_manager)) diff --git a/sdk/examples/wallet/split_funds.rs b/sdk/examples/wallet/split_funds.rs index 8c9f03a3bd..56cc6e118f 100644 --- a/sdk/examples/wallet/split_funds.rs +++ b/sdk/examples/wallet/split_funds.rs @@ -24,7 +24,7 @@ async fn main() -> Result<()> { let client_options = ClientOptions::new().with_node(&std::env::var("NODE_URL").unwrap())?; let secret_manager = - MnemonicSecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + MnemonicSecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let wallet = Wallet::builder() .with_secret_manager(SecretManager::Mnemonic(secret_manager)) diff --git a/sdk/examples/wallet/storage.rs b/sdk/examples/wallet/storage.rs index 7ca9fe53b7..4c4cea4f33 100644 --- a/sdk/examples/wallet/storage.rs +++ b/sdk/examples/wallet/storage.rs @@ -21,7 +21,7 @@ async fn main() -> Result<()> { dotenvy::dotenv().ok(); let secret_manager = - MnemonicSecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + MnemonicSecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let client_options = ClientOptions::new().with_node(&std::env::var("NODE_URL").unwrap())?; diff --git a/sdk/examples/wallet/threads.rs b/sdk/examples/wallet/threads.rs index 012b116839..278b453690 100644 --- a/sdk/examples/wallet/threads.rs +++ b/sdk/examples/wallet/threads.rs @@ -22,7 +22,7 @@ async fn main() -> Result<()> { let client_options = ClientOptions::new().with_node(&std::env::var("NODE_URL").unwrap())?; let secret_manager = - MnemonicSecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + MnemonicSecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let wallet = Wallet::builder() .with_secret_manager(SecretManager::Mnemonic(secret_manager)) diff --git a/sdk/examples/wallet/wallet.rs b/sdk/examples/wallet/wallet.rs index d5baabbbe9..5ac0688047 100644 --- a/sdk/examples/wallet/wallet.rs +++ b/sdk/examples/wallet/wallet.rs @@ -23,7 +23,7 @@ async fn main() -> Result<()> { let client_options = ClientOptions::new().with_node(&std::env::var("NODE_URL").unwrap())?; let secret_manager = - MnemonicSecretManager::try_from_mnemonic(&std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; + MnemonicSecretManager::try_from_mnemonic(std::env::var("NON_SECURE_USE_OF_DEVELOPMENT_MNEMONIC_1").unwrap())?; let wallet = Wallet::builder() .with_secret_manager(SecretManager::Mnemonic(secret_manager)) diff --git a/sdk/src/client/secret/mnemonic.rs b/sdk/src/client/secret/mnemonic.rs index 6132f1a3c8..0a5476bd6c 100644 --- a/sdk/src/client/secret/mnemonic.rs +++ b/sdk/src/client/secret/mnemonic.rs @@ -14,7 +14,7 @@ use crypto::{ secp256k1_ecdsa::{self, EvmAddress}, }, }; -use zeroize::Zeroize; +use zeroize::Zeroizing; use super::{GenerateAddressOptions, SecretManage}; use crate::{ @@ -119,16 +119,15 @@ impl MnemonicSecretManager { /// Create a new [`MnemonicSecretManager`] from a BIP-39 mnemonic in English. /// /// For more information, see . - pub fn try_from_mnemonic(mnemonic: &str) -> Result { - Ok(Self(Client::mnemonic_to_seed(mnemonic)?)) + pub fn try_from_mnemonic(mnemonic: impl Into>) -> Result { + Ok(Self(Client::mnemonic_to_seed(mnemonic.into())?)) } /// Create a new [`MnemonicSecretManager`] from a hex-encoded raw seed string. - pub fn try_from_hex_seed(mut hex: String) -> Result { - let mut bytes: Vec = prefix_hex::decode(hex.as_str())?; - let seed = Seed::from_bytes(&bytes); - hex.zeroize(); - bytes.zeroize(); + pub fn try_from_hex_seed(hex: impl Into>) -> Result { + let hex = hex.into(); + let bytes = Zeroizing::new(prefix_hex::decode::>(hex.as_str())?); + let seed = Seed::from_bytes(bytes.as_ref()); Ok(Self(seed)) } } @@ -143,7 +142,7 @@ mod tests { use crate::client::constants::IOTA_COIN_TYPE; let mnemonic = "giant dynamic museum toddler six deny defense ostrich bomb access mercy blood explain muscle shoot shallow glad autumn author calm heavy hawk abuse rally"; - let secret_manager = MnemonicSecretManager::try_from_mnemonic(mnemonic).unwrap(); + let secret_manager = MnemonicSecretManager::try_from_mnemonic(mnemonic.to_owned()).unwrap(); let addresses = secret_manager .generate_ed25519_addresses(IOTA_COIN_TYPE, 0, 0..1, None) diff --git a/sdk/src/client/secret/mod.rs b/sdk/src/client/secret/mod.rs index b492ee735d..d3f093d183 100644 --- a/sdk/src/client/secret/mod.rs +++ b/sdk/src/client/secret/mod.rs @@ -27,6 +27,7 @@ use crypto::{ signatures::secp256k1_ecdsa::{self, EvmAddress}, }; use serde::{Deserialize, Serialize}; +use zeroize::Zeroizing; #[cfg(feature = "ledger_nano")] use self::ledger_nano::LedgerSecretManager; @@ -158,7 +159,7 @@ impl FromStr for SecretManager { } /// DTO for secret manager types with required data. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Clone, Debug, Serialize, Deserialize)] pub enum SecretManagerDto { /// Stronghold #[cfg(feature = "stronghold")] @@ -172,10 +173,10 @@ pub enum SecretManagerDto { LedgerNano(bool), /// Mnemonic #[serde(alias = "mnemonic")] - Mnemonic(String), + Mnemonic(Zeroizing), /// Hex seed #[serde(alias = "hexSeed")] - HexSeed(String), + HexSeed(Zeroizing), /// Placeholder #[serde(alias = "placeholder")] Placeholder, @@ -204,9 +205,7 @@ impl TryFrom for SecretManager { #[cfg(feature = "ledger_nano")] SecretManagerDto::LedgerNano(is_simulator) => Self::LedgerNano(LedgerSecretManager::new(is_simulator)), - SecretManagerDto::Mnemonic(mnemonic) => { - Self::Mnemonic(MnemonicSecretManager::try_from_mnemonic(&mnemonic)?) - } + SecretManagerDto::Mnemonic(mnemonic) => Self::Mnemonic(MnemonicSecretManager::try_from_mnemonic(mnemonic)?), SecretManagerDto::HexSeed(hex_seed) => { // `SecretManagerDto` is `ZeroizeOnDrop` so it will take care of zeroizing the original. @@ -239,7 +238,7 @@ impl From<&SecretManager> for SecretManagerDto { // `MnemonicSecretManager(Seed)` doesn't have Debug or Display implemented and in the current use cases of // the client/wallet we also don't need to convert it in this direction with the mnemonic/seed, we only need // to know the type - SecretManager::Mnemonic(_mnemonic) => Self::Mnemonic("...".to_string()), + SecretManager::Mnemonic(_mnemonic) => Self::Mnemonic("...".to_string().into()), SecretManager::Placeholder(_) => Self::Placeholder, } } @@ -366,12 +365,12 @@ impl SignTransactionEssence for SecretManager { impl SecretManager { /// Tries to create a [`SecretManager`] from a mnemonic string. - pub fn try_from_mnemonic(mnemonic: &str) -> crate::client::Result { + pub fn try_from_mnemonic(mnemonic: impl Into>) -> crate::client::Result { Ok(Self::Mnemonic(MnemonicSecretManager::try_from_mnemonic(mnemonic)?)) } /// Tries to create a [`SecretManager`] from a seed hex string. - pub fn try_from_hex_seed(seed: String) -> crate::client::Result { + pub fn try_from_hex_seed(seed: impl Into>) -> crate::client::Result { Ok(Self::Mnemonic(MnemonicSecretManager::try_from_hex_seed(seed)?)) } diff --git a/sdk/src/client/utils.rs b/sdk/src/client/utils.rs index f26496eed9..609d98e9c8 100644 --- a/sdk/src/client/utils.rs +++ b/sdk/src/client/utils.rs @@ -11,7 +11,7 @@ use crypto::{ utils, }; use serde::{Deserialize, Serialize}; -use zeroize::{Zeroize, ZeroizeOnDrop}; +use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; use super::{Client, ClientInner}; use crate::{ @@ -72,14 +72,14 @@ pub fn mnemonic_to_hex_seed(mnemonic: &str) -> Result { } /// Returns a seed for a mnemonic. -pub fn mnemonic_to_seed(mnemonic: &str) -> Result { +pub fn mnemonic_to_seed(mnemonic: Zeroizing) -> Result { // trim because empty spaces could create a different seed https://github.com/iotaledger/crypto.rs/issues/125 - let mnemonic = mnemonic.trim(); + let mnemonic = mnemonic.as_str().trim(); // first we check if the mnemonic is valid to give meaningful errors verify_mnemonic(mnemonic)?; - let mut mnemonic_seed = [0u8; 64]; + let mut mnemonic_seed = Zeroizing::new([0u8; 64]); crypto::keys::bip39::mnemonic_to_seed(mnemonic, "", &mut mnemonic_seed); - Ok(Seed::from_bytes(&mnemonic_seed)) + Ok(Seed::from_bytes(mnemonic_seed.as_ref())) } /// Verifies that a &str is a valid mnemonic. @@ -169,7 +169,7 @@ impl Client { } /// Returns a seed for a mnemonic. - pub fn mnemonic_to_seed(mnemonic: &str) -> Result { + pub fn mnemonic_to_seed(mnemonic: Zeroizing) -> Result { mnemonic_to_seed(mnemonic) } diff --git a/sdk/tests/client/addresses.rs b/sdk/tests/client/addresses.rs index baaa1341ec..e4696f92be 100644 --- a/sdk/tests/client/addresses.rs +++ b/sdk/tests/client/addresses.rs @@ -56,7 +56,7 @@ async fn public_key_to_address() { #[tokio::test] async fn mnemonic_address_generation_iota() { - let mnemonic = "acoustic trophy damage hint search taste love bicycle foster cradle brown govern endless depend situate athlete pudding blame question genius transfer van random vast"; + let mnemonic = "acoustic trophy damage hint search taste love bicycle foster cradle brown govern endless depend situate athlete pudding blame question genius transfer van random vast".to_owned(); let secret_manager = SecretManager::try_from_mnemonic(mnemonic).unwrap(); // account 0, address 0 and 1 @@ -100,7 +100,7 @@ async fn mnemonic_address_generation_iota() { #[tokio::test] async fn mnemonic_address_generation_shimmer() { - let mnemonic = "acoustic trophy damage hint search taste love bicycle foster cradle brown govern endless depend situate athlete pudding blame question genius transfer van random vast"; + let mnemonic = "acoustic trophy damage hint search taste love bicycle foster cradle brown govern endless depend situate athlete pudding blame question genius transfer van random vast".to_owned(); let secret_manager = SecretManager::try_from_mnemonic(mnemonic).unwrap(); // account 0, address 0 and 1 @@ -163,7 +163,7 @@ async fn address_generation() { serde_json::from_value(general.get("address_generations").unwrap().clone()).unwrap(); for address in &addresses_data { - let secret_manager = SecretManager::try_from_mnemonic(&address.mnemonic).unwrap(); + let secret_manager = SecretManager::try_from_mnemonic(address.mnemonic.clone()).unwrap(); let addresses = secret_manager .generate_ed25519_addresses( GetAddressesOptions::default() diff --git a/sdk/tests/client/common/mod.rs b/sdk/tests/client/common/mod.rs index a73ee7d638..9fbe2d524f 100644 --- a/sdk/tests/client/common/mod.rs +++ b/sdk/tests/client/common/mod.rs @@ -19,10 +19,10 @@ pub async fn setup_client_with_node_health_ignored() -> Client { /// Create a client with `DEFAULT_DEVNET_NODE_URL` and a random mnemonic, request funds from the faucet to the first /// address and wait until they arrived. -pub async fn create_client_and_secret_manager_with_funds(mnemonic: Option<&str>) -> Result<(Client, SecretManager)> { +pub async fn create_client_and_secret_manager_with_funds(mnemonic: Option) -> Result<(Client, SecretManager)> { let client = Client::builder().with_node(NODE_LOCAL)?.finish().await?; - let secret_manager = SecretManager::try_from_mnemonic(mnemonic.unwrap_or(&Client::generate_mnemonic().unwrap()))?; + let secret_manager = SecretManager::try_from_mnemonic(mnemonic.unwrap_or(Client::generate_mnemonic().unwrap()))?; let address = secret_manager .generate_ed25519_addresses( diff --git a/sdk/tests/client/signing/alias.rs b/sdk/tests/client/signing/alias.rs index 1785ff93e4..70354e97b9 100644 --- a/sdk/tests/client/signing/alias.rs +++ b/sdk/tests/client/signing/alias.rs @@ -36,7 +36,7 @@ use crate::client::{ #[tokio::test] async fn sign_alias_state_transition() -> Result<()> { - let secret_manager = SecretManager::try_from_mnemonic(&Client::generate_mnemonic()?)?; + let secret_manager = SecretManager::try_from_mnemonic(Client::generate_mnemonic()?)?; let bech32_address_0 = &secret_manager .generate_ed25519_addresses( @@ -127,7 +127,7 @@ async fn sign_alias_state_transition() -> Result<()> { #[tokio::test] async fn sign_alias_governance_transition() -> Result<()> { - let secret_manager = SecretManager::try_from_mnemonic(&Client::generate_mnemonic()?)?; + let secret_manager = SecretManager::try_from_mnemonic(Client::generate_mnemonic()?)?; let bech32_address_0 = &secret_manager .generate_ed25519_addresses( @@ -218,7 +218,7 @@ async fn sign_alias_governance_transition() -> Result<()> { #[tokio::test] async fn alias_reference_unlocks() -> Result<()> { - let secret_manager = SecretManager::try_from_mnemonic(&Client::generate_mnemonic()?)?; + let secret_manager = SecretManager::try_from_mnemonic(Client::generate_mnemonic()?)?; let bech32_address_0 = &secret_manager .generate_ed25519_addresses( diff --git a/sdk/tests/client/signing/basic.rs b/sdk/tests/client/signing/basic.rs index efd1166daf..2afc589aa9 100644 --- a/sdk/tests/client/signing/basic.rs +++ b/sdk/tests/client/signing/basic.rs @@ -30,7 +30,7 @@ use crate::client::{build_inputs, build_outputs, Build::Basic}; #[tokio::test] async fn single_ed25519_unlock() -> Result<()> { - let secret_manager = SecretManager::try_from_mnemonic(&Client::generate_mnemonic()?)?; + let secret_manager = SecretManager::try_from_mnemonic(Client::generate_mnemonic()?)?; let bech32_address_0 = &secret_manager .generate_ed25519_addresses( @@ -110,7 +110,7 @@ async fn single_ed25519_unlock() -> Result<()> { #[tokio::test] async fn ed25519_reference_unlocks() -> Result<()> { - let secret_manager = SecretManager::try_from_mnemonic(&Client::generate_mnemonic()?)?; + let secret_manager = SecretManager::try_from_mnemonic(Client::generate_mnemonic()?)?; let bech32_address_0 = &secret_manager .generate_ed25519_addresses( @@ -224,7 +224,7 @@ async fn ed25519_reference_unlocks() -> Result<()> { #[tokio::test] async fn two_signature_unlocks() -> Result<()> { - let secret_manager = SecretManager::try_from_mnemonic(&Client::generate_mnemonic()?)?; + let secret_manager = SecretManager::try_from_mnemonic(Client::generate_mnemonic()?)?; let bech32_address_0 = &secret_manager .generate_ed25519_addresses( diff --git a/sdk/tests/client/signing/mod.rs b/sdk/tests/client/signing/mod.rs index 55417341d2..22ac31590f 100644 --- a/sdk/tests/client/signing/mod.rs +++ b/sdk/tests/client/signing/mod.rs @@ -42,7 +42,7 @@ use crate::client::{ async fn all_combined() -> Result<()> { let secret_manager = SecretManager::try_from_mnemonic( // mnemonic needs to be hardcoded to make the ordering deterministic - "mirror add nothing long orphan hat this rough scare gallery fork twelve old shrug voyage job table obscure mimic holiday possible proud giraffe fan", + "mirror add nothing long orphan hat this rough scare gallery fork twelve old shrug voyage job table obscure mimic holiday possible proud giraffe fan".to_owned(), )?; let protocol_parameters = protocol_parameters(); diff --git a/sdk/tests/client/signing/nft.rs b/sdk/tests/client/signing/nft.rs index e789fc12a6..6a4027f565 100644 --- a/sdk/tests/client/signing/nft.rs +++ b/sdk/tests/client/signing/nft.rs @@ -36,7 +36,7 @@ use crate::client::{ #[tokio::test] async fn nft_reference_unlocks() -> Result<()> { - let secret_manager = SecretManager::try_from_mnemonic(&Client::generate_mnemonic()?)?; + let secret_manager = SecretManager::try_from_mnemonic(Client::generate_mnemonic()?)?; let bech32_address_0 = &secret_manager .generate_ed25519_addresses( diff --git a/sdk/tests/wallet/account_recovery.rs b/sdk/tests/wallet/account_recovery.rs index 8b2b78a655..2168ef797b 100644 --- a/sdk/tests/wallet/account_recovery.rs +++ b/sdk/tests/wallet/account_recovery.rs @@ -66,7 +66,7 @@ async fn account_recovery_with_balance_and_empty_addresses() -> Result<()> { .finish() .await?; - let secret_manager = SecretManager::Mnemonic(MnemonicSecretManager::try_from_mnemonic(&mnemonic)?); + let secret_manager = SecretManager::Mnemonic(MnemonicSecretManager::try_from_mnemonic(mnemonic.clone())?); let addresses = secret_manager .generate_ed25519_addresses( @@ -84,7 +84,7 @@ async fn account_recovery_with_balance_and_empty_addresses() -> Result<()> { // Wait for faucet transaction tokio::time::sleep(Duration::new(10, 0)).await; - let wallet = make_wallet(storage_path, Some(&mnemonic), None).await?; + let wallet = make_wallet(storage_path, Some(mnemonic), None).await?; let accounts = wallet.recover_accounts(0, 3, 2, None).await?; diff --git a/sdk/tests/wallet/backup_restore.rs b/sdk/tests/wallet/backup_restore.rs index fd7ae384a9..6c733949c2 100644 --- a/sdk/tests/wallet/backup_restore.rs +++ b/sdk/tests/wallet/backup_restore.rs @@ -121,7 +121,7 @@ async fn backup_and_restore_mnemonic_secret_manager() -> Result<()> { let client_options = ClientOptions::new().with_node(NODE_LOCAL)?; let secret_manager = MnemonicSecretManager::try_from_mnemonic( - "inhale gorilla deny three celery song category owner lottery rent author wealth penalty crawl hobby obtain glad warm early rain clutch slab august bleak", + "inhale gorilla deny three celery song category owner lottery rent author wealth penalty crawl hobby obtain glad warm early rain clutch slab august bleak".to_owned(), )?; let wallet = Wallet::builder() @@ -148,7 +148,7 @@ async fn backup_and_restore_mnemonic_secret_manager() -> Result<()> { // restore from backup let secret_manager = MnemonicSecretManager::try_from_mnemonic( - "inhale gorilla deny three celery song category owner lottery rent author wealth penalty crawl hobby obtain glad warm early rain clutch slab august bleak", + "inhale gorilla deny three celery song category owner lottery rent author wealth penalty crawl hobby obtain glad warm early rain clutch slab august bleak".to_owned(), )?; let restore_wallet = Wallet::builder() diff --git a/sdk/tests/wallet/common/mod.rs b/sdk/tests/wallet/common/mod.rs index df7d999cb7..b9479a9908 100644 --- a/sdk/tests/wallet/common/mod.rs +++ b/sdk/tests/wallet/common/mod.rs @@ -30,10 +30,10 @@ pub use self::constants::*; /// /// An Wallet #[allow(dead_code, unused_variables)] -pub(crate) async fn make_wallet(storage_path: &str, mnemonic: Option<&str>, node: Option<&str>) -> Result { +pub(crate) async fn make_wallet(storage_path: &str, mnemonic: Option, node: Option<&str>) -> Result { let client_options = ClientOptions::new().with_node(node.unwrap_or(NODE_LOCAL))?; let secret_manager = - MnemonicSecretManager::try_from_mnemonic(mnemonic.unwrap_or(&Client::generate_mnemonic().unwrap()))?; + MnemonicSecretManager::try_from_mnemonic(mnemonic.unwrap_or(Client::generate_mnemonic().unwrap()))?; #[allow(unused_mut)] let mut wallet_builder = Wallet::builder() diff --git a/sdk/tests/wallet/wallet.rs b/sdk/tests/wallet/wallet.rs index 04fa921d07..48bcfb7f44 100644 --- a/sdk/tests/wallet/wallet.rs +++ b/sdk/tests/wallet/wallet.rs @@ -86,7 +86,9 @@ async fn changed_coin_type() -> Result<()> { let storage_path = "test-storage/changed_coin_type"; setup(storage_path)?; - let wallet = make_wallet(storage_path, Some(DEFAULT_MNEMONIC), None).await?; + let mnemonic = DEFAULT_MNEMONIC.to_owned(); + + let wallet = make_wallet(storage_path, Some(mnemonic.clone()), None).await?; let _account = wallet.create_account().with_alias("Alice".to_string()).finish().await?; drop(_account); @@ -94,7 +96,7 @@ async fn changed_coin_type() -> Result<()> { let err = Wallet::builder() .with_secret_manager(SecretManager::Mnemonic(MnemonicSecretManager::try_from_mnemonic( - DEFAULT_MNEMONIC, + mnemonic.clone(), )?)) .with_coin_type(IOTA_COIN_TYPE) .with_storage_path(storage_path) @@ -114,7 +116,7 @@ async fn changed_coin_type() -> Result<()> { // Building the wallet with the same coin type still works let wallet = Wallet::builder() .with_secret_manager(SecretManager::Mnemonic(MnemonicSecretManager::try_from_mnemonic( - DEFAULT_MNEMONIC, + mnemonic, )?)) .with_storage_path(storage_path) .finish() @@ -137,7 +139,7 @@ async fn shimmer_coin_type() -> Result<()> { let storage_path = "test-storage/shimmer_coin_type"; setup(storage_path)?; - let wallet = make_wallet(storage_path, Some(DEFAULT_MNEMONIC), None).await?; + let wallet = make_wallet(storage_path, Some(DEFAULT_MNEMONIC.to_owned()), None).await?; let account = wallet.create_account().finish().await?; // Creating a new account with providing a coin type will use the Shimmer coin type with shimmer testnet bech32 hrp @@ -156,7 +158,7 @@ async fn iota_coin_type() -> Result<()> { setup(storage_path)?; let client_options = ClientOptions::new().with_node(NODE_LOCAL)?; - let secret_manager = MnemonicSecretManager::try_from_mnemonic(DEFAULT_MNEMONIC)?; + let secret_manager = MnemonicSecretManager::try_from_mnemonic(DEFAULT_MNEMONIC.to_owned())?; #[allow(unused_mut)] let mut wallet_builder = Wallet::builder() @@ -188,7 +190,7 @@ async fn wallet_address_generation() -> Result<()> { setup(storage_path)?; let client_options = ClientOptions::new().with_node(NODE_LOCAL)?; - let secret_manager = MnemonicSecretManager::try_from_mnemonic(DEFAULT_MNEMONIC)?; + let secret_manager = MnemonicSecretManager::try_from_mnemonic(DEFAULT_MNEMONIC.to_owned())?; #[allow(unused_mut)] let mut wallet_builder = Wallet::builder() From 05a4d23c04d8c0363f7bc4834537431b3f18763f Mon Sep 17 00:00:00 2001 From: Alex Coats Date: Thu, 8 Jun 2023 10:33:27 -0400 Subject: [PATCH 8/8] fix wasm --- sdk/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/Cargo.toml b/sdk/Cargo.toml index f2ec207457..ace8992ae4 100644 --- a/sdk/Cargo.toml +++ b/sdk/Cargo.toml @@ -87,7 +87,7 @@ participation = [ "storage" ] pow = [ "std", "num_cpus", "iota-crypto/curl-p" ] rand = [ "dep:rand" ] rocksdb = [ "dep:rocksdb", "storage" ] -serde = [ "serde_repr", "serde-big-array", "hashbrown/serde", "packable/serde", "primitive-types/serde_no_std" ] +serde = [ "serde_repr", "serde-big-array", "hashbrown/serde", "packable/serde", "primitive-types/serde_no_std", "zeroize?/serde" ] std = [ "packable/std", "prefix-hex/std", "primitive-types/std", "bech32/std", "bitflags/std", "rand?/std_rng", "regex?/std", "backtrace?/std", "derive_builder?/std", "iota_stronghold?/std", "iota-crypto/std", "once_cell?/std" ] storage = [ "iota-crypto/chacha", "dep:time", "dep:anymap", "dep:once_cell" ] stronghold = [ "iota_stronghold", "derive_builder", "iota-crypto/chacha", "dep:time", "dep:anymap", "dep:once_cell" ]