forked from SO4-Markets/so4-oracle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeeper.rs
More file actions
348 lines (300 loc) · 11.7 KB
/
Copy pathkeeper.rs
File metadata and controls
348 lines (300 loc) · 11.7 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
use std::sync::atomic::{AtomicBool, Ordering};
use crate::stellar_rpc::{get_account_balance_stroops, RpcError};
/// 1 XLM expressed in stroops.
pub const XLM_IN_STROOPS: i64 = 10_000_000;
/// Default minimum keeper balance: 10 XLM.
pub const DEFAULT_MIN_KEEPER_BALANCE_XLM: f64 = 10.0;
/// Tracks whether the keeper was already below the minimum so `/ready` probes
/// do not re-emit `error!` on every poll for a sustained low-balance condition.
static KEEPER_BALANCE_BELOW_MIN: AtomicBool = AtomicBool::new(false);
pub struct KeeperBalanceConfig {
pub horizon_url: String,
pub account_id: String,
/// Minimum acceptable balance in XLM.
pub min_balance_xlm: f64,
}
/// Check the keeper balance. Returns the current balance in stroops.
///
/// Logs `error!` only on the transition into the low-balance state (and
/// `info!` on recovery). Subsequent checks while the balance remains low
/// use `debug!` so readiness probes do not flood logs.
pub async fn check_keeper_balance(cfg: &KeeperBalanceConfig) -> Result<i64, RpcError> {
let stroops = get_account_balance_stroops(&cfg.horizon_url, &cfg.account_id).await?;
let xlm = stroops as f64 / XLM_IN_STROOPS as f64;
if xlm < cfg.min_balance_xlm {
let was_below = KEEPER_BALANCE_BELOW_MIN.swap(true, Ordering::Relaxed);
if was_below {
tracing::debug!(
balance_xlm = xlm,
min_balance_xlm = cfg.min_balance_xlm,
account_id = cfg.account_id,
"keeper balance still below minimum"
);
} else {
tracing::error!(
balance_xlm = xlm,
min_balance_xlm = cfg.min_balance_xlm,
account_id = cfg.account_id,
"keeper balance below minimum"
);
}
return Err(RpcError::BalanceBelowMinimum {
balance_xlm: xlm,
min_xlm: cfg.min_balance_xlm,
});
}
if KEEPER_BALANCE_BELOW_MIN.swap(false, Ordering::Relaxed) {
tracing::info!(
balance_xlm = xlm,
min_balance_xlm = cfg.min_balance_xlm,
"keeper balance recovered above minimum"
);
} else {
tracing::debug!(
balance_xlm = xlm,
min_balance_xlm = cfg.min_balance_xlm,
"keeper balance ok"
);
}
Ok(stroops)
}
/// JSON-serialisable balance response for the HTTP endpoint.
#[derive(serde::Serialize)]
pub struct BalanceResponse {
pub account_id: String,
pub balance_stroops: i64,
pub balance_xlm: f64,
pub below_minimum: bool,
pub min_balance_xlm: f64,
}
pub fn build_balance_response(cfg: &KeeperBalanceConfig, stroops: i64) -> BalanceResponse {
let xlm = stroops as f64 / XLM_IN_STROOPS as f64;
BalanceResponse {
account_id: cfg.account_id.clone(),
balance_stroops: stroops,
balance_xlm: xlm,
below_minimum: xlm < cfg.min_balance_xlm,
min_balance_xlm: cfg.min_balance_xlm,
}
}
/// Testnet Friendbot URL base (Issue #120).
pub const FRIENDBOT_URL: &str = "https://friendbot.stellar.org";
/// Call the Stellar testnet Friendbot to fund `account_id`.
pub async fn fund_keeper_via_friendbot(account_id: &str) -> Result<(), String> {
fund_keeper_at(FRIENDBOT_URL, account_id).await
}
async fn fund_keeper_at(base_url: &str, account_id: &str) -> Result<(), String> {
let url = format!("{base_url}?addr={account_id}");
tracing::info!(account_id, "calling Friendbot");
let response = crate::http::client()
.get(url)
.send()
.await
.map_err(|e| format!("Friendbot fetch failed: {e}"))?;
let status = response.status().as_u16();
if status == 200 {
tracing::info!(
account_id,
status,
"Friendbot response accepted (newly funded)"
);
return Ok(());
}
let body = response
.text()
.await
.unwrap_or_else(|_| "(unreadable body)".to_string());
if status == 400 && body.contains("createAccountAlreadyExist") {
tracing::info!(
account_id,
status,
"Friendbot response accepted (already funded)"
);
return Ok(());
}
Err(format!(
"Friendbot returned {status} for {account_id}: {body}"
))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::stellar_rpc::parse_account_balance_response;
use wiremock::matchers::method;
use wiremock::{Mock, MockServer, ResponseTemplate};
fn low_balance_body() -> &'static str {
r#"{"id":"GABC","balances":[{"asset_type":"native","balance":"3.0000000"}]}"#
}
#[test]
fn parse_low_balance_from_mocked_rpc() {
let stroops = parse_account_balance_response(low_balance_body()).unwrap();
assert_eq!(stroops, 30_000_000); // 3 XLM in stroops
}
#[test]
fn below_minimum_detected() {
let stroops = 30_000_000i64; // 3 XLM
let cfg = KeeperBalanceConfig {
horizon_url: "https://horizon-testnet.stellar.org".to_string(),
account_id: "GABC".to_string(),
min_balance_xlm: 10.0,
};
let resp = build_balance_response(&cfg, stroops);
assert!(resp.below_minimum);
assert_eq!(resp.balance_xlm, 3.0);
}
#[test]
fn above_minimum_not_flagged() {
let stroops = 200_000_000i64; // 20 XLM
let cfg = KeeperBalanceConfig {
horizon_url: "https://horizon-testnet.stellar.org".to_string(),
account_id: "GABC".to_string(),
min_balance_xlm: 10.0,
};
let resp = build_balance_response(&cfg, stroops);
assert!(!resp.below_minimum);
assert_eq!(resp.balance_xlm, 20.0);
}
// ── check_keeper_balance — HTTP-level tests (#406) ────────────────────────
/// Closes #414: above minimum returns Ok(stroops).
#[tokio::test]
async fn check_keeper_balance_above_minimum_returns_ok() {
use wiremock::matchers::path;
let server = MockServer::start().await;
let body = r#"{
"id": "GKEEPER",
"balances": [{"asset_type":"native","balance":"20.0000000"}]
}"#;
Mock::given(method("GET"))
.and(path("/accounts/GKEEPER"))
.respond_with(ResponseTemplate::new(200).set_body_raw(body, "application/json"))
.mount(&server)
.await;
let cfg = KeeperBalanceConfig {
horizon_url: server.uri(),
account_id: "GKEEPER".to_string(),
min_balance_xlm: 10.0,
};
let stroops = check_keeper_balance(&cfg).await.unwrap();
assert_eq!(stroops, 200_000_000); // 20 XLM in stroops
}
/// Closes #413: below minimum returns Err(BalanceBelowMinimum).
#[tokio::test]
async fn check_keeper_balance_below_minimum_returns_err() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"balances": [{"asset_type": "native", "balance": "3.0000000"}]
})))
.mount(&server)
.await;
let cfg = KeeperBalanceConfig {
horizon_url: server.uri(),
account_id: "GKEEPER".to_string(),
min_balance_xlm: 10.0,
};
let err = check_keeper_balance(&cfg).await.unwrap_err();
assert!(matches!(err, RpcError::BalanceBelowMinimum { .. }));
}
/// Horizon unreachable returns NetworkError.
#[tokio::test]
async fn check_keeper_balance_horizon_unreachable_returns_network_error() {
let cfg = KeeperBalanceConfig {
horizon_url: "http://127.0.0.1:19999".to_string(), // nothing listening
account_id: "GKEEPER".to_string(),
min_balance_xlm: 10.0,
};
let err = check_keeper_balance(&cfg).await.unwrap_err();
assert!(matches!(err, RpcError::NetworkError(_)));
}
// ── fund_keeper_via_friendbot — HTTP-level tests ─────────────────────────
/// Verifies that a 400 response from Friendbot (account already funded) is
/// treated as success — the operation is idempotent.
#[tokio::test]
async fn fund_keeper_via_friendbot_already_funded_400_returns_ok() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.respond_with(
ResponseTemplate::new(400).set_body_string(
r#"{"detail":"createAccountAlreadyExist","status":400,"title":"Transaction Failed"}"#,
),
)
.mount(&server)
.await;
let result = super::fund_keeper_at(&server.uri(), "GNEWACCOUNT").await;
assert!(result.is_ok());
}
/// Verifies that a 200 response from Friendbot (new account funded) returns Ok.
#[tokio::test]
async fn fund_keeper_via_friendbot_new_account_200_returns_ok() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.respond_with(
ResponseTemplate::new(200).set_body_string(r#"{"hash":"abc123","ledger":12345}"#),
)
.mount(&server)
.await;
let result = super::fund_keeper_at(&server.uri(), "GNEWACCOUNT").await;
assert!(result.is_ok());
}
/// Verifies that an unrelated 400 response from Friendbot is treated as an error.
#[tokio::test]
async fn fund_keeper_via_friendbot_unrelated_400_returns_err() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(400).set_body_string(
r#"{"detail":"invalid_field","status":400,"title":"Transaction Failed"}"#,
))
.mount(&server)
.await;
let result = super::fund_keeper_at(&server.uri(), "GNEWACCOUNT").await;
assert!(result.is_err());
let err_msg = result.unwrap_err();
assert!(err_msg.contains("Friendbot returned 400"));
assert!(err_msg.contains("invalid_field"));
}
/// Verifies that a non-200/400 response (e.g. 500) returns an error
/// containing both the status code and the response body.
/// Closes #526.
#[tokio::test]
async fn fund_keeper_via_friendbot_500_returns_error_with_status_and_body() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.respond_with(
ResponseTemplate::new(500).set_body_string(r#"{"detail":"internal server error"}"#),
)
.mount(&server)
.await;
let err = super::fund_keeper_at(&server.uri(), "GKEEPER")
.await
.unwrap_err();
assert!(
err.contains("500"),
"error should contain status code, got: {err}"
);
assert!(
err.contains("internal server error"),
"error should contain response body, got: {err}"
);
}
/// Verifies that a 429 (rate-limited) response surfaces the body for debugging.
/// Closes #526.
#[tokio::test]
async fn fund_keeper_via_friendbot_429_returns_error_with_status_and_body() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(429).set_body_string(r#"{"error":"rate limited"}"#))
.mount(&server)
.await;
let err = super::fund_keeper_at(&server.uri(), "GKEEPER")
.await
.unwrap_err();
assert!(
err.contains("429"),
"error should contain status code, got: {err}"
);
assert!(
err.contains("rate limited"),
"error should contain response body, got: {err}"
);
}
}