Skip to content

Commit 456c3f1

Browse files
committed
init SlowAdjustingFeeUpdate
1 parent b7fe237 commit 456c3f1

File tree

6 files changed

+188
-11
lines changed

6 files changed

+188
-11
lines changed

sugondat-chain/pallets/blobs/Cargo.toml

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ frame-support = { git = "https://github.com/paritytech/polkadot-sdk", default-fe
2020
frame-system = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0" }
2121
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0" }
2222
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0" }
23-
sp-io = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0", optional = true}
23+
sp-io = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0"}
2424

2525
# Local
2626
sugondat-primitives = { path = "../../primitives", default-features = false }
@@ -34,7 +34,6 @@ quickcheck_macros = "1.0.0"
3434

3535
# Substrate
3636
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0" }
37-
sp-io = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0"}
3837
sp-state-machine = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0"}
3938
sp-trie = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0"}
4039

@@ -45,7 +44,6 @@ runtime-benchmarks = [
4544
"frame-support/runtime-benchmarks",
4645
"frame-system/runtime-benchmarks",
4746
"sp-runtime/runtime-benchmarks",
48-
"dep:sp-io"
4947
]
5048
std = [
5149
"codec/std",
@@ -54,6 +52,7 @@ std = [
5452
"frame-support/std",
5553
"frame-system/std",
5654
"sp-std/std",
55+
"sp-io/std",
5756
"sugondat-nmt/native",
5857
"sugondat-primitives/std",
5958
]

sugondat-chain/pallets/blobs/src/lib.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,23 @@ pub mod pallet {
227227
});
228228
Ok(().into())
229229
}
230+
231+
#[pallet::call_index(1)]
232+
#[pallet::weight(0)]
233+
pub fn update_parameter(
234+
origin: OriginFor<T>,
235+
parameter: Vec<u8>,
236+
// already encoded value
237+
value: Vec<u8>,
238+
) -> DispatchResultWithPostInfo {
239+
let who = ensure_root(origin)?;
240+
let key = match (parameter.first(), parameter.last()) {
241+
(Some(b':'), Some(b':')) => parameter,
242+
_ => [vec![b':'], parameter, vec![b':']].concat(),
243+
};
244+
sp_io::storage::set(&key, &value);
245+
Ok(().into())
246+
}
230247
}
231248

232249
fn sha2_hash(data: &[u8]) -> [u8; 32] {

sugondat-chain/primitives/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ use sp_runtime::{
55
MultiSignature,
66
};
77

8+
pub const MAX_BLOCK_LENGTH: u32 = 5 * 1024 * 1024;
9+
810
/// An index to a block.
911
pub type BlockNumber = u32;
1012

sugondat-chain/runtimes/sugondat-kusama/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ sp-session = { git = "https://github.com/paritytech/polkadot-sdk", default-featu
5353
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0" }
5454
sp-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0" }
5555
sp-version = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0" }
56+
sp-io = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0"}
5657

5758
# Polkadot
5859
pallet-xcm = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0" }
@@ -78,7 +79,6 @@ parachain-info = { package = "staging-parachain-info", git = "https://github.com
7879
parachains-common = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "release-polkadot-v1.4.0", default-features = false }
7980

8081
[dev-dependencies]
81-
sp-io = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0"}
8282
sp-tracing = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, branch = "release-polkadot-v1.4.0"}
8383

8484
[features]

sugondat-chain/runtimes/sugondat-kusama/src/constants.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ pub mod consensus {
2525
// Time is measured by number of blocks.
2626
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
2727
pub const HOURS: BlockNumber = MINUTES * 60;
28+
pub const DAYS: BlockNumber = HOURS * 24;
2829

2930
/// We assume that ~5% of the block weight is consumed by `on_initialize` handlers. This is
3031
/// used to limit the maximal weight of a single extrinsic.

sugondat-chain/runtimes/sugondat-kusama/src/lib.rs

Lines changed: 165 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,15 @@ pub mod xcm_config;
1212

1313
use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
1414
use cumulus_primitives_core::{AggregateMessageOrigin, ParaId};
15+
use pallet_transaction_payment::{Multiplier, MultiplierUpdate};
1516
use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery;
1617
use sp_api::impl_runtime_apis;
1718
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
1819
use sp_runtime::{
1920
create_runtime_str, generic, impl_opaque_keys,
20-
traits::{AccountIdLookup, BlakeTwo256, Block as BlockT},
21+
traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, Bounded, Convert},
2122
transaction_validity::{TransactionSource, TransactionValidity},
22-
ApplyExtrinsicResult,
23+
ApplyExtrinsicResult, Perquintill,
2324
};
2425

2526
use sp_std::prelude::*;
@@ -34,7 +35,7 @@ use frame_support::{
3435
dispatch::DispatchClass,
3536
genesis_builder_helper::{build_config, create_default_config},
3637
parameter_types,
37-
traits::{ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, TransformOrigin},
38+
traits::{ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, Get, TransformOrigin},
3839
weights::{ConstantMultiplier, Weight},
3940
PalletId,
4041
};
@@ -45,16 +46,20 @@ use frame_system::{
4546
use pallet_xcm::{EnsureXcm, IsVoiceOfBody};
4647
use parachains_common::message_queue::{NarrowOriginToSibling, ParaIdToSibling};
4748

48-
use sugondat_primitives::{AccountId, AuraId, Balance, BlockNumber, Nonce, Signature};
49+
use sugondat_primitives::{
50+
AccountId, AuraId, Balance, BlockNumber, Nonce, Signature, MAX_BLOCK_LENGTH,
51+
};
4952

53+
use pallet_transaction_payment::TargetedFeeAdjustment;
54+
use sp_runtime::FixedPointNumber;
5055
pub use sp_runtime::{MultiAddress, Perbill, Permill};
5156
use xcm_config::{KusamaLocation, XcmOriginToTransactDispatchOrigin};
5257

5358
#[cfg(any(feature = "std", test))]
5459
pub use sp_runtime::BuildStorage;
5560

5661
// Polkadot imports
57-
use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
62+
use polkadot_runtime_common::BlockHashCount;
5863

5964
use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
6065

@@ -142,7 +147,7 @@ parameter_types! {
142147
// `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
143148
// the lazy contract deletion.
144149
pub RuntimeBlockLength: BlockLength =
145-
BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
150+
BlockLength::max_with_normal_ratio(MAX_BLOCK_LENGTH, NORMAL_DISPATCH_RATIO);
146151
pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
147152
.base_block(BlockExecutionWeight::get())
148153
.for_class(DispatchClass::all(), |weights| {
@@ -267,14 +272,167 @@ impl pallet_balances::Config for Runtime {
267272
parameter_types! {
268273
/// Relay Chain `TransactionByteFee` / 10
269274
pub const TransactionByteFee: Balance = MILLICENTS;
275+
276+
// Common constants used in all runtimes for SlowAdjustingFeeUpdate
277+
278+
/// The portion of the `NORMAL_DISPATCH_RATIO` that we adjust the fees with. Blocks filled less
279+
/// than this will decrease the weight and more will increase.
280+
pub storage TargetBlockFullness: Perquintill = Perquintill::from_percent(25);
281+
282+
/// The adjustment variable of the runtime. Higher values will cause `TargetBlockFullness` to
283+
/// change the fees more rapidly.
284+
pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(75, 1000_000);
285+
/// that combined with `AdjustmentVariable`, we can recover from the minimum.
286+
/// See `multiplier_can_grow_from_zero`.
287+
pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 10u128);
288+
/// The maximum amount of the multiplier.
289+
pub MaximumMultiplier: Multiplier = Bounded::max_value();
290+
291+
// parameters used in BlobsFeeAdjustment
292+
pub storage TargetBlockSize: u32 = 820 * 1024; // 0.8MiB
293+
294+
// A positive number represents the count of consecutive blocks that exceeded
295+
// the TargetBlockSize, while a negative number represents the count of
296+
// consecutive blocks that were below the TargetBlockSize - NegativeDeltaTargetBlockFullness.
297+
pub storage BlockSizeTracker: u32 = 0; // 0.8MiB
298+
299+
// The number of consecutive blocks after which the TargetBlockSize will increase
300+
pub storage IncreaseDeltaBlocks: u32 = 10 * DAYS;
301+
302+
// The number of bytes that will be added to TargetBlockSize each update
303+
pub storage DeltaTargetBlockSize: u32 = 205 * 1024;// 0.2MiB
304+
305+
//pub storage DecreaseDeltaBlocks: u32 = 10 * DAYS;,
306+
//pub storage LowerBoundTargetBlockSize
307+
308+
}
309+
310+
/// Parameterized slow adjusting fee updated based on
311+
/// <https://research.web3.foundation/Polkadot/overview/token-economics#2-slow-adjusting-mechanism>
312+
//pub type SlowAdjustingFeeUpdate<R> = TargetedFeeAdjustment<
313+
// R,
314+
// TargetBlockFullness,
315+
// AdjustmentVariable,
316+
// MinimumMultiplier,
317+
// MaximumMultiplier,
318+
//>;
319+
320+
// Wrapper around TargetedFeeAdjustment,
321+
//
322+
// `TargetedFeeAdjustment` uses the block weight and the cost of the traffic,
323+
// so it only depends on `ref_time` and `proof_size` (using `<frame_system::Pallet<T>>::block_weight()`)
324+
//
325+
// This struct also takes into consideration the total amount of submitted blob size
326+
// and adjusts TargetBlockFullness based on the amount of data present and expected in a block.
327+
pub struct BlobsFeeAdjustment<T: frame_system::Config>(core::marker::PhantomData<T>);
328+
329+
impl<T: frame_system::Config> Convert<Multiplier, Multiplier> for BlobsFeeAdjustment<T>
330+
where
331+
T: frame_system::Config,
332+
{
333+
fn convert(previous: Multiplier) -> Multiplier {
334+
// The size of the submit_blob extrinsic with an empty vec.
335+
//
336+
// Since the Scale encoding for the Vec uses varint to represent the size of the vec,
337+
// the size of the encoded extrinsic may not be exactly ext_min_len + X if the blob size is X.
338+
// It will likely be slightly different.
339+
use codec::{Decode, Encode};
340+
let ext_min_len = RuntimeCall::from(pallet_sugondat_blobs::Call::submit_blob {
341+
namespace_id: 0.into(),
342+
blob: vec![],
343+
})
344+
.size_hint() as u32;
345+
346+
let total_blob_size: u32 = pallet_sugondat_blobs::TotalBlobSize::<Runtime>::get();
347+
let total_blobs: u32 = pallet_sugondat_blobs::TotalBlobs::<Runtime>::get();
348+
349+
// Current usage of the block
350+
let used_block_size = (total_blobs * ext_min_len) + total_blob_size;
351+
if used_block_size > TargetBlockSize::get() {
352+
// Increase the tracker if needed
353+
let tracker = BlockSizeTracker::get();
354+
355+
// If the used_block_size is larger than the TargetBlockSize
356+
// for more than IncreaseDeltaBlocks consecutive, then the TargetBlockSize
357+
// will be increased by DeltaTargetBlockSize.
358+
if tracker + 1 >= IncreaseDeltaBlocks::get() {
359+
let current_target_block_size = TargetBlockSize::get();
360+
TargetBlockSize::set(&(current_target_block_size + DeltaTargetBlockSize::get()));
361+
}
362+
363+
BlockSizeTracker::set(&(tracker + 1));
364+
} else {
365+
// The logic for updating to a new TargetBlockSize currently requires IncreaseDeltaBlocks
366+
// to be constantly larger than TargetBlockSize. However, it might be possible
367+
// to implement a window where we reset the tracker only if the
368+
// block size remains below the TargetBlockSize for a certain number of blocks
369+
BlockSizeTracker::set(&0);
370+
}
371+
372+
// Define TargetBlockFullness based on our expectations
373+
// of how we want our blocks to be full
374+
// TODO: refactor
375+
let avarage_blob_size = total_blob_size / total_blobs;
376+
377+
let expected_extrinsics =
378+
match TargetBlockSize::get().checked_div(ext_min_len + avarage_blob_size) {
379+
Some(val) => val,
380+
_ => todo!(),
381+
} as u64;
382+
383+
// TODO: find a way to share this with `submit_blob` function
384+
use pallet_sugondat_blobs::weights::{SubstrateWeight, WeightInfo};
385+
let avarage_extrinsic_weight =
386+
SubstrateWeight::<T>::submit_blob(MaxBlobs::get() / 2, avarage_blob_size as u32)
387+
.saturating_add(
388+
SubstrateWeight::<T>::on_finalize(0) / (MaxBlobs::get() / 4) as u64,
389+
);
390+
let target_ref_time =
391+
expected_extrinsics.saturating_mul(avarage_extrinsic_weight.ref_time());
392+
393+
let weights = T::BlockWeights::get();
394+
let normal_max_weight = weights
395+
.get(DispatchClass::Normal)
396+
.max_total
397+
.unwrap_or(weights.max_block);
398+
399+
let target_block_fullness =
400+
Perquintill::from_rational(target_ref_time, normal_max_weight.ref_time());
401+
402+
TargetBlockFullness::set(&target_block_fullness);
403+
404+
TargetedFeeAdjustment::<
405+
T,
406+
TargetBlockFullness,
407+
AdjustmentVariable,
408+
MinimumMultiplier,
409+
MaximumMultiplier,
410+
>::convert(previous)
411+
}
412+
}
413+
414+
impl<T: frame_system::Config> MultiplierUpdate for BlobsFeeAdjustment<T> {
415+
fn min() -> Multiplier {
416+
MinimumMultiplier::get()
417+
}
418+
fn max() -> Multiplier {
419+
MaximumMultiplier::get()
420+
}
421+
fn target() -> Perquintill {
422+
TargetBlockFullness::get()
423+
}
424+
fn variability() -> Multiplier {
425+
AdjustmentVariable::get()
426+
}
270427
}
271428

272429
impl pallet_transaction_payment::Config for Runtime {
273430
type RuntimeEvent = RuntimeEvent;
274431
type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, ()>;
275432
type WeightToFee = WeightToFee;
276433
type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
277-
type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
434+
//type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
435+
type FeeMultiplierUpdate = BlobsFeeAdjustment<Self>;
278436
type OperationalFeeMultiplier = ConstU8<5>;
279437
}
280438

0 commit comments

Comments
 (0)