Skip to content

Commit

Permalink
Remove client block builder (#674)
Browse files Browse the repository at this point in the history
* Remove client block builder

* Add imports

* Remove unused import

* Fix example

* Add issue link
  • Loading branch information
Thoralf-M authored and thibault-martinez committed Jul 17, 2023
1 parent 4b7f753 commit 3614940
Show file tree
Hide file tree
Showing 77 changed files with 376 additions and 5,652 deletions.
49 changes: 1 addition & 48 deletions bindings/core/src/method/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,7 @@ use derivative::Derivative;
#[cfg(feature = "mqtt")]
use iota_sdk::client::mqtt::Topic;
use iota_sdk::{
client::{
api::{
ClientBlockBuilderOptions as BuildBlockOptions, GetAddressesOptions as GenerateAddressesOptions,
PreparedTransactionDataDto,
},
node_api::indexer::query_parameters::QueryParameter,
node_manager::node::NodeAuth,
secret::SecretManagerDto,
},
client::{node_api::indexer::query_parameters::QueryParameter, node_manager::node::NodeAuth},
types::block::{
address::{Bech32Address, Hrp},
output::{
Expand All @@ -28,8 +20,6 @@ use iota_sdk::{
};
use serde::{Deserialize, Serialize};

use crate::OmittedDebug;

/// Each public client method.
#[derive(Clone, Derivative, Serialize, Deserialize)]
#[derivative(Debug)]
Expand Down Expand Up @@ -97,15 +87,6 @@ pub enum ClientMethod {
/// Topics for which listeners should be removed.
topics: Vec<Topic>,
},
/// Build and post a block
#[serde(rename_all = "camelCase")]
BuildAndPostBlock {
/// Secret manager
#[derivative(Debug(format_with = "OmittedDebug::omitted_fmt"))]
secret_manager: Option<SecretManagerDto>,
/// Options
options: Option<BuildBlockOptions>,
},
/// Get a node candidate from the healthy node pool.
GetNode,
/// Gets the network related information such as network_id and min_pow_score
Expand Down Expand Up @@ -136,24 +117,6 @@ pub enum ClientMethod {
query_params: Vec<String>,
request_object: Option<String>,
},
/// Prepare a transaction for signing
#[serde(rename_all = "camelCase")]
PrepareTransaction {
/// Secret manager
#[derivative(Debug(format_with = "OmittedDebug::omitted_fmt"))]
secret_manager: Option<SecretManagerDto>,
/// Options
options: Option<BuildBlockOptions>,
},
/// Sign a transaction
#[serde(rename_all = "camelCase")]
SignTransaction {
/// Secret manager
#[derivative(Debug(format_with = "OmittedDebug::omitted_fmt"))]
secret_manager: SecretManagerDto,
/// Prepared transaction data
prepared_transaction_data: PreparedTransactionDataDto,
},
/// Build a block containing the specified payload and post it to the network.
PostBlockPayload {
/// The payload to send
Expand Down Expand Up @@ -321,16 +284,6 @@ pub enum ClientMethod {
/// Maximum attempts
max_attempts: Option<u64>,
},
/// Function to consolidate all funds from a range of addresses to the address with the lowest index in that range
/// Returns the address to which the funds got consolidated, if any were available
#[serde(rename_all = "camelCase")]
ConsolidateFunds {
/// Secret manager
#[derivative(Debug(format_with = "OmittedDebug::omitted_fmt"))]
secret_manager: SecretManagerDto,
/// Addresses generation options
generate_addresses_options: GenerateAddressesOptions,
},
/// Function to find inputs from addresses for a provided amount (useful for offline signing)
FindInputs {
/// Addresses
Expand Down
99 changes: 10 additions & 89 deletions bindings/core/src/method_handler/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@
#[cfg(feature = "mqtt")]
use iota_sdk::client::mqtt::{MqttPayload, Topic};
use iota_sdk::{
client::{
api::{PreparedTransactionData, PreparedTransactionDataDto},
request_funds_from_faucet, Client,
},
client::{request_funds_from_faucet, Client},
types::{
api::core::response::OutputWithMetadataResponse,
block::{
Expand All @@ -16,7 +13,7 @@ use iota_sdk::{
dto::{OutputBuilderAmountDto, OutputDto, OutputMetadataDto},
AliasOutput, BasicOutput, FoundryOutput, NftOutput, Output, Rent, RentStructure,
},
payload::{dto::PayloadDto, Payload},
payload::Payload,
protocol::dto::ProtocolParametersDto,
Block, BlockDto,
},
Expand Down Expand Up @@ -160,31 +157,6 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM

Response::Output(OutputDto::from(&output))
}
ClientMethod::BuildAndPostBlock {
secret_manager,
options,
} => {
// Prepare transaction
let mut block_builder = client.build_block();

let secret_manager = match secret_manager {
Some(secret_manager) => Some(secret_manager.try_into()?),
None => None,
};

if let Some(secret_manager) = &secret_manager {
block_builder = block_builder.with_secret_manager(secret_manager);
}

if let Some(options) = options {
block_builder = block_builder.set_options(options).await?;
}

let block = block_builder.finish().await?;
let block_id = block.id();

Response::BlockIdWithBlock(block_id, BlockDto::from(&block))
}
#[cfg(feature = "mqtt")]
ClientMethod::ClearListeners { topics } => {
client.unsubscribe(topics).await?;
Expand Down Expand Up @@ -217,55 +189,15 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM
}
ClientMethod::GetLocalPow => Response::Bool(client.get_local_pow().await),
ClientMethod::GetFallbackToLocalPow => Response::Bool(client.get_fallback_to_local_pow().await),
ClientMethod::PrepareTransaction {
secret_manager,
options,
} => {
let mut block_builder = client.build_block();

let secret_manager = match secret_manager {
Some(secret_manager) => Some(secret_manager.try_into()?),
None => None,
};

if let Some(secret_manager) = &secret_manager {
block_builder = block_builder.with_secret_manager(secret_manager);
}

if let Some(options) = options {
block_builder = block_builder.set_options(options).await?;
}

Response::PreparedTransactionData(PreparedTransactionDataDto::from(
&block_builder.prepare_transaction().await?,
))
}
ClientMethod::SignTransaction {
secret_manager,
prepared_transaction_data,
} => {
let mut block_builder = client.build_block();

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,
)?)
.await?,
))
}
ClientMethod::PostBlockPayload { payload } => {
let block_builder = client.build_block();

let block = block_builder
.finish_block(Some(Payload::try_from_dto(
payload,
&client.get_protocol_parameters().await?,
)?))
let block = client
.finish_block_builder(
None,
Some(Payload::try_from_dto(
payload,
&client.get_protocol_parameters().await?,
)?),
)
.await?;

let block_id = block.id();
Expand Down Expand Up @@ -369,17 +301,6 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM
.collect();
Response::RetryUntilIncludedSuccessful(res)
}
ClientMethod::ConsolidateFunds {
secret_manager,
generate_addresses_options,
} => {
let secret_manager = secret_manager.try_into()?;
Response::ConsolidatedFunds(
client
.consolidate_funds(&secret_manager, generate_addresses_options)
.await?,
)
}
ClientMethod::FindInputs { addresses, amount } => Response::Inputs(
client
.find_inputs(addresses, amount)
Expand Down
9 changes: 1 addition & 8 deletions bindings/core/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,7 @@ pub enum Response {
/// - [`GetProtocolParameters`](crate::method::ClientMethod::GetProtocolParameters)
ProtocolParameters(ProtocolParametersDto),
/// Response for:
/// - [`PrepareTransaction`](crate::method::ClientMethod::PrepareTransaction)
PreparedTransactionData(PreparedTransactionDataDto),
/// Response for:
/// - [`SignTransaction`](crate::method::ClientMethod::SignTransaction)
/// - [`SignTransaction`](crate::method::SecretManagerMethod::SignTransaction)
SignedTransaction(PayloadDto),
/// Response for:
/// - [`SignatureUnlock`](crate::method::SecretManagerMethod::SignatureUnlock)
Expand Down Expand Up @@ -118,7 +115,6 @@ pub enum Response {
/// - [`GetIncludedBlock`](crate::method::ClientMethod::GetIncludedBlock)
Block(BlockDto),
/// Response for:
/// - [`BuildAndPostBlock`](crate::method::ClientMethod::BuildAndPostBlock)
/// - [`PostBlockPayload`](crate::method::ClientMethod::PostBlockPayload)
/// - [`Retry`](crate::method::ClientMethod::Retry)
BlockIdWithBlock(BlockId, BlockDto),
Expand Down Expand Up @@ -159,9 +155,6 @@ pub enum Response {
/// - [`RetryUntilIncluded`](crate::method::ClientMethod::RetryUntilIncluded)
RetryUntilIncludedSuccessful(Vec<(BlockId, BlockDto)>),
/// Response for:
/// - [`ConsolidateFunds`](crate::method::ClientMethod::ConsolidateFunds)
ConsolidatedFunds(Bech32Address),
/// Response for:
/// - [`FindInputs`](crate::method::ClientMethod::FindInputs)
Inputs(Vec<UtxoInputDto>),
/// Response for:
Expand Down
27 changes: 3 additions & 24 deletions bindings/core/tests/secrets_debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,15 @@
// SPDX-License-Identifier: Apache-2.0

use iota_sdk::client::secret::SecretManagerDto;
use iota_sdk_bindings_core::{ClientMethod, Response, UtilsMethod, WalletOptions};
use iota_sdk_bindings_core::{Response, UtilsMethod, WalletOptions};

#[test]
fn method_interface_secrets_debug() {
let client_method = ClientMethod::BuildAndPostBlock {
secret_manager: None,
options: None,
};
assert_eq!(
format!("{:?}", client_method),
"BuildAndPostBlock { secret_manager: None, options: None }"
);

#[cfg(feature = "ledger_nano")]
{
let client_method = ClientMethod::BuildAndPostBlock {
secret_manager: Some(SecretManagerDto::LedgerNano(false)),
options: None,
};
assert_eq!(
format!("{:?}", client_method),
"BuildAndPostBlock { secret_manager: Some(<omitted>), options: None }"
);
}

let client_method = UtilsMethod::MnemonicToHexSeed {
let utils_method = UtilsMethod::MnemonicToHexSeed {
mnemonic: "mnemonic".to_string(),
};
assert_eq!(
format!("{:?}", client_method),
format!("{:?}", utils_method),
"MnemonicToHexSeed { mnemonic: <omitted> }"
);

Expand Down
7 changes: 5 additions & 2 deletions bindings/nodejs/examples/client/06-simple-block.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2021-2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

import { Client, initLogger } from '@iota/sdk';
import { Client, initLogger, TaggedDataPayload, utf8ToHex } from '@iota/sdk';
require('dotenv').config({ path: '.env' });

// Run with command:
Expand All @@ -22,7 +22,10 @@ async function run() {

try {
// Create block with no payload
const blockIdAndBlock = await client.buildAndPostBlock();
// TODO: have a way in the bindings to send an empty block https://github.com/iotaledger/iota-sdk/issues/647
const blockIdAndBlock = await client.postBlockPayload(
new TaggedDataPayload(utf8ToHex('Hello'), utf8ToHex('Tangle')),
);
console.log('Block:', blockIdAndBlock, '\n');

console.log(
Expand Down
13 changes: 2 additions & 11 deletions bindings/nodejs/examples/client/08-data-block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
initLogger,
TaggedDataPayload,
utf8ToHex,
Utils,
} from '@iota/sdk';
require('dotenv').config({ path: '.env' });

Expand All @@ -26,18 +25,10 @@ async function run() {
nodes: [process.env.NODE_URL],
});

const options = {
tag: utf8ToHex('Hello'),
data: utf8ToHex('Tangle'),
};
try {
const mnemonic = Utils.generateMnemonic();
const secretManager = { mnemonic: mnemonic };

// Create block with tagged payload
const blockIdAndBlock = await client.buildAndPostBlock(
secretManager,
options,
const blockIdAndBlock = await client.postBlockPayload(
new TaggedDataPayload(utf8ToHex('Hello'), utf8ToHex('Tangle')),
);

console.log(
Expand Down
Loading

0 comments on commit 3614940

Please sign in to comment.