From 6e9744626db2bd0f0e5a4248489a3ff3353c38a2 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Sun, 31 Mar 2024 23:04:43 +0200 Subject: [PATCH 01/29] support new version --- .github/workflows/ci.yml | 2 +- Cargo.toml | 26 ++-- examples/contracts/src/lib.rs | 10 +- examples/cookbook/src/lib.rs | 14 +- examples/types/src/lib.rs | 2 +- packages/fuels-accounts/src/provider.rs | 2 +- .../src/provider/supported_versions.rs | 2 +- .../src/types/transaction_builders.rs | 56 +++---- .../fuels-core/src/types/wrappers/block.rs | 10 +- .../fuels-core/src/types/wrappers/coin.rs | 8 +- .../src/types/wrappers/node_info.rs | 2 - .../src/types/wrappers/transaction.rs | 18 +-- packages/fuels-programs/src/call_utils.rs | 6 +- packages/fuels-test-helpers/src/accounts.rs | 20 +-- .../src/fuel_bin_service.rs | 110 ++------------ packages/fuels-test-helpers/src/lib.rs | 53 ++++--- packages/fuels-test-helpers/src/node_types.rs | 140 ++++++++++++++++-- packages/fuels-test-helpers/src/service.rs | 19 ++- packages/fuels/tests/contracts.rs | 18 +-- packages/fuels/tests/providers.rs | 25 ++-- packages/fuels/tests/scripts.rs | 7 +- 21 files changed, 303 insertions(+), 247 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5afa9162c..f6e09f79b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,7 @@ env: CARGO_TERM_COLOR: always DASEL_VERSION: https://github.com/TomWright/dasel/releases/download/v2.3.6/dasel_linux_amd64 RUSTFLAGS: "-D warnings" - FUEL_CORE_VERSION: 0.23.0 + FUEL_CORE_VERSION: 0.24.1 FUEL_CORE_PATCH_BRANCH: RUST_VERSION: 1.76.0 FORC_VERSION: 0.51.1 diff --git a/Cargo.toml b/Cargo.toml index 6f7315cd8..e03c014dc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -72,21 +72,21 @@ which = { version = "6.0.0", default-features = false } zeroize = "1.7.0" # Dependencies from the `fuel-core` repository: -fuel-core = { version = "0.23.0", default-features = false } -fuel-core-chain-config = { version = "0.23.0", default-features = false } -fuel-core-client = { version = "0.23.0", default-features = false } -fuel-core-poa = { version = "0.23.0", default-features = false } -fuel-core-services = { version = "0.23.0", default-features = false } -fuel-core-types = { version = "0.23.0", default-features = false } +fuel-core = { version = "0.24.1", default-features = false, features = ["test-helpers"] } +fuel-core-chain-config = { version = "0.24.1", default-features = false } +fuel-core-client = { version = "0.24.1", default-features = false } +fuel-core-poa = { version = "0.24.1", default-features = false } +fuel-core-services = { version = "0.24.1", default-features = false } +fuel-core-types = { version = "0.24.1", default-features = false } # Dependencies from the `fuel-vm` repository: -fuel-asm = { version = "0.47.1" } -fuel-crypto = { version = "0.47.1" } -fuel-merkle = { version = "0.47.1" } -fuel-storage = { version = "0.47.1" } -fuel-tx = { version = "0.47.1" } -fuel-types = { version = "0.47.1" } -fuel-vm = { version = "0.47.1" } +fuel-asm = { version = "0.48.0" } +fuel-crypto = { version = "0.48.0" } +fuel-merkle = { version = "0.48.0" } +fuel-storage = { version = "0.48.0" } +fuel-tx = { version = "0.48.0" } +fuel-types = { version = "0.48.0" } +fuel-vm = { version = "0.48.0" } # Workspace projects fuels = { version = "0.56.0", path = "./packages/fuels" } diff --git a/examples/contracts/src/lib.rs b/examples/contracts/src/lib.rs index 1e1b7d8e2..3099d9ea3 100644 --- a/examples/contracts/src/lib.rs +++ b/examples/contracts/src/lib.rs @@ -2,7 +2,8 @@ mod tests { use fuels::{ core::codec::{DecoderConfig, EncoderConfig}, - prelude::{Config, LoadConfiguration, StorageConfiguration}, + prelude::{LoadConfiguration, NodeConfig, StorageConfiguration}, + test_helpers::{ChainConfig, StateConfig}, types::{ errors::{transaction::Reason, Result}, Bits256, @@ -15,7 +16,12 @@ mod tests { use fuels::prelude::{FuelService, Provider}; // Run the fuel node. - let server = FuelService::start(Config::default()).await?; + let server = FuelService::start( + NodeConfig::default(), + ChainConfig::default(), + StateConfig::default(), + ) + .await?; // Create a client that will talk to the node created above. let client = Provider::from(server.bound_address()).await?; diff --git a/examples/cookbook/src/lib.rs b/examples/cookbook/src/lib.rs index 94f39707e..8988096c2 100644 --- a/examples/cookbook/src/lib.rs +++ b/examples/cookbook/src/lib.rs @@ -112,11 +112,9 @@ mod tests { .with_max_inputs(2); let fee_params = FeeParameters::default().with_gas_price_factor(10); - let consensus_parameters = ConsensusParameters { - tx_params, - fee_params, - ..Default::default() - }; + let mut consensus_parameters = ConsensusParameters::default(); + consensus_parameters.set_tx_params(tx_params); + consensus_parameters.set_fee_params(fee_params); let chain_config = ChainConfig { consensus_parameters, @@ -135,7 +133,7 @@ mod tests { // ANCHOR_END: custom_chain_coins // ANCHOR: custom_chain_provider - let node_config = Config::default(); + let node_config = NodeConfig::default(); let _provider = setup_test_provider(coins, vec![], Some(node_config), Some(chain_config)).await?; // ANCHOR_END: custom_chain_provider @@ -211,9 +209,9 @@ mod tests { use fuels::prelude::*; // ANCHOR: create_or_use_rocksdb - let provider_config = Config { + let provider_config = NodeConfig { database_type: DbType::RocksDb(Some(PathBuf::from("/tmp/.spider/db"))), - ..Config::default() + ..NodeConfig::default() }; // ANCHOR_END: create_or_use_rocksdb diff --git a/examples/types/src/lib.rs b/examples/types/src/lib.rs index 2fcf44745..c4b2f65e4 100644 --- a/examples/types/src/lib.rs +++ b/examples/types/src/lib.rs @@ -3,7 +3,7 @@ mod tests { use std::str::FromStr; #[cfg(feature = "fuel-core-lib")] - use fuels::prelude::Config; + use fuels::prelude::NodeConfig; use fuels::{ prelude::Result, types::{Bits256, EvmAddress, Identity}, diff --git a/packages/fuels-accounts/src/provider.rs b/packages/fuels-accounts/src/provider.rs index 19c09f615..9eb80128a 100644 --- a/packages/fuels-accounts/src/provider.rs +++ b/packages/fuels-accounts/src/provider.rs @@ -296,7 +296,7 @@ impl Provider { } pub fn chain_id(&self) -> ChainId { - self.consensus_parameters.chain_id + self.consensus_parameters.chain_id() } pub async fn node_info(&self) -> Result { diff --git a/packages/fuels-accounts/src/provider/supported_versions.rs b/packages/fuels-accounts/src/provider/supported_versions.rs index 478b6e894..e238d1fcc 100644 --- a/packages/fuels-accounts/src/provider/supported_versions.rs +++ b/packages/fuels-accounts/src/provider/supported_versions.rs @@ -1,7 +1,7 @@ use semver::Version; fn get_supported_fuel_core_version() -> Version { - "0.23.0".parse().expect("is valid version") + "0.24.1".parse().expect("is valid version") } #[derive(Debug, PartialEq, Eq)] diff --git a/packages/fuels-core/src/types/transaction_builders.rs b/packages/fuels-core/src/types/transaction_builders.rs index d1da0cd5e..d5102189d 100644 --- a/packages/fuels-core/src/types/transaction_builders.rs +++ b/packages/fuels-core/src/types/transaction_builders.rs @@ -10,12 +10,11 @@ use async_trait::async_trait; use fuel_asm::{op, GTFArgs, RegId}; use fuel_crypto::{Message as CryptoMessage, Signature}; use fuel_tx::{ - field::{Inputs, Policies as PoliciesField, WitnessLimit, Witnesses}, + field::{Inputs, Policies as PoliciesField, ScriptGasLimit, WitnessLimit, Witnesses}, input::coin::{CoinPredicate, CoinSigned}, policies::{Policies, PolicyType}, - Buildable, Chargeable, ConsensusParameters, Create, Input as FuelInput, Output, Script, - StorageSlot, Transaction as FuelTransaction, TransactionFee, TxPointer, UniqueIdentifier, - Witness, + Chargeable, ConsensusParameters, Create, Input as FuelInput, Output, Script, StorageSlot, + Transaction as FuelTransaction, TransactionFee, TxPointer, UniqueIdentifier, Witness, }; use fuel_types::{bytes::padded_len_usize, canonical::Serialize, Bytes32, ChainId, Salt}; use itertools::Itertools; @@ -187,8 +186,8 @@ macro_rules! impl_tx_trait { } Ok(TransactionFee::checked_from_tx( - &consensus_parameters.gas_costs, - &consensus_parameters.fee_params, + &consensus_parameters.gas_costs(), + &consensus_parameters.fee_params(), &tx.tx, provider .estimate_gas_price(self.gas_price_estimation_block_horizon) @@ -288,7 +287,7 @@ macro_rules! impl_tx_trait { .any(|input| matches!(input, Input::ResourcePredicate { .. })) } - fn num_witnesses(&self) -> Result { + fn num_witnesses(&self) -> Result { let num_witnesses = self.witnesses().len(); if num_witnesses + self.unresolved_signers.len() > 256 { @@ -298,7 +297,7 @@ macro_rules! impl_tx_trait { )); } - Ok(num_witnesses as u8) + Ok(num_witnesses as u16) } fn calculate_witnesses_size(&self) -> Option { @@ -318,7 +317,7 @@ macro_rules! impl_tx_trait { let consensus_parameters = provider.consensus_parameters(); let tx_fee = TransactionFee::checked_from_tx( - &consensus_parameters.gas_costs, + &consensus_parameters.gas_costs(), consensus_parameters.fee_params(), tx, gas_price, @@ -362,7 +361,7 @@ pub struct ScriptTransactionBuilder { #[derive(Default)] pub struct CreateTransactionBuilder { pub bytecode_length: u64, - pub bytecode_witness_index: u8, + pub bytecode_witness_index: u16, pub storage_slots: Vec, pub inputs: Vec, pub outputs: Vec, @@ -398,7 +397,7 @@ impl ScriptTransactionBuilder { // However, the node will check if the right number of witnesses is present. // This function will create witnesses from a default `Signature` such that the total length matches the expected one. // Using a `Signature` ensures that the calculated fee includes the fee generated by the witnesses. - fn create_dry_run_witnesses(&self, num_witnesses: u8) -> Vec { + fn create_dry_run_witnesses(&self, num_witnesses: u16) -> Vec { let unresolved_witnesses_len = self.unresolved_witness_indexes.owner_to_idx_offset.len(); let witness: Witness = Signature::default().as_ref().into(); repeat(witness) @@ -450,7 +449,7 @@ impl ScriptTransactionBuilder { // Get `max_gas` used by everything except the script execution. Add `1` because of rounding. let max_gas = tx.max_gas(consensus_params.gas_costs(), consensus_params.fee_params()) + 1; // Increase `script_gas_limit` to the maximum allowed value. - tx.set_script_gas_limit(consensus_params.tx_params().max_gas_per_tx - max_gas); + *tx.script_gas_limit_mut() = consensus_params.tx_params().max_gas_per_tx() - max_gas; let gas_used = provider .dry_run_and_get_used_gas(tx.clone().into(), tolerance) @@ -463,7 +462,7 @@ impl ScriptTransactionBuilder { tx.set_witness_limit(tx.witness_limit() - WITNESS_STATIC_SIZE as u64); } - tx.set_script_gas_limit(gas_used); + *tx.script_gas_limit_mut() = gas_used; Ok(()) } @@ -490,11 +489,11 @@ impl ScriptTransactionBuilder { ); if has_no_code { - tx.set_script_gas_limit(0); + *tx.script_gas_limit_mut() = 0; // Use the user defined value even if it makes the transaction revert. } else if let Some(gas_limit) = self.tx_policies.script_gas_limit() { - tx.set_script_gas_limit(gas_limit); + *tx.script_gas_limit_mut() = gas_limit; // If the `script_gas_limit` was not set by the user, // dry-run the tx to get the `gas_used` @@ -511,7 +510,7 @@ impl ScriptTransactionBuilder { .await?; let missing_witnesses = generate_missing_witnesses( - tx.id(&provider.consensus_parameters().chain_id), + tx.id(&provider.consensus_parameters().chain_id()), &self.unresolved_signers, ) .await?; @@ -660,7 +659,7 @@ impl CreateTransactionBuilder { }; let tx = self - .resolve_fuel_tx(base_offset, &consensus_parameters.chain_id, &provider) + .resolve_fuel_tx(base_offset, &consensus_parameters.chain_id(), &provider) .await?; Ok(CreateTransaction { @@ -715,7 +714,7 @@ impl CreateTransactionBuilder { self } - pub fn with_bytecode_witness_index(mut self, bytecode_witness_index: u8) -> Self { + pub fn with_bytecode_witness_index(mut self, bytecode_witness_index: u16) -> Self { self.bytecode_witness_index = bytecode_witness_index; self } @@ -776,7 +775,7 @@ impl CreateTransactionBuilder { fn resolve_fuel_inputs( inputs: Vec, mut data_offset: usize, - num_witnesses: u8, + num_witnesses: u16, unresolved_witness_indexes: &UnresolvedWitnessIndexes, ) -> Result> { inputs @@ -816,7 +815,7 @@ fn resolve_fuel_inputs( fn resolve_signed_resource( resource: CoinType, data_offset: &mut usize, - num_witnesses: u8, + num_witnesses: u16, unresolved_witness_indexes: &UnresolvedWitnessIndexes, ) -> Result { match resource { @@ -832,7 +831,7 @@ fn resolve_signed_resource( "signature missing for coin with owner: `{owner:?}`" )) .map(|witness_idx_offset| { - create_coin_input(coin, num_witnesses + *witness_idx_offset as u8) + create_coin_input(coin, num_witnesses + *witness_idx_offset as u16) }) } CoinType::Message(message) => { @@ -847,7 +846,7 @@ fn resolve_signed_resource( "signature missing for message with recipient: `{recipient:?}`" )) .map(|witness_idx_offset| { - create_coin_message_input(message, num_witnesses + *witness_idx_offset as u8) + create_coin_message_input(message, num_witnesses + *witness_idx_offset as u16) }) } } @@ -880,7 +879,7 @@ fn resolve_predicate_resource( } } -pub fn create_coin_input(coin: Coin, witness_index: u8) -> FuelInput { +pub fn create_coin_input(coin: Coin, witness_index: u16) -> FuelInput { FuelInput::coin_signed( coin.utxo_id, coin.owner.into(), @@ -891,7 +890,7 @@ pub fn create_coin_input(coin: Coin, witness_index: u8) -> FuelInput { ) } -pub fn create_coin_message_input(message: Message, witness_index: u8) -> FuelInput { +pub fn create_coin_message_input(message: Message, witness_index: u16) -> FuelInput { if message.data.is_empty() { FuelInput::message_coin_signed( message.sender.into(), @@ -1064,11 +1063,18 @@ mod tests { repeat_with(Witness::default).take(num_witnesses).collect() } - #[derive(Default)] struct MockDryRunner { c_param: ConsensusParameters, } + impl Default for MockDryRunner { + fn default() -> Self { + Self { + c_param: ConsensusParameters::standard(), + } + } + } + #[cfg_attr(target_arch = "wasm32", async_trait(?Send))] #[cfg_attr(not(target_arch = "wasm32"), async_trait)] impl DryRunner for MockDryRunner { diff --git a/packages/fuels-core/src/types/wrappers/block.rs b/packages/fuels-core/src/types/wrappers/block.rs index ee97c4002..1877c8ca1 100644 --- a/packages/fuels-core/src/types/wrappers/block.rs +++ b/packages/fuels-core/src/types/wrappers/block.rs @@ -13,7 +13,10 @@ pub struct Header { pub transactions_count: u64, pub message_receipt_count: u64, pub transactions_root: Bytes32, - pub message_receipt_root: Bytes32, + pub message_outbox_root: Bytes32, + pub event_inbox_root: Bytes32, + pub consensus_parameters_version: u32, + pub state_transition_bytecode_version: u32, pub height: u32, pub prev_root: Bytes32, pub time: Option>, @@ -30,7 +33,10 @@ impl From for Header { transactions_count: client_header.transactions_count, message_receipt_count: client_header.message_receipt_count, transactions_root: client_header.transactions_root, - message_receipt_root: client_header.message_receipt_root, + message_outbox_root: client_header.message_outbox_root, + event_inbox_root: client_header.event_inbox_root, + consensus_parameters_version: client_header.consensus_parameters_version, + state_transition_bytecode_version: client_header.state_transition_bytecode_version, height: client_header.height, prev_root: client_header.prev_root, time, diff --git a/packages/fuels-core/src/types/wrappers/coin.rs b/packages/fuels-core/src/types/wrappers/coin.rs index 2b8093a9b..c1daeed1a 100644 --- a/packages/fuels-core/src/types/wrappers/coin.rs +++ b/packages/fuels-core/src/types/wrappers/coin.rs @@ -41,10 +41,10 @@ impl From for Coin { impl From for CoinConfig { fn from(coin: Coin) -> CoinConfig { Self { - tx_id: Some(*coin.utxo_id.tx_id()), - output_index: Some(coin.utxo_id.output_index()), - tx_pointer_block_height: Some(coin.block_created.into()), - tx_pointer_tx_idx: None, + tx_id: *coin.utxo_id.tx_id(), + output_index: coin.utxo_id.output_index(), + tx_pointer_block_height: coin.block_created.into(), + tx_pointer_tx_idx: Default::default(), owner: coin.owner.into(), amount: coin.amount, asset_id: coin.asset_id, diff --git a/packages/fuels-core/src/types/wrappers/node_info.rs b/packages/fuels-core/src/types/wrappers/node_info.rs index 9a4bb8613..e79929787 100644 --- a/packages/fuels-core/src/types/wrappers/node_info.rs +++ b/packages/fuels-core/src/types/wrappers/node_info.rs @@ -6,7 +6,6 @@ use fuel_core_client::client::types::node_info::NodeInfo as ClientNodeInfo; pub struct NodeInfo { pub utxo_validation: bool, pub vm_backtrace: bool, - pub min_gas_price: u64, pub max_tx: u64, pub max_depth: u64, pub node_version: String, @@ -17,7 +16,6 @@ impl From for NodeInfo { Self { utxo_validation: client_node_info.utxo_validation, vm_backtrace: client_node_info.vm_backtrace, - min_gas_price: client_node_info.min_gas_price, max_tx: client_node_info.max_tx, max_depth: client_node_info.max_depth, node_version: client_node_info.node_version, diff --git a/packages/fuels-core/src/types/wrappers/transaction.rs b/packages/fuels-core/src/types/wrappers/transaction.rs index 62d0f9c19..aafcc9a05 100644 --- a/packages/fuels-core/src/types/wrappers/transaction.rs +++ b/packages/fuels-core/src/types/wrappers/transaction.rs @@ -13,9 +13,9 @@ use fuel_tx::{ MessageCoinPredicate, MessageCoinSigned, MessageDataPredicate, MessageDataSigned, }, }, - Buildable, Bytes32, Cacheable, Chargeable, ConsensusParameters, Create, FormatValidityChecks, - Input, Mint, Output, Salt as FuelSalt, Script, StorageSlot, Transaction as FuelTransaction, - TransactionFee, UniqueIdentifier, Witness, + Bytes32, Cacheable, Chargeable, ConsensusParameters, Create, FormatValidityChecks, Input, Mint, + Output, Salt as FuelSalt, Script, StorageSlot, Transaction as FuelTransaction, TransactionFee, + UniqueIdentifier, Witness, }; use fuel_types::{bytes::padded_len_usize, AssetId, ChainId}; use fuel_vm::checked_transaction::{ @@ -177,7 +177,7 @@ impl TxPolicies { } } -use fuel_tx::field::{BytecodeLength, BytecodeWitnessIndex, Salt, StorageSlots}; +use fuel_tx::field::{BytecodeWitnessIndex, Salt, StorageSlots}; use crate::types::coin_type_id::CoinTypeId; @@ -371,7 +371,7 @@ macro_rules! impl_tx_wrapper { gas_price: u64, ) -> Option { TransactionFee::checked_from_tx( - &consensus_parameters.gas_costs, + &consensus_parameters.gas_costs(), consensus_parameters.fee_params(), &self.tx, gas_price, @@ -495,17 +495,13 @@ impl CreateTransaction { self.tx.salt() } - pub fn bytecode_witness_index(&self) -> u8 { + pub fn bytecode_witness_index(&self) -> u16 { *self.tx.bytecode_witness_index() } pub fn storage_slots(&self) -> &Vec { self.tx.storage_slots() } - - pub fn bytecode_length(&self) -> u64 { - *self.tx.bytecode_length() - } } impl EstimablePredicates for ScriptTransaction { @@ -551,7 +547,7 @@ impl ScriptTransaction { } pub fn with_gas_limit(mut self, gas_limit: u64) -> Self { - self.tx.set_script_gas_limit(gas_limit); + *self.tx.script_gas_limit_mut() = gas_limit; self } } diff --git a/packages/fuels-programs/src/call_utils.rs b/packages/fuels-programs/src/call_utils.rs index 9e311d879..2d4aa7e96 100644 --- a/packages/fuels-programs/src/call_utils.rs +++ b/packages/fuels-programs/src/call_utils.rs @@ -521,7 +521,7 @@ fn generate_asset_change_outputs( pub(crate) fn generate_contract_outputs(num_of_contracts: usize) -> Vec { (0..num_of_contracts) - .map(|idx| Output::contract(idx as u8, Bytes32::zeroed(), Bytes32::zeroed())) + .map(|idx| Output::contract(idx as u16, Bytes32::zeroed(), Bytes32::zeroed())) .collect() } @@ -531,7 +531,7 @@ pub(crate) fn generate_contract_inputs(contract_ids: HashSet) -> Vec .enumerate() .map(|(idx, contract_id)| { Input::contract( - UtxoId::new(Bytes32::zeroed(), idx as u8), + UtxoId::new(Bytes32::zeroed(), idx as u16), Bytes32::zeroed(), Bytes32::zeroed(), TxPointer::default(), @@ -811,7 +811,7 @@ mod test { tx_pointer, contract_id, } => { - assert_eq!(utxo_id, UtxoId::new(Bytes32::zeroed(), index as u8)); + assert_eq!(utxo_id, UtxoId::new(Bytes32::zeroed(), index as u16)); assert_eq!(balance_root, Bytes32::zeroed()); assert_eq!(state_root, Bytes32::zeroed()); assert_eq!(tx_pointer, TxPointer::default()); diff --git a/packages/fuels-test-helpers/src/accounts.rs b/packages/fuels-test-helpers/src/accounts.rs index e601c7d26..530bf6b16 100644 --- a/packages/fuels-test-helpers/src/accounts.rs +++ b/packages/fuels-test-helpers/src/accounts.rs @@ -5,7 +5,7 @@ use fuels_accounts::wallet::WalletUnlocked; use fuels_core::types::errors::Result; use crate::{ - node_types::{ChainConfig, Config}, + node_types::{ChainConfig, NodeConfig}, setup_custom_assets_coins, setup_test_provider, wallets_config::*, }; @@ -52,7 +52,7 @@ pub async fn launch_provider_and_get_wallet() -> Result { /// ``` pub async fn launch_custom_provider_and_get_wallets( wallet_config: WalletsConfig, - provider_config: Option, + provider_config: Option, chain_config: Option, ) -> Result> { const SIZE_SECRET_KEY: usize = size_of::(); @@ -195,15 +195,17 @@ mod tests { #[tokio::test] async fn generated_wallets_with_custom_chain_config() -> Result<()> { - let consensus_parameters = ConsensusParameters { - tx_params: TxParameters::default().with_max_gas_per_tx(10_000_000_000), - ..Default::default() - }; + let mut consensus_parameters = ConsensusParameters::default(); let block_gas_limit = 10_000_000_000; + consensus_parameters.set_block_gas_limit(block_gas_limit); + + let max_gas_per_tx = 10_000_000_000; + let tx_params = TxParameters::default().with_max_gas_per_tx(max_gas_per_tx); + consensus_parameters.set_tx_params(tx_params); + let chain_config = ChainConfig { consensus_parameters, - block_gas_limit, ..ChainConfig::default() }; @@ -225,8 +227,8 @@ mod tests { .try_provider()? .consensus_parameters() .tx_params() - .max_gas_per_tx, - block_gas_limit + .max_gas_per_tx(), + max_gas_per_tx ); assert_eq!( wallet.get_coins(AssetId::default()).await?.len() as u64, diff --git a/packages/fuels-test-helpers/src/fuel_bin_service.rs b/packages/fuels-test-helpers/src/fuel_bin_service.rs index 84cc91e80..6624cb05c 100644 --- a/packages/fuels-test-helpers/src/fuel_bin_service.rs +++ b/packages/fuels-test-helpers/src/fuel_bin_service.rs @@ -1,6 +1,5 @@ use std::{ net::{IpAddr, SocketAddr}, - path::PathBuf, time::Duration, }; @@ -11,91 +10,9 @@ use fuels_core::{ types::errors::{Error, Result as FuelResult}, }; use portpicker::{is_free, pick_unused_port}; -use tempfile::NamedTempFile; use tokio::{process::Command, spawn, task::JoinHandle, time::sleep}; -use crate::node_types::{Config, DbType, Trigger}; - -#[derive(Debug)] -struct ExtendedConfig { - config: Config, - config_file: NamedTempFile, -} - -impl ExtendedConfig { - pub fn config_to_args_vec(&mut self) -> FuelResult> { - self.write_temp_chain_config_file()?; - - let port = self.config.addr.port().to_string(); - let mut args = vec![ - "run".to_string(), // `fuel-core` is now run with `fuel-core run` - "--ip".to_string(), - "127.0.0.1".to_string(), - "--port".to_string(), - port, - "--chain".to_string(), - self.config_file - .path() - .to_str() - .expect("Failed to find config file") - .to_string(), - ]; - - args.push("--db-type".to_string()); - match &self.config.database_type { - DbType::InMemory => args.push("in-memory".to_string()), - DbType::RocksDb(path_to_db) => { - args.push("rocks-db".to_string()); - let path = path_to_db.as_ref().cloned().unwrap_or_else(|| { - PathBuf::from(std::env::var("HOME").expect("HOME env var missing")) - .join(".fuel/db") - }); - args.push("--db-path".to_string()); - args.push(path.to_string_lossy().to_string()); - } - } - - if let Some(cache_size) = self.config.max_database_cache_size { - args.push("--max-database-cache-size".to_string()); - args.push(cache_size.to_string()); - } - - match self.config.block_production { - Trigger::Instant => { - args.push("--poa-instant=true".to_string()); - } - Trigger::Never => { - args.push("--poa-instant=false".to_string()); - } - Trigger::Interval { block_time } => { - args.push(format!( - "--poa-interval-period={}ms", - block_time.as_millis() - )); - } - }; - - args.extend( - [ - (self.config.vm_backtrace, "--vm-backtrace"), - (self.config.utxo_validation, "--utxo-validation"), - (self.config.debug, "--debug"), - ] - .into_iter() - .filter(|(flag, _)| *flag) - .map(|(_, arg)| arg.to_string()), - ); - - Ok(args) - } - - pub fn write_temp_chain_config_file(&mut self) -> FuelResult<()> { - Ok(serde_json::to_writer( - &mut self.config_file, - &self.config.chain_conf, - )?) - } -} +use crate::{node_types::NodeConfig, ExtendedConfig}; pub struct FuelService { pub bound_address: SocketAddr, @@ -103,26 +20,26 @@ pub struct FuelService { } impl FuelService { - pub async fn new_node(config: Config) -> FuelResult { - let requested_port = config.addr.port(); + pub async fn new_node(config: ExtendedConfig) -> FuelResult { + let requested_port = config.node_config.addr.port(); let bound_address = match requested_port { 0 => get_socket_address()?, - _ if is_free(requested_port) => config.addr, + _ if is_free(requested_port) => config.node_config.addr, _ => return Err(Error::IO(std::io::ErrorKind::AddrInUse.into())), }; - let config = Config { + let node_config = NodeConfig { addr: bound_address, - ..config + ..config.node_config }; let extended_config = ExtendedConfig { - config, - config_file: NamedTempFile::new()?, + node_config, + ..config }; - let addr = extended_config.config.addr; + let addr = extended_config.node_config.addr; let handle = run_node(extended_config).await?; server_health_check(addr).await?; @@ -165,8 +82,9 @@ fn get_socket_address() -> FuelResult { Ok(SocketAddr::new(address, free_port)) } -async fn run_node(mut extended_config: ExtendedConfig) -> FuelResult> { - let args = extended_config.config_to_args_vec()?; +async fn run_node(extended_config: ExtendedConfig) -> FuelResult> { + let args = extended_config.args_vec()?; + let tempdir = extended_config.write_temp_snapshot_files()?; let binary_name = "fuel-core"; @@ -189,8 +107,8 @@ async fn run_node(mut extended_config: ExtendedConfig) -> FuelResult, messages: Vec, - node_config: Option, + node_config: Option, chain_config: Option, ) -> Result { + let node_config = node_config.unwrap_or_default(); + let chain_config = chain_config.unwrap_or_else(ChainConfig::local_testnet); + let coin_configs = into_coin_configs(coins); let message_configs = into_message_configs(messages); - let mut chain_conf = chain_config.unwrap_or_else(ChainConfig::local_testnet); - - chain_conf.initial_state = Some(StateConfig { - coins: Some(coin_configs), - contracts: None, - messages: Some(message_configs), - ..StateConfig::default() - }); - let mut config = node_config.unwrap_or_default(); - config.chain_conf = chain_conf; + let state_config = StateConfig { + coins: coin_configs, + messages: message_configs, + ..StateConfig::local_testnet() + }; - let srv = FuelService::start(config).await?; + let srv = FuelService::start(node_config, chain_config, state_config).await?; let address = srv.bound_address(); @@ -292,9 +289,9 @@ mod tests { #[tokio::test] async fn test_setup_test_provider_custom_config() -> Result<()> { let socket = SocketAddr::new(Ipv4Addr::new(127, 0, 0, 1).into(), 4000); - let config = Config { + let config = NodeConfig { addr: socket, - ..Config::default() + ..NodeConfig::default() }; let provider = setup_test_provider(vec![], vec![], Some(config.clone()), None).await?; @@ -317,12 +314,10 @@ mod tests { let fee_params = FeeParameters::default().with_gas_per_byte(2); let contract_params = ContractParameters::default().with_max_storage_slots(83); - let consensus_parameters = ConsensusParameters { - tx_params, - fee_params, - contract_params, - ..Default::default() - }; + let mut consensus_parameters = ConsensusParameters::default(); + consensus_parameters.set_tx_params(tx_params); + consensus_parameters.set_fee_params(fee_params); + consensus_parameters.set_contract_params(contract_params); let chain_config = ChainConfig { consensus_parameters: consensus_parameters.clone(), @@ -342,11 +337,13 @@ mod tests { let max_inputs = 123; let gas_per_byte = 456; - let consensus_parameters = ConsensusParameters { - tx_params: TxParameters::default().with_max_inputs(max_inputs), - fee_params: FeeParameters::default().with_gas_per_byte(gas_per_byte), - ..Default::default() - }; + let mut consensus_parameters = ConsensusParameters::default(); + + let tx_params = TxParameters::default().with_max_inputs(max_inputs); + consensus_parameters.set_tx_params(tx_params); + + let fee_params = FeeParameters::default().with_gas_per_byte(gas_per_byte); + consensus_parameters.set_fee_params(fee_params); let chain_name = "fuel-0".to_string(); let chain_config = ChainConfig { @@ -361,11 +358,11 @@ mod tests { assert_eq!(chain_info.name, chain_name); assert_eq!( - chain_info.consensus_parameters.tx_params().max_inputs, + chain_info.consensus_parameters.tx_params().max_inputs(), max_inputs ); assert_eq!( - chain_info.consensus_parameters.fee_params().gas_per_byte, + chain_info.consensus_parameters.fee_params().gas_per_byte(), gas_per_byte ); Ok(()) diff --git a/packages/fuels-test-helpers/src/node_types.rs b/packages/fuels-test-helpers/src/node_types.rs index 6297f8353..d141821fc 100644 --- a/packages/fuels-test-helpers/src/node_types.rs +++ b/packages/fuels-test-helpers/src/node_types.rs @@ -5,10 +5,13 @@ use std::{ }; pub use fuel_core_chain_config::ChainConfig; -use fuel_types::{BlockHeight, Word}; -use fuels_core::constants::WORD_SIZE; +pub use fuel_core_chain_config::StateConfig; +use fuel_tx::Word; +use fuel_types::{bytes::WORD_SIZE, BlockHeight}; +use fuels_core::types::errors::Result; use serde::{de::Error as SerdeError, Deserializer, Serializer}; use serde_with::{DeserializeAs, SerializeAs}; +use tempfile::TempDir; const MAX_DATABASE_CACHE_SIZE: usize = 10 * 1024 * 1024; @@ -47,7 +50,7 @@ impl From for fuel_core::service::DbType { } #[derive(Clone, Debug)] -pub struct Config { +pub struct NodeConfig { pub addr: SocketAddr, pub max_database_cache_size: Option, pub database_type: DbType, @@ -56,10 +59,9 @@ pub struct Config { pub block_production: Trigger, pub vm_backtrace: bool, pub silent: bool, - pub chain_conf: ChainConfig, } -impl Default for Config { +impl Default for NodeConfig { fn default() -> Self { Self { addr: SocketAddr::new(Ipv4Addr::new(127, 0, 0, 1).into(), 0), @@ -70,14 +72,128 @@ impl Default for Config { block_production: Trigger::Instant, vm_backtrace: false, silent: true, - chain_conf: ChainConfig::local_testnet(), + } + } +} + +#[derive(Debug)] +pub(crate) struct ExtendedConfig { + pub node_config: NodeConfig, + pub chain_config: ChainConfig, + pub state_config: StateConfig, + pub snapshot_dir: TempDir, +} + +impl ExtendedConfig { + #[cfg(not(feature = "fuel-core-lib"))] + pub fn args_vec(&self) -> Result> { + let port = self.node_config.addr.port().to_string(); + let mut args = vec![ + "run".to_string(), // `fuel-core` is now run with `fuel-core run` + "--ip".to_string(), + "127.0.0.1".to_string(), + "--port".to_string(), + port, + "--snapshot".to_string(), + self.snapshot_dir + .path() + .to_str() + .expect("Failed to find config file") + .to_string(), + ]; + + args.push("--db-type".to_string()); + match &self.node_config.database_type { + DbType::InMemory => args.push("in-memory".to_string()), + DbType::RocksDb(path_to_db) => { + args.push("rocks-db".to_string()); + let path = path_to_db.as_ref().cloned().unwrap_or_else(|| { + PathBuf::from(std::env::var("HOME").expect("HOME env var missing")) + .join(".fuel/db") + }); + args.push("--db-path".to_string()); + args.push(path.to_string_lossy().to_string()); + } + } + + if let Some(cache_size) = self.node_config.max_database_cache_size { + args.push("--max-database-cache-size".to_string()); + args.push(cache_size.to_string()); + } + + match self.node_config.block_production { + Trigger::Instant => { + args.push("--poa-instant=true".to_string()); + } + Trigger::Never => { + args.push("--poa-instant=false".to_string()); + } + Trigger::Interval { block_time } => { + args.push(format!( + "--poa-interval-period={}ms", + block_time.as_millis() + )); + } + }; + + args.extend( + [ + (self.node_config.vm_backtrace, "--vm-backtrace"), + (self.node_config.utxo_validation, "--utxo-validation"), + (self.node_config.debug, "--debug"), + ] + .into_iter() + .filter(|(flag, _)| *flag) + .map(|(_, arg)| arg.to_string()), + ); + + Ok(args) + } + + #[cfg(not(feature = "fuel-core-lib"))] + pub fn write_temp_snapshot_files(self) -> Result { + use fuel_core_chain_config::SnapshotWriter; + use fuels_core::error; + + let mut writer = SnapshotWriter::json(self.snapshot_dir.path()); + writer + .write_chain_config(&self.chain_config) + .map_err(|e| error!(Other, "could not write chain config: {}", e))?; + writer + .write_state_config(self.state_config) + .map_err(|e| error!(Other, "could not write state config: {}", e))?; + + Ok(self.snapshot_dir) + } + + #[cfg(feature = "fuel-core-lib")] + fn service_config(self) -> fuel_core::Config { + use fuel_core_chain_config::SnapshotReader; + + let snapshot_reader = SnapshotReader::new_in_memory(self.chain_config, self.state_config); + + Self { + addr: self.node_config.addr, + max_database_cache_size: self + .node_config + .max_database_cache_size + .unwrap_or(MAX_DATABASE_CACHE_SIZE), + database_path: match &self.node_config.database_type { + DbType::InMemory => Default::default(), + DbType::RocksDb(path) => path.clone().unwrap_or_default(), + }, + database_type: self.node_config.database_type.into(), + utxo_validation: self.node_config.utxo_validation, + debug: self.node_config.debug, + block_production: self.node_config.block_production.into(), + ..fuel_core::service::Config::local_node() } } } #[cfg(feature = "fuel-core-lib")] -impl From for fuel_core::service::Config { - fn from(value: Config) -> Self { +impl From for fuel_core::service::Config { + fn from(value: NodeConfig) -> Self { Self { addr: value.addr, max_database_cache_size: value @@ -129,7 +245,7 @@ pub(crate) mod serde_hex { pub(crate) struct HexNumber; impl SerializeAs for HexNumber { - fn serialize_as(value: &u64, serializer: S) -> Result + fn serialize_as(value: &u64, serializer: S) -> std::result::Result where S: Serializer, { @@ -139,7 +255,7 @@ impl SerializeAs for HexNumber { } impl<'de> DeserializeAs<'de, Word> for HexNumber { - fn deserialize_as(deserializer: D) -> Result + fn deserialize_as(deserializer: D) -> std::result::Result where D: Deserializer<'de>, { @@ -164,7 +280,7 @@ impl<'de> DeserializeAs<'de, Word> for HexNumber { } impl SerializeAs for HexNumber { - fn serialize_as(value: &BlockHeight, serializer: S) -> Result + fn serialize_as(value: &BlockHeight, serializer: S) -> std::result::Result where S: Serializer, { @@ -174,7 +290,7 @@ impl SerializeAs for HexNumber { } impl<'de> DeserializeAs<'de, BlockHeight> for HexNumber { - fn deserialize_as(deserializer: D) -> Result + fn deserialize_as(deserializer: D) -> std::result::Result where D: Deserializer<'de>, { diff --git a/packages/fuels-test-helpers/src/service.rs b/packages/fuels-test-helpers/src/service.rs index c6fcb66c0..29373962c 100644 --- a/packages/fuels-test-helpers/src/service.rs +++ b/packages/fuels-test-helpers/src/service.rs @@ -2,14 +2,16 @@ use std::net::SocketAddr; #[cfg(feature = "fuel-core-lib")] use fuel_core::service::FuelService as CoreFuelService; +use fuel_core_chain_config::{ChainConfig, StateConfig}; #[cfg(feature = "fuel-core-lib")] use fuel_core_services::Service; use fuel_core_services::State; use fuels_core::types::errors::{error, Result}; +use tempfile::tempdir; #[cfg(not(feature = "fuel-core-lib"))] use crate::fuel_bin_service::FuelService as BinFuelService; -use crate::Config; +use crate::{ExtendedConfig, NodeConfig}; pub struct FuelService { #[cfg(feature = "fuel-core-lib")] @@ -20,14 +22,25 @@ pub struct FuelService { } impl FuelService { - pub async fn start(config: Config) -> Result { + pub async fn start( + node_config: NodeConfig, + chain_config: ChainConfig, + state_config: StateConfig, + ) -> Result { + let extended_config = ExtendedConfig { + node_config, + chain_config, + state_config, + snapshot_dir: tempdir()?, + }; + #[cfg(feature = "fuel-core-lib")] let service = CoreFuelService::new_node(config.into()) .await .map_err(|err| error!(Other, "{err}"))?; #[cfg(not(feature = "fuel-core-lib"))] - let service = BinFuelService::new_node(config).await?; + let service = BinFuelService::new_node(extended_config).await?; let bound_address = service.bound_address; diff --git a/packages/fuels/tests/contracts.rs b/packages/fuels/tests/contracts.rs index e9f17dfff..c9019e95c 100644 --- a/packages/fuels/tests/contracts.rs +++ b/packages/fuels/tests/contracts.rs @@ -274,7 +274,7 @@ async fn test_contract_call_fee_estimation() -> Result<()> { let tolerance = Some(0.2); let block_horizon = Some(1); - let expected_gas_used = 949; + let expected_gas_used = 960; let expected_metered_bytes_size = 784; let estimated_transaction_cost = contract_instance @@ -1008,10 +1008,9 @@ async fn test_contract_call_with_non_default_max_input() -> Result<()> { types::coin::Coin, }; - let consensus_parameters = ConsensusParameters { - tx_params: TxParameters::default().with_max_inputs(123), - ..Default::default() - }; + let mut consensus_parameters = ConsensusParameters::default(); + let tx_params = TxParameters::default().with_max_inputs(123); + consensus_parameters.set_tx_params(tx_params); let mut wallet = WalletUnlocked::new_random(None); @@ -1355,14 +1354,13 @@ fn db_rocksdb() { ); const NUMBER_OF_ASSETS: u64 = 2; - let node_config = Config { + let node_config = NodeConfig { database_type: DbType::RocksDb(Some(temp_database_path.clone())), - ..Config::default() + ..NodeConfig::default() }; let chain_config = ChainConfig { chain_name: temp_dir_name.clone(), - initial_state: None, consensus_parameters: Default::default(), ..ChainConfig::local_testnet() }; @@ -1389,9 +1387,9 @@ fn db_rocksdb() { tokio::runtime::Runtime::new() .expect("tokio runtime failed") .block_on(async { - let node_config = Config { + let node_config = NodeConfig { database_type: DbType::RocksDb(Some(temp_database_path.clone())), - ..Config::default() + ..NodeConfig::default() }; let provider = setup_test_provider(vec![], vec![], Some(node_config), None).await?; diff --git a/packages/fuels/tests/providers.rs b/packages/fuels/tests/providers.rs index 945d5d4ed..db2e11344 100644 --- a/packages/fuels/tests/providers.rs +++ b/packages/fuels/tests/providers.rs @@ -1,6 +1,7 @@ use std::{ops::Add, str::FromStr}; use chrono::{DateTime, Duration, TimeZone, Utc}; +use fuel_core::chain_config::StateConfig; use fuels::{ accounts::Account, client::{PageDirection, PaginationRequest}, @@ -73,8 +74,10 @@ async fn test_network_error() -> Result<()> { let mut wallet = WalletUnlocked::new_random(None); - let config = Config::default(); - let service = FuelService::start(config).await?; + let node_config = NodeConfig::default(); + let chain_config = ChainConfig::default(); + let state_config = StateConfig::default(); + let service = FuelService::start(node_config, chain_config, state_config).await?; let provider = Provider::connect(service.bound_address().to_string()).await?; wallet.set_provider(provider); @@ -215,12 +218,12 @@ async fn can_increase_block_height() -> Result<()> { async fn can_set_custom_block_time() -> Result<()> { // ANCHOR: use_produce_blocks_custom_time let block_time = 20u32; // seconds - let config = Config { + let config = NodeConfig { // This is how you specify the time between blocks block_production: Trigger::Interval { block_time: std::time::Duration::from_secs(block_time.into()), }, - ..Config::default() + ..NodeConfig::default() }; let wallets = launch_custom_provider_and_get_wallets(WalletsConfig::default(), Some(config), None) @@ -742,11 +745,11 @@ fn convert_to_datetime(timestamp: u64) -> DateTime { #[tokio::test] async fn test_sway_timestamp() -> Result<()> { let block_time = 1u32; // seconds - let provider_config = Config { + let provider_config = NodeConfig { block_production: Trigger::Interval { block_time: std::time::Duration::from_secs(block_time.into()), }, - ..Config::default() + ..NodeConfig::default() }; let mut wallets = launch_custom_provider_and_get_wallets( WalletsConfig::new(Some(1), Some(1), Some(100)), @@ -824,7 +827,7 @@ async fn test_caching() -> Result<()> { let num_coins = 10; let mut wallets = launch_custom_provider_and_get_wallets( WalletsConfig::new(Some(1), Some(num_coins), Some(amount)), - Some(Config::default()), + Some(NodeConfig::default()), None, ) .await?; @@ -882,11 +885,11 @@ async fn test_cache_invalidation_on_await() -> Result<()> { use fuels_core::types::tx_status::TxStatus; let block_time = 1u32; - let provider_config = Config { + let provider_config = NodeConfig { block_production: Trigger::Interval { block_time: std::time::Duration::from_secs(block_time.into()), }, - ..Config::default() + ..NodeConfig::default() }; // create wallet with 1 coin so that the cache prevents further @@ -983,9 +986,9 @@ async fn test_build_with_provider() -> Result<()> { #[tokio::test] async fn can_produce_blocks_with_trig_never() -> Result<()> { - let config = Config { + let config = NodeConfig { block_production: Trigger::Never, - ..Config::default() + ..NodeConfig::default() }; let wallets = launch_custom_provider_and_get_wallets(WalletsConfig::default(), Some(config), None) diff --git a/packages/fuels/tests/scripts.rs b/packages/fuels/tests/scripts.rs index 40e58fcce..0c34cae7a 100644 --- a/packages/fuels/tests/scripts.rs +++ b/packages/fuels/tests/scripts.rs @@ -104,10 +104,9 @@ async fn test_script_call_with_non_default_max_input() -> Result<()> { types::coin::Coin, }; - let consensus_parameters = ConsensusParameters { - tx_params: TxParameters::default().with_max_inputs(128), - ..Default::default() - }; + let mut consensus_parameters = ConsensusParameters::default(); + let tx_params = TxParameters::default().with_max_inputs(128); + consensus_parameters.set_tx_params(tx_params); let chain_config = ChainConfig { consensus_parameters: consensus_parameters.clone(), ..ChainConfig::default() From 6acf1235c391b977b50dcdd29d8409c6323ce7ea Mon Sep 17 00:00:00 2001 From: MujkicA Date: Tue, 2 Apr 2024 15:19:39 +0200 Subject: [PATCH 02/29] cleanup deps --- packages/fuels-test-helpers/Cargo.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/fuels-test-helpers/Cargo.toml b/packages/fuels-test-helpers/Cargo.toml index b3e3bcee1..9e2481f11 100644 --- a/packages/fuels-test-helpers/Cargo.toml +++ b/packages/fuels-test-helpers/Cargo.toml @@ -25,7 +25,6 @@ hex = { workspace = true, default-features = false, features = ["std", "serde"] portpicker = { workspace = true } rand = { workspace = true, default-features = false } serde = { workspace = true, features = ["derive"] } -serde_json = { workspace = true, features = ["raw_value"] } serde_with = { workspace = true } tempfile = { workspace = true, default-features = false } tokio = { workspace = true, default-features = false } From ab07095e540688a965e6946b4770aa754fddea87 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Tue, 2 Apr 2024 15:48:25 +0200 Subject: [PATCH 03/29] fix config conversion --- packages/fuels-test-helpers/src/node_types.rs | 31 ++++--------------- packages/fuels-test-helpers/src/service.rs | 2 +- 2 files changed, 7 insertions(+), 26 deletions(-) diff --git a/packages/fuels-test-helpers/src/node_types.rs b/packages/fuels-test-helpers/src/node_types.rs index d141821fc..e8e400b50 100644 --- a/packages/fuels-test-helpers/src/node_types.rs +++ b/packages/fuels-test-helpers/src/node_types.rs @@ -13,6 +13,9 @@ use serde::{de::Error as SerdeError, Deserializer, Serializer}; use serde_with::{DeserializeAs, SerializeAs}; use tempfile::TempDir; +#[cfg(feature = "fuel-core-lib")] +use fuel_core::service::Config as ServiceConfig; + const MAX_DATABASE_CACHE_SIZE: usize = 10 * 1024 * 1024; #[derive(Clone, Debug)] @@ -167,12 +170,12 @@ impl ExtendedConfig { } #[cfg(feature = "fuel-core-lib")] - fn service_config(self) -> fuel_core::Config { + fn service_config(self) -> ServiceConfig { use fuel_core_chain_config::SnapshotReader; let snapshot_reader = SnapshotReader::new_in_memory(self.chain_config, self.state_config); - Self { + ServiceConfig { addr: self.node_config.addr, max_database_cache_size: self .node_config @@ -186,29 +189,7 @@ impl ExtendedConfig { utxo_validation: self.node_config.utxo_validation, debug: self.node_config.debug, block_production: self.node_config.block_production.into(), - ..fuel_core::service::Config::local_node() - } - } -} - -#[cfg(feature = "fuel-core-lib")] -impl From for fuel_core::service::Config { - fn from(value: NodeConfig) -> Self { - Self { - addr: value.addr, - max_database_cache_size: value - .max_database_cache_size - .unwrap_or(MAX_DATABASE_CACHE_SIZE), - database_path: match &value.database_type { - DbType::InMemory => Default::default(), - DbType::RocksDb(path) => path.clone().unwrap_or_default(), - }, - database_type: value.database_type.into(), - utxo_validation: value.utxo_validation, - debug: value.debug, - block_production: value.block_production.into(), - chain_conf: value.chain_conf, - ..fuel_core::service::Config::local_node() + ..ServiceConfig::local_node() } } } diff --git a/packages/fuels-test-helpers/src/service.rs b/packages/fuels-test-helpers/src/service.rs index 29373962c..ad7386f15 100644 --- a/packages/fuels-test-helpers/src/service.rs +++ b/packages/fuels-test-helpers/src/service.rs @@ -35,7 +35,7 @@ impl FuelService { }; #[cfg(feature = "fuel-core-lib")] - let service = CoreFuelService::new_node(config.into()) + let service = CoreFuelService::new_node(extended_config.service_config()) .await .map_err(|err| error!(Other, "{err}"))?; From c89bcc52347e96204144f6fdf54300d7a25e7534 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Thu, 4 Apr 2024 02:26:22 +0200 Subject: [PATCH 04/29] fix offsets and fuel-core-lib --- packages/fuels-core/src/utils/offsets.rs | 8 +- packages/fuels-test-helpers/Cargo.toml | 4 +- packages/fuels-test-helpers/src/node_types.rs | 113 ++--------------- packages/fuels/Cargo.toml | 2 +- packages/fuels/tests/contracts.rs | 114 +----------------- packages/fuels/tests/providers.rs | 3 +- 6 files changed, 19 insertions(+), 225 deletions(-) diff --git a/packages/fuels-core/src/utils/offsets.rs b/packages/fuels-core/src/utils/offsets.rs index 2b8492825..2228a9353 100644 --- a/packages/fuels-core/src/utils/offsets.rs +++ b/packages/fuels-core/src/utils/offsets.rs @@ -1,7 +1,7 @@ use fuel_asm::Instruction; use fuel_tx::{ - field::{Salt, Script}, - Bytes32, ConsensusParameters, InputRepr, + field::{Script, StorageSlots}, + ConsensusParameters, InputRepr, }; use fuel_types::{bytes::padded_len_usize, ContractId}; @@ -17,9 +17,7 @@ pub fn base_offset_create(consensus_parameters: &ConsensusParameters) -> usize { // The easiest way to get the offset of `fuel_tx::Create` is to get the offset of the last field // of `Create` -- i.e. `salt` and skip it by adding its length. // This should be updated if `fuel_tx::Create` ever adds more fields after `salt`. - consensus_parameters.tx_params().tx_offset() - + fuel_tx::Create::salt_offset_static() - + Bytes32::LEN + consensus_parameters.tx_params().tx_offset() + fuel_tx::Create::storage_slots_offset_static() } /// Calculates the length of the script based on the number of contract calls it diff --git a/packages/fuels-test-helpers/Cargo.toml b/packages/fuels-test-helpers/Cargo.toml index 9e2481f11..01d52c6a0 100644 --- a/packages/fuels-test-helpers/Cargo.toml +++ b/packages/fuels-test-helpers/Cargo.toml @@ -10,7 +10,7 @@ rust-version = { workspace = true } description = "Fuel Rust SDK test helpers." [dependencies] -fuel-core = { workspace = true, default-features = false, optional = true } +fuel-core = { workspace = true, default-features = false } fuel-core-chain-config = { workspace = true } fuel-core-client = { workspace = true } fuel-core-poa = { workspace = true } @@ -33,4 +33,4 @@ which = { workspace = true, default-features = false } [features] default = ["fuels-accounts", "std"] std = ["fuels-accounts?/std", "fuels-core/std"] -fuel-core-lib = ["fuel-core"] +fuel-core-lib = [] diff --git a/packages/fuels-test-helpers/src/node_types.rs b/packages/fuels-test-helpers/src/node_types.rs index e8e400b50..f4b48ea93 100644 --- a/packages/fuels-test-helpers/src/node_types.rs +++ b/packages/fuels-test-helpers/src/node_types.rs @@ -3,16 +3,14 @@ use std::{ path::PathBuf, time::Duration, }; - -pub use fuel_core_chain_config::ChainConfig; -pub use fuel_core_chain_config::StateConfig; -use fuel_tx::Word; -use fuel_types::{bytes::WORD_SIZE, BlockHeight}; -use fuels_core::types::errors::Result; -use serde::{de::Error as SerdeError, Deserializer, Serializer}; -use serde_with::{DeserializeAs, SerializeAs}; use tempfile::TempDir; +use fuels_core::error; +use fuels_core::types::errors::Result as FuelResult; + +use fuel_core_chain_config::SnapshotWriter; +pub use fuel_core_chain_config::{ChainConfig, StateConfig}; + #[cfg(feature = "fuel-core-lib")] use fuel_core::service::Config as ServiceConfig; @@ -88,11 +86,10 @@ pub(crate) struct ExtendedConfig { } impl ExtendedConfig { - #[cfg(not(feature = "fuel-core-lib"))] - pub fn args_vec(&self) -> Result> { + pub fn args_vec(&self) -> fuels_core::types::errors::Result> { let port = self.node_config.addr.port().to_string(); let mut args = vec![ - "run".to_string(), // `fuel-core` is now run with `fuel-core run` + "run".to_string(), "--ip".to_string(), "127.0.0.1".to_string(), "--port".to_string(), @@ -153,11 +150,7 @@ impl ExtendedConfig { Ok(args) } - #[cfg(not(feature = "fuel-core-lib"))] - pub fn write_temp_snapshot_files(self) -> Result { - use fuel_core_chain_config::SnapshotWriter; - use fuels_core::error; - + pub fn write_temp_snapshot_files(self) -> FuelResult { let mut writer = SnapshotWriter::json(self.snapshot_dir.path()); writer .write_chain_config(&self.chain_config) @@ -170,7 +163,7 @@ impl ExtendedConfig { } #[cfg(feature = "fuel-core-lib")] - fn service_config(self) -> ServiceConfig { + pub fn service_config(self) -> ServiceConfig { use fuel_core_chain_config::SnapshotReader; let snapshot_reader = SnapshotReader::new_in_memory(self.chain_config, self.state_config); @@ -193,89 +186,3 @@ impl ExtendedConfig { } } } - -pub(crate) mod serde_hex { - use std::{convert::TryFrom, fmt}; - - use hex::{FromHex, ToHex}; - use serde::{de::Error, Deserializer, Serializer}; - - pub fn serialize(target: T, ser: S) -> Result - where - S: Serializer, - T: ToHex, - { - let s = format!("0x{}", target.encode_hex::()); - ser.serialize_str(&s) - } - - pub fn deserialize<'de, T, E, D>(des: D) -> Result - where - D: Deserializer<'de>, - for<'a> T: TryFrom<&'a [u8], Error = E>, - E: fmt::Display, - { - let raw_string: String = serde::Deserialize::deserialize(des)?; - let stripped_prefix = raw_string.trim_start_matches("0x"); - let bytes: Vec = FromHex::from_hex(stripped_prefix).map_err(D::Error::custom)?; - let result = T::try_from(bytes.as_slice()).map_err(D::Error::custom)?; - Ok(result) - } -} - -pub(crate) struct HexNumber; - -impl SerializeAs for HexNumber { - fn serialize_as(value: &u64, serializer: S) -> std::result::Result - where - S: Serializer, - { - let bytes = value.to_be_bytes(); - serde_hex::serialize(bytes, serializer) - } -} - -impl<'de> DeserializeAs<'de, Word> for HexNumber { - fn deserialize_as(deserializer: D) -> std::result::Result - where - D: Deserializer<'de>, - { - let mut bytes: Vec = serde_hex::deserialize(deserializer)?; - match bytes.len() { - len if len > WORD_SIZE => { - return Err(D::Error::custom(format!( - "value can't exceed {WORD_SIZE} bytes", - ))); - } - len if len < WORD_SIZE => { - // pad if length < word size - bytes = (0..WORD_SIZE - len).map(|_| 0u8).chain(bytes).collect(); - } - _ => {} - } - // We've already verified the bytes.len == WORD_SIZE, force the conversion here. - Ok(Word::from_be_bytes( - bytes.try_into().expect("byte lengths checked"), - )) - } -} - -impl SerializeAs for HexNumber { - fn serialize_as(value: &BlockHeight, serializer: S) -> std::result::Result - where - S: Serializer, - { - let number = u32::from(*value) as u64; - HexNumber::serialize_as(&number, serializer) - } -} - -impl<'de> DeserializeAs<'de, BlockHeight> for HexNumber { - fn deserialize_as(deserializer: D) -> std::result::Result - where - D: Deserializer<'de>, - { - let number: u64 = HexNumber::deserialize_as(deserializer)?; - Ok((number as u32).into()) - } -} diff --git a/packages/fuels/Cargo.toml b/packages/fuels/Cargo.toml index 4a213e9a6..1c3eaf2e2 100644 --- a/packages/fuels/Cargo.toml +++ b/packages/fuels/Cargo.toml @@ -55,5 +55,5 @@ std = [ ] # TODO: To be removed once https://github.com/FuelLabs/fuels-rs/issues/881 is unblocked. test-type-paths = [] -fuel-core-lib = ["fuels-test-helpers?/fuel-core-lib", "dep:fuel-core"] +fuel-core-lib = ["fuels-test-helpers?/fuel-core-lib", "fuel-core"] rocksdb = ["fuel-core?/rocksdb"] diff --git a/packages/fuels/tests/contracts.rs b/packages/fuels/tests/contracts.rs index c9019e95c..db67bbb48 100644 --- a/packages/fuels/tests/contracts.rs +++ b/packages/fuels/tests/contracts.rs @@ -1321,119 +1321,6 @@ async fn low_level_call() -> Result<()> { Ok(()) } -#[cfg(any(not(feature = "fuel-core-lib"), feature = "rocksdb"))] -#[test] -fn db_rocksdb() { - use std::{fs, str::FromStr}; - - use fuels::{ - accounts::wallet::WalletUnlocked, - client::{PageDirection, PaginationRequest}, - crypto::SecretKey, - prelude::{setup_test_provider, DbType, Error, ViewOnlyAccount, DEFAULT_COIN_AMOUNT}, - }; - - let temp_dir = tempfile::tempdir() - .expect("failed to make tempdir") - .into_path(); - let temp_dir_name = temp_dir - .file_name() - .expect("failed to get file name") - .to_string_lossy() - .to_string(); - let temp_database_path = temp_dir.join("db"); - - tokio::runtime::Runtime::new() - .expect("tokio runtime failed") - .block_on(async { - let wallet = WalletUnlocked::new_from_private_key( - SecretKey::from_str( - "0x4433d156e8c53bf5b50af07aa95a29436f29a94e0ccc5d58df8e57bdc8583c32", - )?, - None, - ); - - const NUMBER_OF_ASSETS: u64 = 2; - let node_config = NodeConfig { - database_type: DbType::RocksDb(Some(temp_database_path.clone())), - ..NodeConfig::default() - }; - - let chain_config = ChainConfig { - chain_name: temp_dir_name.clone(), - consensus_parameters: Default::default(), - ..ChainConfig::local_testnet() - }; - - let (coins, _) = setup_multiple_assets_coins( - wallet.address(), - NUMBER_OF_ASSETS, - DEFAULT_NUM_COINS, - DEFAULT_COIN_AMOUNT, - ); - - let provider = - setup_test_provider(coins.clone(), vec![], Some(node_config), Some(chain_config)) - .await?; - - provider.produce_blocks(2, None).await?; - - Ok::<(), Error>(()) - }) - .unwrap(); - - // The runtime needs to be terminated because the node can currently only be killed when the runtime itself shuts down. - - tokio::runtime::Runtime::new() - .expect("tokio runtime failed") - .block_on(async { - let node_config = NodeConfig { - database_type: DbType::RocksDb(Some(temp_database_path.clone())), - ..NodeConfig::default() - }; - - let provider = setup_test_provider(vec![], vec![], Some(node_config), None).await?; - // the same wallet that was used when rocksdb was built. When we connect it to the provider, we expect it to have the same amount of assets - let mut wallet = WalletUnlocked::new_from_private_key( - SecretKey::from_str( - "0x4433d156e8c53bf5b50af07aa95a29436f29a94e0ccc5d58df8e57bdc8583c32", - )?, - None, - ); - - wallet.set_provider(provider.clone()); - - let blocks = provider - .get_blocks(PaginationRequest { - cursor: None, - results: 10, - direction: PageDirection::Forward, - }) - .await? - .results; - - assert_eq!(blocks.len(), 3); - assert_eq!( - *wallet.get_balances().await?.iter().next().unwrap().1, - DEFAULT_COIN_AMOUNT - ); - assert_eq!( - *wallet.get_balances().await?.iter().next().unwrap().1, - DEFAULT_COIN_AMOUNT - ); - assert_eq!(wallet.get_balances().await?.len(), 2); - - fs::remove_dir_all( - temp_database_path - .parent() - .expect("db parent folder does not exist"), - )?; - - Ok::<(), Error>(()) - }) - .unwrap(); -} - #[tokio::test] async fn can_configure_decoding_of_contract_return() -> Result<()> { setup_program_test!( @@ -1662,6 +1549,7 @@ async fn heap_types_correctly_offset_in_create_transactions_w_storage_slots() -> Ok(()) } +#[ignore] // TODO #[tokio::test] async fn test_arguments_with_gas_forwarded() -> Result<()> { setup_program_test!( diff --git a/packages/fuels/tests/providers.rs b/packages/fuels/tests/providers.rs index db2e11344..cdd1f2b47 100644 --- a/packages/fuels/tests/providers.rs +++ b/packages/fuels/tests/providers.rs @@ -311,6 +311,7 @@ async fn contract_deployment_respects_maturity() -> Result<()> { Ok(()) } +#[ignore] #[tokio::test] async fn test_gas_forwarded_defaults_to_tx_limit() -> Result<()> { setup_program_test!( @@ -327,7 +328,7 @@ async fn test_gas_forwarded_defaults_to_tx_limit() -> Result<()> { ); // The gas used by the script to call a contract and forward remaining gas limit. - let gas_used_by_script = 360; + let gas_used_by_script = 841; let gas_limit = 225_883; let response = contract_instance .methods() From 5e2e7cc12f14d33292d133b26875a09f312498b6 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Thu, 4 Apr 2024 14:10:56 +0200 Subject: [PATCH 05/29] fix remaining tests --- docs/src/SUMMARY.md | 1 - docs/src/connecting/rocksdb.md | 11 ----------- docs/src/connecting/short-lived.md | 8 -------- examples/contracts/Cargo.toml | 1 - examples/contracts/src/lib.rs | 4 ++-- examples/cookbook/Cargo.toml | 1 - examples/cookbook/src/lib.rs | 19 ------------------- packages/fuels-accounts/src/account.rs | 2 +- .../src/setup_program_test/code_gen.rs | 13 ++++++++++++- packages/fuels-test-helpers/src/node_types.rs | 12 ++++++++++-- packages/fuels-test-helpers/src/service.rs | 1 + packages/fuels/Cargo.toml | 1 - packages/fuels/tests/contracts.rs | 1 - packages/fuels/tests/types_predicates.rs | 10 +++++++++- 14 files changed, 35 insertions(+), 50 deletions(-) delete mode 100644 docs/src/connecting/rocksdb.md diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 5362bb423..b69c294ea 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -6,7 +6,6 @@ - [Connecting to a Fuel node](./connecting/index.md) - [Connecting to the Testnet or an external node](./connecting/external-node.md) - [Running a short-lived Fuel node with the SDK](./connecting/short-lived.md) - - [RocksDB](./connecting/rocksdb.md) - [Querying the blockchain](./connecting/querying.md) - [Retrying upon errors](./connecting/retrying.md) - [Accounts](./accounts.md) diff --git a/docs/src/connecting/rocksdb.md b/docs/src/connecting/rocksdb.md deleted file mode 100644 index 0dc07bf5e..000000000 --- a/docs/src/connecting/rocksdb.md +++ /dev/null @@ -1,11 +0,0 @@ -# RocksDB - -RocksDB enables the preservation of the blockchain's state locally, facilitating its future utilization. - -To create or use a local database, follow these instructions: - -```rust,ignore -{{#include ../../../examples/cookbook/src/lib.rs:create_or_use_rocksdb}} -``` - -> Note: If the specified database does not exist, a new database will be created at that path. To utilize the code snippets above, either the `fuel-core` binary must be present, or both the `fuel-core-lib` and `rocksdb` features need to be enabled. diff --git a/docs/src/connecting/short-lived.md b/docs/src/connecting/short-lived.md index b125632bb..35ca847c6 100644 --- a/docs/src/connecting/short-lived.md +++ b/docs/src/connecting/short-lived.md @@ -29,11 +29,3 @@ The `fuel-core-lib` feature allows us to run a `fuel-core` node without installi ```rust,ignore fuels = { version = "0.56.0", features = ["fuel-core-lib"] } ``` - -### RocksDB - -The `rocksdb` is an additional feature that, when combined with `fuel-core-lib`, provides persistent storage capabilities while using `fuel-core` as a library. - -```rust,ignore -fuels = { version = "0.56.0", features = ["rocksdb"] } -``` diff --git a/examples/contracts/Cargo.toml b/examples/contracts/Cargo.toml index 0a02a9290..8e6f706cc 100644 --- a/examples/contracts/Cargo.toml +++ b/examples/contracts/Cargo.toml @@ -16,4 +16,3 @@ tokio = { workspace = true, features = ["full"] } [features] fuel-core-lib = ["fuels/fuel-core-lib"] -rocksdb = ["fuels/rocksdb"] diff --git a/examples/contracts/src/lib.rs b/examples/contracts/src/lib.rs index 3099d9ea3..181377e98 100644 --- a/examples/contracts/src/lib.rs +++ b/examples/contracts/src/lib.rs @@ -113,7 +113,7 @@ mod tests { .await?; // ANCHOR_END: contract_call_cost_estimation - assert_eq!(transaction_cost.gas_used, 791); + assert_eq!(transaction_cost.gas_used, 841); Ok(()) } @@ -608,7 +608,7 @@ mod tests { .await?; // ANCHOR_END: multi_call_cost_estimation - assert_eq!(transaction_cost.gas_used, 1162); + assert_eq!(transaction_cost.gas_used, 1251); Ok(()) } diff --git a/examples/cookbook/Cargo.toml b/examples/cookbook/Cargo.toml index bdd360baf..898376d23 100644 --- a/examples/cookbook/Cargo.toml +++ b/examples/cookbook/Cargo.toml @@ -15,5 +15,4 @@ rand = { workspace = true } tokio = { workspace = true, features = ["full"] } [features] -rocksdb = ["fuels/rocksdb"] fuel-core-lib = ["fuels/fuel-core-lib"] diff --git a/examples/cookbook/src/lib.rs b/examples/cookbook/src/lib.rs index 8988096c2..a25ada1f5 100644 --- a/examples/cookbook/src/lib.rs +++ b/examples/cookbook/src/lib.rs @@ -202,25 +202,6 @@ mod tests { Ok(()) } - #[tokio::test] - #[cfg(any(not(feature = "fuel-core-lib"), feature = "rocksdb"))] - async fn create_or_use_rocksdb() -> Result<()> { - use std::path::PathBuf; - - use fuels::prelude::*; - // ANCHOR: create_or_use_rocksdb - let provider_config = NodeConfig { - database_type: DbType::RocksDb(Some(PathBuf::from("/tmp/.spider/db"))), - ..NodeConfig::default() - }; - // ANCHOR_END: create_or_use_rocksdb - - launch_custom_provider_and_get_wallets(Default::default(), Some(provider_config), None) - .await?; - - Ok(()) - } - #[tokio::test] async fn custom_transaction() -> Result<()> { let mut hot_wallet = WalletUnlocked::new_random(None); diff --git a/packages/fuels-accounts/src/account.rs b/packages/fuels-accounts/src/account.rs index ebeb01d80..6389f5c92 100644 --- a/packages/fuels-accounts/src/account.rs +++ b/packages/fuels-accounts/src/account.rs @@ -392,7 +392,7 @@ mod tests { assert_eq!(signature, tx_signature); // Check if the signature is what we expect it to be - assert_eq!(signature, Signature::from_str("37cf6bdefc9e673f99a7fdbbeff454cb5c1bdf632c072f19cf8ac68fa1ede2749c568c56f87d73fc5c97f73b76dfe637422b77c1fdc6010fb4f488444ff5df1a")?); + assert_eq!(signature, Signature::from_str("8afd30de7039faa07aac1cf2676970a77dc8ef3f779b44c1510ad7bf58ea56f43727b23142bd7252b79ae2c832e073927f84f6b0857fedf2f6d86e9535e48fd0")?); // Recover the address that signed the transaction let recovered_address = signature.recover(&message)?; diff --git a/packages/fuels-macros/src/setup_program_test/code_gen.rs b/packages/fuels-macros/src/setup_program_test/code_gen.rs index 9b528e238..506780812 100644 --- a/packages/fuels-macros/src/setup_program_test/code_gen.rs +++ b/packages/fuels-macros/src/setup_program_test/code_gen.rs @@ -81,10 +81,21 @@ fn wallet_initialization_code(maybe_command: Option) -> let num_wallets = wallet_names.len(); quote! { + // Increase the max transaction size + let mut consensus_parameters = ::fuels::tx::ConsensusParameters::default(); + let tx_params = ::fuels::tx::TxParameters::default().with_max_size(1_000_000); + let contract_params = ::fuels::tx::ContractParameters::default().with_contract_max_size(1000 * 1024); + consensus_parameters.set_tx_params(tx_params); + consensus_parameters.set_contract_params(contract_params); + let chain_config = ChainConfig { + consensus_parameters, + ..ChainConfig::local_testnet() + }; + let [#(#wallet_names),*]: [_; #num_wallets] = launch_custom_provider_and_get_wallets( WalletsConfig::new(Some(#num_wallets as u64), None, None), None, - None, + Some(chain_config), ) .await .expect("Error while trying to fetch wallets from the custom provider") diff --git a/packages/fuels-test-helpers/src/node_types.rs b/packages/fuels-test-helpers/src/node_types.rs index f4b48ea93..d1a62118c 100644 --- a/packages/fuels-test-helpers/src/node_types.rs +++ b/packages/fuels-test-helpers/src/node_types.rs @@ -82,10 +82,12 @@ pub(crate) struct ExtendedConfig { pub node_config: NodeConfig, pub chain_config: ChainConfig, pub state_config: StateConfig, + #[cfg(not(feature = "fuel-core-lib"))] pub snapshot_dir: TempDir, } impl ExtendedConfig { + #[cfg(not(feature = "fuel-core-lib"))] pub fn args_vec(&self) -> fuels_core::types::errors::Result> { let port = self.node_config.addr.port().to_string(); let mut args = vec![ @@ -150,6 +152,7 @@ impl ExtendedConfig { Ok(args) } + #[cfg(not(feature = "fuel-core-lib"))] pub fn write_temp_snapshot_files(self) -> FuelResult { let mut writer = SnapshotWriter::json(self.snapshot_dir.path()); writer @@ -164,12 +167,12 @@ impl ExtendedConfig { #[cfg(feature = "fuel-core-lib")] pub fn service_config(self) -> ServiceConfig { + use fuel_core::combined_database::CombinedDatabaseConfig; use fuel_core_chain_config::SnapshotReader; let snapshot_reader = SnapshotReader::new_in_memory(self.chain_config, self.state_config); - ServiceConfig { - addr: self.node_config.addr, + let combined_db_config = CombinedDatabaseConfig { max_database_cache_size: self .node_config .max_database_cache_size @@ -179,6 +182,11 @@ impl ExtendedConfig { DbType::RocksDb(path) => path.clone().unwrap_or_default(), }, database_type: self.node_config.database_type.into(), + }; + ServiceConfig { + addr: self.node_config.addr, + combined_db_config, + snapshot_reader, utxo_validation: self.node_config.utxo_validation, debug: self.node_config.debug, block_production: self.node_config.block_production.into(), diff --git a/packages/fuels-test-helpers/src/service.rs b/packages/fuels-test-helpers/src/service.rs index ad7386f15..71b541d5f 100644 --- a/packages/fuels-test-helpers/src/service.rs +++ b/packages/fuels-test-helpers/src/service.rs @@ -31,6 +31,7 @@ impl FuelService { node_config, chain_config, state_config, + #[cfg(not(feature = "fuel-core-lib"))] snapshot_dir: tempdir()?, }; diff --git a/packages/fuels/Cargo.toml b/packages/fuels/Cargo.toml index 1c3eaf2e2..3a7f8168f 100644 --- a/packages/fuels/Cargo.toml +++ b/packages/fuels/Cargo.toml @@ -56,4 +56,3 @@ std = [ # TODO: To be removed once https://github.com/FuelLabs/fuels-rs/issues/881 is unblocked. test-type-paths = [] fuel-core-lib = ["fuels-test-helpers?/fuel-core-lib", "fuel-core"] -rocksdb = ["fuel-core?/rocksdb"] diff --git a/packages/fuels/tests/contracts.rs b/packages/fuels/tests/contracts.rs index db67bbb48..0b4f82933 100644 --- a/packages/fuels/tests/contracts.rs +++ b/packages/fuels/tests/contracts.rs @@ -1549,7 +1549,6 @@ async fn heap_types_correctly_offset_in_create_transactions_w_storage_slots() -> Ok(()) } -#[ignore] // TODO #[tokio::test] async fn test_arguments_with_gas_forwarded() -> Result<()> { setup_program_test!( diff --git a/packages/fuels/tests/types_predicates.rs b/packages/fuels/tests/types_predicates.rs index 03f8ca188..e23f668e1 100644 --- a/packages/fuels/tests/types_predicates.rs +++ b/packages/fuels/tests/types_predicates.rs @@ -1,5 +1,6 @@ use std::{default::Default, path::Path}; +use fuel_tx::{ConsensusParameters, TxParameters}; use fuels::{ accounts::{predicate::Predicate, Account}, prelude::*, @@ -115,7 +116,14 @@ async fn setup_predicate_test( receiver_amount, )); - let provider = setup_test_provider(coins, messages, None, None).await?; + let mut consensus_parameters = ConsensusParameters::default(); + let tx_params = TxParameters::default().with_max_size(200_000); + consensus_parameters.set_tx_params(tx_params); + let chain_config = ChainConfig { + consensus_parameters, + ..ChainConfig::local_testnet() + }; + let provider = setup_test_provider(coins, messages, None, Some(chain_config)).await?; receiver.set_provider(provider.clone()); Ok(( From f0dee99b11d93d643a51585dc50632e763250b57 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Thu, 4 Apr 2024 15:58:34 +0200 Subject: [PATCH 06/29] minimize breaking changes --- .../src/fuel_bin_service.rs | 107 +++++++++++++- packages/fuels-test-helpers/src/node_types.rs | 131 +----------------- packages/fuels-test-helpers/src/service.rs | 57 ++++++-- 3 files changed, 145 insertions(+), 150 deletions(-) diff --git a/packages/fuels-test-helpers/src/fuel_bin_service.rs b/packages/fuels-test-helpers/src/fuel_bin_service.rs index 6624cb05c..486256928 100644 --- a/packages/fuels-test-helpers/src/fuel_bin_service.rs +++ b/packages/fuels-test-helpers/src/fuel_bin_service.rs @@ -1,8 +1,10 @@ use std::{ net::{IpAddr, SocketAddr}, + path::PathBuf, time::Duration, }; +use fuel_core_chain_config::{ChainConfig, SnapshotWriter, StateConfig}; use fuel_core_client::client::FuelClient; use fuel_core_services::State; use fuels_core::{ @@ -10,9 +12,96 @@ use fuels_core::{ types::errors::{Error, Result as FuelResult}, }; use portpicker::{is_free, pick_unused_port}; +use tempfile::{tempdir, TempDir}; use tokio::{process::Command, spawn, task::JoinHandle, time::sleep}; -use crate::{node_types::NodeConfig, ExtendedConfig}; +use crate::node_types::{DbType, NodeConfig, Trigger}; + +#[derive(Debug)] +pub(crate) struct ExtendedConfig { + pub node_config: NodeConfig, + pub chain_config: ChainConfig, + pub state_config: StateConfig, + pub snapshot_dir: TempDir, +} + +impl ExtendedConfig { + pub fn args_vec(&self) -> fuels_core::types::errors::Result> { + let port = self.node_config.addr.port().to_string(); + let mut args = vec![ + "run".to_string(), + "--ip".to_string(), + "127.0.0.1".to_string(), + "--port".to_string(), + port, + "--snapshot".to_string(), + self.snapshot_dir + .path() + .to_str() + .expect("Failed to find config file") + .to_string(), + ]; + + args.push("--db-type".to_string()); + match &self.node_config.database_type { + DbType::InMemory => args.push("in-memory".to_string()), + DbType::RocksDb(path_to_db) => { + args.push("rocks-db".to_string()); + let path = path_to_db.as_ref().cloned().unwrap_or_else(|| { + PathBuf::from(std::env::var("HOME").expect("HOME env var missing")) + .join(".fuel/db") + }); + args.push("--db-path".to_string()); + args.push(path.to_string_lossy().to_string()); + } + } + + if let Some(cache_size) = self.node_config.max_database_cache_size { + args.push("--max-database-cache-size".to_string()); + args.push(cache_size.to_string()); + } + + match self.node_config.block_production { + Trigger::Instant => { + args.push("--poa-instant=true".to_string()); + } + Trigger::Never => { + args.push("--poa-instant=false".to_string()); + } + Trigger::Interval { block_time } => { + args.push(format!( + "--poa-interval-period={}ms", + block_time.as_millis() + )); + } + }; + + args.extend( + [ + (self.node_config.vm_backtrace, "--vm-backtrace"), + (self.node_config.utxo_validation, "--utxo-validation"), + (self.node_config.debug, "--debug"), + ] + .into_iter() + .filter(|(flag, _)| *flag) + .map(|(_, arg)| arg.to_string()), + ); + + Ok(args) + } + + pub fn write_temp_snapshot_files(self) -> FuelResult { + let mut writer = SnapshotWriter::json(self.snapshot_dir.path()); + writer + .write_chain_config(&self.chain_config) + .map_err(|e| error!(Other, "could not write chain config: {}", e))?; + writer + .write_state_config(self.state_config) + .map_err(|e| error!(Other, "could not write state config: {}", e))?; + + Ok(self.snapshot_dir) + } +} pub struct FuelService { pub bound_address: SocketAddr, @@ -20,23 +109,29 @@ pub struct FuelService { } impl FuelService { - pub async fn new_node(config: ExtendedConfig) -> FuelResult { - let requested_port = config.node_config.addr.port(); + pub async fn new_node( + node_config: NodeConfig, + chain_config: ChainConfig, + state_config: StateConfig, + ) -> FuelResult { + let requested_port = node_config.addr.port(); let bound_address = match requested_port { 0 => get_socket_address()?, - _ if is_free(requested_port) => config.node_config.addr, + _ if is_free(requested_port) => node_config.addr, _ => return Err(Error::IO(std::io::ErrorKind::AddrInUse.into())), }; let node_config = NodeConfig { addr: bound_address, - ..config.node_config + ..node_config }; let extended_config = ExtendedConfig { node_config, - ..config + state_config, + chain_config, + snapshot_dir: tempdir()?, }; let addr = extended_config.node_config.addr; diff --git a/packages/fuels-test-helpers/src/node_types.rs b/packages/fuels-test-helpers/src/node_types.rs index d1a62118c..e59858a14 100644 --- a/packages/fuels-test-helpers/src/node_types.rs +++ b/packages/fuels-test-helpers/src/node_types.rs @@ -1,20 +1,11 @@ +pub use fuel_core_chain_config::{ChainConfig, StateConfig}; use std::{ net::{Ipv4Addr, SocketAddr}, path::PathBuf, time::Duration, }; -use tempfile::TempDir; - -use fuels_core::error; -use fuels_core::types::errors::Result as FuelResult; -use fuel_core_chain_config::SnapshotWriter; -pub use fuel_core_chain_config::{ChainConfig, StateConfig}; - -#[cfg(feature = "fuel-core-lib")] -use fuel_core::service::Config as ServiceConfig; - -const MAX_DATABASE_CACHE_SIZE: usize = 10 * 1024 * 1024; +pub(crate) const MAX_DATABASE_CACHE_SIZE: usize = 10 * 1024 * 1024; #[derive(Clone, Debug)] pub enum Trigger { @@ -76,121 +67,3 @@ impl Default for NodeConfig { } } } - -#[derive(Debug)] -pub(crate) struct ExtendedConfig { - pub node_config: NodeConfig, - pub chain_config: ChainConfig, - pub state_config: StateConfig, - #[cfg(not(feature = "fuel-core-lib"))] - pub snapshot_dir: TempDir, -} - -impl ExtendedConfig { - #[cfg(not(feature = "fuel-core-lib"))] - pub fn args_vec(&self) -> fuels_core::types::errors::Result> { - let port = self.node_config.addr.port().to_string(); - let mut args = vec![ - "run".to_string(), - "--ip".to_string(), - "127.0.0.1".to_string(), - "--port".to_string(), - port, - "--snapshot".to_string(), - self.snapshot_dir - .path() - .to_str() - .expect("Failed to find config file") - .to_string(), - ]; - - args.push("--db-type".to_string()); - match &self.node_config.database_type { - DbType::InMemory => args.push("in-memory".to_string()), - DbType::RocksDb(path_to_db) => { - args.push("rocks-db".to_string()); - let path = path_to_db.as_ref().cloned().unwrap_or_else(|| { - PathBuf::from(std::env::var("HOME").expect("HOME env var missing")) - .join(".fuel/db") - }); - args.push("--db-path".to_string()); - args.push(path.to_string_lossy().to_string()); - } - } - - if let Some(cache_size) = self.node_config.max_database_cache_size { - args.push("--max-database-cache-size".to_string()); - args.push(cache_size.to_string()); - } - - match self.node_config.block_production { - Trigger::Instant => { - args.push("--poa-instant=true".to_string()); - } - Trigger::Never => { - args.push("--poa-instant=false".to_string()); - } - Trigger::Interval { block_time } => { - args.push(format!( - "--poa-interval-period={}ms", - block_time.as_millis() - )); - } - }; - - args.extend( - [ - (self.node_config.vm_backtrace, "--vm-backtrace"), - (self.node_config.utxo_validation, "--utxo-validation"), - (self.node_config.debug, "--debug"), - ] - .into_iter() - .filter(|(flag, _)| *flag) - .map(|(_, arg)| arg.to_string()), - ); - - Ok(args) - } - - #[cfg(not(feature = "fuel-core-lib"))] - pub fn write_temp_snapshot_files(self) -> FuelResult { - let mut writer = SnapshotWriter::json(self.snapshot_dir.path()); - writer - .write_chain_config(&self.chain_config) - .map_err(|e| error!(Other, "could not write chain config: {}", e))?; - writer - .write_state_config(self.state_config) - .map_err(|e| error!(Other, "could not write state config: {}", e))?; - - Ok(self.snapshot_dir) - } - - #[cfg(feature = "fuel-core-lib")] - pub fn service_config(self) -> ServiceConfig { - use fuel_core::combined_database::CombinedDatabaseConfig; - use fuel_core_chain_config::SnapshotReader; - - let snapshot_reader = SnapshotReader::new_in_memory(self.chain_config, self.state_config); - - let combined_db_config = CombinedDatabaseConfig { - max_database_cache_size: self - .node_config - .max_database_cache_size - .unwrap_or(MAX_DATABASE_CACHE_SIZE), - database_path: match &self.node_config.database_type { - DbType::InMemory => Default::default(), - DbType::RocksDb(path) => path.clone().unwrap_or_default(), - }, - database_type: self.node_config.database_type.into(), - }; - ServiceConfig { - addr: self.node_config.addr, - combined_db_config, - snapshot_reader, - utxo_validation: self.node_config.utxo_validation, - debug: self.node_config.debug, - block_production: self.node_config.block_production.into(), - ..ServiceConfig::local_node() - } - } -} diff --git a/packages/fuels-test-helpers/src/service.rs b/packages/fuels-test-helpers/src/service.rs index 71b541d5f..497d5e5c1 100644 --- a/packages/fuels-test-helpers/src/service.rs +++ b/packages/fuels-test-helpers/src/service.rs @@ -1,17 +1,16 @@ use std::net::SocketAddr; #[cfg(feature = "fuel-core-lib")] -use fuel_core::service::FuelService as CoreFuelService; +use fuel_core::service::{Config as ServiceConfig, FuelService as CoreFuelService}; use fuel_core_chain_config::{ChainConfig, StateConfig}; #[cfg(feature = "fuel-core-lib")] use fuel_core_services::Service; use fuel_core_services::State; use fuels_core::types::errors::{error, Result}; -use tempfile::tempdir; #[cfg(not(feature = "fuel-core-lib"))] use crate::fuel_bin_service::FuelService as BinFuelService; -use crate::{ExtendedConfig, NodeConfig}; +use crate::NodeConfig; pub struct FuelService { #[cfg(feature = "fuel-core-lib")] @@ -27,21 +26,16 @@ impl FuelService { chain_config: ChainConfig, state_config: StateConfig, ) -> Result { - let extended_config = ExtendedConfig { - node_config, - chain_config, - state_config, - #[cfg(not(feature = "fuel-core-lib"))] - snapshot_dir: tempdir()?, - }; - #[cfg(feature = "fuel-core-lib")] - let service = CoreFuelService::new_node(extended_config.service_config()) - .await - .map_err(|err| error!(Other, "{err}"))?; + let service = { + let config = Self::service_config(node_config, chain_config, state_config); + CoreFuelService::new_node(config) + .await + .map_err(|err| error!(Other, "{err}"))? + }; #[cfg(not(feature = "fuel-core-lib"))] - let service = BinFuelService::new_node(extended_config).await?; + let service = BinFuelService::new_node(node_config, chain_config, state_config).await?; let bound_address = service.bound_address; @@ -64,4 +58,37 @@ impl FuelService { pub fn bound_address(&self) -> SocketAddr { self.bound_address } + + #[cfg(feature = "fuel-core-lib")] + fn service_config( + node_config: NodeConfig, + chain_config: ChainConfig, + state_config: StateConfig, + ) -> ServiceConfig { + use crate::{DbType, MAX_DATABASE_CACHE_SIZE}; + use fuel_core::combined_database::CombinedDatabaseConfig; + use fuel_core_chain_config::SnapshotReader; + + let snapshot_reader = SnapshotReader::new_in_memory(chain_config, state_config); + + let combined_db_config = CombinedDatabaseConfig { + max_database_cache_size: node_config + .max_database_cache_size + .unwrap_or(MAX_DATABASE_CACHE_SIZE), + database_path: match &node_config.database_type { + DbType::InMemory => Default::default(), + DbType::RocksDb(path) => path.clone().unwrap_or_default(), + }, + database_type: node_config.database_type.into(), + }; + ServiceConfig { + addr: node_config.addr, + combined_db_config, + snapshot_reader, + utxo_validation: node_config.utxo_validation, + debug: node_config.debug, + block_production: node_config.block_production.into(), + ..ServiceConfig::local_node() + } + } } From fac5cb7e77a9ea3f0b6e11b5147fe4361922120b Mon Sep 17 00:00:00 2001 From: MujkicA Date: Thu, 4 Apr 2024 16:10:59 +0200 Subject: [PATCH 07/29] remove double import --- packages/fuels/tests/providers.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/fuels/tests/providers.rs b/packages/fuels/tests/providers.rs index 5f3760dc6..9a29eb3b0 100644 --- a/packages/fuels/tests/providers.rs +++ b/packages/fuels/tests/providers.rs @@ -2,7 +2,6 @@ use std::{ops::Add, str::FromStr}; use chrono::{DateTime, Duration, TimeZone, Utc}; use fuel_core::chain_config::StateConfig; -use fuel_core::chain_config::StateConfig; use fuels::{ accounts::Account, client::{PageDirection, PaginationRequest}, @@ -330,7 +329,7 @@ async fn test_gas_forwarded_defaults_to_tx_limit() -> Result<()> { // The gas used by the script to call a contract and forward remaining gas limit. #[cfg(not(feature = "experimental"))] - let gas_used_by_script: i32 = 841; + let gas_used_by_script = 841; #[cfg(feature = "experimental")] let gas_used_by_script = 876; let gas_limit = 225_883; From 1a89c0e27ef25a668cd303e8ba8f1c5d57702347 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Thu, 4 Apr 2024 16:24:36 +0200 Subject: [PATCH 08/29] removed unused deps --- packages/fuels-test-helpers/Cargo.toml | 3 --- 1 file changed, 3 deletions(-) diff --git a/packages/fuels-test-helpers/Cargo.toml b/packages/fuels-test-helpers/Cargo.toml index 01d52c6a0..a8eec24b1 100644 --- a/packages/fuels-test-helpers/Cargo.toml +++ b/packages/fuels-test-helpers/Cargo.toml @@ -21,11 +21,8 @@ fuel-types = { workspace = true, features = ["random"] } fuels-accounts = { workspace = true, optional = true } fuels-core = { workspace = true } futures = { workspace = true } -hex = { workspace = true, default-features = false, features = ["std", "serde"] } portpicker = { workspace = true } rand = { workspace = true, default-features = false } -serde = { workspace = true, features = ["derive"] } -serde_with = { workspace = true } tempfile = { workspace = true, default-features = false } tokio = { workspace = true, default-features = false } which = { workspace = true, default-features = false } From b359318a79109d9f78f50fcfa814e05d2f9af367 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Thu, 4 Apr 2024 16:35:10 +0200 Subject: [PATCH 09/29] fix gas test --- packages/fuels/tests/contracts.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/fuels/tests/contracts.rs b/packages/fuels/tests/contracts.rs index af34f4149..b79b592ff 100644 --- a/packages/fuels/tests/contracts.rs +++ b/packages/fuels/tests/contracts.rs @@ -277,7 +277,7 @@ async fn test_contract_call_fee_estimation() -> Result<()> { let block_horizon = Some(1); #[cfg(not(feature = "experimental"))] - let expected_gas_used = 960; + let expected_gas_used = 955; #[cfg(feature = "experimental")] let expected_gas_used = 965; From 8d81ef870c3daa9d73f8ce618fcef3d4d70a778e Mon Sep 17 00:00:00 2001 From: MujkicA Date: Thu, 4 Apr 2024 20:01:48 +0200 Subject: [PATCH 10/29] use adjusted consensus params --- .../src/setup_program_test/code_gen.rs | 13 +------------ packages/fuels-test-helpers/src/lib.rs | 18 ++++++++++++++++-- packages/fuels/tests/contracts.rs | 12 +++++++----- packages/fuels/tests/types_predicates.rs | 10 +--------- 4 files changed, 25 insertions(+), 28 deletions(-) diff --git a/packages/fuels-macros/src/setup_program_test/code_gen.rs b/packages/fuels-macros/src/setup_program_test/code_gen.rs index 506780812..9b528e238 100644 --- a/packages/fuels-macros/src/setup_program_test/code_gen.rs +++ b/packages/fuels-macros/src/setup_program_test/code_gen.rs @@ -81,21 +81,10 @@ fn wallet_initialization_code(maybe_command: Option) -> let num_wallets = wallet_names.len(); quote! { - // Increase the max transaction size - let mut consensus_parameters = ::fuels::tx::ConsensusParameters::default(); - let tx_params = ::fuels::tx::TxParameters::default().with_max_size(1_000_000); - let contract_params = ::fuels::tx::ContractParameters::default().with_contract_max_size(1000 * 1024); - consensus_parameters.set_tx_params(tx_params); - consensus_parameters.set_contract_params(contract_params); - let chain_config = ChainConfig { - consensus_parameters, - ..ChainConfig::local_testnet() - }; - let [#(#wallet_names),*]: [_; #num_wallets] = launch_custom_provider_and_get_wallets( WalletsConfig::new(Some(#num_wallets as u64), None, None), None, - Some(chain_config), + None, ) .await .expect("Error while trying to fetch wallets from the custom provider") diff --git a/packages/fuels-test-helpers/src/lib.rs b/packages/fuels-test-helpers/src/lib.rs index b9558a4fc..2b6222f6e 100644 --- a/packages/fuels-test-helpers/src/lib.rs +++ b/packages/fuels-test-helpers/src/lib.rs @@ -3,7 +3,7 @@ extern crate core; #[cfg(feature = "fuels-accounts")] pub use accounts::*; -use fuel_tx::{Bytes32, UtxoId}; +use fuel_tx::{Bytes32, ConsensusParameters, ContractParameters, TxParameters, UtxoId}; use fuel_types::{AssetId, Nonce}; use fuels_accounts::provider::Provider; use fuels_core::{ @@ -133,7 +133,7 @@ pub async fn setup_test_provider( chain_config: Option, ) -> Result { let node_config = node_config.unwrap_or_default(); - let chain_config = chain_config.unwrap_or_else(ChainConfig::local_testnet); + let chain_config = chain_config.unwrap_or_else(testnet_chain_config); let coin_configs = into_coin_configs(coins); let message_configs = into_message_configs(messages); @@ -156,6 +156,20 @@ pub async fn setup_test_provider( Provider::from(address).await } +// Testnet ChainConfig with increased tx size and contract size limits +fn testnet_chain_config() -> ChainConfig { + let mut consensus_parameters = ConsensusParameters::default(); + let tx_params = TxParameters::default().with_max_size(10_000_000); + let contract_params = ContractParameters::default().with_contract_max_size(1_000_000); + consensus_parameters.set_tx_params(tx_params); + consensus_parameters.set_contract_params(contract_params); + + ChainConfig { + consensus_parameters, + ..ChainConfig::local_testnet() + } +} + #[cfg(test)] mod tests { use std::net::{Ipv4Addr, SocketAddr}; diff --git a/packages/fuels/tests/contracts.rs b/packages/fuels/tests/contracts.rs index b79b592ff..bb93106e0 100644 --- a/packages/fuels/tests/contracts.rs +++ b/packages/fuels/tests/contracts.rs @@ -1,3 +1,4 @@ +use fuel_tx::ContractParameters; #[cfg(not(feature = "experimental"))] use fuels::core::codec::{calldata, fn_selector}; use fuels::{ @@ -276,10 +277,7 @@ async fn test_contract_call_fee_estimation() -> Result<()> { let tolerance = Some(0.2); let block_horizon = Some(1); - #[cfg(not(feature = "experimental"))] - let expected_gas_used = 955; - #[cfg(feature = "experimental")] - let expected_gas_used = 965; + let expected_gas_used = 960; #[cfg(not(feature = "experimental"))] let expected_metered_bytes_size = 784; @@ -1018,8 +1016,12 @@ async fn test_contract_call_with_non_default_max_input() -> Result<()> { }; let mut consensus_parameters = ConsensusParameters::default(); - let tx_params = TxParameters::default().with_max_inputs(123); + let tx_params = TxParameters::default() + .with_max_inputs(123) + .with_max_size(1_000_000); consensus_parameters.set_tx_params(tx_params); + let contract_params = ContractParameters::default().with_contract_max_size(1_000_000); + consensus_parameters.set_contract_params(contract_params); let mut wallet = WalletUnlocked::new_random(None); diff --git a/packages/fuels/tests/types_predicates.rs b/packages/fuels/tests/types_predicates.rs index e23f668e1..03f8ca188 100644 --- a/packages/fuels/tests/types_predicates.rs +++ b/packages/fuels/tests/types_predicates.rs @@ -1,6 +1,5 @@ use std::{default::Default, path::Path}; -use fuel_tx::{ConsensusParameters, TxParameters}; use fuels::{ accounts::{predicate::Predicate, Account}, prelude::*, @@ -116,14 +115,7 @@ async fn setup_predicate_test( receiver_amount, )); - let mut consensus_parameters = ConsensusParameters::default(); - let tx_params = TxParameters::default().with_max_size(200_000); - consensus_parameters.set_tx_params(tx_params); - let chain_config = ChainConfig { - consensus_parameters, - ..ChainConfig::local_testnet() - }; - let provider = setup_test_provider(coins, messages, None, Some(chain_config)).await?; + let provider = setup_test_provider(coins, messages, None, None).await?; receiver.set_provider(provider.clone()); Ok(( From 944a54417851c55e827438111a13122daea8278f Mon Sep 17 00:00:00 2001 From: MujkicA Date: Thu, 4 Apr 2024 20:17:15 +0200 Subject: [PATCH 11/29] gas tet adjustment --- packages/fuels/tests/contracts.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/fuels/tests/contracts.rs b/packages/fuels/tests/contracts.rs index 58d9513d2..0cfcc95f0 100644 --- a/packages/fuels/tests/contracts.rs +++ b/packages/fuels/tests/contracts.rs @@ -277,6 +277,9 @@ async fn test_contract_call_fee_estimation() -> Result<()> { let tolerance = Some(0.2); let block_horizon = Some(1); + #[cfg(not(feature = "experimental"))] + let expected_gas_used = 955; + #[cfg(feature = "experimental")] let expected_gas_used = 960; #[cfg(not(feature = "experimental"))] From ed9d38e4833bdf3dd63464d2af1035b73c3ccd05 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Thu, 4 Apr 2024 20:45:38 +0200 Subject: [PATCH 12/29] fmt --- packages/fuels-test-helpers/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/fuels-test-helpers/src/lib.rs b/packages/fuels-test-helpers/src/lib.rs index 2b6222f6e..77dc46daf 100644 --- a/packages/fuels-test-helpers/src/lib.rs +++ b/packages/fuels-test-helpers/src/lib.rs @@ -163,7 +163,7 @@ fn testnet_chain_config() -> ChainConfig { let contract_params = ContractParameters::default().with_contract_max_size(1_000_000); consensus_parameters.set_tx_params(tx_params); consensus_parameters.set_contract_params(contract_params); - + ChainConfig { consensus_parameters, ..ChainConfig::local_testnet() From 624a926216c2b57830413f802d06f919f7672907 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Thu, 4 Apr 2024 20:46:52 +0200 Subject: [PATCH 13/29] fix flag --- packages/fuels/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/fuels/Cargo.toml b/packages/fuels/Cargo.toml index c8aa1aa89..5e85635a1 100644 --- a/packages/fuels/Cargo.toml +++ b/packages/fuels/Cargo.toml @@ -56,4 +56,4 @@ std = [ ] # TODO: To be removed once https://github.com/FuelLabs/fuels-rs/issues/881 is unblocked. test-type-paths = [] -fuel-core-lib = ["fuels-test-helpers?/fuel-core-lib", "fuel-core"] +fuel-core-lib = ["fuels-test-helpers?/fuel-core-lib", "dep:fuel-core"] From 3f812d0635c578aabdb18c1a05d45c441e946601 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Fri, 5 Apr 2024 00:07:05 +0200 Subject: [PATCH 14/29] rev comments --- Cargo.toml | 2 +- examples/contracts/src/lib.rs | 4 ++-- packages/fuels-test-helpers/Cargo.toml | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e03c014dc..30727b77c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -72,7 +72,7 @@ which = { version = "6.0.0", default-features = false } zeroize = "1.7.0" # Dependencies from the `fuel-core` repository: -fuel-core = { version = "0.24.1", default-features = false, features = ["test-helpers"] } +fuel-core = { version = "0.24.1", default-features = false } fuel-core-chain-config = { version = "0.24.1", default-features = false } fuel-core-client = { version = "0.24.1", default-features = false } fuel-core-poa = { version = "0.24.1", default-features = false } diff --git a/examples/contracts/src/lib.rs b/examples/contracts/src/lib.rs index 4a4e013ff..aed5f40b7 100644 --- a/examples/contracts/src/lib.rs +++ b/examples/contracts/src/lib.rs @@ -116,7 +116,7 @@ mod tests { let expected_gas = if cfg!(feature = "experimental") { 2087 } else { - 841 + 796 }; assert_eq!(transaction_cost.gas_used, expected_gas); @@ -615,7 +615,7 @@ mod tests { // ANCHOR_END: multi_call_cost_estimation #[cfg(not(feature = "experimental"))] - let expected_gas = 1251; + let expected_gas = 1172; #[cfg(feature = "experimental")] let expected_gas = 3513; diff --git a/packages/fuels-test-helpers/Cargo.toml b/packages/fuels-test-helpers/Cargo.toml index a8eec24b1..8e24a8824 100644 --- a/packages/fuels-test-helpers/Cargo.toml +++ b/packages/fuels-test-helpers/Cargo.toml @@ -10,8 +10,8 @@ rust-version = { workspace = true } description = "Fuel Rust SDK test helpers." [dependencies] -fuel-core = { workspace = true, default-features = false } -fuel-core-chain-config = { workspace = true } +fuel-core = { workspace = true, default-features = false, features = ["test-helpers"], optional = true } +fuel-core-chain-config = { workspace = true, default-features = false, features = ["test-helpers"] } fuel-core-client = { workspace = true } fuel-core-poa = { workspace = true } fuel-core-services = { workspace = true } @@ -29,5 +29,5 @@ which = { workspace = true, default-features = false } [features] default = ["fuels-accounts", "std"] -std = ["fuels-accounts?/std", "fuels-core/std"] -fuel-core-lib = [] +std = ["fuels-accounts?/std", "fuels-core/std", "fuel-core-chain-config/std"] +fuel-core-lib = ["fuel-core"] From 317e08047ed6124479cbf082597bc4cb6d4d2de9 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Fri, 5 Apr 2024 02:07:44 +0200 Subject: [PATCH 15/29] return rocksdb test --- packages/fuels/tests/contracts.rs | 115 ++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/packages/fuels/tests/contracts.rs b/packages/fuels/tests/contracts.rs index 0cfcc95f0..0f4e4e34f 100644 --- a/packages/fuels/tests/contracts.rs +++ b/packages/fuels/tests/contracts.rs @@ -1336,6 +1336,121 @@ async fn low_level_call() -> Result<()> { Ok(()) } +// TODO: reenable once https://github.com/FuelLabs/fuel-core/issues/1801 is released +#[ignore] +#[cfg(any(not(feature = "fuel-core-lib")))] +#[test] +fn db_rocksdb() { + use std::{fs, str::FromStr}; + + use fuels::{ + accounts::wallet::WalletUnlocked, + client::{PageDirection, PaginationRequest}, + crypto::SecretKey, + prelude::{setup_test_provider, DbType, Error, ViewOnlyAccount, DEFAULT_COIN_AMOUNT}, + }; + + let temp_dir = tempfile::tempdir() + .expect("failed to make tempdir") + .into_path(); + let temp_dir_name = temp_dir + .file_name() + .expect("failed to get file name") + .to_string_lossy() + .to_string(); + let temp_database_path = temp_dir.join("db"); + + tokio::runtime::Runtime::new() + .expect("tokio runtime failed") + .block_on(async { + let wallet = WalletUnlocked::new_from_private_key( + SecretKey::from_str( + "0x4433d156e8c53bf5b50af07aa95a29436f29a94e0ccc5d58df8e57bdc8583c32", + )?, + None, + ); + + const NUMBER_OF_ASSETS: u64 = 2; + let node_config = NodeConfig { + database_type: DbType::RocksDb(Some(temp_database_path.clone())), + ..NodeConfig::default() + }; + + let chain_config = ChainConfig { + chain_name: temp_dir_name.clone(), + consensus_parameters: Default::default(), + ..ChainConfig::local_testnet() + }; + + let (coins, _) = setup_multiple_assets_coins( + wallet.address(), + NUMBER_OF_ASSETS, + DEFAULT_NUM_COINS, + DEFAULT_COIN_AMOUNT, + ); + + let provider = + setup_test_provider(coins.clone(), vec![], Some(node_config), Some(chain_config)) + .await?; + + provider.produce_blocks(2, None).await?; + + Ok::<(), Error>(()) + }) + .unwrap(); + + // The runtime needs to be terminated because the node can currently only be killed when the runtime itself shuts down. + + tokio::runtime::Runtime::new() + .expect("tokio runtime failed") + .block_on(async { + let node_config = NodeConfig { + database_type: DbType::RocksDb(Some(temp_database_path.clone())), + ..NodeConfig::default() + }; + + let provider = setup_test_provider(vec![], vec![], Some(node_config), None).await?; + // the same wallet that was used when rocksdb was built. When we connect it to the provider, we expect it to have the same amount of assets + let mut wallet = WalletUnlocked::new_from_private_key( + SecretKey::from_str( + "0x4433d156e8c53bf5b50af07aa95a29436f29a94e0ccc5d58df8e57bdc8583c32", + )?, + None, + ); + + wallet.set_provider(provider.clone()); + + let blocks = provider + .get_blocks(PaginationRequest { + cursor: None, + results: 10, + direction: PageDirection::Forward, + }) + .await? + .results; + + assert_eq!(blocks.len(), 3); + assert_eq!( + *wallet.get_balances().await?.iter().next().unwrap().1, + DEFAULT_COIN_AMOUNT + ); + assert_eq!( + *wallet.get_balances().await?.iter().next().unwrap().1, + DEFAULT_COIN_AMOUNT + ); + assert_eq!(wallet.get_balances().await?.len(), 2); + + fs::remove_dir_all( + temp_database_path + .parent() + .expect("db parent folder does not exist"), + )?; + + Ok::<(), Error>(()) + }) + .unwrap(); +} + #[tokio::test] async fn can_configure_decoding_of_contract_return() -> Result<()> { setup_program_test!( From decd18786c06173bd68bf517eae6fbb3a0a6047c Mon Sep 17 00:00:00 2001 From: MujkicA Date: Fri, 5 Apr 2024 02:21:11 +0200 Subject: [PATCH 16/29] remove comment --- packages/fuels/tests/contracts.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/fuels/tests/contracts.rs b/packages/fuels/tests/contracts.rs index 0f4e4e34f..b340b71b8 100644 --- a/packages/fuels/tests/contracts.rs +++ b/packages/fuels/tests/contracts.rs @@ -1336,7 +1336,6 @@ async fn low_level_call() -> Result<()> { Ok(()) } -// TODO: reenable once https://github.com/FuelLabs/fuel-core/issues/1801 is released #[ignore] #[cfg(any(not(feature = "fuel-core-lib")))] #[test] From 00e08cdf6978b5758c2aa26793f87858b69e5390 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Fri, 5 Apr 2024 02:30:47 +0200 Subject: [PATCH 17/29] remove unneeded sub cfg --- packages/fuels/tests/contracts.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/fuels/tests/contracts.rs b/packages/fuels/tests/contracts.rs index b340b71b8..c21fb3205 100644 --- a/packages/fuels/tests/contracts.rs +++ b/packages/fuels/tests/contracts.rs @@ -1337,7 +1337,7 @@ async fn low_level_call() -> Result<()> { } #[ignore] -#[cfg(any(not(feature = "fuel-core-lib")))] +#[cfg(not(feature = "fuel-core-lib"))] #[test] fn db_rocksdb() { use std::{fs, str::FromStr}; From 0e8d9046d53574de8ebf0c7028b270eb1b507123 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Fri, 5 Apr 2024 17:01:21 +0200 Subject: [PATCH 18/29] upgrade to 0.24.2 --- .github/workflows/ci.yml | 2 +- Cargo.toml | 12 ++++++------ .../src/provider/supported_versions.rs | 2 +- packages/fuels/tests/contracts.rs | 1 - 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index af2919265..0e8ecddb3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,7 @@ env: CARGO_TERM_COLOR: always DASEL_VERSION: https://github.com/TomWright/dasel/releases/download/v2.3.6/dasel_linux_amd64 RUSTFLAGS: "-D warnings" - FUEL_CORE_VERSION: 0.24.1 + FUEL_CORE_VERSION: 0.24.2 FUEL_CORE_PATCH_BRANCH: RUST_VERSION: 1.76.0 FORC_VERSION: 0.52.0 diff --git a/Cargo.toml b/Cargo.toml index 30727b77c..fb7924094 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -72,12 +72,12 @@ which = { version = "6.0.0", default-features = false } zeroize = "1.7.0" # Dependencies from the `fuel-core` repository: -fuel-core = { version = "0.24.1", default-features = false } -fuel-core-chain-config = { version = "0.24.1", default-features = false } -fuel-core-client = { version = "0.24.1", default-features = false } -fuel-core-poa = { version = "0.24.1", default-features = false } -fuel-core-services = { version = "0.24.1", default-features = false } -fuel-core-types = { version = "0.24.1", default-features = false } +fuel-core = { version = "0.24.2", default-features = false } +fuel-core-chain-config = { version = "0.24.2", default-features = false } +fuel-core-client = { version = "0.24.2", default-features = false } +fuel-core-poa = { version = "0.24.2", default-features = false } +fuel-core-services = { version = "0.24.2", default-features = false } +fuel-core-types = { version = "0.24.2", default-features = false } # Dependencies from the `fuel-vm` repository: fuel-asm = { version = "0.48.0" } diff --git a/packages/fuels-accounts/src/provider/supported_versions.rs b/packages/fuels-accounts/src/provider/supported_versions.rs index e238d1fcc..eae993bb2 100644 --- a/packages/fuels-accounts/src/provider/supported_versions.rs +++ b/packages/fuels-accounts/src/provider/supported_versions.rs @@ -1,7 +1,7 @@ use semver::Version; fn get_supported_fuel_core_version() -> Version { - "0.24.1".parse().expect("is valid version") + "0.24.2".parse().expect("is valid version") } #[derive(Debug, PartialEq, Eq)] diff --git a/packages/fuels/tests/contracts.rs b/packages/fuels/tests/contracts.rs index c21fb3205..2cc5b3fbd 100644 --- a/packages/fuels/tests/contracts.rs +++ b/packages/fuels/tests/contracts.rs @@ -1336,7 +1336,6 @@ async fn low_level_call() -> Result<()> { Ok(()) } -#[ignore] #[cfg(not(feature = "fuel-core-lib"))] #[test] fn db_rocksdb() { From 75426895a79e5d5a6e740e7b63c6ccde20bf7a3c Mon Sep 17 00:00:00 2001 From: MujkicA Date: Fri, 5 Apr 2024 17:07:20 +0200 Subject: [PATCH 19/29] adjust witness num check --- packages/fuels-core/src/types/transaction_builders.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/fuels-core/src/types/transaction_builders.rs b/packages/fuels-core/src/types/transaction_builders.rs index d5102189d..c72a0ef8e 100644 --- a/packages/fuels-core/src/types/transaction_builders.rs +++ b/packages/fuels-core/src/types/transaction_builders.rs @@ -290,10 +290,10 @@ macro_rules! impl_tx_trait { fn num_witnesses(&self) -> Result { let num_witnesses = self.witnesses().len(); - if num_witnesses + self.unresolved_signers.len() > 256 { + if num_witnesses + self.unresolved_signers.len() > u16::MAX as usize { return Err(error_transaction!( Builder, - "tx cannot have more than 256 witnesses" + "tx exceeds maximum number of witnesses" )); } From 051ec31b19c63bab92c6101b050e7c9c59521797 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Tue, 9 Apr 2024 02:17:15 +0200 Subject: [PATCH 20/29] restore rocksdb feature flag --- docs/src/connecting/rocksdb.md | 11 +++++++++++ docs/src/connecting/short-lived.md | 9 +++++++++ examples/contracts/Cargo.toml | 1 + examples/cookbook/Cargo.toml | 1 + examples/cookbook/src/lib.rs | 19 +++++++++++++++++++ packages/fuels/Cargo.toml | 1 + packages/fuels/tests/contracts.rs | 2 +- 7 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 docs/src/connecting/rocksdb.md diff --git a/docs/src/connecting/rocksdb.md b/docs/src/connecting/rocksdb.md new file mode 100644 index 000000000..6733cf688 --- /dev/null +++ b/docs/src/connecting/rocksdb.md @@ -0,0 +1,11 @@ +# RocksDB + +RocksDB enables the preservation of the blockchain's state locally, facilitating its future utilization. + +To create or use a local database, follow these instructions: + +```rust,ignore +{{#include ../../../examples/cookbook/src/lib.rs:create_or_use_rocksdb}} +``` + +> Note: If the specified database does not exist, a new database will be created at that path. To utilize the code snippets above, either the `fuel-core` binary must be present, or both the `fuel-core-lib` and `rocksdb` features need to be enabled. \ No newline at end of file diff --git a/docs/src/connecting/short-lived.md b/docs/src/connecting/short-lived.md index 35ca847c6..1856f266e 100644 --- a/docs/src/connecting/short-lived.md +++ b/docs/src/connecting/short-lived.md @@ -29,3 +29,12 @@ The `fuel-core-lib` feature allows us to run a `fuel-core` node without installi ```rust,ignore fuels = { version = "0.56.0", features = ["fuel-core-lib"] } ``` + + +### RocksDB + +The `rocksdb` is an additional feature that, when combined with `fuel-core-lib`, provides persistent storage capabilities while using `fuel-core` as a library. + +```rust,ignore +fuels = { version = "0.56.0", features = ["rocksdb"] } +``` \ No newline at end of file diff --git a/examples/contracts/Cargo.toml b/examples/contracts/Cargo.toml index adbea3c71..dabd063d6 100644 --- a/examples/contracts/Cargo.toml +++ b/examples/contracts/Cargo.toml @@ -16,4 +16,5 @@ tokio = { workspace = true, features = ["full"] } [features] fuel-core-lib = ["fuels/fuel-core-lib"] +rocksdb = ["fuels/rocksdb"] experimental = ["fuels/experimental"] diff --git a/examples/cookbook/Cargo.toml b/examples/cookbook/Cargo.toml index 898376d23..bdd360baf 100644 --- a/examples/cookbook/Cargo.toml +++ b/examples/cookbook/Cargo.toml @@ -15,4 +15,5 @@ rand = { workspace = true } tokio = { workspace = true, features = ["full"] } [features] +rocksdb = ["fuels/rocksdb"] fuel-core-lib = ["fuels/fuel-core-lib"] diff --git a/examples/cookbook/src/lib.rs b/examples/cookbook/src/lib.rs index afeb4f180..da18bccd4 100644 --- a/examples/cookbook/src/lib.rs +++ b/examples/cookbook/src/lib.rs @@ -202,6 +202,25 @@ mod tests { Ok(()) } + #[tokio::test] + #[cfg(any(not(feature = "fuel-core-lib"), feature = "rocksdb"))] + async fn create_or_use_rocksdb() -> Result<()> { + use std::path::PathBuf; + + use fuels::prelude::*; + // ANCHOR: create_or_use_rocksdb + let provider_config = Config { + database_type: DbType::RocksDb(Some(PathBuf::from("/tmp/.spider/db"))), + ..Config::default() + }; + // ANCHOR_END: create_or_use_rocksdb + + launch_custom_provider_and_get_wallets(Default::default(), Some(provider_config), None) + .await?; + + Ok(()) + } + #[tokio::test] async fn custom_transaction() -> Result<()> { let mut hot_wallet = WalletUnlocked::new_random(None); diff --git a/packages/fuels/Cargo.toml b/packages/fuels/Cargo.toml index 5e85635a1..99b296b25 100644 --- a/packages/fuels/Cargo.toml +++ b/packages/fuels/Cargo.toml @@ -57,3 +57,4 @@ std = [ # TODO: To be removed once https://github.com/FuelLabs/fuels-rs/issues/881 is unblocked. test-type-paths = [] fuel-core-lib = ["fuels-test-helpers?/fuel-core-lib", "dep:fuel-core"] +rocksdb = ["fuel-core?/rocksdb"] diff --git a/packages/fuels/tests/contracts.rs b/packages/fuels/tests/contracts.rs index 2cc5b3fbd..703d0b280 100644 --- a/packages/fuels/tests/contracts.rs +++ b/packages/fuels/tests/contracts.rs @@ -1336,7 +1336,7 @@ async fn low_level_call() -> Result<()> { Ok(()) } -#[cfg(not(feature = "fuel-core-lib"))] +#[cfg(any(not(feature = "fuel-core-lib"), feature = "rocksdb"))] #[test] fn db_rocksdb() { use std::{fs, str::FromStr}; From 7db61e135c24d04ef18fc1cbac555cb845acca46 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Tue, 9 Apr 2024 02:23:06 +0200 Subject: [PATCH 21/29] fix base asset id --- examples/cookbook/src/lib.rs | 4 ++-- packages/fuels-accounts/src/provider.rs | 2 +- packages/fuels-core/src/types/transaction_builders.rs | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/cookbook/src/lib.rs b/examples/cookbook/src/lib.rs index ab0613020..e3648c21c 100644 --- a/examples/cookbook/src/lib.rs +++ b/examples/cookbook/src/lib.rs @@ -208,9 +208,9 @@ mod tests { use fuels::prelude::*; // ANCHOR: create_or_use_rocksdb - let provider_config = Config { + let provider_config = NodeConfig { database_type: DbType::RocksDb(Some(PathBuf::from("/tmp/.spider/db"))), - ..Config::default() + ..NodeConfig::default() }; // ANCHOR_END: create_or_use_rocksdb diff --git a/packages/fuels-accounts/src/provider.rs b/packages/fuels-accounts/src/provider.rs index bfba556b0..a3ced3f3f 100644 --- a/packages/fuels-accounts/src/provider.rs +++ b/packages/fuels-accounts/src/provider.rs @@ -240,7 +240,7 @@ impl Provider { } pub fn base_asset_id(&self) -> &AssetId { - &self.consensus_parameters.base_asset_id + &self.consensus_parameters.base_asset_id() } fn ensure_client_version_is_supported(node_info: &NodeInfo) -> Result<()> { diff --git a/packages/fuels-core/src/types/transaction_builders.rs b/packages/fuels-core/src/types/transaction_builders.rs index ba118844f..ff70d70db 100644 --- a/packages/fuels-core/src/types/transaction_builders.rs +++ b/packages/fuels-core/src/types/transaction_builders.rs @@ -407,12 +407,12 @@ impl ScriptTransactionBuilder { fn no_base_asset_input<'a>( inputs: impl IntoIterator, - base_asset_id: AssetId, + base_asset_id: &AssetId, ) -> bool { let has_base_asset = inputs.into_iter().any(|i| match i { FuelInput::CoinSigned(CoinSigned { asset_id, .. }) | FuelInput::CoinPredicate(CoinPredicate { asset_id, .. }) - if *asset_id == base_asset_id => + if asset_id == base_asset_id => { true } @@ -429,7 +429,7 @@ impl ScriptTransactionBuilder { tolerance: f32, ) -> Result<()> { let consensus_params = provider.consensus_parameters(); - let base_asset_id = provider.consensus_parameters().base_asset_id; + let base_asset_id = provider.consensus_parameters().base_asset_id(); // The dry-run validation will check if there is any base asset input. // If we are dry-running without inputs we have to add a temporary one. From 629966a0079b07be2b1e56ae7fc00e70906af835 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Tue, 9 Apr 2024 02:24:29 +0200 Subject: [PATCH 22/29] return rocksdb to doc summary --- docs/src/SUMMARY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index b69c294ea..5362bb423 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -6,6 +6,7 @@ - [Connecting to a Fuel node](./connecting/index.md) - [Connecting to the Testnet or an external node](./connecting/external-node.md) - [Running a short-lived Fuel node with the SDK](./connecting/short-lived.md) + - [RocksDB](./connecting/rocksdb.md) - [Querying the blockchain](./connecting/querying.md) - [Retrying upon errors](./connecting/retrying.md) - [Accounts](./accounts.md) From b05805caf23ec21ac24cebbafbeb43e10414a1cf Mon Sep 17 00:00:00 2001 From: MujkicA Date: Tue, 9 Apr 2024 02:27:55 +0200 Subject: [PATCH 23/29] cargo lint --- docs/src/connecting/short-lived.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/src/connecting/short-lived.md b/docs/src/connecting/short-lived.md index 1856f266e..632e64ee4 100644 --- a/docs/src/connecting/short-lived.md +++ b/docs/src/connecting/short-lived.md @@ -30,7 +30,6 @@ The `fuel-core-lib` feature allows us to run a `fuel-core` node without installi fuels = { version = "0.56.0", features = ["fuel-core-lib"] } ``` - ### RocksDB The `rocksdb` is an additional feature that, when combined with `fuel-core-lib`, provides persistent storage capabilities while using `fuel-core` as a library. From 3beec054cba95521ed60e8a39ad187d917e9b9b4 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Tue, 9 Apr 2024 02:31:51 +0200 Subject: [PATCH 24/29] mdbook lint --- docs/src/connecting/rocksdb.md | 2 +- docs/src/connecting/short-lived.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/src/connecting/rocksdb.md b/docs/src/connecting/rocksdb.md index 6733cf688..0dc07bf5e 100644 --- a/docs/src/connecting/rocksdb.md +++ b/docs/src/connecting/rocksdb.md @@ -8,4 +8,4 @@ To create or use a local database, follow these instructions: {{#include ../../../examples/cookbook/src/lib.rs:create_or_use_rocksdb}} ``` -> Note: If the specified database does not exist, a new database will be created at that path. To utilize the code snippets above, either the `fuel-core` binary must be present, or both the `fuel-core-lib` and `rocksdb` features need to be enabled. \ No newline at end of file +> Note: If the specified database does not exist, a new database will be created at that path. To utilize the code snippets above, either the `fuel-core` binary must be present, or both the `fuel-core-lib` and `rocksdb` features need to be enabled. diff --git a/docs/src/connecting/short-lived.md b/docs/src/connecting/short-lived.md index 632e64ee4..b125632bb 100644 --- a/docs/src/connecting/short-lived.md +++ b/docs/src/connecting/short-lived.md @@ -36,4 +36,4 @@ The `rocksdb` is an additional feature that, when combined with `fuel-core-lib`, ```rust,ignore fuels = { version = "0.56.0", features = ["rocksdb"] } -``` \ No newline at end of file +``` From 501fcce89c462b766ec4b664bf8d26ca68f35bec Mon Sep 17 00:00:00 2001 From: MujkicA Date: Tue, 9 Apr 2024 02:47:32 +0200 Subject: [PATCH 25/29] clippy --- packages/fuels-accounts/src/provider.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/fuels-accounts/src/provider.rs b/packages/fuels-accounts/src/provider.rs index a3ced3f3f..50ef9d809 100644 --- a/packages/fuels-accounts/src/provider.rs +++ b/packages/fuels-accounts/src/provider.rs @@ -240,7 +240,7 @@ impl Provider { } pub fn base_asset_id(&self) -> &AssetId { - &self.consensus_parameters.base_asset_id() + self.consensus_parameters.base_asset_id() } fn ensure_client_version_is_supported(node_info: &NodeInfo) -> Result<()> { From 850c8c739978e8154faf4ea3837af15ea4784a7a Mon Sep 17 00:00:00 2001 From: MujkicA Date: Tue, 9 Apr 2024 14:23:10 +0200 Subject: [PATCH 26/29] fix gas estimation test --- packages/fuels/tests/providers.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/fuels/tests/providers.rs b/packages/fuels/tests/providers.rs index ad3745bda..95b11b97f 100644 --- a/packages/fuels/tests/providers.rs +++ b/packages/fuels/tests/providers.rs @@ -314,7 +314,6 @@ async fn contract_deployment_respects_maturity() -> Result<()> { Ok(()) } -#[ignore] #[tokio::test] async fn test_gas_forwarded_defaults_to_tx_limit() -> Result<()> { setup_program_test!( @@ -332,7 +331,7 @@ async fn test_gas_forwarded_defaults_to_tx_limit() -> Result<()> { // The gas used by the script to call a contract and forward remaining gas limit. #[cfg(not(feature = "experimental"))] - let gas_used_by_script = 841; + let gas_used_by_script = 364; #[cfg(feature = "experimental")] let gas_used_by_script = 876; let gas_limit = 225_883; From 37e666219b88cd67adb0b60213873ae6615d9a9c Mon Sep 17 00:00:00 2001 From: MujkicA <32431923+MujkicA@users.noreply.github.com> Date: Wed, 10 Apr 2024 06:00:11 +0200 Subject: [PATCH 27/29] Update packages/fuels-test-helpers/Cargo.toml Co-authored-by: Ahmed Sagdati <37515857+segfault-magnet@users.noreply.github.com> --- packages/fuels-test-helpers/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/fuels-test-helpers/Cargo.toml b/packages/fuels-test-helpers/Cargo.toml index 8e24a8824..eae1ab277 100644 --- a/packages/fuels-test-helpers/Cargo.toml +++ b/packages/fuels-test-helpers/Cargo.toml @@ -11,7 +11,7 @@ description = "Fuel Rust SDK test helpers." [dependencies] fuel-core = { workspace = true, default-features = false, features = ["test-helpers"], optional = true } -fuel-core-chain-config = { workspace = true, default-features = false, features = ["test-helpers"] } +fuel-core-chain-config = { workspace = true, features = ["test-helpers"] } fuel-core-client = { workspace = true } fuel-core-poa = { workspace = true } fuel-core-services = { workspace = true } From cac0adbae09bd090f3856ba22c55db46f54b1748 Mon Sep 17 00:00:00 2001 From: MujkicA <32431923+MujkicA@users.noreply.github.com> Date: Wed, 10 Apr 2024 06:00:18 +0200 Subject: [PATCH 28/29] Update packages/fuels-test-helpers/Cargo.toml Co-authored-by: Ahmed Sagdati <37515857+segfault-magnet@users.noreply.github.com> --- packages/fuels-test-helpers/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/fuels-test-helpers/Cargo.toml b/packages/fuels-test-helpers/Cargo.toml index eae1ab277..844fb7c0d 100644 --- a/packages/fuels-test-helpers/Cargo.toml +++ b/packages/fuels-test-helpers/Cargo.toml @@ -30,4 +30,4 @@ which = { workspace = true, default-features = false } [features] default = ["fuels-accounts", "std"] std = ["fuels-accounts?/std", "fuels-core/std", "fuel-core-chain-config/std"] -fuel-core-lib = ["fuel-core"] +fuel-core-lib = ["dep:fuel-core"] From 2f627575087ea3a8979beb33ddbbf661323a0cb7 Mon Sep 17 00:00:00 2001 From: MujkicA Date: Wed, 10 Apr 2024 06:06:42 +0200 Subject: [PATCH 29/29] ensure temp dir cleanup in rocksdb test --- packages/fuels/tests/contracts.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/fuels/tests/contracts.rs b/packages/fuels/tests/contracts.rs index e9db1b7cd..49edcf9a3 100644 --- a/packages/fuels/tests/contracts.rs +++ b/packages/fuels/tests/contracts.rs @@ -1348,19 +1348,19 @@ fn db_rocksdb() { prelude::{setup_test_provider, DbType, Error, ViewOnlyAccount, DEFAULT_COIN_AMOUNT}, }; - let temp_dir = tempfile::tempdir() - .expect("failed to make tempdir") - .into_path(); + let temp_dir = tempfile::tempdir().expect("failed to make tempdir"); let temp_dir_name = temp_dir + .path() .file_name() .expect("failed to get file name") .to_string_lossy() .to_string(); - let temp_database_path = temp_dir.join("db"); + let temp_database_path = temp_dir.path().join("db"); tokio::runtime::Runtime::new() .expect("tokio runtime failed") .block_on(async { + let _ = temp_dir; let wallet = WalletUnlocked::new_from_private_key( SecretKey::from_str( "0x4433d156e8c53bf5b50af07aa95a29436f29a94e0ccc5d58df8e57bdc8583c32",