1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
use super::decimal::SwitchboardDecimal;
use super::error::SwitchboardError;
use anchor_lang::prelude::*;
use anchor_lang::Discriminator;
use rust_decimal::Decimal;
use std::cell::Ref;
#[zero_copy]
#[repr(packed)]
#[derive(Default, Debug, PartialEq, Eq)]
pub struct Hash {
pub data: [u8; 32],
}
#[zero_copy]
#[repr(packed)]
#[derive(Default, Debug, PartialEq, Eq)]
pub struct AggregatorRound {
pub num_success: u32,
pub num_error: u32,
pub is_closed: bool,
pub round_open_slot: u64,
pub round_open_timestamp: i64,
pub result: SwitchboardDecimal,
pub std_deviation: SwitchboardDecimal,
pub min_response: SwitchboardDecimal,
pub max_response: SwitchboardDecimal,
pub oracle_pubkeys_data: [Pubkey; 16],
pub medians_data: [SwitchboardDecimal; 16],
pub current_payout: [i64; 16],
pub medians_fulfilled: [bool; 16],
pub errors_fulfilled: [bool; 16],
}
#[derive(Copy, Clone, Debug, AnchorSerialize, AnchorDeserialize, Eq, PartialEq)]
#[repr(u8)]
pub enum AggregatorResolutionMode {
ModeRoundResolution = 0,
ModeSlidingResolution = 1,
}
#[account(zero_copy)]
#[repr(packed)]
pub struct SlidingResultAccountData {
pub data: [SlidingWindowElement; 16],
pub bump: u8,
pub _ebuf: [u8; 512],
}
#[zero_copy]
#[derive(Default)]
#[repr(packed)]
pub struct SlidingWindowElement {
pub oracle_key: Pubkey,
pub value: SwitchboardDecimal,
pub slot: u64,
pub timestamp: i64,
}
#[account(zero_copy)]
#[repr(packed)]
#[derive(Debug, PartialEq)]
pub struct AggregatorAccountData {
pub name: [u8; 32],
pub metadata: [u8; 128],
pub _reserved1: [u8; 32],
pub queue_pubkey: Pubkey,
pub oracle_request_batch_size: u32,
pub min_oracle_results: u32,
pub min_job_results: u32,
pub min_update_delay_seconds: u32,
pub start_after: i64,
pub variance_threshold: SwitchboardDecimal,
pub force_report_period: i64,
pub expiration: i64,
pub consecutive_failure_count: u64,
pub next_allowed_update_time: i64,
pub is_locked: bool,
pub crank_pubkey: Pubkey,
pub latest_confirmed_round: AggregatorRound,
pub current_round: AggregatorRound,
pub job_pubkeys_data: [Pubkey; 16],
pub job_hashes: [Hash; 16],
pub job_pubkeys_size: u32,
pub jobs_checksum: [u8; 32],
pub authority: Pubkey,
pub history_buffer: Pubkey,
pub previous_confirmed_round_result: SwitchboardDecimal,
pub previous_confirmed_round_slot: u64,
pub disable_crank: bool,
pub job_weights: [u8; 16],
pub creation_timestamp: i64,
pub resolution_mode: AggregatorResolutionMode,
pub _ebuf: [u8; 138],
}
impl AggregatorAccountData {
pub fn new<'info>(
switchboard_feed: &'info AccountInfo<'info>,
) -> anchor_lang::Result<Ref<'info, AggregatorAccountData>> {
let data = switchboard_feed.try_borrow_data()?;
if data.len() < AggregatorAccountData::discriminator().len() {
return Err(ErrorCode::AccountDiscriminatorNotFound.into());
}
let mut disc_bytes = [0u8; 8];
disc_bytes.copy_from_slice(&data[..8]);
if disc_bytes != AggregatorAccountData::discriminator() {
return Err(ErrorCode::AccountDiscriminatorMismatch.into());
}
Ok(Ref::map(data, |data| {
bytemuck::from_bytes(&data[8..std::mem::size_of::<AggregatorAccountData>() + 8])
}))
}
pub fn new_from_bytes(data: &[u8]) -> anchor_lang::Result<&AggregatorAccountData> {
if data.len() < AggregatorAccountData::discriminator().len() {
return Err(ErrorCode::AccountDiscriminatorNotFound.into());
}
let mut disc_bytes = [0u8; 8];
disc_bytes.copy_from_slice(&data[..8]);
if disc_bytes != AggregatorAccountData::discriminator() {
return Err(ErrorCode::AccountDiscriminatorMismatch.into());
}
Ok(bytemuck::from_bytes(
&data[8..std::mem::size_of::<AggregatorAccountData>() + 8],
))
}
pub fn get_result(&self) -> anchor_lang::Result<SwitchboardDecimal> {
if self.resolution_mode == AggregatorResolutionMode::ModeSlidingResolution {
return Ok(self.latest_confirmed_round.result);
}
let min_oracle_results = self.min_oracle_results;
let latest_confirmed_round_num_success = self.latest_confirmed_round.num_success;
if min_oracle_results > latest_confirmed_round_num_success {
return Err(SwitchboardError::InvalidAggregatorRound.into());
}
Ok(self.latest_confirmed_round.result)
}
pub fn check_confidence_interval(
&self,
max_confidence_interval: SwitchboardDecimal,
) -> anchor_lang::Result<()> {
if self.latest_confirmed_round.std_deviation > max_confidence_interval {
return Err(SwitchboardError::ConfidenceIntervalExceeded.into());
}
Ok(())
}
pub fn check_variace(&self, max_variance: Decimal) -> anchor_lang::Result<()> {
if max_variance > Decimal::ONE {
return Err(SwitchboardError::InvalidFunctionInput.into());
}
let min: Decimal = self.latest_confirmed_round.min_response.try_into().unwrap();
let max: Decimal = self.latest_confirmed_round.max_response.try_into().unwrap();
if min < Decimal::ZERO || max < Decimal::ZERO || min > max {
return Err(SwitchboardError::AllowedVarianceExceeded.into());
}
if min / max > max_variance {
return Err(SwitchboardError::AllowedVarianceExceeded.into());
}
Ok(())
}
pub fn check_staleness(
&self,
unix_timestamp: i64,
max_staleness: i64,
) -> anchor_lang::Result<()> {
let staleness = unix_timestamp - self.latest_confirmed_round.round_open_timestamp;
if staleness > max_staleness {
msg!("Feed has not been updated in {} seconds!", staleness);
return Err(SwitchboardError::StaleFeed.into());
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
impl<'info> Default for AggregatorAccountData {
fn default() -> Self {
unsafe { std::mem::zeroed() }
}
}
fn create_aggregator(lastest_round: AggregatorRound) -> AggregatorAccountData {
let mut aggregator = AggregatorAccountData::default();
aggregator.min_update_delay_seconds = 10;
aggregator.latest_confirmed_round = lastest_round;
aggregator.min_job_results = 10;
aggregator.min_oracle_results = 10;
return aggregator;
}
fn create_round(value: f64, num_success: u32, num_error: u32) -> AggregatorRound {
let mut result = AggregatorRound::default();
result.num_success = num_success;
result.num_error = num_error;
result.result = SwitchboardDecimal::from_f64(value);
return result;
}
#[test]
fn test_accept_current_on_sucess_count() {
let lastest_round = create_round(100.0, 30, 0); let aggregator = create_aggregator(lastest_round.clone());
assert_eq!(
aggregator.get_result().unwrap(),
lastest_round.result.clone()
);
}
#[test]
fn test_reject_current_on_sucess_count() {
let lastest_round = create_round(100.0, 5, 0); let aggregator = create_aggregator(lastest_round.clone());
assert!(
aggregator.get_result().is_err(),
"Aggregator is not currently populated with a valid round."
);
}
#[test]
fn test_no_valid_aggregator_result() {
let aggregator = create_aggregator(AggregatorRound::default());
assert!(
aggregator.get_result().is_err(),
"Aggregator is not currently populated with a valid round."
);
}
}