RPC to query transaction fee + weight + info (#3876)

* initial version for testing

* New version that compiles

* optional at block parameter

* Fix some more view grumbles.

* Update srml/transaction-payment/src/lib.rs
This commit is contained in:
Kian Paimani
2019-10-28 16:04:45 +01:00
committed by Gavin Wood
parent 9b1dd268bf
commit 7e87dfdc07
15 changed files with 359 additions and 21 deletions
+1 -1
View File
@@ -571,7 +571,7 @@ mod tests {
assert!(Executive::apply_extrinsic(x2.clone()).unwrap().is_ok());
// default weight for `TestXt` == encoded length.
assert_eq!(<system::Module<Runtime>>::all_extrinsics_weight(), (3 * len).into());
assert_eq!(<system::Module<Runtime>>::all_extrinsics_weight(), (3 * len) as u32);
assert_eq!(<system::Module<Runtime>>::all_extrinsics_len(), 3 * len);
let _ = <system::Module<Runtime>>::finalize();
@@ -10,6 +10,7 @@ rstd = { package = "sr-std", path = "../../core/sr-std", default-features = fals
sr-primitives = { path = "../../core/sr-primitives", default-features = false }
support = { package = "srml-support", path = "../support", default-features = false }
system = { package = "srml-system", path = "../system", default-features = false }
transaction-payment-rpc-runtime-api = { package = "srml-transaction-payment-rpc-runtime-api", path = "./rpc/runtime-api", default-features = false }
[dev-dependencies]
runtime-io = { package = "sr-io", path = "../../core/sr-io" }
@@ -24,4 +25,5 @@ std = [
"sr-primitives/std",
"support/std",
"system/std",
"transaction-payment-rpc-runtime-api/std"
]
@@ -0,0 +1,17 @@
[package]
name = "srml-transaction-payment-rpc"
version = "2.0.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
[dependencies]
client = { package = "substrate-client", path = "../../../core/client" }
codec = { package = "parity-scale-codec", version = "1.0.0" }
jsonrpc-core = "13.2.0"
jsonrpc-core-client = "13.2.0"
jsonrpc-derive = "13.2.0"
primitives = { package = "substrate-primitives", path = "../../../core/primitives" }
rpc-primitives = { package = "substrate-rpc-primitives", path = "../../../core/rpc/primitives" }
serde = { version = "1.0.101", features = ["derive"] }
sr-primitives = { path = "../../../core/sr-primitives" }
srml-transaction-payment-rpc-runtime-api = { path = "./runtime-api" }
@@ -0,0 +1,22 @@
[package]
name = "srml-transaction-payment-rpc-runtime-api"
version = "2.0.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
[dependencies]
serde = { version = "1.0.101", optional = true, features = ["derive"] }
client = { package = "substrate-client", path = "../../../../core/client", default-features = false }
codec = { package = "parity-scale-codec", version = "1.0.6", default-features = false, features = ["derive"] }
rstd = { package = "sr-std", path = "../../../../core/sr-std", default-features = false }
sr-primitives = { path = "../../../../core/sr-primitives", default-features = false }
[features]
default = ["std"]
std = [
"serde",
"client/std",
"codec/std",
"rstd/std",
"sr-primitives/std",
]
@@ -0,0 +1,47 @@
// Copyright 2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Runtime API definition for transaction payment module.
#![cfg_attr(not(feature = "std"), no_std)]
use rstd::prelude::*;
use sr_primitives::weights::{Weight, DispatchClass};
use codec::{Encode, Codec, Decode};
#[cfg(feature = "std")]
use serde::{Serialize, Deserialize};
/// Some information related to a dispatchable that can be queried from the runtime.
#[derive(Eq, PartialEq, Encode, Decode, Default)]
#[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))]
pub struct RuntimeDispatchInfo<Balance> {
/// Weight of this dispatch.
pub weight: Weight,
/// Class of this dispatch.
pub class: DispatchClass,
/// The partial inclusion fee of this dispatch. This does not include tip or anything else which
/// is dependent on the signature (aka. depends on a `SignedExtension`).
pub partial_fee: Balance,
}
client::decl_runtime_apis! {
pub trait TransactionPaymentApi<Balance, Extrinsic> where
Balance: Codec,
Extrinsic: Codec,
{
fn query_info(uxt: Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance>;
}
}
@@ -0,0 +1,108 @@
// Copyright 2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! RPC interface for the transaction payment module.
use std::sync::Arc;
use codec::{Codec, Decode};
use client::blockchain::HeaderBackend;
use jsonrpc_core::{Error as RpcError, ErrorCode, Result};
use jsonrpc_derive::rpc;
use sr_primitives::{
generic::BlockId,
traits::{Block as BlockT, ProvideRuntimeApi},
};
use primitives::Bytes;
use srml_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo;
pub use srml_transaction_payment_rpc_runtime_api::TransactionPaymentApi as TransactionPaymentRuntimeApi;
pub use self::gen_client::Client as TransactionPaymentClient;
#[rpc]
pub trait TransactionPaymentApi<BlockHash, Balance> {
#[rpc(name = "payment_queryInfo")]
fn query_info(
&self,
encoded_xt: Bytes,
at: Option<BlockHash>
) -> Result<RuntimeDispatchInfo<Balance>>;
}
/// A struct that implements the [`TransactionPaymentApi`].
pub struct TransactionPayment<C, P> {
client: Arc<C>,
_marker: std::marker::PhantomData<P>,
}
impl<C, P> TransactionPayment<C, P> {
/// Create new `TransactionPayment` with the given reference to the client.
pub fn new(client: Arc<C>) -> Self {
TransactionPayment { client, _marker: Default::default() }
}
}
/// Error type of this RPC api.
pub enum Error {
/// The transaction was not decodable.
DecodeError,
/// The call to runtime failed.
RuntimeError,
}
impl From<Error> for i64 {
fn from(e: Error) -> i64 {
match e {
Error::RuntimeError => 1,
Error::DecodeError => 2,
}
}
}
impl<C, Block, Balance, Extrinsic> TransactionPaymentApi<<Block as BlockT>::Hash, Balance>
for TransactionPayment<C, (Block, Extrinsic)>
where
Block: BlockT,
C: Send + Sync + 'static,
C: ProvideRuntimeApi,
C: HeaderBackend<Block>,
C::Api: TransactionPaymentRuntimeApi<Block, Balance, Extrinsic>,
Balance: Codec,
Extrinsic: Codec + Send + Sync + 'static,
{
fn query_info(
&self,
encoded_xt: Bytes,
at: Option<<Block as BlockT>::Hash>
) -> Result<RuntimeDispatchInfo<Balance>> {
let api = self.client.runtime_api();
let at = BlockId::hash(at.unwrap_or_else(||
// If the block hash is not supplied assume the best block.
self.client.info().best_hash
));
let encoded_len = encoded_xt.len() as u32;
let uxt: Extrinsic = Decode::decode(&mut &*encoded_xt).map_err(|e| RpcError {
code: ErrorCode::ServerError(Error::DecodeError.into()),
message: "Unable to query dispatch info.".into(),
data: Some(format!("{:?}", e).into()),
})?;
api.query_info(&at, uxt, encoded_len).map_err(|e| RpcError {
code: ErrorCode::ServerError(Error::RuntimeError.into()),
message: "Unable to query dispatch info.".into(),
data: Some(format!("{:?}", e).into()),
})
}
}
+83 -11
View File
@@ -44,8 +44,9 @@ use sr_primitives::{
TransactionValidity,
},
traits::{Zero, Saturating, SignedExtension, SaturatedConversion, Convert},
weights::{Weight, DispatchInfo},
weights::{Weight, DispatchInfo, GetDispatchInfo},
};
use transaction_payment_rpc_runtime_api::RuntimeDispatchInfo;
type Multiplier = Fixed64;
type BalanceOf<T> =
@@ -95,7 +96,33 @@ decl_module! {
}
}
impl<T: Trait> Module<T> {}
impl<T: Trait> Module<T> {
/// Query the data that we know about the fee of a given `call`.
///
/// As this module is not and cannot be aware of the internals of a signed extension, it only
/// interprets them as some encoded value and takes their length into account.
///
/// All dispatchables must be annotated with weight and will have some fee info. This function
/// always returns.
// NOTE: we can actually make it understand `ChargeTransactionPayment`, but would be some hassle
// for sure. We have to make it aware of the index of `ChargeTransactionPayment` in `Extra`.
// Alternatively, we could actually execute the tx's per-dispatch and record the balance of the
// sender before and after the pipeline.. but this is way too much hassle for a very very little
// potential gain in the future.
pub fn query_info<Extrinsic: GetDispatchInfo>(
unchecked_extrinsic: Extrinsic,
len: u32,
) -> RuntimeDispatchInfo<BalanceOf<T>>
where T: Send + Sync,
{
let dispatch_info = <Extrinsic as GetDispatchInfo>::get_dispatch_info(&unchecked_extrinsic);
let partial_fee = <ChargeTransactionPayment<T>>::compute_fee(len, dispatch_info, 0u32.into());
let DispatchInfo { weight, class } = dispatch_info;
RuntimeDispatchInfo { weight, class, partial_fee }
}
}
/// Require the transactor pay for themselves and maybe include a tip to gain additional priority
/// in the queue.
@@ -117,9 +144,9 @@ impl<T: Trait + Send + Sync> ChargeTransactionPayment<T> {
/// and the time it consumes.
/// - (optional) _tip_: if included in the transaction, it will be added on top. Only signed
/// transactions can have a tip.
fn compute_fee(len: usize, info: DispatchInfo, tip: BalanceOf<T>) -> BalanceOf<T> {
fn compute_fee(len: u32, info: DispatchInfo, tip: BalanceOf<T>) -> BalanceOf<T> {
let len_fee = if info.pay_length_fee() {
let len = <BalanceOf<T>>::from(len as u32);
let len = <BalanceOf<T>>::from(len);
let base = T::TransactionBaseFee::get();
let per_byte = T::TransactionByteFee::get();
base.saturating_add(per_byte.saturating_mul(len))
@@ -172,7 +199,7 @@ impl<T: Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T>
) -> TransactionValidity {
// pay any fees.
let tip = self.0;
let fee = Self::compute_fee(len, info, tip);
let fee = Self::compute_fee(len as u32, info, tip);
let imbalance = match T::Currency::withdraw(
who,
fee,
@@ -199,17 +226,27 @@ impl<T: Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T>
#[cfg(test)]
mod tests {
use super::*;
use support::{parameter_types, impl_outer_origin};
use codec::Encode;
use support::{parameter_types, impl_outer_origin, impl_outer_dispatch};
use primitives::H256;
use sr_primitives::{
Perbill,
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
weights::DispatchClass,
testing::{Header, TestXt},
traits::{BlakeTwo256, IdentityLookup, Extrinsic},
weights::{DispatchClass, DispatchInfo, GetDispatchInfo},
};
use balances::Call as BalancesCall;
use rstd::cell::RefCell;
use transaction_payment_rpc_runtime_api::RuntimeDispatchInfo;
const CALL: &<Runtime as system::Trait>::Call = &();
const CALL: &<Runtime as system::Trait>::Call = &Call::Balances(BalancesCall::transfer(2, 69));
impl_outer_dispatch! {
pub enum Call for Runtime where origin: Origin {
balances::Balances,
system::System,
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Runtime;
@@ -229,7 +266,7 @@ mod tests {
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Call = ();
type Call = Call;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = u64;
@@ -294,6 +331,8 @@ mod tests {
}
type Balances = balances::Module<Runtime>;
type System = system::Module<Runtime>;
type TransactionPayment = Module<Runtime>;
pub struct ExtBuilder {
balance_factor: u64,
@@ -457,6 +496,39 @@ mod tests {
assert_eq!(Balances::free_balance(&1), 100 - 10 - (5 + 10 + 3) * 3 / 2);
})
}
#[test]
fn query_info_works() {
let call = Call::Balances(BalancesCall::transfer(2, 69));
let origin = 111111;
let extra = ();
let xt = TestXt::new(call, Some((origin, extra))).unwrap();
let info = xt.get_dispatch_info();
let ext = xt.encode();
let len = ext.len() as u32;
ExtBuilder::default()
.fees(5, 1, 2)
.build()
.execute_with(||
{
// all fees should be x1.5
NextFeeMultiplier::put(Fixed64::from_rational(1, 2));
assert_eq!(
TransactionPayment::query_info(xt, len),
RuntimeDispatchInfo {
weight: info.weight,
class: info.class,
partial_fee: (
5 /* base */
+ len as u64 /* len * 1 */
+ info.weight.min(MaximumBlockWeight::get()) as u64 * 2 /* weight * weight_to_fee */
) * 3 / 2
},
);
});
}
}