Skip to content

Commit

Permalink
prepare orml_oracle benchmarking
Browse files Browse the repository at this point in the history
  • Loading branch information
ermalkaleci committed Jul 11, 2024
1 parent 89a141c commit 8f2e8dc
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 71 deletions.
9 changes: 4 additions & 5 deletions primitives/src/oracle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@ use sp_std::vec::Vec;
/// Interface for fetching price of the native token.
pub trait PriceProvider {
/// Get the price of the native token.
fn average_price() -> CurrencyAmount;
fn average_price() -> Price;
}

pub type Price = FixedU128;
pub type CurrencyAmount = FixedU128;

#[derive(Encode, Decode, MaxEncodedLen, Clone, Copy, Debug, PartialEq, Eq, TypeInfo)]
Expand All @@ -34,10 +35,8 @@ pub enum CurrencyId {
SDN,
}

type TimestampedValue<T, I = ()> = orml_oracle::TimestampedValue<
CurrencyAmount,
<<T as orml_oracle::Config<I>>::Time as Time>::Moment,
>;
type TimestampedValue<T, I = ()> =
orml_oracle::TimestampedValue<Price, <<T as orml_oracle::Config<I>>::Time as Time>::Moment>;

/// A dummy implementation of `CombineData` trait that does nothing.
pub struct DummyCombineData<T, I = ()>(PhantomData<(T, I)>);
Expand Down
13 changes: 7 additions & 6 deletions runtime/astar/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ use astar_primitives::{
PeriodNumber, RankedTier, SmartContract, StandardTierSlots,
},
evm::EvmRevertCodeHandler,
oracle::{CurrencyAmount, CurrencyId, DummyCombineData},
oracle::{CurrencyId, DummyCombineData, Price},
xcm::AssetLocationIdConverter,
Address, AssetId, BlockNumber, Hash, Header, Nonce,
};
Expand Down Expand Up @@ -364,12 +364,12 @@ impl pallet_dapp_staking_v3::BenchmarkHelper<SmartContract<AccountId>, AccountId
}
}
#[cfg(feature = "runtime-benchmarks")]
impl<SC, ACC> orml_oracle::BenchmarkHelper<CurrencyId, FixedU128, ConstU32<2>>
impl<SC, ACC> orml_oracle::BenchmarkHelper<CurrencyId, Price, ConstU32<2>>
for BenchmarkHelper<SC, ACC>
{
fn get_currency_id_value_pairs() -> sp_runtime::BoundedVec<(CurrencyId, FixedU128), ConstU32<2>>
{
sp_runtime::BoundedVec::default()
fn get_currency_id_value_pairs() -> sp_runtime::BoundedVec<(CurrencyId, Price), ConstU32<2>> {
sp_runtime::BoundedVec::try_from(vec![(CurrencyId::ASTR, Price::from_rational(15, 100))])
.expect("out of bounds")
}
}

Expand Down Expand Up @@ -1119,7 +1119,7 @@ impl orml_oracle::Config for Runtime {
type CombineData = DummyCombineData<Runtime>;
type Time = Timestamp;
type OracleKey = CurrencyId;
type OracleValue = CurrencyAmount;
type OracleValue = Price;
type RootOperatorAccountId = RootOperatorAccountId;
type Members = OracleMembership;
type MaxHasDispatchedSize = ConstU32<8>;
Expand Down Expand Up @@ -1327,6 +1327,7 @@ mod benches {
[pallet_dynamic_evm_base_fee, DynamicEvmBaseFee]
[xcm_benchmarks_generic, XcmGeneric]
[xcm_benchmarks_fungible, XcmFungible]
[orml_oracle, Oracle]
);
}

Expand Down
81 changes: 37 additions & 44 deletions runtime/shibuya/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ use astar_primitives::{
MainCouncilMembershipInst, MainTreasuryInst, OracleMembershipInst,
TechnicalCommitteeCollectiveInst, TechnicalCommitteeMembershipInst,
},
oracle::{CurrencyAmount, CurrencyId, DummyCombineData},
oracle::{CurrencyId, DummyCombineData, Price},
xcm::AssetLocationIdConverter,
Address, AssetId, BlockNumber, Hash, Header, Nonce,
};
Expand Down Expand Up @@ -415,10 +415,10 @@ impl pallet_preimage::Config for Runtime {
}

#[cfg(feature = "runtime-benchmarks")]
pub struct BenchmarkHelper<SC, ACC>(sp_std::marker::PhantomData<(SC, ACC)>);
pub struct DAppStakingBenchmarkHelper<SC, ACC>(sp_std::marker::PhantomData<(SC, ACC)>);
#[cfg(feature = "runtime-benchmarks")]
impl pallet_dapp_staking_v3::BenchmarkHelper<SmartContract<AccountId>, AccountId>
for BenchmarkHelper<SmartContract<AccountId>, AccountId>
for DAppStakingBenchmarkHelper<SmartContract<AccountId>, AccountId>
{
fn get_smart_contract(id: u32) -> SmartContract<AccountId> {
let id_bytes = id.to_le_bytes();
Expand All @@ -434,15 +434,6 @@ impl pallet_dapp_staking_v3::BenchmarkHelper<SmartContract<AccountId>, AccountId
.expect("Must succeed in test/benchmark environment.");
}
}
#[cfg(feature = "runtime-benchmarks")]
impl<SC, ACC> orml_oracle::BenchmarkHelper<CurrencyId, FixedU128, ConstU32<2>>
for BenchmarkHelper<SC, ACC>
{
fn get_currency_id_value_pairs() -> sp_runtime::BoundedVec<(CurrencyId, FixedU128), ConstU32<2>>
{
sp_runtime::BoundedVec::default()
}
}

pub struct AccountCheck;
impl DappStakingAccountCheck<AccountId> for AccountCheck {
Expand Down Expand Up @@ -483,7 +474,7 @@ impl pallet_dapp_staking_v3::Config for Runtime {
type RankingEnabled = ConstBool<true>;
type WeightInfo = weights::pallet_dapp_staking_v3::SubstrateWeight<Runtime>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = BenchmarkHelper<SmartContract<AccountId>, AccountId>;
type BenchmarkHelper = DAppStakingBenchmarkHelper<SmartContract<AccountId>, AccountId>;
}

pub struct InflationPayoutPerBlock;
Expand Down Expand Up @@ -1206,6 +1197,19 @@ impl pallet_price_aggregator::Config for Runtime {
type WeightInfo = pallet_price_aggregator::weights::SubstrateWeight<Runtime>;
}

#[cfg(feature = "runtime-benchmarks")]
pub struct OracleBenchmarkHelper;
#[cfg(feature = "runtime-benchmarks")]
impl orml_oracle::BenchmarkHelper<CurrencyId, Price, ConstU32<2>> for OracleBenchmarkHelper {
fn get_currency_id_value_pairs() -> sp_runtime::BoundedVec<(CurrencyId, Price), ConstU32<2>> {
sp_runtime::BoundedVec::try_from(vec![
(CurrencyId::ASTR, Price::from_rational(15, 100)),
(CurrencyId::ASTR, Price::from_rational(15, 100)),
])
.expect("out of bounds")
}
}

parameter_types! {
// Cannot specify `Root` so need to do it like this, unfortunately.
pub RootOperatorAccountId: AccountId = AccountId::from([0xffu8; 32]);
Expand All @@ -1217,8 +1221,11 @@ impl orml_oracle::Config for Runtime {
type CombineData = DummyCombineData<Runtime>;
type Time = Timestamp;
type OracleKey = CurrencyId;
type OracleValue = CurrencyAmount;
type OracleValue = Price;
type RootOperatorAccountId = RootOperatorAccountId;
#[cfg(feature = "runtime-benchmarks")]
type Members = OracleMembershipWrapper;
#[cfg(not(feature = "runtime-benchmarks"))]
type Members = OracleMembership;
type MaxHasDispatchedSize = ConstU32<8>;
type WeightInfo = oracle_benchmarks::weights::SubstrateWeight<Runtime>;
Expand All @@ -1227,7 +1234,7 @@ impl orml_oracle::Config for Runtime {
#[cfg(not(feature = "runtime-benchmarks"))]
type MaxFeedValues = ConstU32<1>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = BenchmarkHelper<SmartContract<AccountId>, AccountId>;
type BenchmarkHelper = OracleBenchmarkHelper;
}

impl pallet_membership::Config<OracleMembershipInst> for Runtime {
Expand All @@ -1244,33 +1251,22 @@ impl pallet_membership::Config<OracleMembershipInst> for Runtime {
type WeightInfo = pallet_membership::weights::SubstrateWeight<Runtime>;
}

// The oracle-benchmarks pallet should be removed once we uplift to high enough version
// (assumption is `polkadot-v1.10.0`) to have access to normal oracle pallet benchmarks).
//
// The pallet is stateless so in order to remove it, only code needs to be cleaned up.
pub struct DummyKeyPairValue;
impl Get<(CurrencyId, CurrencyAmount)> for DummyKeyPairValue {
fn get() -> (CurrencyId, CurrencyAmount) {
(CurrencyId::ASTR, CurrencyAmount::from_rational(15, 100))
}
}
pub struct AddMemberBenchmark;
impl oracle_benchmarks::AddMember<AccountId> for AddMemberBenchmark {
fn add_member(account: AccountId) {
use frame_support::assert_ok;
use frame_system::RawOrigin;
assert_ok!(
pallet_membership::Pallet::<Runtime, OracleMembershipInst>::add_member(
RawOrigin::Root.into(),
account.into()
)
);
/// OracleMembership wrapper used by benchmarks
#[cfg(feature = "runtime-benchmarks")]
pub struct OracleMembershipWrapper;

#[cfg(feature = "runtime-benchmarks")]
impl frame_support::traits::SortedMembers<AccountId> for OracleMembershipWrapper {
fn sorted_members() -> Vec<AccountId> {
OracleMembership::sorted_members()
}
}

impl oracle_benchmarks::Config for Runtime {
type BenchmarkCurrencyIdValuePair = DummyKeyPairValue;
type AddMember = AddMemberBenchmark;
fn add(account: &AccountId) {
frame_support::assert_ok!(OracleMembership::add_member(
frame_system::RawOrigin::Root.into(),
account.to_owned().into()
));
}
}

parameter_types! {
Expand Down Expand Up @@ -1579,9 +1575,6 @@ construct_runtime!(
Treasury: pallet_treasury::<Instance1> = 107,
CommunityTreasury: pallet_treasury::<Instance2> = 108,
CollectiveProxy: pallet_collective_proxy = 109,

// Remove after benchmarks are available in orml_oracle
OracleBenchmarks: oracle_benchmarks = 251,
}
);

Expand Down Expand Up @@ -1721,8 +1714,8 @@ mod benches {
[xcm_benchmarks_fungible, XcmFungible]
[pallet_price_aggregator, PriceAggregator]
[pallet_membership, OracleMembership]
[oracle_benchmarks, OracleBenchmarks]
[pallet_collective_proxy, CollectiveProxy]
[orml_oracle, Oracle]
);
}

Expand Down
15 changes: 8 additions & 7 deletions runtime/shiden/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ use astar_primitives::{
},
evm::EvmRevertCodeHandler,
governance::OracleMembershipInst,
oracle::{CurrencyAmount, CurrencyId, DummyCombineData},
oracle::{CurrencyId, DummyCombineData, Price},
xcm::AssetLocationIdConverter,
Address, AssetId, BlockNumber, Hash, Header, Nonce,
};
Expand Down Expand Up @@ -389,12 +389,12 @@ impl pallet_dapp_staking_v3::BenchmarkHelper<SmartContract<AccountId>, AccountId
}
}
#[cfg(feature = "runtime-benchmarks")]
impl<SC, ACC> orml_oracle::BenchmarkHelper<CurrencyId, FixedU128, ConstU32<2>>
impl<SC, ACC> orml_oracle::BenchmarkHelper<CurrencyId, Price, ConstU32<2>>
for BenchmarkHelper<SC, ACC>
{
fn get_currency_id_value_pairs() -> sp_runtime::BoundedVec<(CurrencyId, FixedU128), ConstU32<2>>
{
sp_runtime::BoundedVec::default()
fn get_currency_id_value_pairs() -> sp_runtime::BoundedVec<(CurrencyId, Price), ConstU32<2>> {
sp_runtime::BoundedVec::try_from(vec![(CurrencyId::ASTR, Price::from_rational(15, 100))])
.expect("out of bounds")
}
}

Expand All @@ -407,7 +407,7 @@ impl DappStakingAccountCheck<AccountId> for AccountCheck {

pub struct ShidenTierSlots;
impl TierSlotsFunc for ShidenTierSlots {
fn number_of_slots(price: CurrencyAmount) -> u16 {
fn number_of_slots(price: Price) -> u16 {
// According to the forum proposal, the original formula's factor is reduced from 1000x to 100x.
let result: u64 = price.saturating_mul_int(100_u64).saturating_add(50);
result.unique_saturated_into()
Expand Down Expand Up @@ -1120,7 +1120,7 @@ impl orml_oracle::Config for Runtime {
type CombineData = DummyCombineData<Runtime>;
type Time = Timestamp;
type OracleKey = CurrencyId;
type OracleValue = CurrencyAmount;
type OracleValue = Price;
type RootOperatorAccountId = RootOperatorAccountId;
type Members = OracleMembership;
type MaxHasDispatchedSize = ConstU32<8>;
Expand Down Expand Up @@ -1331,6 +1331,7 @@ mod benches {
[xcm_benchmarks_fungible, XcmFungible]
[pallet_price_aggregator, PriceAggregator]
[pallet_membership, OracleMembership]
[orml_oracle, Oracle]
);
}

Expand Down
13 changes: 6 additions & 7 deletions tests/integration/src/oracle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

use crate::setup::*;

use astar_primitives::oracle::{CurrencyAmount, PriceProvider};
use astar_primitives::oracle::{Price, PriceProvider};
use pallet_price_aggregator::{IntermediateValueAggregator, ValueAggregator};

#[test]
Expand All @@ -33,13 +33,13 @@ fn price_submission_works() {
IntermediateValueAggregator::<Runtime>::put(ValueAggregator::new(limit_block));

// 1. Submit a price for a valid asset - the native currency
let price_1 = CurrencyAmount::from_rational(15, 100);
let price_1 = Price::from_rational(15, 100);
assert_ok!(Oracle::feed_values(
RuntimeOrigin::signed(ALICE.clone()),
vec![(native_currency_id, price_1)].try_into().unwrap()
));

let price_2 = CurrencyAmount::from_rational(17, 100);
let price_2 = Price::from_rational(17, 100);
assert_ok!(Oracle::feed_values(
RuntimeOrigin::signed(BOB.clone()),
vec![(native_currency_id, price_2)].try_into().unwrap()
Expand All @@ -48,7 +48,7 @@ fn price_submission_works() {
// 2. Advance a block, and check price aggregator intermediate state is as expected
// (perhaps a bit detailed, but still good to check whether it's integrated)
run_for_blocks(1);
let expected_average = (price_1 + price_2) * CurrencyAmount::from_rational(1, 2);
let expected_average = (price_1 + price_2) * Price::from_rational(1, 2);
assert_eq!(
IntermediateValueAggregator::<Runtime>::get().average(),
expected_average
Expand All @@ -57,7 +57,7 @@ fn price_submission_works() {
// 3. Keep advancing blocks, adding new values only each other block, and verify the average is as expected at the end
for i in System::block_number() + 1..limit_block {
if i % 2 == 0 {
let step = CurrencyAmount::from_rational(i as u128 % 5, 100);
let step = Price::from_rational(i as u128 % 5, 100);

assert_ok!(Oracle::feed_values(
RuntimeOrigin::signed(ALICE.clone()),
Expand All @@ -77,8 +77,7 @@ fn price_submission_works() {

// 4. Execute limit block and verify state is updated as expected
run_for_blocks(2); // Need to run on_finalize of the limit block
let expected_moving_average =
(expected_average + INIT_PRICE) * CurrencyAmount::from_rational(1, 2);
let expected_moving_average = (expected_average + INIT_PRICE) * Price::from_rational(1, 2);
assert_eq!(PriceAggregator::average_price(), expected_moving_average);

// 5. Run until next limit block without any transactions, don't expect any changes
Expand Down
4 changes: 2 additions & 2 deletions tests/integration/src/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub use astar_primitives::{
CommunityCouncilMembershipInst, MainCouncilMembershipInst, OracleMembershipInst,
TechnicalCommitteeMembershipInst,
},
oracle::CurrencyAmount,
oracle::Price,
BlockNumber,
};

Expand Down Expand Up @@ -135,7 +135,7 @@ pub const CAT: AccountId32 = AccountId32::new([3_u8; 32]);

pub const INITIAL_AMOUNT: u128 = 100_000 * UNIT;

pub const INIT_PRICE: CurrencyAmount = CurrencyAmount::from_rational(1, 10);
pub const INIT_PRICE: Price = Price::from_rational(1, 10);

pub type SystemError = frame_system::Error<Runtime>;
pub use pallet_balances::Call as BalancesCall;
Expand Down

0 comments on commit 8f2e8dc

Please sign in to comment.