Skip to content

Commit

Permalink
Add V0 algorithm to actual services (#2025)
Browse files Browse the repository at this point in the history
Part of #1624

The [previous PR](#1983) added
all the code for working with the dynamic gas price, but didn't plug it
into our services. This PR does the actual dep injection. It also adds
gas price estimation to AlgoirthmV0.

This change includes new flags for the CLI:
- "starting-gas-price" - the starting gas price for the gas price
algorithm
- "gas-price-change-percent" - the percent change for each gas price
update
- "gas-price-threshold-percent" - the threshold percent for determining
if the gas price will be increase or decreased
    And the following CLI flags are serving a new purpose
- "min-gas-price" - the minimum gas price that the gas price algorithm
will return

## Checklist
- [ ] Breaking changes are clearly marked as such in the PR description
and changelog
- [ ] New behavior is reflected in tests
- [ ] [The specification](https://github.com/FuelLabs/fuel-specs/)
matches the implemented behavior (link update PR if changes are needed)

### Before requesting review
- [x] I have reviewed the code myself
- [ ] I have created follow-up issues caused by this PR and linked them
here

### After merging, notify other teams

[Add or remove entries as needed]

- [ ] [Rust SDK](https://github.com/FuelLabs/fuels-rs/)
- [ ] [Sway compiler](https://github.com/FuelLabs/sway/)
- [ ] [Platform
documentation](https://github.com/FuelLabs/devrel-requests/issues/new?assignees=&labels=new+request&projects=&template=NEW-REQUEST.yml&title=%5BRequest%5D%3A+)
(for out-of-organization contributors, the person merging the PR will do
this)
- [ ] Someone else?

---------

Co-authored-by: human <jamesturner@Zenobia.hsd1.wa.comcast.net>
Co-authored-by: Green Baneling <XgreenX9999@gmail.com>
Co-authored-by: Hannes Karppila <2204863+Dentosal@users.noreply.github.com>
  • Loading branch information
4 people authored Jul 19, 2024
1 parent 983409b commit ab5a937
Show file tree
Hide file tree
Showing 53 changed files with 833 additions and 412 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
### Added
- [1983](https://github.com/FuelLabs/fuel-core/pull/1983): Add adapters for gas price service for accessing database values

### Breaking
- [2025](https://github.com/FuelLabs/fuel-core/pull/2025): Add new V0 algorithm for gas price to services.
This change includes new flags for the CLI:
- "starting-gas-price" - the starting gas price for the gas price algorithm
- "gas-price-change-percent" - the percent change for each gas price update
- "gas-price-threshold-percent" - the threshold percent for determining if the gas price will be increase or decreased
And the following CLI flags are serving a new purpose
- "min-gas-price" - the minimum gas price that the gas price algorithm will return
## [Version 0.31.0]

### Added
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion benches/benches/block_target_gas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,12 @@ fn service_with_many_contracts(
}

let service = FuelService::new(
CombinedDatabase::new(database, Default::default(), Default::default()),
CombinedDatabase::new(
database,
Default::default(),
Default::default(),
Default::default(),
),
config.clone(),
)
.expect("Unable to start a FuelService");
Expand Down
25 changes: 15 additions & 10 deletions bin/e2e-test-client/src/test_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ impl Wallet {
];

// build transaction
let mut tx = TransactionBuilder::script(
let mut tx_builder = TransactionBuilder::script(
script.into_iter().collect(),
asset_id
.to_bytes()
Expand All @@ -202,10 +202,11 @@ impl Wallet {
.chain(0u64.to_bytes().into_iter())
.collect(),
);
tx.max_fee_limit(BASE_AMOUNT);
tx.script_gas_limit(self.consensus_params.tx_params().max_gas_per_tx() / 10);
tx_builder.max_fee_limit(BASE_AMOUNT);
tx_builder
.script_gas_limit(self.consensus_params.tx_params().max_gas_per_tx() / 10);

tx.add_input(Input::contract(
tx_builder.add_input(Input::contract(
Default::default(),
Default::default(),
Default::default(),
Expand All @@ -214,7 +215,7 @@ impl Wallet {
));
for coin in coins {
if let CoinType::Coin(coin) = coin {
tx.add_unsigned_coin_input(
tx_builder.add_unsigned_coin_input(
self.secret,
coin.utxo_id,
coin.amount,
Expand All @@ -223,20 +224,24 @@ impl Wallet {
);
}
}
tx.add_output(Output::contract(0, Default::default(), Default::default()));
tx.add_output(Output::Change {
tx_builder.add_output(Output::contract(
0,
Default::default(),
Default::default(),
));
tx_builder.add_output(Output::Change {
to: self.address,
amount: 0,
asset_id,
});
tx.add_output(Output::Variable {
tx_builder.add_output(Output::Variable {
to: Default::default(),
amount: Default::default(),
asset_id: Default::default(),
});
tx.with_params(self.consensus_params.clone());
tx_builder.with_params(self.consensus_params.clone());

Ok(tx.finalize_as_transaction())
Ok(tx_builder.finalize_as_transaction())
}

/// Transfers coins from this wallet to another
Expand Down
3 changes: 2 additions & 1 deletion bin/e2e-test-client/src/tests/collect_fee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ pub async fn collect_fee(ctx: &TestContext) -> Result<(), Failed> {
.iter()
.any(|receipt| matches!(receipt, Receipt::TransferOut { .. }))
{
return Err("collect fee hasn't produced `TransferOut` receipt".into())
let msg = format!("TransferOut receipt not found in receipts: {:?}", receipts);
return Err(msg.into())
}

Ok(())
Expand Down
8 changes: 4 additions & 4 deletions bin/e2e-test-client/src/tests/script.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@ use fuel_core_types::{
UniqueIdentifier,
},
fuel_types::{
canonical::Deserialize,
canonical::{
Deserialize,
Serialize,
},
Salt,
},
services::executor::TransactionExecutionResult,
};

use fuel_core_types::fuel_types::canonical::Serialize;
use libtest_mimic::Failed;
use std::{
path::Path,
Expand Down Expand Up @@ -145,7 +146,6 @@ pub async fn run_contract_large_state(ctx: &TestContext) -> Result<(), Failed> {
pub async fn arbitrary_transaction(ctx: &TestContext) -> Result<(), Failed> {
const RAW_PATH: &str = "src/tests/test_data/arbitrary_tx.raw";
const JSON_PATH: &str = "src/tests/test_data/arbitrary_tx.json";

let dry_run_raw =
std::fs::read_to_string(RAW_PATH).expect("Should read the raw transaction");
let dry_run_json =
Expand Down
2 changes: 1 addition & 1 deletion bin/e2e-test-client/src/tests/test_data/arbitrary_tx.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
0,
0,
0,
100000
30000000
]
},
"inputs": [
Expand Down
2 changes: 1 addition & 1 deletion bin/e2e-test-client/src/tests/test_data/arbitrary_tx.raw
Original file line number Diff line number Diff line change
@@ -1 +1 @@
000000000000000000000000000186a00000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000008000000000000000100000000000000020000000000000001240000000000000000000000000186a000000000000000008b5a47933cbb7ddbc0392a45a124a2a01f17c657d34d4951324003a2f9aff24a000000000000000157cd0f26d30e6e0361742800f0cb39b87d2bd58e052c4389d7e507e39e504a01000000001d34a76ef8f8b6283d7fa5b672b530cbb84fcccb4ff8dc40f8176ef4544ddb1f1952ad070000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000eeb709945b9058c3d50f3922bd1b49f92ced2950a9ecaf810aa7829295550cd20000000000002710f8f8b6283d7fa5b672b530cbb84fcccb4ff8dc40f8176ef4544ddb1f1952ad07000000000000000357cd0f26d30e6e0361742800f0cb39b87d2bd58e052c4389d7e507e39e504a01000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000186a0000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000800000000000000010000000000000002000000000000000124000000000000000000000001c9c38000000000000000008b5a47933cbb7ddbc0392a45a124a2a01f17c657d34d4951324003a2f9aff24a000000000000000157cd0f26d30e6e0361742800f0cb39b87d2bd58e052c4389d7e507e39e504a01000000001d34a76ef8f8b6283d7fa5b672b530cbb84fcccb4ff8dc40f8176ef4544ddb1f1952ad070000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000eeb709945b9058c3d50f3922bd1b49f92ced2950a9ecaf810aa7829295550cd20000000000002710f8f8b6283d7fa5b672b530cbb84fcccb4ff8dc40f8176ef4544ddb1f1952ad07000000000000000357cd0f26d30e6e0361742800f0cb39b87d2bd58e052c4389d7e507e39e504a01000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Original file line number Diff line number Diff line change
Expand Up @@ -4138,7 +4138,7 @@
0,
0,
0,
100000
12390831
]
},
"inputs": [
Expand Down
2 changes: 1 addition & 1 deletion bin/e2e-test-client/tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ fn dev_config() -> Config {
let reader = reader.with_chain_config(chain_config);

let mut config = Config::local_node_with_reader(reader);
config.static_gas_price = 1;
config.starting_gas_price = 1;
config.block_producer.coinbase_recipient = Some(
ContractId::from_str(
"0x7777777777777777777777777777777777777777777777777777777777777777",
Expand Down
2 changes: 1 addition & 1 deletion bin/fuel-core/chainspec/local-testnet/chain_config.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
},
"fee_params": {
"V1": {
"gas_price_factor": 92,
"gas_price_factor": 92000,
"gas_per_byte": 63
}
},
Expand Down
Binary file not shown.
20 changes: 19 additions & 1 deletion bin/fuel-core/src/cli/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,10 +165,22 @@ pub struct Command {
#[arg(long = "native-executor-version", env)]
pub native_executor_version: Option<StateTransitionBytecodeVersion>,

/// The starting gas price for the network
#[arg(long = "starting-gas-price", default_value = "0", env)]
pub starting_gas_price: u64,

/// The percentage change in gas price per block
#[arg(long = "gas-price-change-percent", default_value = "0", env)]
pub gas_price_change_percent: u64,

/// The minimum allowed gas price
#[arg(long = "min-gas-price", default_value = "0", env)]
pub min_gas_price: u64,

/// The percentage threshold for gas price increase
#[arg(long = "gas-price-threshold-percent", default_value = "50", env)]
pub gas_price_threshold_percent: u64,

/// The signing key used when producing blocks.
/// Setting via the `CONSENSUS_KEY_SECRET` ENV var is preferred.
#[arg(long = "consensus-key", env)]
Expand Down Expand Up @@ -245,7 +257,10 @@ impl Command {
debug,
utxo_validation,
native_executor_version,
starting_gas_price,
gas_price_change_percent,
min_gas_price,
gas_price_threshold_percent,
consensus_key,
poa_trigger,
coinbase_recipient,
Expand Down Expand Up @@ -408,7 +423,10 @@ impl Command {
coinbase_recipient,
metrics,
},
static_gas_price: min_gas_price,
starting_gas_price,
gas_price_change_percent,
min_gas_price,
gas_price_threshold_percent,
block_importer,
#[cfg(feature = "relayer")]
relayer: relayer_cfg,
Expand Down
1 change: 1 addition & 0 deletions crates/client/src/client/types/gas_price.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::client::schema;
use fuel_core_types::fuel_types::BlockHeight;

#[derive(Debug, Copy, Clone)]
pub struct LatestGasPrice {
pub gas_price: u64,
pub block_height: BlockHeight,
Expand Down
22 changes: 19 additions & 3 deletions crates/fuel-core/src/combined_database.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#[cfg(feature = "rocksdb")]
use crate::state::historical_rocksdb::StateRewindPolicy;
use crate::{
database::{
database_description::{
gas_price::GasPriceDatabase,
off_chain::OffChain,
on_chain::OnChain,
relayer::Relayer,
Expand Down Expand Up @@ -28,9 +31,6 @@ use fuel_core_storage::tables::{
use fuel_core_storage::Result as StorageResult;
use std::path::PathBuf;

#[cfg(feature = "rocksdb")]
use crate::state::historical_rocksdb::StateRewindPolicy;

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CombinedDatabaseConfig {
pub database_path: PathBuf,
Expand All @@ -46,18 +46,21 @@ pub struct CombinedDatabase {
on_chain: Database<OnChain>,
off_chain: Database<OffChain>,
relayer: Database<Relayer>,
gas_price: Database<GasPriceDatabase>,
}

impl CombinedDatabase {
pub fn new(
on_chain: Database<OnChain>,
off_chain: Database<OffChain>,
relayer: Database<Relayer>,
gas_price: Database<GasPriceDatabase>,
) -> Self {
Self {
on_chain,
off_chain,
relayer,
gas_price,
}
}

Expand All @@ -66,6 +69,7 @@ impl CombinedDatabase {
crate::state::rocks_db::RocksDb::<OnChain>::prune(path)?;
crate::state::rocks_db::RocksDb::<OffChain>::prune(path)?;
crate::state::rocks_db::RocksDb::<Relayer>::prune(path)?;
crate::state::rocks_db::RocksDb::<GasPriceDatabase>::prune(path)?;
Ok(())
}

Expand All @@ -80,10 +84,12 @@ impl CombinedDatabase {
let off_chain = Database::open_rocksdb(path, capacity, state_rewind_policy)?;
let relayer =
Database::open_rocksdb(path, capacity, StateRewindPolicy::NoRewind)?;
let gas_price = Database::open_rocksdb(path, capacity, state_rewind_policy)?;
Ok(Self {
on_chain,
off_chain,
relayer,
gas_price,
})
}

Expand Down Expand Up @@ -124,6 +130,7 @@ impl CombinedDatabase {
Database::in_memory(),
Database::in_memory(),
Database::in_memory(),
Database::in_memory(),
)
}

Expand Down Expand Up @@ -161,6 +168,15 @@ impl CombinedDatabase {
&mut self.relayer
}

pub fn gas_price(&self) -> &Database<GasPriceDatabase> {
&self.gas_price
}

#[cfg(any(feature = "test-helpers", test))]
pub fn gas_price_mut(&mut self) -> &mut Database<GasPriceDatabase> {
&mut self.gas_price
}

#[cfg(feature = "test-helpers")]
pub fn read_state_config(&self) -> StorageResult<StateConfig> {
use fuel_core_chain_config::AddTable;
Expand Down
8 changes: 6 additions & 2 deletions crates/fuel-core/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,12 @@ impl FuelService {
database: Database,
config: Config,
) -> anyhow::Result<Self> {
let combined_database =
CombinedDatabase::new(database, Default::default(), Default::default());
let combined_database = CombinedDatabase::new(
database,
Default::default(),
Default::default(),
Default::default(),
);
Self::from_combined_database(combined_database, config).await
}

Expand Down
20 changes: 8 additions & 12 deletions crates/fuel-core/src/service/adapters/fuel_gas_price_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use fuel_core_gas_price_service::{
SharedGasPriceAlgo,
};
use fuel_core_producer::block_producer::gas_price::GasPriceProvider as ProducerGasPriceProvider;
use fuel_core_txpool::ports::GasPriceProvider as TxPoolGasPricProvider;
use fuel_core_txpool::ports::GasPriceProvider as TxPoolGasPriceProvider;
use fuel_core_types::{
fuel_types::BlockHeight,
services::txpool::Result as TxPoolResult,
Expand Down Expand Up @@ -53,12 +53,8 @@ impl<A> FuelGasPriceProvider<A>
where
A: GasPriceAlgorithm + Send + Sync,
{
async fn next_gas_price(&self, block_bytes: u64) -> u64 {
self.algorithm.next_gas_price(block_bytes).await
}

async fn last_gas_price(&self) -> u64 {
self.algorithm.last_gas_price().await
async fn next_gas_price(&self) -> u64 {
self.algorithm.next_gas_price().await
}
}

Expand All @@ -67,18 +63,18 @@ impl<A> ProducerGasPriceProvider for FuelGasPriceProvider<A>
where
A: GasPriceAlgorithm + Send + Sync,
{
async fn next_gas_price(&self, block_bytes: u64) -> anyhow::Result<u64> {
Ok(self.next_gas_price(block_bytes).await)
async fn next_gas_price(&self) -> anyhow::Result<u64> {
Ok(self.next_gas_price().await)
}
}

#[async_trait::async_trait]
impl<A> TxPoolGasPricProvider for FuelGasPriceProvider<A>
impl<A> TxPoolGasPriceProvider for FuelGasPriceProvider<A>
where
A: GasPriceAlgorithm + Send + Sync,
{
async fn last_gas_price(&self) -> TxPoolResult<u64> {
Ok(self.last_gas_price().await)
async fn next_gas_price(&self) -> TxPoolResult<u64> {
Ok(self.next_gas_price().await)
}
}

Expand Down
Loading

0 comments on commit ab5a937

Please sign in to comment.