Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Frame: Agile Coretime Broker pallet (RFC-1) #14568

Merged
merged 143 commits into from
Aug 24, 2023
Merged
Show file tree
Hide file tree
Changes from 130 commits
Commits
Show all changes
143 commits
Select commit Hold shift + click to select a range
bec7b68
Add Broker pallet
gavofyork Jul 8, 2023
c73ce75
Flesh out CorePart
gavofyork Jul 8, 2023
fd58ded
Repotting and fleshing out
gavofyork Jul 8, 2023
4d085c1
more drafting
gavofyork Jul 8, 2023
7a42089
process timeslice
gavofyork Jul 9, 2023
c17ef17
Test Fungibles completed
gavofyork Jul 9, 2023
797f70d
Auctions
gavofyork Jul 9, 2023
055ac7e
Price morphing
gavofyork Jul 9, 2023
1949774
First tests
gavofyork Jul 9, 2023
afa138d
Tidying up config/status
gavofyork Jul 10, 2023
3caa44b
Docs
gavofyork Jul 10, 2023
60fb792
Timeslice todying
gavofyork Jul 10, 2023
036dd96
More Timeslice tidying
gavofyork Jul 10, 2023
8d299ca
Tests]
gavofyork Jul 10, 2023
99de31f
Repotting.
gavofyork Jul 10, 2023
08e9eb1
Tests
gavofyork Jul 10, 2023
6f13d32
Tests
gavofyork Jul 10, 2023
68df2d1
System InstaPool cores and payout
gavofyork Jul 10, 2023
ed57518
Better Relay Test framework
gavofyork Jul 10, 2023
f09cde2
Tests and instapool fixes
gavofyork Jul 10, 2023
bd090a1
Support NFT interface
gavofyork Jul 11, 2023
ad48ade
Proper renewals
gavofyork Jul 11, 2023
065b019
Better events, results
gavofyork Jul 11, 2023
46852d2
Test transfer
gavofyork Jul 11, 2023
e309594
Renewal test
gavofyork Jul 11, 2023
955356f
Repot some impls and make dispatchables.
gavofyork Jul 11, 2023
2f20e0a
Better weight
gavofyork Jul 11, 2023
3638f55
Test migration
gavofyork Jul 12, 2023
66b8082
Document events
gavofyork Jul 12, 2023
f9a3665
Introduce durations
gavofyork Jul 12, 2023
a5c4062
Core count
gavofyork Jul 12, 2023
08c08ac
Allow reassignment
gavofyork Jul 14, 2023
72bf053
Better naming
gavofyork Jul 14, 2023
de702d0
Error docs
gavofyork Jul 14, 2023
f86115a
Docs
gavofyork Jul 14, 2023
1f6cac9
Formatting
gavofyork Jul 14, 2023
140b2c5
Advance notice period is in RC blocks, not timeslices
gavofyork Jul 14, 2023
d4b6bad
Docs
gavofyork Jul 14, 2023
197c1e1
Formatting
gavofyork Jul 14, 2023
0f6450e
Docs
gavofyork Jul 14, 2023
3cc1d83
Missing file
gavofyork Jul 14, 2023
8ff28b9
Added some events
gavofyork Jul 14, 2023
633ab28
Events for all dispatchables
gavofyork Jul 14, 2023
ea7de69
Remove benchmark
gavofyork Jul 14, 2023
96102a3
Fix
gavofyork Jul 14, 2023
dc02d15
Adds benchmark for configure and some basic setup
gupnik Jul 15, 2023
57015e7
Adds benchmark for reserve and unreserve
gupnik Jul 15, 2023
e403464
Adds a couple of more benchmarks
gupnik Jul 15, 2023
478462a
Docs
gavofyork Jul 15, 2023
01b54ab
Event
gavofyork Jul 15, 2023
ea9c31e
Fix
gavofyork Jul 15, 2023
ec8b546
Adds benchmark for purchase
gupnik Jul 16, 2023
904fae5
Dedup
gavofyork Jul 16, 2023
d39c4f0
Merge branch 'gav-broker' of github.com:paritytech/substrate into gav…
gavofyork Jul 16, 2023
2675695
Add some weight breakdowns
gavofyork Jul 17, 2023
c112d09
Repotting
gavofyork Jul 17, 2023
81ba2fa
Adds more benchmarks
gupnik Jul 17, 2023
60c11f1
Renaming and one more event
gavofyork Jul 17, 2023
627f776
Merge branch 'gav-broker' of github.com:paritytech/substrate into gav…
gavofyork Jul 17, 2023
6f8f2d3
Sale event
gavofyork Jul 17, 2023
2e9cd55
Better price API and docs
gavofyork Jul 17, 2023
40d8c19
Avoid possibility of clobbering renewal record
gavofyork Jul 18, 2023
3e70d96
Avoid possibility of clobbering renewal record
gavofyork Jul 18, 2023
b379922
Fixes a few benchmarks
gupnik Jul 18, 2023
b565bdb
Another test
gavofyork Jul 18, 2023
6c7b4d3
Merge branch 'gav-broker' of github.com:paritytech/substrate into gav…
gavofyork Jul 18, 2023
3ad2499
More tests
gavofyork Jul 18, 2023
5ce6b79
Drop history test
gavofyork Jul 18, 2023
8838982
Rename and CORE_MASK_BITS constant
gavofyork Jul 18, 2023
bcffbe5
Update frame/broker/src/dispatchable_impls.rs
gavofyork Jul 18, 2023
ba8c4a1
Update frame/broker/src/dispatchable_impls.rs
gavofyork Jul 18, 2023
80f5d7b
Update frame/broker/src/dispatchable_impls.rs
gavofyork Jul 18, 2023
8d6af15
Update frame/broker/src/utility_impls.rs
gavofyork Jul 18, 2023
5aa621c
Update frame/broker/src/dispatchable_impls.rs
gavofyork Jul 18, 2023
0ab7449
Update frame/broker/src/mock.rs
gavofyork Jul 18, 2023
ad351b4
Addresses few review comments
gupnik Jul 19, 2023
eef2843
Addresses few review comments
gupnik Jul 19, 2023
5be7e91
Addresses few review comments
gupnik Jul 19, 2023
faf42a4
Merge branch 'master' of github.com:paritytech/substrate into gav-broker
gupnik Jul 19, 2023
6b6ea4f
Merge
gupnik Jul 19, 2023
02cbe44
Merge
gupnik Jul 19, 2023
8732e11
".git/.scripts/commands/fmt/fmt.sh"
Jul 19, 2023
6ffb4aa
Integrates broker in kitchensink
gupnik Jul 19, 2023
053bc3f
Minor update
gupnik Jul 19, 2023
db5db14
Fixes typo
gupnik Jul 19, 2023
9645b1f
Moves balance back to u64
gupnik Jul 19, 2023
cd60c54
Fixes kitchensink build
gupnik Jul 19, 2023
ad24d8d
Fixes worst case for assign
gupnik Jul 20, 2023
f81e09d
Adds benchmark for process_core_count
gupnik Jul 20, 2023
98c8ad1
Adds a couple of more benchmarks
gupnik Jul 20, 2023
140e80b
Adds an assert for partition
gupnik Jul 21, 2023
64079a7
Uses max_timeslices as input in claim_revenue benchmark
gupnik Jul 21, 2023
d4e397b
Adds benchmark for drop_renewal
gupnik Jul 21, 2023
000181c
Adds benchmark for process_core_schedule
gupnik Jul 21, 2023
03f2881
Adds benchmark for process_pool
gupnik Jul 21, 2023
92892c3
Adds assertion for transfer
gupnik Jul 21, 2023
c593447
Fixes benchmark for broker in kitchensink
gupnik Jul 23, 2023
0d28100
Adds todo for process_revenue benchmark
gupnik Jul 23, 2023
b44a3b1
Minor update
gupnik Jul 23, 2023
9308872
Fix for pool revenue history
gavofyork Jul 25, 2023
387e1f2
Merge branch 'gav-broker' of github.com:paritytech/substrate into gav…
gavofyork Jul 25, 2023
bf8e094
remove TODOs
gavofyork Jul 25, 2023
1ade824
Fix tests
gavofyork Jul 25, 2023
c0b60cc
Document CoretimeInterface
gavofyork Jul 25, 2023
3eb4a9b
rename part to mask
gavofyork Jul 25, 2023
82c9ebe
Fixes
gavofyork Jul 25, 2023
856fbad
Grumble
gavofyork Jul 25, 2023
7b39cce
Merge branch 'master' of https://github.com/paritytech/substrate into…
Jul 25, 2023
7b7cb98
".git/.scripts/commands/bench/bench.sh" --subcommand=pallet --runtime…
Jul 25, 2023
6b6e7aa
Adds benchmark for drop_history and fixes worst case for claim_revenue
gupnik Jul 29, 2023
87bba2c
Adds drop_history in WeightInfo
gupnik Jul 29, 2023
e6f45e3
Merge branch 'master' of https://github.com/paritytech/substrate into…
Jul 29, 2023
56a92b4
".git/.scripts/commands/bench/bench.sh" --subcommand=pallet --runtime…
Jul 29, 2023
343b695
Minor fix for Quick Benchmark CI
gupnik Jul 29, 2023
c588f3c
Fixes
gavofyork Jul 29, 2023
7f0a803
Merge branch 'gav-broker' of github.com:paritytech/substrate into gav…
gavofyork Jul 29, 2023
def03b9
Docs
gavofyork Jul 31, 2023
0560151
Headers
gavofyork Jul 31, 2023
3ccb610
Expose a couple of APIs for benchmarking (#14688)
gupnik Jul 31, 2023
e1c7720
Cap renewal price
gavofyork Jul 31, 2023
c4dfa4a
Merge branch 'gav-broker' of github.com:paritytech/substrate into gav…
gavofyork Jul 31, 2023
7098c1f
Merge branch 'master' of github.com:paritytech/substrate into gav-broker
gupnik Aug 1, 2023
841b9d2
Adds a few tests
gupnik Aug 1, 2023
f8fed4a
Adds more tests
gupnik Aug 2, 2023
913bc91
Minor updates
gupnik Aug 2, 2023
3b0bd20
Adds a test for an edge case
gupnik Aug 3, 2023
f79dc82
Merge branch 'master' of github.com:paritytech/substrate into gav-broker
gupnik Aug 3, 2023
8e6072c
Fixes feature propagation
gupnik Aug 3, 2023
8eb3187
Fixes feature propagation
gupnik Aug 3, 2023
b863d5d
Adds doc fix
gupnik Aug 3, 2023
fbb570f
Syntax nits
ggwpez Aug 24, 2023
0478e09
Reuse Bit assign functions
ggwpez Aug 24, 2023
7cc753f
Bitwise tests
ggwpez Aug 24, 2023
6e2dd79
adapt_price: Edge case for sold == target
ggwpez Aug 24, 2023
94105d3
Add sanity checking to ConfigRecord
ggwpez Aug 24, 2023
6103d1d
Add deny(missing_docs) where possible
ggwpez Aug 24, 2023
a71813d
partition: forbid pivot_offset == 0
ggwpez Aug 24, 2023
2622540
Merge remote-tracking branch 'origin/master' into gav-broker
ggwpez Aug 24, 2023
0e4b434
Sort features
ggwpez Aug 24, 2023
3df2580
Import Zero from new location
ggwpez Aug 24, 2023
b6bdc4f
Clippy: remove redundant clone
ggwpez Aug 24, 2023
08bb271
try to fix build
ggwpez Aug 24, 2023
7bced00
Fix CI
ggwpez Aug 24, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 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 @@ -131,6 +131,7 @@ members = [
"frame/benchmarking",
"frame/benchmarking/pov",
"frame/bounties",
"frame/broker",
"frame/child-bounties",
"frame/collective",
"frame/contracts",
Expand Down
4 changes: 4 additions & 0 deletions bin/node/runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ pallet-babe = { version = "4.0.0-dev", default-features = false, path = "../../.
pallet-bags-list = { version = "4.0.0-dev", default-features = false, path = "../../../frame/bags-list" }
pallet-balances = { version = "4.0.0-dev", default-features = false, path = "../../../frame/balances" }
pallet-bounties = { version = "4.0.0-dev", default-features = false, path = "../../../frame/bounties" }
pallet-broker = { version = "0.1.0", default-features = false, path = "../../../frame/broker" }
pallet-child-bounties = { version = "4.0.0-dev", default-features = false, path = "../../../frame/child-bounties" }
pallet-collective = { version = "4.0.0-dev", default-features = false, path = "../../../frame/collective" }
pallet-contracts = { version = "4.0.0-dev", default-features = false, path = "../../../frame/contracts" }
Expand Down Expand Up @@ -153,6 +154,7 @@ std = [
"pallet-bags-list/std",
"pallet-balances/std",
"pallet-bounties/std",
"pallet-broker/std",
"sp-block-builder/std",
"codec/std",
"scale-info/std",
Expand Down Expand Up @@ -249,6 +251,7 @@ runtime-benchmarks = [
"pallet-bags-list/runtime-benchmarks",
"pallet-balances/runtime-benchmarks",
"pallet-bounties/runtime-benchmarks",
"pallet-broker/runtime-benchmarks",
"pallet-child-bounties/runtime-benchmarks",
"pallet-collective/runtime-benchmarks",
"pallet-contracts/runtime-benchmarks",
Expand Down Expand Up @@ -318,6 +321,7 @@ try-runtime = [
"pallet-bags-list/try-runtime",
"pallet-balances/try-runtime",
"pallet-bounties/try-runtime",
"pallet-broker/try-runtime",
"pallet-child-bounties/try-runtime",
"pallet-collective/try-runtime",
"pallet-contracts/try-runtime",
Expand Down
76 changes: 75 additions & 1 deletion bin/node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use frame_support::{
pallet_prelude::Get,
parameter_types,
traits::{
fungible::ItemOf,
fungible::{Balanced, Credit, ItemOf},
tokens::{nonfungibles_v2::Inspect, GetSalary, PayFromAccount},
AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU16, ConstU32, Currency, EitherOfDiverse,
EqualPrivilegeOnly, Everything, Imbalance, InstanceFilter, KeyOwnerProofSystem,
Expand All @@ -55,6 +55,7 @@ use frame_system::{
pub use node_primitives::{AccountId, Signature};
use node_primitives::{AccountIndex, Balance, BlockNumber, Hash, Moment, Nonce};
use pallet_asset_conversion::{NativeOrAssetId, NativeOrAssetIdConverter};
use pallet_broker::{CoreAssignment, CoreIndex, CoretimeInterface, PartsOf57600};
use pallet_election_provider_multi_phase::SolutionAccuracyOf;
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
use pallet_nfts::PalletFeatures;
Expand Down Expand Up @@ -1871,6 +1872,77 @@ impl pallet_statement::Config for Runtime {
type MaxAllowedBytes = MaxAllowedBytes;
}

parameter_types! {
pub const BrokerPalletId: PalletId = PalletId(*b"py/broke");
}

pub struct IntoAuthor;
impl OnUnbalanced<Credit<AccountId, Balances>> for IntoAuthor {
fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
if let Some(author) = Authorship::author() {
let _ = <Balances as Balanced<_>>::resolve(&author, credit);
}
}
}

parameter_types! {
pub storage CoreCount: Option<CoreIndex> = None;
pub storage CoretimeRevenue: Option<(BlockNumber, Balance)> = None;
}

pub struct CoretimeProvider;
impl CoretimeInterface for CoretimeProvider {
type AccountId = AccountId;
type Balance = Balance;
type BlockNumber = BlockNumber;
fn latest() -> Self::BlockNumber {
System::block_number()
}
fn request_core_count(_count: CoreIndex) {}
fn request_revenue_info_at(_when: Self::BlockNumber) {}
fn credit_account(_who: Self::AccountId, _amount: Self::Balance) {}
fn assign_core(
_core: CoreIndex,
_begin: Self::BlockNumber,
_assignment: Vec<(CoreAssignment, PartsOf57600)>,
_end_hint: Option<Self::BlockNumber>,
) {
}
fn check_notify_core_count() -> Option<u16> {
let count = CoreCount::get();
CoreCount::set(&None);
count
}
fn check_notify_revenue_info() -> Option<(Self::BlockNumber, Self::Balance)> {
let revenue = CoretimeRevenue::get();
CoretimeRevenue::set(&None);
revenue
}
#[cfg(feature = "runtime-benchmarks")]
fn ensure_notify_core_count(count: u16) {
CoreCount::set(&Some(count));
}
#[cfg(feature = "runtime-benchmarks")]
fn ensure_notify_revenue_info(when: Self::BlockNumber, revenue: Self::Balance) {
CoretimeRevenue::set(&Some((when, revenue)));
}
}

impl pallet_broker::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type OnRevenue = IntoAuthor;
type TimeslicePeriod = ConstU32<2>;
type MaxLeasedCores = ConstU32<5>;
type MaxReservedCores = ConstU32<5>;
type Coretime = CoretimeProvider;
type ConvertBalance = traits::Identity;
type WeightInfo = ();
type PalletId = BrokerPalletId;
type AdminOrigin = EnsureRoot<AccountId>;
type PriceAdapter = pallet_broker::Linear;
}

construct_runtime!(
pub struct Runtime
{
Expand Down Expand Up @@ -1944,6 +2016,7 @@ construct_runtime!(
MessageQueue: pallet_message_queue,
Pov: frame_benchmarking_pallet_pov,
Statement: pallet_statement,
Broker: pallet_broker,
}
);

Expand Down Expand Up @@ -2024,6 +2097,7 @@ mod benches {
[pallet_bags_list, VoterList]
[pallet_balances, Balances]
[pallet_bounties, Bounties]
[pallet_broker, Broker]
[pallet_child_bounties, ChildBounties]
[pallet_collective, Council]
[pallet_conviction_voting, ConvictionVoting]
Expand Down
4 changes: 1 addition & 3 deletions client/consensus/grandpa/src/communication/gossip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -546,9 +546,7 @@ impl<N: Ord> Peers<N> {
who: &PeerId,
update: NeighborPacket<N>,
) -> Result<Option<&View<N>>, Misbehavior> {
let Some(peer) = self.inner.get_mut(who) else {
return Ok(None)
};
let Some(peer) = self.inner.get_mut(who) else { return Ok(None) };

let invalid_change = peer.view.set_id > update.set_id ||
peer.view.round > update.round && peer.view.set_id == update.set_id ||
Expand Down
4 changes: 3 additions & 1 deletion frame/asset-conversion/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1194,7 +1194,9 @@ pub mod pallet {
()
);
} else {
let MultiAssetIdConversionResult::Converted(asset_id) = T::MultiAssetIdConverter::try_convert(asset) else {
let MultiAssetIdConversionResult::Converted(asset_id) =
T::MultiAssetIdConverter::try_convert(asset)
else {
return Err(())
};
let minimal = T::Assets::minimum_balance(asset_id);
Expand Down
6 changes: 5 additions & 1 deletion frame/asset-conversion/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,11 @@ fn pool_assets() -> Vec<u32> {

fn create_tokens(owner: u128, tokens: Vec<NativeOrAssetId<u32>>) {
for token_id in tokens {
let MultiAssetIdConversionResult::Converted(asset_id) = NativeOrAssetIdConverter::try_convert(&token_id) else { unreachable!("invalid token") };
let MultiAssetIdConversionResult::Converted(asset_id) =
NativeOrAssetIdConverter::try_convert(&token_id)
else {
unreachable!("invalid token")
};
assert_ok!(Assets::force_create(RuntimeOrigin::root(), asset_id, owner, false, 1));
}
}
Expand Down
56 changes: 56 additions & 0 deletions frame/broker/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
[package]
name = "pallet-broker"
version = "0.1.0"
description = "Brokerage tool for managing Polkadot Core scheduling"
authors = ["Parity Technologies <admin@parity.io>"]
homepage = "https://substrate.io"
edition = "2021"
license = "Apache-2.0"
repository = "https://github.com/paritytech/substrate"

[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ "derive"] }
scale-info = { version = "2.0.0", default-features = false, features = ["derive"] }
bitvec = "1"
sp-std = { version = "8.0.0", default-features = false, path = "../../primitives/std" }
sp-arithmetic = { version = "16.0.0", default-features = false, path = "../../primitives/arithmetic" }
sp-core = { version = "21.0.0", default-features = false, path = "../../primitives/core" }
sp-runtime = { version = "24.0.0", default-features = false, path = "../../primitives/runtime" }
frame-benchmarking = { version = "4.0.0-dev", default-features = false, optional = true, path = "../benchmarking" }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" }

[dev-dependencies]
sp-io = { version = "23.0.0", path = "../../primitives/io" }

[features]
default = ["std"]

std = [
"codec/std",
"frame-benchmarking?/std",
"frame-support/std",
"frame-system/std",
"scale-info/std",
"sp-runtime/std",
"sp-arithmetic/std",
"sp-core/std",
"sp-io/std",
"sp-std/std",
]

runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
]

try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
"sp-runtime/try-runtime"
]
26 changes: 26 additions & 0 deletions frame/broker/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Pallet Broker

Brokerage tool for managing Polkadot Core scheduling.

Properly described in RFC-0001 Agile Coretime.

## Implemnentation Specifics

### Core Mask Bits

This is 1/80th of a Polkadot Core per timeslice. Assuming timeslices are 80 blocks, then this
indicates usage of a single core one time over a timeslice.

### The Sale

```nocompile
1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
--------------------------------------------------------
< interlude >
< sale >
... of which ...
< descending-price >< fixed-price >
| <-------\
price fixed, unsold assigned to instapool, system cores reserved -/
```
60 changes: 60 additions & 0 deletions frame/broker/src/adapt_price.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::CoreIndex;
use sp_arithmetic::{traits::One, FixedU64};

/// Type for determining how to set price.
pub trait AdaptPrice {
/// Return the factor by which the regular price must be multiplied during the leadin period.
///
/// - `when`: The amount through the leadin period; between zero and one.
fn leadin_factor_at(when: FixedU64) -> FixedU64;
/// Return the correction factor by which the regular price must be multiplied based on market
/// performance.
///
/// - `sold`: The number of cores sold.
/// - `target`: The target number of cores to be sold.
/// - `limit`: The maximum number of cores to be sold.
ggwpez marked this conversation as resolved.
Show resolved Hide resolved
fn adapt_price(sold: CoreIndex, target: CoreIndex, limit: CoreIndex) -> FixedU64;
}

impl AdaptPrice for () {
fn leadin_factor_at(_: FixedU64) -> FixedU64 {
FixedU64::one()
Comment on lines +39 to +40
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The argument could be a Perbill to prevent underflows.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bit ugly to pass in a Perbill and require a FixedU64 out, but sure I guess.

}
fn adapt_price(_: CoreIndex, _: CoreIndex, _: CoreIndex) -> FixedU64 {
FixedU64::one()
}
}

/// Simple implementation of `AdaptPrice` giving a monotonic leadin and a linear price change based
/// on cores sold.
pub struct Linear;
impl AdaptPrice for Linear {
fn leadin_factor_at(when: FixedU64) -> FixedU64 {
FixedU64::from(2) - when
}
fn adapt_price(sold: CoreIndex, target: CoreIndex, limit: CoreIndex) -> FixedU64 {
if sold < target {
FixedU64::from_rational(sold.into(), target.into())
} else {
FixedU64::one() +
FixedU64::from_rational((sold - target).into(), (limit - target).into())
}
}
}
Loading