Skip to content

Commit

Permalink
remove generics
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Coats committed Dec 7, 2023
1 parent 8c1f7f9 commit ea20926
Show file tree
Hide file tree
Showing 72 changed files with 334 additions and 929 deletions.
4 changes: 3 additions & 1 deletion bindings/core/src/method/secret_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,10 @@ pub enum SecretManagerMethod {
#[serde(rename_all = "camelCase")]
SignTransaction {
/// Prepared transaction data
prepared_transaction_data: PreparedTransactionDataDto<serde_json::Value>,
prepared_transaction_data: PreparedTransactionDataDto,
protocol_parameters: ProtocolParameters,
/// Options used to sign the transaction
signing_options: serde_json::Value,
},
// Sign a block.
#[serde(rename_all = "camelCase")]
Expand Down
2 changes: 1 addition & 1 deletion bindings/core/src/method/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ pub enum UtilsMethod {
/// Verifies the semantic of a transaction.
VerifyTransactionSemantic {
transaction: TransactionDto,
inputs: Vec<InputSigningData<serde_json::Value>>,
inputs: Vec<InputSigningData>,
unlocks: Option<Vec<Unlock>>,
},
}
9 changes: 4 additions & 5 deletions bindings/core/src/method/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
#[cfg(feature = "stronghold")]
use std::path::PathBuf;

use crypto::keys::bip44::Bip44;
use derivative::Derivative;
#[cfg(feature = "events")]
use iota_sdk::wallet::events::types::{WalletEvent, WalletEventType};
Expand Down Expand Up @@ -390,19 +389,19 @@ pub enum WalletMethod {
/// Expected response: [`SentTransaction`](crate::Response::SentTransaction)
#[serde(rename_all = "camelCase")]
SignAndSubmitTransaction {
prepared_transaction_data: PreparedTransactionDataDto<serde_json::Value>,
prepared_transaction_data: PreparedTransactionDataDto,
},
/// Sign a prepared transaction.
/// Expected response: [`SignedTransactionData`](crate::Response::SignedTransactionData)
#[serde(rename_all = "camelCase")]
SignTransaction {
prepared_transaction_data: PreparedTransactionDataDto<serde_json::Value>,
prepared_transaction_data: PreparedTransactionDataDto,
},
/// Validate the transaction, submit it to a node and store it in the wallet.
/// Expected response: [`SentTransaction`](crate::Response::SentTransaction)
#[serde(rename_all = "camelCase")]
SubmitAndStoreTransaction {
signed_transaction_data: SignedTransactionDataDto<serde_json::Value>,
signed_transaction_data: SignedTransactionDataDto,
},
/// Sync the wallet by fetching new information from the nodes. Will also reissue pending transactions
/// if necessary. A custom default can be set using SetDefaultSyncOptions.
Expand All @@ -423,7 +422,7 @@ pub enum WalletMethod {
/// Expected response: [`Ok`](crate::Response::Ok)
#[cfg(feature = "events")]
#[cfg_attr(docsrs, doc(cfg(feature = "events")))]
EmitTestEvent { event: WalletEvent<serde_json::Value> },
EmitTestEvent { event: WalletEvent },

// TODO: reconsider whether to have the following methods on the wallet
/// Get the ledger nano status
Expand Down
2 changes: 2 additions & 0 deletions bindings/core/src/method_handler/secret_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,13 @@ pub(crate) async fn call_secret_manager_method_internal(
SecretManagerMethod::SignTransaction {
prepared_transaction_data,
protocol_parameters,
signing_options,
} => {
let transaction = &secret_manager
.sign_transaction(
PreparedTransactionData::try_from_dto(prepared_transaction_data)?,
&protocol_parameters,
&signing_options,
)
.await
.map_err(iota_sdk::client::Error::from)?;
Expand Down
10 changes: 5 additions & 5 deletions bindings/core/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,11 +270,11 @@ pub enum Response {
OutputIds(Vec<OutputId>),
/// Response for:
/// - [`GetOutput`](crate::method::WalletMethod::GetOutput)
OutputData(Option<Box<OutputData<serde_json::Value>>>),
OutputData(Option<Box<OutputData>>),
/// Response for:
/// - [`Outputs`](crate::method::WalletMethod::Outputs),
/// - [`UnspentOutputs`](crate::method::WalletMethod::UnspentOutputs)
OutputsData(Vec<OutputData<serde_json::Value>>),
OutputsData(Vec<OutputData>),
/// Response for:
/// - [`PrepareBurn`](crate::method::WalletMethod::PrepareBurn),
/// - [`PrepareClaimOutputs`](crate::method::WalletMethod::PrepareClaimOutputs)
Expand All @@ -292,10 +292,10 @@ pub enum Response {
/// - [`PrepareTransaction`](crate::method::WalletMethod::PrepareTransaction)
/// - [`PrepareVote`](crate::method::WalletMethod::PrepareVote)
/// - [`PrepareImplicitAccountTransition`](crate::method::WalletMethod::PrepareImplicitAccountTransition)
PreparedTransaction(PreparedTransactionDataDto<serde_json::Value>),
PreparedTransaction(PreparedTransactionDataDto),
/// Response for:
/// - [`PrepareCreateNativeToken`](crate::method::WalletMethod::PrepareCreateNativeToken),
PreparedCreateNativeTokenTransaction(PreparedCreateNativeTokenTransactionDto<serde_json::Value>),
PreparedCreateNativeTokenTransaction(PreparedCreateNativeTokenTransactionDto),
/// Response for:
/// - [`GetIncomingTransaction`](crate::method::WalletMethod::GetIncomingTransaction)
/// - [`GetTransaction`](crate::method::WalletMethod::GetTransaction),
Expand All @@ -307,7 +307,7 @@ pub enum Response {
Transactions(Vec<TransactionWithMetadataDto>),
/// Response for:
/// - [`SignTransaction`](crate::method::WalletMethod::SignTransaction)
SignedTransactionData(SignedTransactionDataDto<serde_json::Value>),
SignedTransactionData(SignedTransactionDataDto),
/// Response for:
/// - [`GetBalance`](crate::method::WalletMethod::GetBalance),
/// - [`Sync`](crate::method::WalletMethod::Sync)
Expand Down
5 changes: 1 addition & 4 deletions bindings/wasm/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,7 @@ pub async fn listen_wallet(
event_types.push(wallet_event_type);
}

let (tx, mut rx): (
UnboundedSender<WalletEvent<serde_json::Value>>,
UnboundedReceiver<WalletEvent<serde_json::Value>>,
) = unbounded_channel();
let (tx, mut rx): (UnboundedSender<WalletEvent>, UnboundedReceiver<WalletEvent>) = unbounded_channel();
method_handler
.wallet
.lock()
Expand Down
2 changes: 1 addition & 1 deletion cli/src/wallet_cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1236,7 +1236,7 @@ pub async fn prompt_internal(
Ok(PromptResponse::Reprompt)
}

fn print_outputs(mut outputs: Vec<OutputData<Bip44>>, title: &str) -> Result<(), Error> {
fn print_outputs(mut outputs: Vec<OutputData>, title: &str) -> Result<(), Error> {
if outputs.is_empty() {
println_log_info!("No outputs found");
} else {
Expand Down
4 changes: 1 addition & 3 deletions sdk/examples/wallet/offline_signing/1_prepare_transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,7 @@ async fn read_address_from_file() -> Result<Bip44Address> {
Ok(serde_json::from_str(&json)?)
}

async fn write_transaction_to_file<O: Clone + Serialize>(
prepared_transaction: PreparedTransactionData<O>,
) -> Result<()> {
async fn write_transaction_to_file(prepared_transaction: PreparedTransactionData) -> Result<()> {
use tokio::io::AsyncWriteExt;

let json = serde_json::to_string_pretty(&PreparedTransactionDataDto::from(&prepared_transaction))?;
Expand Down
18 changes: 8 additions & 10 deletions sdk/examples/wallet/offline_signing/2_sign_transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,22 @@
//! cargo run --release --all-features --example 2_sign_transaction
//! ```
use crypto::keys::bip44::Bip44;
use iota_sdk::{
client::{
api::{
transaction::validate_signed_transaction_payload_length, PreparedTransactionData, SignedTransactionData,
SignedTransactionDataDto,
},
constants::IOTA_COIN_TYPE,
secret::{stronghold::StrongholdSecretManager, SignTransaction},
},
types::{
block::{
payload::SignedTransactionPayload,
protocol::{protocol_parameters, ProtocolParameters},
},
block::{payload::SignedTransactionPayload, protocol::protocol_parameters},
TryFromDto,
},
wallet::Result,
};
use serde::{de::DeserializeOwned, Serialize};

const STRONGHOLD_SNAPSHOT_PATH: &str = "./examples/wallet/offline_signing/example.stronghold";
const PREPARED_TRANSACTION_FILE_PATH: &str = "./examples/wallet/offline_signing/example.prepared_transaction.json";
Expand All @@ -46,13 +44,15 @@ async fn main() -> Result<()> {
.password(std::env::var("STRONGHOLD_PASSWORD").unwrap())
.build(STRONGHOLD_SNAPSHOT_PATH)?;

let signing_options = Bip44::new(IOTA_COIN_TYPE);

let prepared_transaction_data = read_prepared_transaction_from_file().await?;

let protocol_parameters = protocol_parameters();

// Signs prepared transaction offline.
let unlocks = secret_manager
.transaction_unlocks(&prepared_transaction_data, &protocol_parameters)
.transaction_unlocks(&prepared_transaction_data, &protocol_parameters, &signing_options)
.await?;

let signed_transaction = SignedTransactionPayload::new(prepared_transaction_data.transaction.clone(), unlocks)?;
Expand All @@ -71,7 +71,7 @@ async fn main() -> Result<()> {
Ok(())
}

async fn read_prepared_transaction_from_file<O: DeserializeOwned>() -> Result<PreparedTransactionData<O>> {
async fn read_prepared_transaction_from_file() -> Result<PreparedTransactionData> {
use tokio::io::AsyncReadExt;

let mut file = tokio::io::BufReader::new(tokio::fs::File::open(PREPARED_TRANSACTION_FILE_PATH).await?);
Expand All @@ -81,9 +81,7 @@ async fn read_prepared_transaction_from_file<O: DeserializeOwned>() -> Result<Pr
Ok(PreparedTransactionData::try_from_dto(serde_json::from_str(&json)?)?)
}

async fn write_signed_transaction_to_file<O: Clone + Serialize>(
signed_transaction_data: &SignedTransactionData<O>,
) -> Result<()> {
async fn write_signed_transaction_to_file(signed_transaction_data: &SignedTransactionData) -> Result<()> {
use tokio::io::AsyncWriteExt;

let dto = SignedTransactionDataDto::from(signed_transaction_data);
Expand Down
7 changes: 2 additions & 5 deletions sdk/examples/wallet/offline_signing/3_send_transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ use iota_sdk::{
wallet::Result,
Wallet,
};
use serde::de::DeserializeOwned;

const ONLINE_WALLET_DB_PATH: &str = "./examples/wallet/offline_signing/example-online-walletdb";
const SIGNED_TRANSACTION_FILE_PATH: &str = "./examples/wallet/offline_signing/example.signed_transaction.json";
Expand Down Expand Up @@ -51,16 +50,14 @@ async fn main() -> Result<()> {
Ok(())
}

async fn read_signed_transaction_from_file<O: Clone + DeserializeOwned>(
client: &Client,
) -> Result<SignedTransactionData<O>> {
async fn read_signed_transaction_from_file(client: &Client) -> Result<SignedTransactionData> {
use tokio::io::AsyncReadExt;

let mut file = tokio::io::BufReader::new(tokio::fs::File::open(SIGNED_TRANSACTION_FILE_PATH).await?);
let mut json = String::new();
file.read_to_string(&mut json).await?;

let dto = serde_json::from_str::<SignedTransactionDataDto<O>>(&json)?;
let dto = serde_json::from_str::<SignedTransactionDataDto>(&json)?;

Ok(SignedTransactionData::try_from_dto_with_params(
dto,
Expand Down
28 changes: 14 additions & 14 deletions sdk/src/client/api/block_builder/input_selection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ use crate::{
};

/// Working state for the input selection algorithm.
pub struct InputSelection<O> {
available_inputs: Vec<InputSigningData<O>>,
pub struct InputSelection {
available_inputs: Vec<InputSigningData>,
required_inputs: HashSet<OutputId>,
forbidden_inputs: HashSet<OutputId>,
selected_inputs: Vec<InputSigningData<O>>,
selected_inputs: Vec<InputSigningData>,
outputs: Vec<Output>,
addresses: HashSet<Address>,
burn: Option<Burn>,
Expand All @@ -48,17 +48,17 @@ pub struct InputSelection<O> {

/// Result of the input selection algorithm.
#[derive(Clone, Debug)]
pub struct Selected<O> {
pub struct Selected {
/// Selected inputs.
pub inputs: Vec<InputSigningData<O>>,
pub inputs: Vec<InputSigningData>,
/// Provided and created outputs.
pub outputs: Vec<Output>,
/// Remainder, if there was one.
pub remainder: Option<RemainderData<O>>,
pub remainder: Option<RemainderData>,
}

impl<O: 'static + Clone + std::fmt::Debug> InputSelection<O> {
fn required_account_nft_addresses(&self, input: &InputSigningData<O>) -> Result<Option<Requirement>, Error> {
impl InputSelection {
fn required_account_nft_addresses(&self, input: &InputSigningData) -> Result<Option<Requirement>, Error> {
let required_address = input
.output
.required_and_unlocked_address(self.slot_index, input.output_id())?
Expand All @@ -75,7 +75,7 @@ impl<O: 'static + Clone + std::fmt::Debug> InputSelection<O> {
}
}

fn select_input(&mut self, input: InputSigningData<O>) -> Result<(), Error> {
fn select_input(&mut self, input: InputSigningData) -> Result<(), Error> {
log::debug!("Selecting input {:?}", input.output_id());

if let Some(output) = self.transition_input(&input)? {
Expand Down Expand Up @@ -145,7 +145,7 @@ impl<O: 'static + Clone + std::fmt::Debug> InputSelection<O> {

/// Creates a new [`InputSelection`].
pub fn new(
available_inputs: impl Into<Vec<InputSigningData<O>>>,
available_inputs: impl Into<Vec<InputSigningData>>,
outputs: impl Into<Vec<Output>>,
addresses: impl IntoIterator<Item = Address>,
protocol_parameters: ProtocolParameters,
Expand Down Expand Up @@ -249,15 +249,15 @@ impl<O: 'static + Clone + std::fmt::Debug> InputSelection<O> {

// Inputs need to be sorted before signing, because the reference unlock conditions can only reference a lower index
pub(crate) fn sort_input_signing_data(
mut inputs: Vec<InputSigningData<O>>,
mut inputs: Vec<InputSigningData>,
slot_index: SlotIndex,
) -> Result<Vec<InputSigningData<O>>, Error> {
) -> Result<Vec<InputSigningData>, Error> {
// initially sort by output to make it deterministic
// TODO: rethink this, we only need it deterministic for tests, for the protocol it doesn't matter, also there
// might be a more efficient way to do this
inputs.sort_by_key(|i| i.output.pack_to_vec());
// filter for ed25519 address first
let (mut sorted_inputs, account_nft_address_inputs): (Vec<InputSigningData<O>>, Vec<InputSigningData<O>>) =
let (mut sorted_inputs, account_nft_address_inputs): (Vec<InputSigningData>, Vec<InputSigningData>) =
inputs.into_iter().partition(|input_signing_data| {
let (input_address, _) = input_signing_data
.output
Expand Down Expand Up @@ -338,7 +338,7 @@ impl<O: 'static + Clone + std::fmt::Debug> InputSelection<O> {

/// Selects inputs that meet the requirements of the outputs to satisfy the semantic validation of the overall
/// transaction. Also creates a remainder output and chain transition outputs if required.
pub fn select(mut self) -> Result<Selected<O>, Error> {
pub fn select(mut self) -> Result<Selected, Error> {
if !OUTPUT_COUNT_RANGE.contains(&(self.outputs.len() as u16)) {
// If burn is provided, outputs will be added later
if !(self.outputs.is_empty() && self.burn.is_some()) {
Expand Down
15 changes: 7 additions & 8 deletions sdk/src/client/api/block_builder/input_selection/remainder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ use crate::{
},
};

impl<O: Clone> InputSelection<O> {
impl InputSelection {
// Gets the remainder address from configuration of finds one from the inputs.
fn get_remainder_address(&self) -> Result<Option<(Address, Option<O>)>, Error> {
fn get_remainder_address(&self) -> Result<Option<Address>, Error> {
if let Some(remainder_address) = &self.remainder_address {
// Search in inputs for the Bip44 chain for the remainder address, so the ledger can regenerate it
for input in self.available_inputs.iter().chain(self.selected_inputs.iter()) {
Expand All @@ -27,10 +27,10 @@ impl<O: Clone> InputSelection<O> {
.required_and_unlocked_address(self.slot_index, input.output_id())?;

if &required_address == remainder_address {
return Ok(Some((remainder_address.clone(), input.signing_options.clone())));
return Ok(Some(remainder_address.clone()));
}
}
return Ok(Some((remainder_address.clone(), None)));
return Ok(Some(remainder_address.clone()));
}

for input in &self.selected_inputs {
Expand All @@ -40,7 +40,7 @@ impl<O: Clone> InputSelection<O> {
.0;

if required_address.is_ed25519() {
return Ok(Some((required_address, input.signing_options.clone())));
return Ok(Some(required_address));
}
}

Expand Down Expand Up @@ -79,7 +79,7 @@ impl<O: Clone> InputSelection<O> {

pub(crate) fn remainder_and_storage_deposit_return_outputs(
&self,
) -> Result<(Option<RemainderData<O>>, Vec<Output>), Error> {
) -> Result<(Option<RemainderData>, Vec<Output>), Error> {
let (inputs_sum, outputs_sum, inputs_sdr, outputs_sdr) =
amount_sums(&self.selected_inputs, &self.outputs, self.slot_index);
let mut storage_deposit_returns = Vec::new();
Expand Down Expand Up @@ -120,7 +120,7 @@ impl<O: Clone> InputSelection<O> {
return Ok((None, storage_deposit_returns));
}

let Some((remainder_address, chain)) = self.get_remainder_address()? else {
let Some(remainder_address) = self.get_remainder_address()? else {
return Err(Error::MissingInputWithEd25519Address);
};

Expand All @@ -145,7 +145,6 @@ impl<O: Clone> InputSelection<O> {
Ok((
Some(RemainderData {
output: remainder,
signing_options: chain,
address: remainder_address,
}),
storage_deposit_returns,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ pub(crate) fn is_account_with_id_non_null(output: &Output, account_id: &AccountI
}
}

impl<O> InputSelection<O> {
impl InputSelection {
/// Fulfills an account requirement by selecting the appropriate account from the available inputs.
pub(crate) fn fulfill_account_requirement(
&mut self,
account_id: AccountId,
) -> Result<Vec<InputSigningData<O>>, Error> {
) -> Result<Vec<InputSigningData>, Error> {
// Check if the requirement is already fulfilled.
if let Some(input) = self
.selected_inputs
Expand Down
Loading

0 comments on commit ea20926

Please sign in to comment.