Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor!: remove NetworkInfo #1231

Merged
merged 6 commits into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/src/custom-transactions/transaction-builders.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

The Rust SDK simplifies the creation of **Create** and **Script** transactions through two handy builder structs `CreateTransactionBuilder`, `ScriptTransactionBuilder`, and the `TransactionBuilder` trait.

Calling `build()` on a builder will result in the corresponding `CreateTransaction` or `ScriptTransaction` that can be submitted to the network.
Calling `build(&provider)` on a builder will result in the corresponding `CreateTransaction` or `ScriptTransaction` that can be submitted to the network.

## Role of the transaction builders

Expand Down
12 changes: 3 additions & 9 deletions examples/cookbook/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,13 +189,8 @@ mod tests {
// ANCHOR_END: transfer_multiple_inout

// ANCHOR: transfer_multiple_transaction
let network_info = provider.network_info().await?;
let mut tb = ScriptTransactionBuilder::prepare_transfer(
inputs,
outputs,
TxPolicies::default(),
network_info,
);
let mut tb =
ScriptTransactionBuilder::prepare_transfer(inputs, outputs, TxPolicies::default());
wallet_1.sign_transaction(&mut tb);
let tx = tb.build(&provider).await?;

Expand Down Expand Up @@ -269,8 +264,7 @@ mod tests {
// ANCHOR_END: custom_tx_receiver

// ANCHOR: custom_tx
let network_info = provider.network_info().await?;
let tb = ScriptTransactionBuilder::new(network_info);
let tb = ScriptTransactionBuilder::default();
// ANCHOR_END: custom_tx

// ANCHOR: custom_tx_io_base
Expand Down
36 changes: 19 additions & 17 deletions packages/fuels-accounts/src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,13 +205,12 @@ pub trait Account: ViewOnlyAccount {
tx_policies: TxPolicies,
) -> Result<(TxId, Vec<Receipt>)> {
let provider = self.try_provider()?;
let network_info = provider.network_info().await?;

let inputs = self.get_asset_inputs_for_amount(asset_id, amount).await?;
let outputs = self.get_asset_outputs_for_amount(to, asset_id, amount);

let mut tx_builder =
ScriptTransactionBuilder::prepare_transfer(inputs, outputs, tx_policies, network_info);
ScriptTransactionBuilder::prepare_transfer(inputs, outputs, tx_policies);

self.add_witnessses(&mut tx_builder);
self.adjust_for_fee(&mut tx_builder, amount).await?;
Expand Down Expand Up @@ -244,7 +243,6 @@ pub trait Account: ViewOnlyAccount {
tx_policies: TxPolicies,
) -> std::result::Result<(String, Vec<Receipt>), Error> {
let provider = self.try_provider()?;
let network_info = provider.network_info().await?;

let zeroes = Bytes32::zeroed();
let plain_contract_id: ContractId = to.into();
Expand Down Expand Up @@ -272,7 +270,6 @@ pub trait Account: ViewOnlyAccount {
inputs,
outputs,
tx_policies,
network_info,
);

self.add_witnessses(&mut tb);
Expand All @@ -299,7 +296,6 @@ pub trait Account: ViewOnlyAccount {
tx_policies: TxPolicies,
) -> std::result::Result<(TxId, Nonce, Vec<Receipt>), Error> {
let provider = self.try_provider()?;
let network_info = provider.network_info().await?;

let inputs = self
.get_asset_inputs_for_amount(BASE_ASSET_ID, amount)
Expand All @@ -310,7 +306,6 @@ pub trait Account: ViewOnlyAccount {
amount,
inputs,
tx_policies,
network_info,
);

self.add_witnessses(&mut tb);
Expand All @@ -335,10 +330,9 @@ mod tests {
use std::str::FromStr;

use fuel_crypto::{Message, SecretKey};
use fuel_tx::{Address, Output, Transaction as FuelTransaction};
use fuel_tx::{Address, ConsensusParameters, Output, Transaction as FuelTransaction};
use fuels_core::types::{
transaction::Transaction,
transaction_builders::{DryRunner, NetworkInfo},
transaction::Transaction, transaction_builders::TransactionBuilderProvider,
};
use rand::{rngs::StdRng, RngCore, SeedableRng};

Expand Down Expand Up @@ -380,13 +374,21 @@ mod tests {
Ok(())
}

struct MockDryRunner;
struct MockDryRunner {
c_param: ConsensusParameters,
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl DryRunner for MockDryRunner {
impl TransactionBuilderProvider for MockDryRunner {
async fn dry_run_and_get_used_gas(&self, _: FuelTransaction, _: f32) -> Result<u64> {
Ok(0)
}
fn consensus_parameters(&self) -> &ConsensusParameters {
&self.c_param
}
async fn min_gas_price(&self) -> Result<u64> {
Ok(0)
}
}

#[tokio::test]
Expand All @@ -397,10 +399,6 @@ mod tests {
)?;
let wallet = WalletUnlocked::new_from_private_key(secret, None);

let network_info = NetworkInfo {
consensus_parameters: Default::default(),
min_gas_price: 0,
};
// Set up a transaction
let mut tb = {
let input_coin = Input::ResourceSigned {
Expand All @@ -423,14 +421,18 @@ mod tests {
vec![input_coin],
vec![output_coin],
Default::default(),
network_info,
)
};

// Sign the transaction
wallet.sign_transaction(&mut tb); // Add the private key to the transaction builder
// ANCHOR_END: sign_tx
let tx = tb.build(MockDryRunner).await?; // Resolve signatures and add corresponding witness indexes

let tx = tb
.build(&MockDryRunner {
c_param: ConsensusParameters::default(),
})
.await?; // Resolve signatures and add corresponding witness indexes

// Extract the signature from the tx witnesses
let bytes = <[u8; Signature::LEN]>::try_from(tx.witnesses().first().unwrap().as_ref())?;
Expand Down
38 changes: 16 additions & 22 deletions packages/fuels-accounts/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use fuels_core::{
message_proof::MessageProof,
node_info::NodeInfo,
transaction::Transaction,
transaction_builders::{DryRunner, NetworkInfo},
transaction_builders::TransactionBuilderProvider,
transaction_response::TransactionResponse,
tx_status::TxStatus,
},
Expand Down Expand Up @@ -167,17 +167,6 @@ pub struct Provider {
}

impl Provider {
pub fn new(url: impl AsRef<str>, consensus_parameters: ConsensusParameters) -> Result<Self> {
let client = RetryableClient::new(&url, Default::default())?;

Ok(Self {
client,
consensus_parameters,
#[cfg(feature = "coin-cache")]
cache: Default::default(),
})
}

pub async fn from(addr: impl Into<SocketAddr>) -> Result<Self> {
let addr = addr.into();
Self::connect(format!("http://{addr}")).await
Expand All @@ -191,6 +180,9 @@ impl Provider {
pub async fn connect(url: impl AsRef<str>) -> Result<Provider> {
let client = RetryableClient::new(&url, Default::default())?;
let consensus_parameters = client.chain_info().await?.consensus_parameters;
let node_info = client.node_info().await?.into();

Self::ensure_client_version_is_supported(&node_info)?;

Ok(Self {
client,
Expand Down Expand Up @@ -285,15 +277,6 @@ impl Provider {
&self.consensus_parameters
}

pub async fn network_info(&self) -> ProviderResult<NetworkInfo> {
let node_info = self.node_info().await?;
let chain_info = self.chain_info().await?;

Self::ensure_client_version_is_supported(&node_info)?;

Ok(NetworkInfo::new(node_info, chain_info))
}

fn ensure_client_version_is_supported(node_info: &NodeInfo) -> ProviderResult<()> {
let node_version = node_info.node_version.parse::<semver::Version>()?;
let VersionCompatibility {
Expand Down Expand Up @@ -733,10 +716,21 @@ impl Provider {
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
impl DryRunner for Provider {
impl TransactionBuilderProvider for Provider {
async fn dry_run_and_get_used_gas(&self, tx: FuelTransaction, tolerance: f32) -> Result<u64> {
let receipts = self.client.dry_run_opt(&tx, Some(false)).await?;
let gas_used = self.get_gas_used(&receipts);
Ok((gas_used as f64 * (1.0 + tolerance as f64)) as u64)
}

async fn min_gas_price(&self) -> Result<u64> {
self.node_info()
.await
.map(|ni| ni.min_gas_price)
.map_err(Into::into)
}

fn consensus_parameters(&self) -> &ConsensusParameters {
self.consensus_parameters()
}
}
Loading