Skip to content

Commit

Permalink
feat: (experimental) optional fee estimator with different algorithms
Browse files Browse the repository at this point in the history
  • Loading branch information
yangby-cryptape committed Jun 4, 2024
1 parent 31e0287 commit f7f60e0
Show file tree
Hide file tree
Showing 29 changed files with 1,550 additions and 8 deletions.
13 changes: 13 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ members = [
"util/instrument",
"rpc",
"util/light-client-protocol-server",
"util/fee-estimator",
"util/launcher",
"devtools/doc/rpc-gen",
"ckb-bin"
Expand Down
7 changes: 7 additions & 0 deletions chain/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,7 @@ impl ChainService {
// is_better_than
let new_best_block = cannon_total_difficulty > current_total_difficulty;

let in_ibd = self.shared.is_initial_block_download();
if new_best_block {
debug!(
"Newly found best block : {} => {:#x}, difficulty diff = {:#x}",
Expand Down Expand Up @@ -517,6 +518,9 @@ impl ChainService {
) {
error!("Notify update_tx_pool_for_reorg error {}", e);
}
if let Err(e) = tx_pool_controller.update_ibd_state(in_ibd) {
error!("Notify update_ibd_state error {}", e);
}
}

let block_ref: &BlockView = █
Expand Down Expand Up @@ -546,6 +550,9 @@ impl ChainService {
if let Err(e) = tx_pool_controller.notify_new_uncle(block_ref.as_uncle()) {
error!("Notify new_uncle error {}", e);
}
if let Err(e) = tx_pool_controller.update_ibd_state(in_ibd) {
error!("Notify update_ibd_state error {}", e);
}
}
}

Expand Down
4 changes: 4 additions & 0 deletions resource/ckb.toml
Original file line number Diff line number Diff line change
Expand Up @@ -218,3 +218,7 @@ block_uncles_cache_size = 30
# db_port = 5432
# db_user = "postgres"
# db_password = "123456"
#
# # [fee_estimator]
# # Specifies the fee estimates algorithm. Current algorithms: ConfirmationFraction, WeightUnitsFlow.
# # algorithm = "WeightUnitsFlow"
61 changes: 61 additions & 0 deletions rpc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ The crate `ckb-rpc`'s minimum supported rustc version is 1.71.1.

* [Method `dry_run_transaction`](#experiment-dry_run_transaction)
* [Method `calculate_dao_maximum_withdraw`](#experiment-calculate_dao_maximum_withdraw)
* [Method `get_fee_estimates`](#experiment-get_fee_estimates)
* [Module Indexer](#module-indexer) [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Indexer&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/nervosnetwork/ckb-rpc-resources/develop/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/nervosnetwork/ckb-rpc-resources/develop/json/indexer_rpc_doc.json)

* [Method `get_indexer_tip`](#indexer-get_indexer_tip)
Expand Down Expand Up @@ -208,6 +209,7 @@ The crate `ckb-rpc`'s minimum supported rustc version is 1.71.1.
* [Type `Ratio`](#type-ratio)
* [Type `RationalU256`](#type-rationalu256)
* [Type `RawTxPool`](#type-rawtxpool)
* [Type `RecommendedFeeRates`](#type-recommendedfeerates)
* [Type `RemoteNode`](#type-remotenode)
* [Type `RemoteNodeProtocol`](#type-remotenodeprotocol)
* [Type `ResponseFormat<BlockView>`](#type-responseformat_for_blockview)
Expand Down Expand Up @@ -2162,6 +2164,50 @@ Response
}
```

<a id="experiment-get_fee_estimates"></a>
#### Method `get_fee_estimates`
* `get_fee_estimates()`

* result: [`RecommendedFeeRates`](#type-recommendedfeerates)

Get fee estimates.

###### Returns

Recommended fee rates in 4 levels of priorities:
- No priority.
- High priority.
- Medium priority.
- Low priority.

###### Examples

Request

```json
{
"id": 42,
"jsonrpc": "2.0",
"method": "get_fee_estimates",
"params": []
}
```

Response

```json
{
"id": 42,
"jsonrpc": "2.0",
"result": {
"high_priority": 1000,
"low_priority": 1000,
"medium_priority": 1000,
"no_priority": 1000
}
}
```

### Module `Indexer`
- [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Indexer&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/nervosnetwork/ckb-rpc-resources/develop/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/nervosnetwork/ckb-rpc-resources/develop/json/indexer_rpc_doc.json)

Expand Down Expand Up @@ -6606,6 +6652,21 @@ All transactions in tx-pool.
[`TxPoolIds`]: struct.TxPoolIds.html
[`TxPoolEntries`]: struct.TxPoolEntries.html

### Type `RecommendedFeeRates`
Recommended fee rates.

#### Fields

`RecommendedFeeRates` is a JSON object with the following fields.

* `high_priority`: `integer` - High-priority fee rate.

* `low_priority`: `integer` - Low-priority fee rate.

* `medium_priority`: `integer` - Medium-priority fee rate.

* `no_priority`: `integer` - Default fee rate.

### Type `RemoteNode`
Information of a remote node.

Expand Down
58 changes: 57 additions & 1 deletion rpc/src/module/experiment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use crate::module::chain::CyclesEstimator;
use async_trait::async_trait;
use ckb_dao::DaoCalculator;
use ckb_jsonrpc_types::{
Capacity, DaoWithdrawingCalculationKind, EstimateCycles, OutPoint, Transaction,
Capacity, DaoWithdrawingCalculationKind, EstimateCycles, OutPoint, RecommendedFeeRates,
Transaction,
};
use ckb_shared::{shared::Shared, Snapshot};
use ckb_store::ChainStore;
Expand Down Expand Up @@ -162,6 +163,46 @@ pub trait ExperimentRpc {
out_point: OutPoint,
kind: DaoWithdrawingCalculationKind,
) -> Result<Capacity>;

/// Get fee estimates.
///
/// ## Returns
///
/// Recommended fee rates in 4 levels of priorities:
/// - No priority.
/// - Low priority.
/// - Medium priority.
/// - High priority.
///
/// ## Examples
///
/// Request
///
/// ```json
/// {
/// "id": 42,
/// "jsonrpc": "2.0",
/// "method": "get_fee_estimates",
/// "params": []
/// }
/// ```
///
/// Response
///
/// ```json
/// {
/// "id": 42,
/// "jsonrpc": "2.0",
/// "result": {
/// "no_priority": 1000,
/// "low_priority": 1000,
/// "medium_priority": 1000,
/// "high_priority": 1000
/// }
/// }
/// ```
#[rpc(name = "get_fee_estimates")]
fn get_fee_estimates(&self) -> Result<RecommendedFeeRates>;
}

#[derive(Clone)]
Expand Down Expand Up @@ -241,4 +282,19 @@ impl ExperimentRpc for ExperimentRpcImpl {
}
}
}

fn get_fee_estimates(&self) -> Result<RecommendedFeeRates> {
let tx_pool = self.shared.tx_pool_controller();
let fee_rates_res = tx_pool
.get_fee_estimates()
.map_err(|err| RPCError::custom(RPCError::CKBInternalError, err.to_string()))?;
if let Ok(Some(fee_rates)) = fee_rates_res {
Ok(fee_rates)
} else {
// TODO merge code from PR#4465
let msg = "fallback fee estimates algorithm is unfinished";
let err = RPCError::custom(RPCError::CKBInternalError, msg.to_owned());
Err(err)
}
}
}
2 changes: 2 additions & 0 deletions rpc/src/tests/examples.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use std::hash;
use std::io::{self, BufRead};
use std::path::PathBuf;

use ckb_jsonrpc_types::RecommendedFeeRates;
use ckb_types::{
core::{capacity_bytes, Capacity, TransactionBuilder, TransactionView},
h256,
Expand Down Expand Up @@ -389,6 +390,7 @@ fn mock_rpc_response(example: &RpcTestExample, response: &mut RpcTestResponse) {
"get_pool_tx_detail_info" => {
response.result["timestamp"] = example.response.result["timestamp"].clone()
}
"get_fee_estimates" => replace_rpc_response::<RecommendedFeeRates>(example, response),
_ => {}
}
}
Expand Down
1 change: 1 addition & 0 deletions shared/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ ckb-systemtime = { path = "../util/systemtime", version = "= 0.117.0-pre" }
ckb-channel = { path = "../util/channel", version = "= 0.117.0-pre" }
ckb-app-config = {path = "../util/app-config", version = "= 0.117.0-pre"}
ckb-migrate = { path = "../util/migrate", version = "= 0.117.0-pre" }
ckb-fee-estimator = {path = "../util/fee-estimator", version = "= 0.117.0-pre"}
once_cell = "1.8.0"
tempfile.workspace = true

Expand Down
Loading

0 comments on commit f7f60e0

Please sign in to comment.