forked from SO4-Markets/so4-oracle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
418 lines (379 loc) · 16.1 KB
/
Copy pathlib.rs
File metadata and controls
418 lines (379 loc) · 16.1 KB
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! Shared token configuration for the so4-oracle workspace.
//!
//! The oracle Worker consumes `TokenConfig` through `PRICE_FEED_CONFIG`.
//! `config/tokens.json` remains as a checked-in example for local setup.
use serde::Deserialize;
use std::collections::HashMap;
use std::path::Path;
// ── Unified token config ─────────────────────────────────────────────────────
/// A single token entry used by both the oracle cron pipeline and the API
/// server. Fields cover both use-cases:
/// - `symbol`, `stellar_address`, `sources` — oracle feed config
/// - `min`, `max`, `sources_used` — API price-lookup metadata
// #504 — deny_unknown_fields ensures a typo'd key (e.g. "max_deviaton_bps") is
// rejected at parse time instead of being silently ignored and falling back to
// the Default value, which would let the oracle run with wrong risk thresholds.
#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(default, deny_unknown_fields)]
pub struct TokenConfig {
/// On-chain token symbol, e.g. "TWBTC", "TETH". Used as the canonical key.
pub symbol: String,
/// External market symbol, e.g. "BTC", "ETH".
pub display_symbol: Option<String>,
/// Stellar contract address for the token.
pub stellar_address: String,
/// Price sources the oracle should query (e.g. `["binance", "coinbase"]`).
pub sources: Vec<String>,
/// Optional Binance-specific symbol override (e.g. "BTCUSDT").
pub binance_symbol: Option<String>,
/// Optional Coinbase-specific base currency override (e.g. "BTC").
pub coinbase_symbol: Option<String>,
/// Optional Pyth feed ID.
pub pyth_feed_id: Option<String>,
/// Fixed price in 1e30 precision, encoded as a decimal integer string.
pub fixed_price: Option<String>,
/// Minimum source count required after source fetches and outlier filtering.
pub min_sources: usize,
/// Maximum allowed source deviation from the median in basis points.
pub max_deviation_bps: u32,
/// Source freshness limit.
pub stale_after_seconds: u64,
/// Minimum movement before on-chain submission, in basis points.
pub submit_threshold_bps: u32,
/// Minimum price bound (used by the API server for display).
pub min: f64,
/// Maximum price bound (used by the API server for display).
pub max: f64,
/// Sources that contributed to the latest price (populated at runtime).
pub sources_used: Vec<String>,
}
impl Default for TokenConfig {
fn default() -> Self {
Self {
symbol: String::new(),
display_symbol: None,
stellar_address: String::new(),
sources: vec![],
binance_symbol: None,
coinbase_symbol: None,
pyth_feed_id: None,
fixed_price: None,
min_sources: 2,
max_deviation_bps: 100,
stale_after_seconds: 60,
submit_threshold_bps: 10,
min: 0.0,
max: 0.0,
sources_used: vec![],
}
}
}
/// Canonical token address for lookups. Returns `stellar_address` if set,
/// otherwise falls back to the lowercased symbol.
impl TokenConfig {
pub fn lookup_key(&self) -> String {
if self.stellar_address.is_empty() {
self.symbol.to_lowercase()
} else {
self.stellar_address.to_lowercase()
}
}
pub fn display_symbol(&self) -> &str {
self.display_symbol.as_deref().unwrap_or(&self.symbol)
}
}
// ── Loading helpers ──────────────────────────────────────────────────────────
/// Error type for configuration loading.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigError {
/// The `PRICE_FEED_CONFIG` env var is missing.
MissingEnvVar,
/// JSON parsing failed.
MalformedJson(String),
/// The token list is empty.
EmptyTokenList,
/// A token entry is invalid.
InvalidToken { symbol: String, reason: String },
/// File I/O error.
IoError(String),
}
impl std::fmt::Display for ConfigError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ConfigError::MissingEnvVar => {
write!(f, "required env var 'PRICE_FEED_CONFIG' is not set")
}
ConfigError::MalformedJson(msg) => {
write!(f, "PRICE_FEED_CONFIG is not valid JSON: {msg}")
}
ConfigError::EmptyTokenList => {
write!(f, "PRICE_FEED_CONFIG must contain at least one token")
}
ConfigError::InvalidToken { symbol, reason } => {
write!(f, "invalid token config for '{symbol}': {reason}")
}
ConfigError::IoError(msg) => {
write!(f, "failed to read token config file: {msg}")
}
}
}
}
impl std::error::Error for ConfigError {}
/// Parse a JSON array of `TokenConfig` entries and validate required fields.
pub fn parse_token_configs(raw: &str) -> Result<Vec<TokenConfig>, ConfigError> {
let tokens: Vec<TokenConfig> =
serde_json::from_str(raw).map_err(|e| ConfigError::MalformedJson(e.to_string()))?;
if tokens.is_empty() {
return Err(ConfigError::EmptyTokenList);
}
let mut symbols_seen = std::collections::HashSet::new();
for token in &tokens {
if token.symbol.is_empty() {
return Err(ConfigError::InvalidToken {
symbol: "(empty)".to_string(),
reason: "symbol must not be empty".to_string(),
});
}
let lower_symbol = token.symbol.to_lowercase();
if !symbols_seen.insert(lower_symbol) {
return Err(ConfigError::InvalidToken {
symbol: token.symbol.clone(),
reason: "duplicate symbol (case-insensitive)".to_string(),
});
}
// stellar_address and sources are optional for the API server path,
// but required for the oracle path — the oracle validates separately.
for source in &token.sources {
match source.as_str() {
"binance" => {
if let Some(ref sym) = token.binance_symbol {
if sym.is_empty()
|| !sym
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
return Err(ConfigError::InvalidToken {
symbol: token.symbol.clone(),
reason: format!("invalid binance_symbol '{sym}': must contain only alphanumeric characters, dashes, or underscores"),
});
}
}
}
"coinbase" => {
if let Some(ref sym) = token.coinbase_symbol {
if sym.is_empty()
|| !sym
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
return Err(ConfigError::InvalidToken {
symbol: token.symbol.clone(),
reason: format!("invalid coinbase_symbol '{sym}': must contain only alphanumeric characters, dashes, or underscores"),
});
}
}
}
"pyth" | "fixed" => {}
other => {
return Err(ConfigError::InvalidToken {
symbol: token.symbol.clone(),
reason: format!("unsupported source '{other}'"),
});
}
}
}
// #504 — range validation so misconfigured tuning fields fail loudly at
// startup rather than silently running with wrong risk thresholds.
if token.max_deviation_bps == 0 || token.max_deviation_bps > 10_000 {
return Err(ConfigError::InvalidToken {
symbol: token.symbol.clone(),
reason: format!(
"max_deviation_bps ({}) must be between 1 and 10000",
token.max_deviation_bps
),
});
}
if token.stale_after_seconds == 0 {
return Err(ConfigError::InvalidToken {
symbol: token.symbol.clone(),
reason: "stale_after_seconds must be greater than 0".to_string(),
});
}
if token.submit_threshold_bps > 10_000 {
return Err(ConfigError::InvalidToken {
symbol: token.symbol.clone(),
reason: format!(
"submit_threshold_bps ({}) must be between 0 and 10000",
token.submit_threshold_bps
),
});
}
if token.min_sources == 0 {
return Err(ConfigError::InvalidToken {
symbol: token.symbol.clone(),
reason: "min_sources must be at least 1".to_string(),
});
}
}
Ok(tokens)
}
/// Load tokens from the `PRICE_FEED_CONFIG` env var (JSON string).
/// Returns `None` if the var is not set (caller can fall back to file).
pub fn load_from_env_var(env_value: Option<&str>) -> Result<Option<Vec<TokenConfig>>, ConfigError> {
match env_value {
Some(raw) => parse_token_configs(raw).map(Some),
None => Ok(None),
}
}
/// Load tokens from a JSON file on disk.
pub fn load_from_file(path: &Path) -> Result<Vec<TokenConfig>, ConfigError> {
let raw = std::fs::read_to_string(path).map_err(|e| ConfigError::IoError(e.to_string()))?;
parse_token_configs(&raw)
}
/// Build a lookup map keyed by lowercased symbol.
pub fn build_lookup(tokens: &[TokenConfig]) -> HashMap<String, &TokenConfig> {
let mut map = HashMap::new();
for token in tokens {
map.insert(token.symbol.to_lowercase(), token);
}
map
}
// ── Tests ────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
const VALID_JSON: &str = r#"[
{"symbol":"BTC","stellar_address":"CBTCADDR","sources":["binance","coinbase"],"min":44000.0,"max":46000.0},
{"symbol":"ETH","stellar_address":"CETHADDR","sources":["binance"],"min":2400.0,"max":2600.0}
]"#;
#[test]
fn parse_valid_config() {
let tokens = parse_token_configs(VALID_JSON).unwrap();
assert_eq!(tokens.len(), 2);
assert_eq!(tokens[0].symbol, "BTC");
assert_eq!(tokens[0].sources, vec!["binance", "coinbase"]);
assert_eq!(tokens[0].min, 44000.0);
}
#[test]
fn reject_malformed_json() {
let err = parse_token_configs("{not json}").unwrap_err();
assert!(matches!(err, ConfigError::MalformedJson(_)));
}
#[test]
fn reject_empty_list() {
let err = parse_token_configs("[]").unwrap_err();
assert!(matches!(err, ConfigError::EmptyTokenList));
}
#[test]
fn reject_empty_symbol() {
let json = r#"[{"symbol":"","stellar_address":"CADDR","sources":["binance"]}]"#;
let err = parse_token_configs(json).unwrap_err();
assert!(matches!(err, ConfigError::InvalidToken { .. }));
}
#[test]
fn reject_case_colliding_symbols() {
let json = r#"[
{"symbol":"BTC","stellar_address":"CBTCADDR","sources":["binance"],"min":44000.0,"max":46000.0},
{"symbol":"btc","stellar_address":"CETHADDR","sources":["binance"],"min":2400.0,"max":2600.0}
]"#;
let err = parse_token_configs(json).unwrap_err();
match err {
ConfigError::InvalidToken { symbol, reason } => {
assert_eq!(symbol, "btc");
assert_eq!(reason, "duplicate symbol (case-insensitive)");
}
_ => panic!("expected ConfigError::InvalidToken"),
}
}
#[test]
fn load_from_env_var_returns_none_when_unset() {
let result = load_from_env_var(None).unwrap();
assert!(result.is_none());
}
#[test]
fn load_from_env_var_parses_json() {
let result = load_from_env_var(Some(VALID_JSON)).unwrap().unwrap();
assert_eq!(result.len(), 2);
}
#[test]
fn lookup_key_uses_stellar_address() {
let tokens = parse_token_configs(VALID_JSON).unwrap();
assert_eq!(tokens[0].lookup_key(), "cbtcaddr");
}
#[test]
fn lookup_key_falls_back_to_symbol() {
let json = r#"[{"symbol":"BTC","sources":["binance"]}]"#;
let tokens = parse_token_configs(json).unwrap();
assert_eq!(tokens[0].lookup_key(), "btc");
}
#[test]
fn build_lookup_creates_lowercase_map() {
let tokens = parse_token_configs(VALID_JSON).unwrap();
let map = build_lookup(&tokens);
assert!(map.contains_key("btc"));
assert!(map.contains_key("eth"));
assert!(!map.contains_key("BTC"));
}
#[test]
fn build_lookup_returns_correct_references() {
let tokens = parse_token_configs(VALID_JSON).unwrap();
let map = build_lookup(&tokens);
assert_eq!(map.get("btc").unwrap().symbol, "BTC");
assert_eq!(map.get("eth").unwrap().symbol, "ETH");
}
#[test]
fn build_lookup_keys_are_lowercased_symbol() {
let json = r#"[{"symbol":"MIXEDcase","sources":["binance"]},{"symbol":"UPPER","sources":["fixed"],"fixed_price":"1"}]"#;
let tokens = parse_token_configs(json).unwrap();
let map = build_lookup(&tokens);
assert!(map.contains_key("mixedcase"));
assert!(map.contains_key("upper"));
assert!(!map.contains_key("MIXEDcase"));
assert!(!map.contains_key("UPPER"));
}
// #504 — deny_unknown_fields: typo'd keys must be rejected, not silently ignored.
#[test]
fn reject_unknown_field_typo() {
let json = r#"[{"symbol":"BTC","sources":["binance"],"max_deviaton_bps":50}]"#;
let err = parse_token_configs(json).unwrap_err();
assert!(
matches!(err, ConfigError::MalformedJson(_)),
"expected MalformedJson for unknown field, got: {err:?}"
);
}
// #504 — range validation: zero max_deviation_bps must fail.
#[test]
fn reject_zero_max_deviation_bps() {
let json = r#"[{"symbol":"BTC","sources":["binance"],"max_deviation_bps":0}]"#;
let err = parse_token_configs(json).unwrap_err();
assert!(matches!(err, ConfigError::InvalidToken { .. }), "{err:?}");
}
// #504 — range validation: max_deviation_bps above 10000 must fail.
#[test]
fn reject_max_deviation_bps_above_10000() {
let json = r#"[{"symbol":"BTC","sources":["binance"],"max_deviation_bps":10001}]"#;
let err = parse_token_configs(json).unwrap_err();
assert!(matches!(err, ConfigError::InvalidToken { .. }), "{err:?}");
}
// #504 — range validation: stale_after_seconds = 0 must fail.
#[test]
fn reject_zero_stale_after_seconds() {
let json = r#"[{"symbol":"BTC","sources":["binance"],"stale_after_seconds":0}]"#;
let err = parse_token_configs(json).unwrap_err();
assert!(matches!(err, ConfigError::InvalidToken { .. }), "{err:?}");
}
// #504 — range validation: submit_threshold_bps above 10000 must fail.
#[test]
fn reject_submit_threshold_bps_above_10000() {
let json = r#"[{"symbol":"BTC","sources":["binance"],"submit_threshold_bps":10001}]"#;
let err = parse_token_configs(json).unwrap_err();
assert!(matches!(err, ConfigError::InvalidToken { .. }), "{err:?}");
}
// #504 — range validation: min_sources = 0 must fail.
#[test]
fn reject_zero_min_sources() {
let json = r#"[{"symbol":"BTC","sources":["binance"],"min_sources":0}]"#;
let err = parse_token_configs(json).unwrap_err();
assert!(matches!(err, ConfigError::InvalidToken { .. }), "{err:?}");
}
}