This repository has been archived by the owner on Nov 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathmevdb.rs
379 lines (339 loc) · 12.2 KB
/
mevdb.rs
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
use crate::inspectors::BatchEvaluationError;
use crate::types::Evaluation;
use ethers::prelude::Middleware;
use ethers::types::{TxHash, U256};
use futures::{Future, FutureExt, Stream, StreamExt};
use rust_decimal::prelude::*;
use std::collections::VecDeque;
use std::pin::Pin;
use std::task::{Context, Poll};
use thiserror::Error;
use tokio_postgres::{config::Config, Client, NoTls};
/// Wrapper around PostGres for storing results in the database
pub struct MevDB {
client: Client,
table_name: String,
overwrite: String,
}
impl MevDB {
/// Connects to the MEV PostGres instance
pub async fn connect(cfg: Config, table_name: impl Into<String>) -> Result<Self, DbError> {
let (client, connection) = cfg.connect(NoTls).await?;
tokio::spawn(async move {
if let Err(e) = connection.await {
eprintln!("connection error: {}", e);
}
});
// TODO: Allow overwriting on conflict
let overwrite = "on conflict do nothing";
Ok(Self {
client,
table_name: table_name.into(),
overwrite: overwrite.to_owned(),
})
}
/// Creates a new table for the MEV data
pub async fn create(&mut self) -> Result<(), DbError> {
self.client
.batch_execute(&format!(
"CREATE TABLE IF NOT EXISTS {} (
hash text PRIMARY KEY,
status text,
block_number NUMERIC,
gas_price NUMERIC,
gas_used NUMERIC,
revenue NUMERIC,
protocols text[],
actions text[],
eoa text,
contract text,
proxy_impl text,
inserted_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
)",
self.table_name
))
.await?;
Ok(())
}
/// Inserts data from this evaluation to PostGres
pub async fn insert(&mut self, evaluation: &Evaluation) -> Result<(), DbError> {
self.client
.execute(
format!(
"INSERT INTO {} (
hash,
status,
block_number,
gas_price,
gas_used,
revenue,
protocols,
actions,
eoa,
contract,
proxy_impl
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
{}",
self.table_name, self.overwrite,
)
.as_str(),
&[
&format!("{:?}", evaluation.inspection.hash),
&format!("{:?}", evaluation.inspection.status),
&Decimal::from(evaluation.inspection.block_number),
&u256_decimal(evaluation.gas_price)?,
&u256_decimal(evaluation.gas_used)?,
&u256_decimal(evaluation.profit)?,
&vec_str(&evaluation.inspection.protocols),
&vec_str(&evaluation.actions),
&format!("{:?}", evaluation.inspection.from),
&format!("{:?}", evaluation.inspection.contract),
&evaluation
.inspection
.proxy_impl
.map(|x| format!("{:?}", x))
.unwrap_or_else(|| "".to_owned()),
],
)
.await?;
Ok(())
}
/// Checks if the transaction hash is already inspected
pub async fn exists(&mut self, hash: TxHash) -> Result<bool, DbError> {
let rows = self
.client
.query(
format!("SELECT hash FROM {} WHERE hash = $1", self.table_name).as_str(),
&[&format!("{:?}", hash)],
)
.await?;
if let Some(row) = rows.get(0) {
let got: String = row.get(0);
Ok(format!("{:?}", hash) == got)
} else {
Ok(false)
}
}
/// Checks if the provided block has been inspected
pub async fn block_exists(&mut self, block: u64) -> Result<bool, DbError> {
let rows = self
.client
.query(
format!(
"SELECT block_number FROM {} WHERE block_number = $1 LIMIT 1;",
self.table_name
)
.as_str(),
&[&Decimal::from_u64(block).ok_or(DbError::InvalidDecimal)?],
)
.await?;
if rows.get(0).is_some() {
Ok(true)
} else {
Ok(false)
}
}
pub async fn clear(&mut self) -> Result<(), DbError> {
self.client
.batch_execute(&format!("DROP TABLE {}", self.table_name))
.await?;
Ok(())
}
}
#[derive(Error, Debug)]
pub enum DbError {
#[error(transparent)]
Decimal(#[from] rust_decimal::Error),
#[error("could not convert u64 to decimal")]
InvalidDecimal,
#[error(transparent)]
TokioPostGres(#[from] tokio_postgres::Error),
}
type EvalInsertion = Pin<Box<dyn Future<Output = Result<(Evaluation, MevDB), (MevDB, DbError)>>>>;
type EvaluationStream<'a, M> =
Pin<Box<dyn Stream<Item = Result<Evaluation, BatchEvaluationError<M>>> + 'a>>;
/// Takes a stream of `Evaluation`s and puts it in the database
pub struct BatchInserts<'a, M: Middleware + Unpin + 'static> {
mev_db: Option<MevDB>,
/// The currently running insert job
insertion: Option<EvalInsertion>,
/// `Evaluation`s ready to insert
insertion_queue: VecDeque<Evaluation>,
/// All the evaluations to insert
pending_evaluations: EvaluationStream<'a, M>,
/// Whether no more evaluations are coming
evals_done: bool,
}
impl<'a, M: Middleware + Unpin + 'static> BatchInserts<'a, M> {
pub fn new<S>(mev_db: MevDB, evals: S) -> Self
where
S: Stream<Item = Result<Evaluation, BatchEvaluationError<M>>> + 'a,
{
Self {
mev_db: Some(mev_db),
insertion: None,
insertion_queue: VecDeque::new(),
pending_evaluations: Box::pin(evals),
evals_done: false,
}
}
/// Returns the database again
///
/// If the DB is currently busy, this waits until the last job is completed
pub async fn get_database(mut self) -> MevDB {
if let Some(db) = self.mev_db.take() {
db
} else {
match self.insertion.expect("DB is busy when not idle").await {
Ok((_, db)) => db,
Err((db, _)) => db,
}
}
}
}
impl<'a, M: Middleware + Unpin> Stream for BatchInserts<'a, M> {
type Item = Result<Evaluation, InsertEvaluationError<M>>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
// start a new insert if ready
if let Some(db) = this.mev_db.take() {
if let Some(next) = this.insertion_queue.pop_front() {
log::trace!(
"start next evaluation insert, {} pending",
this.insertion_queue.len()
);
this.insertion = Some(Box::pin(insert_evaluation(next, db)));
} else {
this.mev_db = Some(db);
}
}
// complete the insertion task
if let Some(mut job) = this.insertion.take() {
match job.poll_unpin(cx) {
Poll::Ready(Ok((eval, db))) => {
this.mev_db = Some(db);
return Poll::Ready(Some(Ok(eval)));
}
Poll::Ready(Err((db, err))) => {
this.mev_db = Some(db);
return Poll::Ready(Some(Err(err.into())));
}
Poll::Pending => {
this.insertion = Some(job);
}
}
}
if !this.evals_done {
// queue in all evaluations that are coming in
loop {
match this.pending_evaluations.poll_next_unpin(cx) {
Poll::Ready(Some(Ok(eval))) => {
log::trace!(
"received new evaluation of block {} with tx {}; waiting evaluations: {}",
eval.inspection.block_number,
eval.inspection.hash,
this.insertion_queue.len() + 1
);
this.insertion_queue.push_back(eval);
}
Poll::Ready(Some(Err(err))) => return Poll::Ready(Some(Err(err.into()))),
Poll::Ready(None) => {
log::trace!("evaluations done");
this.evals_done = true;
break;
}
Poll::Pending => break,
}
}
}
// If more evaluations and insertions are processed we're not done yet
if this.evals_done && this.insertion_queue.is_empty() && this.insertion.is_none() {
log::trace!("batch insert done");
Poll::Ready(None)
} else {
Poll::Pending
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let insertions = self.insertion_queue.len() + self.insertion.is_some() as usize;
let (evals, _) = self.pending_evaluations.size_hint();
(insertions + evals, None)
}
}
async fn insert_evaluation(
eval: Evaluation,
mut db: MevDB,
) -> Result<(Evaluation, MevDB), (MevDB, DbError)> {
if let Err(err) = db.insert(&eval).await {
log::error!("DB insert failed: {:?}", err);
Err((db, err))
} else {
log::debug!(
"inserted evaluation of block {} with tx {}",
eval.inspection.block_number,
eval.inspection.hash
);
Ok((eval, db))
}
}
#[derive(Error, Debug)]
pub enum InsertEvaluationError<M: Middleware + 'static> {
#[error(transparent)]
DbError(#[from] DbError),
#[error(transparent)]
BatchEvaluationError(#[from] BatchEvaluationError<M>),
}
// helpers
fn vec_str<T: std::fmt::Debug, I: IntoIterator<Item = T>>(t: I) -> Vec<String> {
t.into_iter()
.map(|i| format!("{:?}", i).to_lowercase())
.collect::<Vec<_>>()
}
fn u256_decimal(src: U256) -> Result<Decimal, rust_decimal::Error> {
Decimal::from_str(&src.to_string())
}
#[cfg(all(test, feature = "postgres-tests"))]
mod tests {
use super::*;
use crate::types::evaluation::ActionType;
use crate::types::Inspection;
use ethers::types::{Address, TxHash};
use std::collections::HashSet;
/// This expects postgres running on localhost:5432 with user `mev_rs_user` and table `mev_inspections_test`
#[tokio::test]
async fn insert_eval() {
let mut config = Config::default();
config
.host("localhost")
.user("mev_rs_user")
.dbname("mev_inspections_test");
let mut client = MevDB::connect(config, "mev_inspections").await.unwrap();
let _ = client.clear().await;
client.create().await.unwrap();
let inspection = Inspection {
status: crate::types::Status::Checked,
actions: Vec::new(),
protocols: HashSet::new(),
from: Address::zero(),
contract: Address::zero(),
proxy_impl: None,
hash: TxHash::zero(),
block_number: 9,
};
let actions = [ActionType::Liquidation, ActionType::Arbitrage]
.iter()
.cloned()
.collect::<HashSet<_>>();
let evaluation = Evaluation {
inspection,
gas_used: 21000.into(),
gas_price: (100e9 as u64).into(),
actions,
profit: (1e18 as u64).into(),
};
client.insert(&evaluation).await.unwrap();
assert!(client.exists(evaluation.as_ref().hash).await.unwrap());
// conflicts get ignored
client.insert(&evaluation).await.unwrap();
}
}