From 6de253498d492cc7f10a572bbe159179b9c43197 Mon Sep 17 00:00:00 2001 From: "artem.ivanov" Date: Fri, 12 Jan 2024 09:45:25 +0300 Subject: [PATCH] Cleaned up VDR data types Signed-off-by: artem.ivanov --- indy-besu/vdr/src/client/client.rs | 30 +++-- .../src/client/implementation/web3/client.rs | 26 +++-- .../client/implementation/web3/contract.rs | 20 ++-- indy-besu/vdr/src/client/quorum.rs | 33 +++--- indy-besu/vdr/src/contracts/auth/role.rs | 6 +- .../cl/credential_definition_registry.rs | 3 +- .../vdr/src/contracts/cl/schema_registry.rs | 5 +- .../cl/types/credential_definition.rs | 18 ++- .../cl/types/credential_definition_id.rs | 27 ++--- .../vdr/src/contracts/cl/types/schema.rs | 11 +- .../vdr/src/contracts/cl/types/schema_id.rs | 27 ++--- .../vdr/src/contracts/did/did_registry.rs | 7 +- .../vdr/src/contracts/did/types/did_doc.rs | 29 +++-- .../contracts/did/types/did_doc_builder.rs | 17 ++- indy-besu/vdr/src/error/mod.rs | 68 ++++++------ .../src/migration/credential_definition.rs | 36 ++---- indy-besu/vdr/src/migration/schema.rs | 22 +--- indy-besu/vdr/src/signer/basic_signer.rs | 13 +-- indy-besu/vdr/src/test.rs | 5 +- indy-besu/vdr/src/types/address.rs | 77 +++---------- indy-besu/vdr/src/types/contract.rs | 105 ++++++++---------- indy-besu/vdr/src/types/transaction.rs | 44 ++++---- indy-besu/vdr/uniffi/src/ffi/error.rs | 26 ++--- indy-besu/vdr/wasm/src/transaction.rs | 4 +- 24 files changed, 271 insertions(+), 388 deletions(-) diff --git a/indy-besu/vdr/src/client/client.rs b/indy-besu/vdr/src/client/client.rs index 958a6085c..737491228 100644 --- a/indy-besu/vdr/src/client/client.rs +++ b/indy-besu/vdr/src/client/client.rs @@ -87,7 +87,7 @@ impl LedgerClient { let result = match transaction.type_ { TransactionType::Read => { self.client - .call_transaction(&transaction.to, &transaction.data) + .call_transaction(transaction.to.as_ref(), &transaction.data) .await } TransactionType::Write => self.client.submit_transaction(&transaction.encode()?).await, @@ -121,9 +121,7 @@ impl LedgerClient { .get(name) .map(|contract| contract.as_ref()) .ok_or_else(|| { - let vdr_error = VdrError::ContractInvalidName { - msg: name.to_string(), - }; + let vdr_error = VdrError::ContractInvalidName(name.to_string()); warn!("Error during getting contract: {:?}", vdr_error); @@ -148,14 +146,14 @@ impl LedgerClient { (Some(spec_path), None) => ContractSpec::from_file(spec_path)?, (None, Some(spec)) => spec.clone(), (Some(_), Some(_)) => { - return Err(VdrError::ContractInvalidSpec { - msg: "Either `spec_path` or `spec` must be provided".to_string(), - }); + return Err(VdrError::ContractInvalidSpec( + "Either `spec_path` or `spec` must be provided".to_string(), + )); } (None, None) => { - return Err(VdrError::ContractInvalidSpec { - msg: "Either `spec_path` or `spec` must be provided".to_string(), - }); + return Err(VdrError::ContractInvalidSpec( + "Either `spec_path` or `spec` must be provided".to_string(), + )); } }; @@ -172,7 +170,7 @@ pub mod test { use super::*; use async_trait::async_trait; use once_cell::sync::Lazy; - use std::{env, fs, ops::Deref}; + use std::{env, fs}; pub const CHAIN_ID: u64 = 1337; pub const CONTRACTS_SPEC_BASE_PATH: &str = "../smart_contracts/artifacts/contracts/"; @@ -223,27 +221,27 @@ pub mod test { fn contracts() -> Vec { vec![ ContractConfig { - address: DID_REGISTRY_ADDRESS.deref().to_string(), + address: DID_REGISTRY_ADDRESS.to_string(), spec_path: Some(build_contract_path(DID_REGISTRY_SPEC_PATH)), spec: None, }, ContractConfig { - address: SCHEMA_REGISTRY_ADDRESS.deref().to_string(), + address: SCHEMA_REGISTRY_ADDRESS.to_string(), spec_path: Some(build_contract_path(SCHEMA_REGISTRY_SPEC_PATH)), spec: None, }, ContractConfig { - address: CRED_DEF_REGISTRY_ADDRESS.deref().to_string(), + address: CRED_DEF_REGISTRY_ADDRESS.to_string(), spec_path: Some(build_contract_path(CRED_DEF_REGISTRY_SPEC_PATH)), spec: None, }, ContractConfig { - address: VALIDATOR_CONTROL_ADDRESS.deref().to_string(), + address: VALIDATOR_CONTROL_ADDRESS.to_string(), spec_path: Some(build_contract_path(VALIDATOR_CONTROL_PATH)), spec: None, }, ContractConfig { - address: ROLE_CONTROL_ADDRESS.deref().to_string(), + address: ROLE_CONTROL_ADDRESS.to_string(), spec_path: Some(build_contract_path(ROLE_CONTROL_PATH)), spec: None, }, diff --git a/indy-besu/vdr/src/client/implementation/web3/client.rs b/indy-besu/vdr/src/client/implementation/web3/client.rs index 2f5735b37..4e369004d 100644 --- a/indy-besu/vdr/src/client/implementation/web3/client.rs +++ b/indy-besu/vdr/src/client/implementation/web3/client.rs @@ -58,10 +58,12 @@ impl Web3Client { #[cfg_attr(feature = "wasm", async_trait(? Send))] impl Client for Web3Client { async fn get_transaction_count(&self, address: &crate::Address) -> VdrResult<[u64; 4]> { - let account_address = - EthAddress::from_str(address).map_err(|_| VdrError::ClientInvalidTransaction { - msg: format!("Invalid transaction sender address {:?}", address), - })?; + let account_address = EthAddress::from_str(address.as_ref()).map_err(|_| { + VdrError::ClientInvalidTransaction(format!( + "Invalid transaction sender address {:?}", + address + )) + })?; let nonce = self .client @@ -100,9 +102,10 @@ impl Client for Web3Client { ); let address = EthAddress::from_str(to).map_err(|_| { - let vdr_error = VdrError::ClientInvalidTransaction { - msg: format!("Invalid transaction target address {:?}", to), - }; + let vdr_error = VdrError::ClientInvalidTransaction(format!( + "Invalid transaction target address {:?}", + to + )); warn!( "Error: {} during calling transaction: {:?}", @@ -129,9 +132,8 @@ impl Client for Web3Client { .transaction_receipt(H256::from_slice(hash)) .await? .ok_or_else(|| { - let vdr_error = VdrError::ClientInvalidResponse { - msg: "Missing transaction receipt".to_string(), - }; + let vdr_error = + VdrError::ClientInvalidResponse("Missing transaction receipt".to_string()); warn!("Error: {} getting receipt", vdr_error,); @@ -162,8 +164,8 @@ impl Client for Web3Client { .eth() .transaction(transaction_id) .await - .map_err(|_| VdrError::GetTransactionError { - msg: "Could not get transaction by hash".to_string(), + .map_err(|_| { + VdrError::GetTransactionError("Could not get transaction by hash".to_string()) })?; let transaction = transaction.map(|transaction| Transaction { diff --git a/indy-besu/vdr/src/client/implementation/web3/contract.rs b/indy-besu/vdr/src/client/implementation/web3/contract.rs index 3a9b323f3..110e0b46a 100644 --- a/indy-besu/vdr/src/client/implementation/web3/contract.rs +++ b/indy-besu/vdr/src/client/implementation/web3/contract.rs @@ -35,24 +35,20 @@ impl Web3Contract { trace!("Started creating new Web3Contract. Address: {:?}", address); let abi = serde_json::to_vec(&contract_spec.abi).map_err(|err| { - let vdr_error = VdrError::CommonInvalidData { - msg: format!( - "Unable to parse contract ABI from specification. Err: {:?}", - err.to_string() - ), - }; + let vdr_error = VdrError::CommonInvalidData(format!( + "Unable to parse contract ABI from specification. Err: {:?}", + err.to_string() + )); warn!("Error: {:?} during creating new Web3Contract", vdr_error); vdr_error })?; let parsed_address = EthAddress::from_str(address).map_err(|err| { - let vdr_error = VdrError::CommonInvalidData { - msg: format!( - "Unable to parse contract address. Err: {:?}", - err.to_string() - ), - }; + let vdr_error = VdrError::CommonInvalidData(format!( + "Unable to parse contract address. Err: {:?}", + err.to_string() + )); warn!("Error: {:?} during creating new Web3Contract", vdr_error); diff --git a/indy-besu/vdr/src/client/quorum.rs b/indy-besu/vdr/src/client/quorum.rs index 1d1f57e35..0f814dfe7 100644 --- a/indy-besu/vdr/src/client/quorum.rs +++ b/indy-besu/vdr/src/client/quorum.rs @@ -1,4 +1,4 @@ -use std::{ops::Deref, sync::Arc, time::Duration}; +use std::{sync::Arc, time::Duration}; use futures::{ channel::{ @@ -169,7 +169,7 @@ impl QuorumHandler { sender, client, type_, - to.deref().to_string(), + to.to_string(), transaction_data, request_retries, request_timeout, @@ -183,7 +183,7 @@ impl QuorumHandler { sender.clone(), client.clone(), type_, - to.deref().to_string(), + to.to_string(), transaction_data, self.request_retries, self.request_timeout, @@ -200,9 +200,10 @@ impl QuorumHandler { Ok(quorum_reached) } else { trace!("Quorum failed for transaction: {:?}", transaction); - Err(VdrError::QuorumNotReached { - msg: format!("Quorum not reached for transaction: {:?}", transaction), - }) + Err(VdrError::QuorumNotReached(format!( + "Quorum not reached for transaction: {:?}", + transaction + ))) } } } @@ -392,7 +393,7 @@ pub mod test { mock_client .expect_call_transaction() .with( - eq(transaction.to.deref().to_string()), + eq(transaction.to.to_string()), eq(transaction.data.to_vec()), ) .returning(move |_, _| expected_output.clone()); @@ -409,7 +410,7 @@ pub mod test { mock_client .expect_call_transaction() .with( - eq(transaction.to.deref().to_string()), + eq(transaction.to.to_string()), eq(transaction.data.to_vec()), ) .returning(move |_, _| { @@ -430,20 +431,16 @@ pub mod test { mock_client .expect_call_transaction() .with( - eq(transaction.to.deref().to_string()), + eq(transaction.to.to_string()), eq(transaction.data.to_vec()), ) .times(retries_num as usize - 1) - .returning(move |_, _| { - Err(VdrError::ContractInvalidResponseData { - msg: "".to_string(), - }) - }); + .returning(move |_, _| Err(VdrError::ContractInvalidResponseData("".to_string()))); mock_client .expect_call_transaction() .with( - eq(transaction.to.deref().to_string()), + eq(transaction.to.to_string()), eq(transaction.data.to_vec()), ) .returning(move |_, _| expected_output.clone()); @@ -464,9 +461,9 @@ pub mod test { #[async_std::test] async fn test_quorum_check_failed_with_timeout() { - let err = Err(VdrError::ClientTransactionReverted { - msg: "Transaction reverted".to_string(), - }); + let err = Err(VdrError::ClientTransactionReverted( + "Transaction reverted".to_string(), + )); let client1 = mock_client(READ_TRANSACTION.clone(), err.clone()); let client2 = mock_client_sleep_before_return( READ_TRANSACTION.clone(), diff --git a/indy-besu/vdr/src/contracts/auth/role.rs b/indy-besu/vdr/src/contracts/auth/role.rs index aa729b746..554b2bf5d 100644 --- a/indy-besu/vdr/src/contracts/auth/role.rs +++ b/indy-besu/vdr/src/contracts/auth/role.rs @@ -80,9 +80,9 @@ impl TryFrom for Role { 1 => Ok(Role::Trustee), 2 => Ok(Role::Endorser), 3 => Ok(Role::Steward), - _ => Err(VdrError::ContractInvalidResponseData { - msg: "Invalid role provided".to_string(), - }), + _ => Err(VdrError::ContractInvalidResponseData( + "Invalid role provided".to_string(), + )), }; trace!( diff --git a/indy-besu/vdr/src/contracts/cl/credential_definition_registry.rs b/indy-besu/vdr/src/contracts/cl/credential_definition_registry.rs index 4c94c31b6..c5641d320 100644 --- a/indy-besu/vdr/src/contracts/cl/credential_definition_registry.rs +++ b/indy-besu/vdr/src/contracts/cl/credential_definition_registry.rs @@ -1,5 +1,4 @@ use log::{debug, info}; -use std::ops::Deref; use crate::{ client::LedgerClient, @@ -75,7 +74,7 @@ pub async fn build_resolve_credential_definition_transaction( let transaction = TransactionBuilder::new() .set_contract(CONTRACT_NAME) .set_method(METHOD_RESOLVE_CREDENTIAL_DEFINITION) - .add_param(ContractParam::String(String::from(id.deref()))) + .add_param(ContractParam::String(id.to_string())) .set_type(TransactionType::Read) .build(client) .await; diff --git a/indy-besu/vdr/src/contracts/cl/schema_registry.rs b/indy-besu/vdr/src/contracts/cl/schema_registry.rs index e0628ef50..0ac1f0eae 100644 --- a/indy-besu/vdr/src/contracts/cl/schema_registry.rs +++ b/indy-besu/vdr/src/contracts/cl/schema_registry.rs @@ -1,5 +1,4 @@ use log::{debug, info}; -use std::ops::Deref; use crate::{ client::LedgerClient, @@ -73,7 +72,7 @@ pub async fn build_resolve_schema_transaction( let transaction = TransactionBuilder::new() .set_contract(CONTRACT_NAME) .set_method(METHOD_RESOLVE_SCHEMA) - .add_param(ContractParam::String(String::from(id.deref()))) + .add_param(ContractParam::String(id.to_string())) .set_type(TransactionType::Read) .build(client) .await; @@ -142,7 +141,7 @@ pub mod test { .unwrap(); let sign_bytes = transaction.get_signing_bytes().unwrap(); - let signature = signer.sign(&sign_bytes, TRUSTEE_ACC.deref()).unwrap(); + let signature = signer.sign(&sign_bytes, TRUSTEE_ACC.as_ref()).unwrap(); transaction.set_signature(signature); client.submit_transaction(&transaction).await.unwrap(); diff --git a/indy-besu/vdr/src/contracts/cl/types/credential_definition.rs b/indy-besu/vdr/src/contracts/cl/types/credential_definition.rs index 7e6177697..b1e8fc7aa 100644 --- a/indy-besu/vdr/src/contracts/cl/types/credential_definition.rs +++ b/indy-besu/vdr/src/contracts/cl/types/credential_definition.rs @@ -3,7 +3,6 @@ use crate::{ types::{ContractOutput, ContractParam}, DID, }; -use std::ops::Deref; use crate::contracts::cl::types::{ credential_definition_id::CredentialDefinitionId, schema_id::SchemaId, @@ -44,9 +43,9 @@ impl From for ContractParam { ); let cred_def_contract_param = ContractParam::Tuple(vec![ - ContractParam::String(value.id.deref().to_string()), - ContractParam::String(value.issuer_id.deref().to_string()), - ContractParam::String(value.schema_id.deref().to_string()), + ContractParam::String(value.id.to_string()), + ContractParam::String(value.issuer_id.to_string()), + ContractParam::String(value.schema_id.to_string()), ContractParam::String(value.cred_def_type.to_string()), ContractParam::String(value.tag.to_string()), ContractParam::String(value.value.to_string()), @@ -73,9 +72,9 @@ impl TryFrom for CredentialDefinition { let cred_def_value = serde_json::from_str::(&value.get_string(5)?) .map_err(|_err| { - let vdr_error = VdrError::ContractInvalidResponseData { - msg: "Unable get to credential definition value".to_string(), - }; + let vdr_error = VdrError::ContractInvalidResponseData( + "Unable get to credential definition value".to_string(), + ); warn!( "Error: {} during CredentialDefinition convert from ContractOutput: {:?}", @@ -172,7 +171,7 @@ pub mod test { schema_id: &SchemaId, tag: &str, ) -> CredentialDefinitionId { - CredentialDefinitionId::build(issuer_id, schema_id.deref(), tag) + CredentialDefinitionId::build(issuer_id, schema_id.as_ref(), tag) } fn credential_definition_value() -> serde_json::Value { @@ -194,7 +193,7 @@ pub mod test { CredentialDefinition { id: credential_definition_id(issuer_id, schema_id, tag.as_str()), issuer_id: issuer_id.clone(), - schema_id: SchemaId::from(schema_id.deref()), + schema_id: SchemaId::from(schema_id.as_ref()), cred_def_type: CREDENTIAL_DEFINITION_TYPE.to_string(), tag: tag.to_string(), value: credential_definition_value(), @@ -209,7 +208,6 @@ pub mod test { &SchemaId::from(SCHEMA_ID), CREDENTIAL_DEFINITION_TAG, ) - .deref() .to_string(), ), ContractParam::String(ISSUER_ID.to_string()), diff --git a/indy-besu/vdr/src/contracts/cl/types/credential_definition_id.rs b/indy-besu/vdr/src/contracts/cl/types/credential_definition_id.rs index 9161da7d1..2b46dea1a 100644 --- a/indy-besu/vdr/src/contracts/cl/types/credential_definition_id.rs +++ b/indy-besu/vdr/src/contracts/cl/types/credential_definition_id.rs @@ -1,12 +1,9 @@ use crate::DID; use log::trace; use serde_derive::{Deserialize, Serialize}; -use std::ops::Deref; #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] -pub struct CredentialDefinitionId { - value: String, -} +pub struct CredentialDefinitionId(String); impl CredentialDefinitionId { const ID_PATH: &'static str = "anoncreds/v0/CLAIM_DEF"; @@ -15,7 +12,7 @@ impl CredentialDefinitionId { let cred_def_id = CredentialDefinitionId::from( format!( "{}/{}/{}/{}", - issuer_id.deref(), + issuer_id.as_ref(), Self::ID_PATH, schema_id, tag @@ -31,20 +28,18 @@ impl CredentialDefinitionId { impl From<&str> for CredentialDefinitionId { fn from(id: &str) -> Self { - let cred_def_id = CredentialDefinitionId { - value: id.to_string(), - }; - - trace!("Created new CredentialDefinitionId: {:?}", cred_def_id); - - cred_def_id + CredentialDefinitionId(id.to_string()) } } -impl Deref for CredentialDefinitionId { - type Target = str; +impl AsRef for CredentialDefinitionId { + fn as_ref(&self) -> &str { + &self.0 + } +} - fn deref(&self) -> &Self::Target { - &self.value +impl ToString for CredentialDefinitionId { + fn to_string(&self) -> String { + self.0.to_string() } } diff --git a/indy-besu/vdr/src/contracts/cl/types/schema.rs b/indy-besu/vdr/src/contracts/cl/types/schema.rs index 02ca7e2b5..dc9fe254c 100644 --- a/indy-besu/vdr/src/contracts/cl/types/schema.rs +++ b/indy-besu/vdr/src/contracts/cl/types/schema.rs @@ -2,7 +2,6 @@ use crate::{ error::VdrError, types::{ContractOutput, ContractParam}, }; -use std::ops::Deref; use crate::{contracts::cl::types::schema_id::SchemaId, DID}; use log::trace; @@ -36,8 +35,8 @@ impl From for ContractParam { trace!("Schema: {:?} convert into ContractParam has started", value); let schema_contract_param = ContractParam::Tuple(vec![ - ContractParam::String(value.id.deref().to_string()), - ContractParam::String(value.issuer_id.deref().to_string()), + ContractParam::String(value.id.to_string()), + ContractParam::String(value.issuer_id.to_string()), ContractParam::String(value.name.to_string()), ContractParam::String(value.version.to_string()), ContractParam::Array( @@ -170,11 +169,7 @@ pub mod test { fn schema_param() -> ContractParam { ContractParam::Tuple(vec![ - ContractParam::String( - schema_id(&DID::from(ISSUER_ID), SCHEMA_NAME) - .deref() - .to_string(), - ), + ContractParam::String(schema_id(&DID::from(ISSUER_ID), SCHEMA_NAME).to_string()), ContractParam::String(ISSUER_ID.to_string()), ContractParam::String(SCHEMA_NAME.to_string()), ContractParam::String(SCHEMA_VERSION.to_string()), diff --git a/indy-besu/vdr/src/contracts/cl/types/schema_id.rs b/indy-besu/vdr/src/contracts/cl/types/schema_id.rs index 33487b5e9..4e04a2485 100644 --- a/indy-besu/vdr/src/contracts/cl/types/schema_id.rs +++ b/indy-besu/vdr/src/contracts/cl/types/schema_id.rs @@ -1,12 +1,9 @@ use crate::DID; use log::trace; use serde_derive::{Deserialize, Serialize}; -use std::ops::Deref; #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] -pub struct SchemaId { - value: String, -} +pub struct SchemaId(String); impl SchemaId { const ID_PATH: &'static str = "anoncreds/v0/SCHEMA"; @@ -15,7 +12,7 @@ impl SchemaId { let schema_id = SchemaId::from( format!( "{}/{}/{}/{}", - issuer_id.deref(), + issuer_id.as_ref(), Self::ID_PATH, name, version @@ -31,20 +28,18 @@ impl SchemaId { impl From<&str> for SchemaId { fn from(id: &str) -> Self { - let schema_id = SchemaId { - value: id.to_string(), - }; - - trace!("Created new SchemaId: {:?}", schema_id); - - schema_id + SchemaId(id.to_string()) } } -impl Deref for SchemaId { - type Target = str; +impl AsRef for SchemaId { + fn as_ref(&self) -> &str { + &self.0 + } +} - fn deref(&self) -> &Self::Target { - &self.value +impl ToString for SchemaId { + fn to_string(&self) -> String { + self.0.to_string() } } diff --git a/indy-besu/vdr/src/contracts/did/did_registry.rs b/indy-besu/vdr/src/contracts/did/did_registry.rs index e21f6ac0d..b98e4d7cc 100644 --- a/indy-besu/vdr/src/contracts/did/did_registry.rs +++ b/indy-besu/vdr/src/contracts/did/did_registry.rs @@ -1,5 +1,4 @@ use log::{debug, info}; -use std::ops::Deref; use crate::{ client::LedgerClient, @@ -111,7 +110,7 @@ pub async fn build_deactivate_did_transaction( let transaction = TransactionBuilder::new() .set_contract(CONTRACT_NAME) .set_method(METHOD_DEACTIVATE_DID) - .add_param(ContractParam::String(String::from(did.clone().deref()))) + .add_param(ContractParam::String(did.to_string())) .set_type(TransactionType::Write) .set_from(from) .build(client) @@ -145,7 +144,7 @@ pub async fn build_resolve_did_transaction( let transaction = TransactionBuilder::new() .set_contract(CONTRACT_NAME) .set_method(METHOD_RESOLVE_DID) - .add_param(ContractParam::String(did.deref().to_string())) + .add_param(ContractParam::String(did.to_string())) .set_type(TransactionType::Read) .build(client) .await; @@ -209,7 +208,7 @@ pub mod test { .unwrap(); let sign_bytes = transaction.get_signing_bytes().unwrap(); - let signature = signer.sign(&sign_bytes, TRUSTEE_ACC.deref()).unwrap(); + let signature = signer.sign(&sign_bytes, TRUSTEE_ACC.as_ref()).unwrap(); transaction.set_signature(signature); client.submit_transaction(&transaction).await.unwrap(); diff --git a/indy-besu/vdr/src/contracts/did/types/did_doc.rs b/indy-besu/vdr/src/contracts/did/types/did_doc.rs index a6a4c65da..3388fb04f 100644 --- a/indy-besu/vdr/src/contracts/did/types/did_doc.rs +++ b/indy-besu/vdr/src/contracts/did/types/did_doc.rs @@ -3,7 +3,6 @@ use crate::{ types::{ContractOutput, ContractParam}, Address, }; -use std::ops::Deref; use log::{trace, warn}; use serde_derive::{Deserialize, Serialize}; @@ -28,14 +27,18 @@ impl From<&str> for DID { } } -impl Deref for DID { - type Target = str; - - fn deref(&self) -> &Self::Target { +impl AsRef for DID { + fn as_ref(&self) -> &str { &self.0 } } +impl ToString for DID { + fn to_string(&self) -> String { + self.0.to_string() + } +} + #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct DidDocumentWithMeta { @@ -147,9 +150,10 @@ impl TryFrom<&str> for VerificationKeyType { Ok(VerificationKeyType::EcdsaSecp256k1VerificationKey2019) } _type => Err({ - let vdr_error = VdrError::CommonInvalidData { - msg: format!("Unexpected verification key type {}", _type), - }; + let vdr_error = VdrError::CommonInvalidData(format!( + "Unexpected verification key type {}", + _type + )); warn!( "Error: {} during converting VerificationKeyType from String: {} ", @@ -272,9 +276,10 @@ impl TryFrom for VerificationMethod { } else { Some( serde_json::from_str::(&public_key_jwk).map_err(|err| { - let vdr_error = VdrError::CommonInvalidData { - msg: format!("Unable to parse JWK key. Err: {:?}", err), - }; + let vdr_error = VdrError::CommonInvalidData(format!( + "Unable to parse JWK key. Err: {:?}", + err + )); warn!( "Error: {:?} during parsing JWK key: {}", @@ -503,7 +508,7 @@ impl From for ContractParam { ); let context: ContractParam = value.context.into(); - let id = ContractParam::String(value.id.deref().to_string()); + let id = ContractParam::String(value.id.to_string()); let controller: ContractParam = value.controller.into(); let verification_method: ContractParam = ContractParam::Array( value diff --git a/indy-besu/vdr/src/contracts/did/types/did_doc_builder.rs b/indy-besu/vdr/src/contracts/did/types/did_doc_builder.rs index 4f35c22f9..415fe0131 100644 --- a/indy-besu/vdr/src/contracts/did/types/did_doc_builder.rs +++ b/indy-besu/vdr/src/contracts/did/types/did_doc_builder.rs @@ -1,6 +1,5 @@ use log::{trace, warn}; use serde_json::Value; -use std::ops::Deref; use crate::{ contracts::did::types::did_doc::{ @@ -41,7 +40,7 @@ impl DidDocumentBuilder { pub fn set_id(mut self, id: &DID) -> DidDocumentBuilder { self.id = id.to_owned(); - trace!("Set id: {} to DidDocumentBuilder: {:?}", id.deref(), self); + trace!("Set id: {} to DidDocumentBuilder: {:?}", id.as_ref(), self); self } @@ -67,13 +66,13 @@ impl DidDocumentBuilder { ) -> DidDocumentBuilder { let id = format!( "{}:KEY-{}", - self.id.deref(), + self.id.as_ref(), self.verification_method.len() + 1 ); let verification_method = VerificationMethod { id, type_, - controller: controller.deref().to_string(), + controller: controller.to_string(), public_key_multibase, public_key_jwk, }; @@ -94,9 +93,7 @@ impl DidDocumentBuilder { .get(index) .ok_or_else(|| { let vdr_error = - VdrError::CommonInvalidData { - msg: "Missing verification method".to_string() - }; + VdrError::CommonInvalidData("Missing verification method".to_string()); warn!( "Error: {} during getting verification method by index: {} from DidDocumentBuilder: {:?}", @@ -226,9 +223,9 @@ impl DidDocumentBuilder { .get(index) .ok_or_else(|| { let vdr_error = - VdrError::CommonInvalidData { - msg: "Missing verification method".to_string() - }; + VdrError::CommonInvalidData( + "Missing verification method".to_string() + ); warn!( "Error: {} during getting verification method by index: {} from DidDocumentBuilder: {:?}", diff --git a/indy-besu/vdr/src/error/mod.rs b/indy-besu/vdr/src/error/mod.rs index c820af6d6..7afc96e8d 100644 --- a/indy-besu/vdr/src/error/mod.rs +++ b/indy-besu/vdr/src/error/mod.rs @@ -8,38 +8,38 @@ use web3_wasm::{ethabi::Error as Web3EthabiError, Error as Web3Error}; #[derive(thiserror::Error, Debug, PartialEq, Clone)] pub enum VdrError { - #[error("Ledger: Quorum not reached: {}", msg)] - QuorumNotReached { msg: String }, + #[error("Ledger: Quorum not reached: {}", _0)] + QuorumNotReached(String), #[error("Ledger Client: Node is unreachable")] ClientNodeUnreachable, - #[error("Ledger Client: Invalid transaction: {}", msg)] - ClientInvalidTransaction { msg: String }, + #[error("Ledger Client: Invalid transaction: {}", _0)] + ClientInvalidTransaction(String), - #[error("Ledger Client: Got invalid response: {}", msg)] - ClientInvalidResponse { msg: String }, + #[error("Ledger Client: Got invalid response: {}", _0)] + ClientInvalidResponse(String), - #[error("Ledger Client: Transaction reverted: {}", msg)] - ClientTransactionReverted { msg: String }, + #[error("Ledger Client: Transaction reverted: {}", _0)] + ClientTransactionReverted(String), - #[error("Ledger Client: Unexpected error occurred: {}", msg)] - ClientUnexpectedError { msg: String }, + #[error("Ledger Client: Unexpected error occurred: {}", _0)] + ClientUnexpectedError(String), - #[error("Ledger Client: Invalid state {}", msg)] - ClientInvalidState { msg: String }, + #[error("Ledger Client: Invalid state {}", _0)] + ClientInvalidState(String), - #[error("Contract: Invalid name: {}", msg)] - ContractInvalidName { msg: String }, + #[error("Contract: Invalid name: {}", _0)] + ContractInvalidName(String), - #[error("Contract: Invalid specification: {}", msg)] - ContractInvalidSpec { msg: String }, + #[error("Contract: Invalid specification: {}", _0)] + ContractInvalidSpec(String), #[error("Contract: Invalid data")] ContractInvalidInputData, - #[error("Contract: Invalid response data: {}", msg)] - ContractInvalidResponseData { msg: String }, + #[error("Contract: Invalid response data: {}", _0)] + ContractInvalidResponseData(String), #[error("Signer: Invalid private key")] SignerInvalidPrivateKey, @@ -47,17 +47,17 @@ pub enum VdrError { #[error("Signer: Invalid message")] SignerInvalidMessage, - #[error("Signer: Key is missing: {}", msg)] - SignerMissingKey { msg: String }, + #[error("Signer: Key is missing: {}", _0)] + SignerMissingKey(String), - #[error("Signer: Unexpected error occurred: {}", msg)] - SignerUnexpectedError { msg: String }, + #[error("Signer: Unexpected error occurred: {}", _0)] + SignerUnexpectedError(String), - #[error("Invalid data: {}", msg)] - CommonInvalidData { msg: String }, + #[error("Invalid data: {}", _0)] + CommonInvalidData(String), - #[error("Could not get transaction: {}", msg)] - GetTransactionError { msg: String }, + #[error("Could not get transaction: {}", _0)] + GetTransactionError(String), } pub type VdrResult = Result; @@ -66,13 +66,9 @@ impl From for VdrError { fn from(value: Web3Error) -> Self { let vdr_error = match value { Web3Error::Unreachable => VdrError::ClientNodeUnreachable, - Web3Error::InvalidResponse(err) => VdrError::ClientInvalidResponse { msg: err }, - Web3Error::Rpc(err) => VdrError::ClientTransactionReverted { - msg: json!(err).to_string(), - }, - _ => VdrError::ClientUnexpectedError { - msg: value.to_string(), - }, + Web3Error::InvalidResponse(err) => VdrError::ClientInvalidResponse(err), + Web3Error::Rpc(err) => VdrError::ClientTransactionReverted(json!(err).to_string()), + _ => VdrError::ClientUnexpectedError(value.to_string()), }; trace!( @@ -87,7 +83,7 @@ impl From for VdrError { impl From for VdrError { fn from(value: Web3EthabiError) -> Self { let vdr_error = match value { - Web3EthabiError::InvalidName(name) => VdrError::ContractInvalidName { msg: name }, + Web3EthabiError::InvalidName(name) => VdrError::ContractInvalidName(name), _ => VdrError::ContractInvalidInputData, }; @@ -106,9 +102,7 @@ impl From for VdrError { match value { secp256k1::Error::InvalidSecretKey => VdrError::SignerInvalidPrivateKey, secp256k1::Error::InvalidMessage => VdrError::SignerInvalidMessage, - err => VdrError::SignerUnexpectedError { - msg: err.to_string(), - }, + err => VdrError::SignerUnexpectedError(err.to_string()), } } } diff --git a/indy-besu/vdr/src/migration/credential_definition.rs b/indy-besu/vdr/src/migration/credential_definition.rs index 791d4446f..eab170362 100644 --- a/indy-besu/vdr/src/migration/credential_definition.rs +++ b/indy-besu/vdr/src/migration/credential_definition.rs @@ -28,9 +28,7 @@ impl CredentialDefinitionId { let parts: Vec<&str> = id.split(':').collect(); let id = parts.get(0).ok_or_else(|| { - let vdr_error = VdrError::CommonInvalidData { - msg: "Invalid indy cred def id".to_string(), - }; + let vdr_error = VdrError::CommonInvalidData("Invalid indy cred def id".to_string()); warn!( "Error: {:?} during converting CredentialDefinitionId from indy format", @@ -40,9 +38,8 @@ impl CredentialDefinitionId { vdr_error })?; let schema_id = parts.get(3).ok_or_else(|| { - let vdr_error = VdrError::CommonInvalidData { - msg: "Invalid indy cred def schema id".to_string(), - }; + let vdr_error = + VdrError::CommonInvalidData("Invalid indy cred def schema id".to_string()); warn!( "Error: {:?} during converting CredentialDefinitionId from indy format", @@ -52,9 +49,7 @@ impl CredentialDefinitionId { vdr_error })?; let tag = parts.get(4).ok_or_else(|| { - let vdr_error = VdrError::CommonInvalidData { - msg: "Invalid indy cred def tag".to_string(), - }; + let vdr_error = VdrError::CommonInvalidData("Invalid indy cred def tag".to_string()); warn!( "Error: {:?} during converting CredentialDefinitionId from indy format", @@ -85,11 +80,8 @@ impl CredentialDefinition { ); let indy_cred_def: IndyCredentialDefinitionFormat = - serde_json::from_str(&credential_definition).map_err(|_err| { - VdrError::CommonInvalidData { - msg: "Invalid indy cred def".to_string(), - } - })?; + serde_json::from_str(&credential_definition) + .map_err(|_err| VdrError::CommonInvalidData("Invalid indy cred def".to_string()))?; let besu_cred_def = CredentialDefinition::try_from(indy_cred_def); trace!( @@ -113,18 +105,14 @@ impl TryFrom for CredentialDefinition { let parts: Vec<&str> = cred_def.id.split(':').collect(); let id = parts.get(0).ok_or_else(|| { - let vdr_error = VdrError::CommonInvalidData { - msg: "Invalid indy cred def id".to_string() - }; + let vdr_error = VdrError::CommonInvalidData("Invalid indy cred def id".to_string()); warn!("Error: {:?} during converting CredentialDefinition from IndyCredentialDefinitionFormat", vdr_error); vdr_error })?; let schema_id_seq_no = parts.get(3).ok_or_else(|| { - let vdr_error = VdrError::CommonInvalidData { - msg: "Invalid indy cred def id".to_string() - }; + let vdr_error = VdrError::CommonInvalidData("Invalid indy cred def id".to_string()); warn!("Error: {:?} during converting CredentialDefinition from IndyCredentialDefinitionFormat", vdr_error); @@ -137,7 +125,7 @@ impl TryFrom for CredentialDefinition { let besu_cred_def = CredentialDefinition { id: CredentialDefinitionId::build(&issuer_id, schema_id_seq_no, &cred_def.tag), issuer_id, - schema_id: SchemaId::new(&schema_id.to_string()), + schema_id: SchemaId::from(schema_id.as_str()), cred_def_type: cred_def.type_.to_string(), tag: cred_def.tag.to_string(), value: cred_def.value.clone(), @@ -162,12 +150,12 @@ impl Into for CredentialDefinition { let indy_cred_def = IndyCredentialDefinitionFormat { id: format!( "{}:3:{}:{}:{}", - self.issuer_id.value(), + self.issuer_id.as_ref(), self.cred_def_type, - self.schema_id.value(), + self.schema_id.as_ref(), self.tag ), - schema_id: self.schema_id.value().to_string(), + schema_id: self.schema_id.to_string(), type_: self.cred_def_type.to_string(), tag: self.tag.to_string(), value: self.value.clone(), diff --git a/indy-besu/vdr/src/migration/schema.rs b/indy-besu/vdr/src/migration/schema.rs index 2325cdfe5..6c75e42bf 100644 --- a/indy-besu/vdr/src/migration/schema.rs +++ b/indy-besu/vdr/src/migration/schema.rs @@ -25,9 +25,7 @@ impl SchemaId { let parts: Vec<&str> = id.split(':').collect(); let id = parts.get(0).ok_or_else(|| { - let vdr_error = VdrError::CommonInvalidData { - msg: "Invalid indy schema id".to_string(), - }; + let vdr_error = VdrError::CommonInvalidData("Invalid indy schema id".to_string()); warn!( "Error: {:?} during converting SchemaId from indy format", @@ -37,9 +35,7 @@ impl SchemaId { vdr_error })?; let name = parts.get(2).ok_or_else(|| { - let vdr_error = VdrError::CommonInvalidData { - msg: "Invalid indy schema name".to_string(), - }; + let vdr_error = VdrError::CommonInvalidData("Invalid indy schema name".to_string()); warn!( "Error: {:?} during converting SchemaId from indy format", @@ -49,9 +45,7 @@ impl SchemaId { vdr_error })?; let version = parts.get(3).ok_or_else(|| { - let vdr_error = VdrError::CommonInvalidData { - msg: "Invalid indy schema version".to_string(), - }; + let vdr_error = VdrError::CommonInvalidData("Invalid indy schema version".to_string()); warn!( "Error: {:?} during converting SchemaId from indy format", @@ -79,9 +73,7 @@ impl Schema { trace!("Schema convert from Indy format: {} has started", schema); let indy_schema: IndySchemaFormat = serde_json::from_str(&schema).map_err(|_err| { - let vdr_error = VdrError::CommonInvalidData { - msg: "Invalid indy schema".to_string(), - }; + let vdr_error = VdrError::CommonInvalidData("Invalid indy schema".to_string()); warn!( "Error: {:?} during converting Schema from indy format", @@ -114,9 +106,7 @@ impl TryFrom for Schema { let parts: Vec<&str> = schema.id.split(':').collect(); let id = parts.get(0).ok_or_else(|| { - let vdr_error = VdrError::CommonInvalidData { - msg: "Invalid indy schema".to_string(), - }; + let vdr_error = VdrError::CommonInvalidData("Invalid indy schema".to_string()); warn!( "Error: {:?} during converting Schema from IndySchemaFormat", @@ -155,7 +145,7 @@ impl Into for Schema { let indy_schema = IndySchemaFormat { id: format!( "{}:2:{}:{}", - self.issuer_id.value(), + self.issuer_id.as_ref(), self.name, self.version ), diff --git a/indy-besu/vdr/src/signer/basic_signer.rs b/indy-besu/vdr/src/signer/basic_signer.rs index 1715cf975..2bc02c994 100644 --- a/indy-besu/vdr/src/signer/basic_signer.rs +++ b/indy-besu/vdr/src/signer/basic_signer.rs @@ -5,7 +5,7 @@ use secp256k1::{All, Message, PublicKey, Secp256k1, SecretKey}; use std::collections::HashMap; use crate::types::{Address, SignatureData}; -use std::{ops::Deref, str::FromStr}; +use std::str::FromStr; use web3::signing::keccak256; pub struct KeyPair { @@ -29,15 +29,13 @@ impl BasicSigner { pub fn create_key(&mut self, private_key: Option<&str>) -> VdrResult<(Address, Vec)> { let (account, key_pair) = self.create_account(private_key)?; let public_key_bytes = key_pair.public_key.serialize_uncompressed().to_vec(); - self.keys.insert(account.deref().to_string(), key_pair); + self.keys.insert(account.to_string(), key_pair); Ok((account, public_key_bytes)) } fn key_for_account(&self, account: &str) -> VdrResult<&KeyPair> { self.keys.get(account).ok_or_else(|| { - let vdr_error = VdrError::SignerMissingKey { - msg: account.to_string(), - }; + let vdr_error = VdrError::SignerMissingKey(account.to_string()); warn!( "Error: {:?} during getting keys for account: {}", @@ -85,7 +83,6 @@ impl BasicSigner { pub mod test { use super::*; use once_cell::sync::Lazy; - use std::ops::Deref; pub static TRUSTEE_ACC: Lazy
= Lazy::new(|| Address::from("0xf0e2db6c8dc6c681bb5d6ad121a107f300e9b2b5")); @@ -109,7 +106,7 @@ pub mod test { #[test] fn add_key_test() { let basic_signer = basic_signer(); - basic_signer.key_for_account(TRUSTEE_ACC.deref()).unwrap(); + basic_signer.key_for_account(TRUSTEE_ACC.as_ref()).unwrap(); } #[test] @@ -119,7 +116,7 @@ pub mod test { 43, 20, 70, 238, 250, 209, 10, 195, 87, 39, 219, 125, 26, 151, 3, 233, 70, 185, 237, 52, 240, 127, 64, 8, 98, 136, 107, 144, 241, 122, 142, 64, ]; - let signature = basic_signer.sign(&data, TRUSTEE_ACC.deref()).unwrap(); + let signature = basic_signer.sign(&data, TRUSTEE_ACC.as_ref()).unwrap(); let expected = vec![ 200, 178, 128, 72, 163, 176, 188, 177, 119, 110, 11, 2, 194, 50, 220, 215, 0, 161, 247, 77, 43, 80, 139, 173, 141, 122, 58, 206, 72, 28, 63, 59, 9, 59, 95, 160, 244, 66, 209, diff --git a/indy-besu/vdr/src/test.rs b/indy-besu/vdr/src/test.rs index c02fb0307..28bfd2e61 100644 --- a/indy-besu/vdr/src/test.rs +++ b/indy-besu/vdr/src/test.rs @@ -17,7 +17,6 @@ use crate::{ types::{Address, Transaction}, LedgerClient, }; -use std::ops::Deref; async fn sign_and_submit_transaction( client: &LedgerClient, @@ -25,7 +24,7 @@ async fn sign_and_submit_transaction( signer: &BasicSigner, ) -> String { let sign_bytes = transaction.get_signing_bytes().unwrap(); - let signature = signer.sign(&sign_bytes, TRUSTEE_ACC.deref()).unwrap(); + let signature = signer.sign(&sign_bytes, TRUSTEE_ACC.as_ref()).unwrap(); transaction.set_signature(signature); let block_hash = client.submit_transaction(&transaction).await.unwrap(); client.get_receipt(&block_hash).await.unwrap() @@ -204,7 +203,7 @@ mod role { .unwrap(); let sign_bytes = transaction.get_signing_bytes().unwrap(); - let signature = signer.sign(&sign_bytes, TRUSTEE_ACC.deref()).unwrap(); + let signature = signer.sign(&sign_bytes, TRUSTEE_ACC.as_ref()).unwrap(); transaction.set_signature(signature); let block_hash = client.submit_transaction(&transaction).await.unwrap(); diff --git a/indy-besu/vdr/src/types/address.rs b/indy-besu/vdr/src/types/address.rs index ca2e7f1a4..27aaf2bfe 100644 --- a/indy-besu/vdr/src/types/address.rs +++ b/indy-besu/vdr/src/types/address.rs @@ -2,75 +2,36 @@ use crate::{ error::VdrError, types::{ContractOutput, ContractParam}, }; -use std::{fmt, ops::Deref}; use ethereum_types::Address as Address_; use log::trace; -use serde::{ - de::{Error, Visitor}, - Deserialize, Deserializer, Serialize, Serializer, -}; +use serde::{Deserialize, Serialize}; use std::str::FromStr; -#[derive(Debug, Default, Clone, PartialEq)] -pub struct Address { - value: String, -} +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] +pub struct Address(String); + +const PREFIX: &str = "0x"; impl From<&str> for Address { fn from(address: &str) -> Self { - if address.starts_with("0x") { - Address { - value: address.to_string(), - } + if address.starts_with(PREFIX) { + Address(address.to_string()) } else { - Address { - value: format!("0x{}", address), - } + Address(format!("{}{}", PREFIX, address)) } } } -impl Deref for Address { - type Target = str; - - fn deref(&self) -> &Self::Target { - &self.value - } -} - -impl Serialize for Address { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - serializer.serialize_str(&self.value) - } -} - -struct IAddressVisitor; - -impl<'de> Visitor<'de> for IAddressVisitor { - type Value = Address; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("string expected") - } - - fn visit_str(self, v: &str) -> Result - where - E: Error, - { - Ok(Address::from(v)) +impl AsRef for Address { + fn as_ref(&self) -> &str { + &self.0 } } -impl<'de> Deserialize<'de> for Address { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - deserializer.deserialize_str(IAddressVisitor) +impl ToString for Address { + fn to_string(&self) -> String { + self.0.to_string() } } @@ -80,11 +41,11 @@ impl TryInto for Address { fn try_into(self) -> Result { trace!("Address: {:?} convert into ContractParam has started", self); - let acc_address = Address_::from_str(&self).map_err(|err| VdrError::CommonInvalidData { - msg: format!( + let acc_address = Address_::from_str(self.as_ref()).map_err(|err| { + VdrError::CommonInvalidData(format!( "Unable to parse account address. Err: {:?}", err.to_string() - ), + )) })?; let acc_address_contract_param = ContractParam::Address(acc_address); @@ -108,9 +69,7 @@ impl TryFrom for Address { value ); - let acc_address = Address { - value: value.get_string(0)?, - }; + let acc_address = Address(value.get_string(0)?); trace!( "Address convert from ContractOutput: {:?} has finished. Result: {:?}", diff --git a/indy-besu/vdr/src/types/contract.rs b/indy-besu/vdr/src/types/contract.rs index 4bc08c862..a00e7889b 100644 --- a/indy-besu/vdr/src/types/contract.rs +++ b/indy-besu/vdr/src/types/contract.rs @@ -30,9 +30,10 @@ impl ContractSpec { /// Read and parse contract specification from a JSON file pub fn from_file(spec_path: &str) -> VdrResult { let contract_spec = std::fs::read_to_string(spec_path).map_err(|err| { - let vdr_error = VdrError::ContractInvalidSpec { - msg: format!("Unable to read contract spec file. Err: {:?}", err), - }; + let vdr_error = VdrError::ContractInvalidSpec(format!( + "Unable to read contract spec file. Err: {:?}", + err + )); warn!( "Error: {:?} during reading contract spec from file", @@ -42,12 +43,10 @@ impl ContractSpec { vdr_error })?; let contract_spec = serde_json::from_str(&contract_spec).map_err(|err| { - let vdr_error = VdrError::ContractInvalidSpec { - msg: format!( - "Unable to parse contract specification. Err: {:?}", - err.to_string() - ), - }; + let vdr_error = VdrError::ContractInvalidSpec(format!( + "Unable to parse contract specification. Err: {:?}", + err.to_string() + )); warn!( "Error: {:?} during paring contract specification", @@ -93,27 +92,25 @@ impl ContractOutput { pub fn get_tuple(&self, index: usize) -> VdrResult { self.0 .get(index) - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing tuple value".to_string(), + .ok_or_else(|| { + VdrError::ContractInvalidResponseData("Missing tuple value".to_string()) })? .clone() .into_tuple() - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing tuple value".to_string(), - }) + .ok_or_else(|| VdrError::ContractInvalidResponseData("Missing tuple value".to_string())) .map(ContractOutput) } pub fn get_string(&self, index: usize) -> VdrResult { self.0 .get(index) - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing string value".to_string(), + .ok_or_else(|| { + VdrError::ContractInvalidResponseData("Missing string value".to_string()) })? .clone() .into_string() - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing string value".to_string(), + .ok_or_else(|| { + VdrError::ContractInvalidResponseData("Missing string value".to_string()) }) } @@ -121,8 +118,8 @@ impl ContractOutput { let address_str = self .0 .get(index) - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing address value".to_string(), + .ok_or_else(|| { + VdrError::ContractInvalidResponseData("Missing address value".to_string()) })? .clone() .to_string(); @@ -133,28 +130,20 @@ impl ContractOutput { pub fn get_bool(&self, index: usize) -> VdrResult { self.0 .get(index) - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing bool value".to_string(), - })? + .ok_or_else(|| VdrError::ContractInvalidResponseData("Missing bool value".to_string()))? .clone() .into_bool() - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing bool value".to_string(), - }) + .ok_or_else(|| VdrError::ContractInvalidResponseData("Missing bool value".to_string())) } pub fn get_u128(&self, index: usize) -> VdrResult { Ok(self .0 .get(index) - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing uint value".to_string(), - })? + .ok_or_else(|| VdrError::ContractInvalidResponseData("Missing uint value".to_string()))? .clone() .into_uint() - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing uint value".to_string(), - })? + .ok_or_else(|| VdrError::ContractInvalidResponseData("Missing uint value".to_string()))? .as_u128()) } @@ -162,35 +151,29 @@ impl ContractOutput { Ok(self .0 .get(index) - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing uint value".to_string(), - })? + .ok_or_else(|| VdrError::ContractInvalidResponseData("Missing uint value".to_string()))? .clone() .into_uint() - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing uint value".to_string(), - })? + .ok_or_else(|| VdrError::ContractInvalidResponseData("Missing uint value".to_string()))? .as_u32() as u8) } pub fn get_string_array(&self, index: usize) -> VdrResult> { self.0 .get(index) - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing string array value".to_string(), + .ok_or_else(|| { + VdrError::ContractInvalidResponseData("Missing string array value".to_string()) })? .clone() .into_array() - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing string array value".to_string(), + .ok_or_else(|| { + VdrError::ContractInvalidResponseData("Missing string array value".to_string()) })? .into_iter() .map(|token| { - token - .into_string() - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing string value".to_string(), - }) + token.into_string().ok_or_else(|| { + VdrError::ContractInvalidResponseData("Missing string value".to_string()) + }) }) .collect() } @@ -199,13 +182,17 @@ impl ContractOutput { Ok(self .0 .get(index) - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing address string array value".to_string(), + .ok_or_else(|| { + VdrError::ContractInvalidResponseData( + "Missing address string array value".to_string(), + ) })? .clone() .into_array() - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing address string array value".to_string(), + .ok_or_else(|| { + VdrError::ContractInvalidResponseData( + "Missing address string array value".to_string(), + ) })? .into_iter() .map(|token| Address::from(token.to_string().as_str())) @@ -216,22 +203,20 @@ impl ContractOutput { let tokens = self .0 .get(index) - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing object array value".to_string(), + .ok_or_else(|| { + VdrError::ContractInvalidResponseData("Missing object array value".to_string()) })? .clone() .into_array() - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing object array value".to_string(), + .ok_or_else(|| { + VdrError::ContractInvalidResponseData("Missing object array value".to_string()) })?; let mut result: Vec = Vec::new(); for item in tokens.into_iter() { - let item = item - .into_tuple() - .ok_or_else(|| VdrError::ContractInvalidResponseData { - msg: "Missing object value".to_string(), - })?; + let item = item.into_tuple().ok_or_else(|| { + VdrError::ContractInvalidResponseData("Missing object value".to_string()) + })?; result.push(ContractOutput(item)) } Ok(result) diff --git a/indy-besu/vdr/src/types/transaction.rs b/indy-besu/vdr/src/types/transaction.rs index b2f11bfcd..93dc68ce1 100644 --- a/indy-besu/vdr/src/types/transaction.rs +++ b/indy-besu/vdr/src/types/transaction.rs @@ -121,8 +121,11 @@ impl Transaction { } fn get_to(&self) -> VdrResult { - H160::from_str(&self.to).map_err(|_| VdrError::ClientInvalidTransaction { - msg: format!("Invalid transaction target address {:?}", self.to), + H160::from_str(self.to.as_ref()).map_err(|_| { + VdrError::ClientInvalidTransaction(format!( + "Invalid transaction target address {:?}", + self.to + )) }) } @@ -130,14 +133,12 @@ impl Transaction { let nonce: [u64; 4] = self .nonce .as_ref() - .ok_or_else(|| VdrError::ClientInvalidTransaction { - msg: "Transaction `nonce` is not set".to_string(), + .ok_or_else(|| { + VdrError::ClientInvalidTransaction("Transaction `nonce` is not set".to_string()) })? .clone() .try_into() - .map_err(|_| VdrError::CommonInvalidData { - msg: "Invalid nonce provided".to_string(), - })?; + .map_err(|_| VdrError::CommonInvalidData("Invalid nonce provided".to_string()))?; Ok(U256(nonce)) } @@ -145,9 +146,7 @@ impl Transaction { let signature = self.signature.read().unwrap(); let signature = signature .as_ref() - .ok_or_else(|| VdrError::ClientInvalidTransaction { - msg: "Missing signature".to_string(), - })? + .ok_or_else(|| VdrError::ClientInvalidTransaction("Missing signature".to_string()))? .clone(); let signature = EthTransactionSignature::new( @@ -155,8 +154,8 @@ impl Transaction { H256::from_slice(&signature.r), H256::from_slice(&signature.s), ) - .ok_or_else(|| VdrError::ClientInvalidTransaction { - msg: "Transaction `nonce` is not set".to_string(), + .ok_or_else(|| { + VdrError::ClientInvalidTransaction("Transaction `nonce` is not set".to_string()) })?; Ok(signature) } @@ -248,12 +247,11 @@ impl TransactionBuilder { let data = contract.encode_input(&self.method, &self.params)?; let nonce = match self.type_ { TransactionType::Write => { - let from = - self.from - .as_ref() - .ok_or_else(|| VdrError::ClientInvalidTransaction { - msg: "Transaction `sender` is not set".to_string(), - })?; + let from = self.from.as_ref().ok_or_else(|| { + VdrError::ClientInvalidTransaction( + "Transaction `sender` is not set".to_string(), + ) + })?; let nonce = client.get_transaction_count(from).await?; Some(nonce.to_vec()) @@ -315,9 +313,8 @@ impl TransactionParser { bytes: &[u8], ) -> VdrResult { if bytes.is_empty() { - let vdr_error = VdrError::ContractInvalidResponseData { - msg: "Empty response bytes".to_string(), - }; + let vdr_error = + VdrError::ContractInvalidResponseData("Empty response bytes".to_string()); warn!("Error: {:?} during transaction output parse", vdr_error); @@ -327,9 +324,8 @@ impl TransactionParser { let output = contract.decode_output(&self.method, bytes)?; if output.is_empty() { - let vdr_error = VdrError::ContractInvalidResponseData { - msg: "Unable to parse response".to_string(), - }; + let vdr_error = + VdrError::ContractInvalidResponseData("Unable to parse response".to_string()); warn!("Error: {:?} during transaction output parse", vdr_error); diff --git a/indy-besu/vdr/uniffi/src/ffi/error.rs b/indy-besu/vdr/uniffi/src/ffi/error.rs index c3562ef98..3565d756d 100644 --- a/indy-besu/vdr/uniffi/src/ffi/error.rs +++ b/indy-besu/vdr/uniffi/src/ffi/error.rs @@ -60,28 +60,28 @@ impl From for VdrError { fn from(error: VdrError_) -> Self { match error { VdrError_::ClientNodeUnreachable => VdrError::ClientNodeUnreachable, - VdrError_::ClientInvalidTransaction { msg } => { + VdrError_::ClientInvalidTransaction(msg) => { VdrError::ClientInvalidTransaction { msg } } - VdrError_::ClientInvalidResponse { msg } => VdrError::ClientInvalidResponse { msg }, - VdrError_::ClientTransactionReverted { msg } => { + VdrError_::ClientInvalidResponse(msg) => VdrError::ClientInvalidResponse { msg }, + VdrError_::ClientTransactionReverted(msg) => { VdrError::ClientTransactionReverted { msg } } - VdrError_::ClientUnexpectedError { msg } => VdrError::ClientUnexpectedError { msg }, - VdrError_::ClientInvalidState { msg } => VdrError::ClientInvalidState { msg }, - VdrError_::ContractInvalidName { msg } => VdrError::ContractInvalidName { msg }, - VdrError_::ContractInvalidSpec { msg } => VdrError::ContractInvalidSpec { msg }, + VdrError_::ClientUnexpectedError(msg) => VdrError::ClientUnexpectedError { msg }, + VdrError_::ClientInvalidState(msg) => VdrError::ClientInvalidState { msg }, + VdrError_::ContractInvalidName(msg) => VdrError::ContractInvalidName { msg }, + VdrError_::ContractInvalidSpec(msg) => VdrError::ContractInvalidSpec { msg }, VdrError_::ContractInvalidInputData => VdrError::ContractInvalidInputData, - VdrError_::ContractInvalidResponseData { msg } => { + VdrError_::ContractInvalidResponseData(msg) => { VdrError::ContractInvalidResponseData { msg } } VdrError_::SignerInvalidPrivateKey => VdrError::SignerInvalidPrivateKey, VdrError_::SignerInvalidMessage => VdrError::SignerInvalidMessage, - VdrError_::SignerMissingKey { msg } => VdrError::SignerMissingKey { msg }, - VdrError_::SignerUnexpectedError { msg } => VdrError::SignerUnexpectedError { msg }, - VdrError_::CommonInvalidData { msg } => VdrError::CommonInvalidData { msg }, - VdrError_::QuorumNotReached { msg } => VdrError::QuorumNotReached { msg }, - VdrError_::GetTransactionError { msg } => VdrError::GetTransactionError { msg }, + VdrError_::SignerMissingKey(msg) => VdrError::SignerMissingKey { msg }, + VdrError_::SignerUnexpectedError(msg) => VdrError::SignerUnexpectedError { msg }, + VdrError_::CommonInvalidData(msg) => VdrError::CommonInvalidData { msg }, + VdrError_::QuorumNotReached(msg) => VdrError::QuorumNotReached { msg }, + VdrError_::GetTransactionError(msg) => VdrError::GetTransactionError { msg }, } } } diff --git a/indy-besu/vdr/wasm/src/transaction.rs b/indy-besu/vdr/wasm/src/transaction.rs index 59fec9f55..bef27cfc9 100644 --- a/indy-besu/vdr/wasm/src/transaction.rs +++ b/indy-besu/vdr/wasm/src/transaction.rs @@ -1,5 +1,5 @@ use indy2_vdr::{SignatureData, Transaction}; -use std::{ops::Deref, rc::Rc}; +use std::rc::Rc; use wasm_bindgen::prelude::*; use crate::error::Result; @@ -10,7 +10,7 @@ pub struct TransactionWrapper(pub(crate) Rc); #[wasm_bindgen(js_class = Transaction)] impl TransactionWrapper { pub fn to(&self) -> Result { - Ok(self.0.to.deref().to_string()) + Ok(self.0.to.to_string()) } #[wasm_bindgen(js_name = getSigningBytes)]