referrerpolicy=no-referrer-when-downgrade

pallet_oracle/
default_combine_data.rs

1// This file is part of Substrate.
2
3// Copyright (C) 2020-2025 Acala Foundation.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use crate::{CombineData, Config, MomentOf, TimestampedValueOf};
19use alloc::vec::Vec;
20use core::marker;
21use frame_support::traits::{Get, Time};
22use sp_runtime::traits::Saturating;
23
24/// Sort by value and returns median timestamped value.
25/// Returns prev_value if not enough valid values.
26pub struct DefaultCombineData<T, MinimumCount, ExpiresIn, I = ()>(
27	marker::PhantomData<(T, I, MinimumCount, ExpiresIn)>,
28);
29
30impl<T, I, MinimumCount, ExpiresIn>
31	CombineData<<T as Config<I>>::OracleKey, TimestampedValueOf<T, I>>
32	for DefaultCombineData<T, MinimumCount, ExpiresIn, I>
33where
34	T: Config<I>,
35	I: 'static,
36	MinimumCount: Get<u32>,
37	ExpiresIn: Get<MomentOf<T, I>>,
38{
39	fn combine_data(
40		_key: &<T as Config<I>>::OracleKey,
41		mut values: Vec<TimestampedValueOf<T, I>>,
42		prev_value: Option<TimestampedValueOf<T, I>>,
43	) -> Option<TimestampedValueOf<T, I>> {
44		let expires_in = ExpiresIn::get();
45		let now = T::Time::now();
46
47		values.retain(|x| x.timestamp.saturating_add(expires_in) > now);
48
49		let count = values.len() as u32;
50		let minimum_count = MinimumCount::get();
51		if count < minimum_count || count == 0 {
52			return prev_value;
53		}
54
55		let mid_index = count / 2;
56		// Won't panic as `values` ensured not empty.
57		let (_, value, _) =
58			values.select_nth_unstable_by(mid_index as usize, |a, b| a.value.cmp(&b.value));
59		Some(value.clone())
60	}
61}