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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
pub mod accounting;
pub mod aggregator;
pub mod batch;
pub mod comparison;
pub mod eth_transfer;
pub mod flashloan;
pub mod lending;
pub mod liquidation;
pub mod liquidity;
pub mod multi_callframe;
pub mod pool;
pub mod self_destruct;
pub mod swaps;
pub mod transfer;
use std::fmt::Debug;

use ::clickhouse::DbRow;
use accounting::{AddressDeltas, TokenAccounting};
pub use aggregator::*;
use alloy_primitives::{Address, Bytes, Log};
pub use batch::*;
use clickhouse::InsertRow;
pub use eth_transfer::*;
pub use flashloan::*;
pub use lending::*;
pub use liquidation::*;
pub use liquidity::*;
pub use multi_callframe::*;
pub use pool::*;
use reth_rpc_types::trace::parity::Action as TraceAction;
pub use self_destruct::*;
pub use swaps::*;
pub use transfer::*;

use crate::{
    structured_trace::{TraceActions, TransactionTraceWithLogs},
    Protocol,
};

pub trait NormalizedAction: Debug + Send + Sync + Clone + PartialEq + Eq {
    fn is_classified(&self) -> bool;
    fn emitted_logs(&self) -> bool;
    fn get_action(&self) -> &Action;
    fn multi_frame_classification(&self) -> Option<MultiFrameRequest>;
    fn get_trace_index(&self) -> u64;
    fn is_create(&self) -> bool;
}

impl NormalizedAction for Action {
    fn is_create(&self) -> bool {
        if let Action::Unclassified(u) = self {
            u.is_create()
        } else {
            matches!(self, Action::NewPool(_))
        }
    }

    fn is_classified(&self) -> bool {
        !matches!(
            self,
            Action::Unclassified(_) | Action::EthTransfer(..) | Action::SelfDestruct(..)
        )
    }

    /// Only relevant for unclassified actions
    fn emitted_logs(&self) -> bool {
        match self {
            Action::Unclassified(u) => !u.logs.is_empty(),
            Action::SelfDestruct(_) => false,
            Action::EthTransfer(_) => false,
            _ => true,
        }
    }

    fn get_action(&self) -> &Action {
        self
    }

    fn multi_frame_classification(&self) -> Option<MultiFrameRequest> {
        MultiFrameRequest::new(self, self.try_get_trace_index()?)
    }

    fn get_trace_index(&self) -> u64 {
        match self {
            Self::Swap(s) => s.trace_index,
            Self::SwapWithFee(s) => s.trace_index,
            Self::FlashLoan(f) => f.trace_index,
            Self::Batch(b) => b.trace_index,
            Self::Mint(m) => m.trace_index,
            Self::Burn(b) => b.trace_index,
            Self::Transfer(t) => t.trace_index,
            Self::Liquidation(t) => t.trace_index,
            Self::Collect(c) => c.trace_index,
            Self::SelfDestruct(c) => c.trace_index,
            Self::EthTransfer(e) => e.trace_index,
            Self::Unclassified(u) => u.trace_idx,
            Self::NewPool(p) => p.trace_index,
            Self::PoolConfigUpdate(p) => p.trace_index,
            Self::Aggregator(a) => a.trace_index,
            Self::Revert => unreachable!("no trace index for revert"),
        }
    }
}

/// A normalized action that has been classified
#[derive(Debug, Clone, serde::Deserialize, PartialEq, Eq)]
pub enum Action {
    Swap(NormalizedSwap),
    SwapWithFee(NormalizedSwapWithFee),
    FlashLoan(NormalizedFlashLoan),
    Batch(NormalizedBatch),
    Transfer(NormalizedTransfer),
    Mint(NormalizedMint),
    Burn(NormalizedBurn),
    Collect(NormalizedCollect),
    Liquidation(NormalizedLiquidation),
    SelfDestruct(SelfdestructWithIndex),
    EthTransfer(NormalizedEthTransfer),
    NewPool(NormalizedNewPool),
    PoolConfigUpdate(NormalizedPoolConfigUpdate),
    Aggregator(NormalizedAggregator),
    Unclassified(TransactionTraceWithLogs),
    Revert,
}

impl InsertRow for Action {
    fn get_column_names(&self) -> &'static [&'static str] {
        match self {
            Action::Swap(_) => NormalizedSwap::COLUMN_NAMES,
            Action::SwapWithFee(_) => NormalizedSwapWithFee::COLUMN_NAMES,
            Action::FlashLoan(_) => NormalizedFlashLoan::COLUMN_NAMES,
            Action::Batch(_) => NormalizedBatch::COLUMN_NAMES,
            Action::Transfer(_) => NormalizedTransfer::COLUMN_NAMES,
            Action::Mint(_) => NormalizedMint::COLUMN_NAMES,
            Action::Burn(_) => NormalizedBurn::COLUMN_NAMES,
            Action::Collect(_) => NormalizedCollect::COLUMN_NAMES,
            Action::Liquidation(_) => NormalizedLiquidation::COLUMN_NAMES,
            Action::SelfDestruct(_) => todo!("joe pls dome this"),
            Action::EthTransfer(_) => todo!("joe pls dome this"),
            Action::NewPool(_) => todo!(),
            Action::PoolConfigUpdate(_) => todo!(),
            Action::Unclassified(..) | Action::Revert => panic!(),
            Action::Aggregator(_) => NormalizedAggregator::COLUMN_NAMES,
        }
    }
}

impl serde::Serialize for Action {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Action::Swap(s) => s.serialize(serializer),
            Action::SwapWithFee(s) => s.serialize(serializer),
            Action::FlashLoan(f) => f.serialize(serializer),
            Action::Aggregator(a) => a.serialize(serializer),
            Action::Batch(b) => b.serialize(serializer),
            Action::Mint(m) => m.serialize(serializer),
            Action::Transfer(t) => t.serialize(serializer),
            Action::Burn(b) => b.serialize(serializer),
            Action::Collect(c) => c.serialize(serializer),
            Action::Liquidation(c) => c.serialize(serializer),
            Action::SelfDestruct(sd) => sd.serialize(serializer),
            Action::EthTransfer(et) => et.serialize(serializer),
            Action::Unclassified(trace) => (trace).serialize(serializer),
            action => format!("{:?}", action).serialize(serializer),
            //action => unreachable!("no action serialization for {action:?}"),
        }
    }
}

impl Action {
    pub fn get_msg_value_not_eth_transfer(&self) -> Option<NormalizedEthTransfer> {
        let res =
            match self {
                Self::Swap(s) => (!s.msg_value.is_zero()).then(|| NormalizedEthTransfer {
                    value: s.msg_value,
                    to: s.pool,
                    from: s.from,
                    ..Default::default()
                }),
                Self::SwapWithFee(s) => (!s.msg_value.is_zero()).then(|| NormalizedEthTransfer {
                    value: s.msg_value,
                    to: s.pool,
                    from: s.from,
                    ..Default::default()
                }),

                Self::FlashLoan(f) => (!f.msg_value.is_zero()).then(|| NormalizedEthTransfer {
                    value: f.msg_value,
                    to: f.receiver_contract,
                    from: f.from,
                    ..Default::default()
                }),
                Self::Batch(b) => (!b.msg_value.is_zero()).then(|| NormalizedEthTransfer {
                    value: b.msg_value,
                    to: b.settlement_contract,
                    from: b.solver,
                    ..Default::default()
                }),
                Self::Liquidation(t) => (!t.msg_value.is_zero()).then(|| NormalizedEthTransfer {
                    value: t.msg_value,
                    to: t.pool,
                    from: t.liquidator,
                    ..Default::default()
                }),
                Self::Unclassified(u) => (!u.get_msg_value().is_zero() && !u.is_delegate_call())
                    .then(|| NormalizedEthTransfer {
                        value: u.get_msg_value(),
                        to: u.get_to_address(),
                        from: u.get_from_addr(),
                        ..Default::default()
                    }),
                Self::Aggregator(a) => (!a.msg_value.is_zero()).then(|| NormalizedEthTransfer {
                    value: a.msg_value,
                    to: a.to,
                    from: a.from,
                    ..Default::default()
                }),
                Self::Mint(_) => None,
                Self::Burn(_) => None,
                Self::Transfer(_) => None,
                Self::Collect(_) => None,
                Self::SelfDestruct(_) => None,
                Self::EthTransfer(_) => None,
                Self::NewPool(_) => None,
                Self::PoolConfigUpdate(_) => None,
                Self::Revert => None,
            };
        if res.is_some() {
            tracing::debug!(?res, ?self, "created eth transfer for internal accounting");
        }
        res
    }

    pub fn force_liquidation(self) -> NormalizedLiquidation {
        match self {
            Action::Liquidation(l) => l,
            _ => unreachable!("not liquidation"),
        }
    }

    fn try_get_trace_index(&self) -> Option<u64> {
        Some(match self {
            Self::Swap(s) => s.trace_index,
            Self::SwapWithFee(s) => s.trace_index,
            Self::FlashLoan(f) => f.trace_index,
            Self::Batch(b) => b.trace_index,
            Self::Mint(m) => m.trace_index,
            Self::Burn(b) => b.trace_index,
            Self::Transfer(t) => t.trace_index,
            Self::Liquidation(t) => t.trace_index,
            Self::Collect(c) => c.trace_index,
            Self::SelfDestruct(c) => c.trace_index,
            Self::EthTransfer(e) => e.trace_index,
            Self::Unclassified(u) => u.trace_idx,
            Self::NewPool(p) => p.trace_index,
            Self::PoolConfigUpdate(p) => p.trace_index,
            Self::Aggregator(a) => a.trace_index,
            Self::Revert => return None,
        })
    }

    pub fn force_swap(self) -> NormalizedSwap {
        match self {
            Action::Swap(s) => s,
            Action::SwapWithFee(s) => s.swap,
            _ => unreachable!("not swap"),
        }
    }

    pub fn force_transfer(self) -> NormalizedTransfer {
        let Action::Transfer(transfer) = self else { unreachable!("not transfer") };
        transfer
    }

    pub fn force_transfer_mut(&mut self) -> &mut NormalizedTransfer {
        let Action::Transfer(transfer) = self else { unreachable!("not transfer") };
        transfer
    }

    pub fn force_swap_ref(&self) -> &NormalizedSwap {
        match self {
            Action::Swap(s) => s,
            Action::SwapWithFee(s) => s,
            _ => unreachable!("not swap"),
        }
    }

    pub fn force_swap_mut(&mut self) -> &mut NormalizedSwap {
        match self {
            Action::Swap(s) => s,
            Action::SwapWithFee(s) => s,
            _ => unreachable!("not swap"),
        }
    }

    pub fn get_logs(&self) -> Vec<Log> {
        match self {
            Self::Unclassified(a) => a.logs.clone(),
            _ => vec![],
        }
    }

    pub fn get_calldata(&self) -> Option<Bytes> {
        if let Action::Unclassified(u) = &self {
            if let TraceAction::Call(call) = &u.trace.action {
                return Some(call.input.clone())
            }
        }

        None
    }

    pub fn get_to_address(&self) -> Address {
        match self {
            Action::Swap(s) => s.pool,
            Action::SwapWithFee(s) => s.pool,
            Action::FlashLoan(f) => f.pool,
            Action::Aggregator(a) => a.to,
            Action::Batch(b) => b.settlement_contract,
            Action::Mint(m) => m.pool,
            Action::Burn(b) => b.pool,
            Action::Transfer(t) => t.to,
            Action::Collect(c) => c.pool,
            Action::Liquidation(c) => c.pool,
            Action::SelfDestruct(c) => c.get_refund_address(),
            Action::Unclassified(t) => match &t.trace.action {
                reth_rpc_types::trace::parity::Action::Call(c) => c.to,
                reth_rpc_types::trace::parity::Action::Create(_) => Address::ZERO,
                reth_rpc_types::trace::parity::Action::Reward(_) => Address::ZERO,
                reth_rpc_types::trace::parity::Action::Selfdestruct(s) => s.address,
            },
            Action::EthTransfer(t) => t.to,
            Action::NewPool(p) => p.pool_address,
            Action::PoolConfigUpdate(p) => p.pool_address,
            Action::Revert => Address::ZERO,
        }
    }

    pub fn get_from_address(&self) -> Address {
        match self {
            Action::Swap(s) => s.from,
            Action::SwapWithFee(s) => s.from,
            Action::FlashLoan(f) => f.from,
            Action::Aggregator(a) => a.from,
            Action::Batch(b) => b.solver,
            Action::Mint(m) => m.from,
            Action::Burn(b) => b.from,
            Action::Transfer(t) => t.from,
            Action::Collect(c) => c.from,
            Action::Liquidation(c) => c.liquidator,
            Action::SelfDestruct(c) => c.get_address(),
            Action::Unclassified(t) => match &t.trace.action {
                reth_rpc_types::trace::parity::Action::Call(c) => c.to,
                reth_rpc_types::trace::parity::Action::Create(_) => Address::ZERO,
                reth_rpc_types::trace::parity::Action::Reward(_) => Address::ZERO,
                reth_rpc_types::trace::parity::Action::Selfdestruct(s) => s.address,
            },
            Action::EthTransfer(t) => t.from,
            Action::Revert => unreachable!(),
            Action::NewPool(_) => Address::ZERO,
            Action::PoolConfigUpdate(_) => Address::ZERO,
        }
    }

    pub const fn is_nested_action(&self) -> bool {
        matches!(self, Action::FlashLoan(_))
            || matches!(self, Action::Batch(_))
            || matches!(self, Action::Aggregator(_))
    }

    pub const fn is_swap(&self) -> bool {
        matches!(self, Action::Swap(_)) || matches!(self, Action::SwapWithFee(_))
    }

    pub const fn is_swap_no_fee(&self) -> bool {
        matches!(self, Action::Swap(_))
    }

    pub const fn is_swap_with_fee(&self) -> bool {
        matches!(self, Action::SwapWithFee(_))
    }

    pub const fn is_flash_loan(&self) -> bool {
        matches!(self, Action::FlashLoan(_))
    }

    pub const fn is_aggregator(&self) -> bool {
        matches!(self, Action::Aggregator(_))
    }

    pub const fn is_liquidation(&self) -> bool {
        matches!(self, Action::Liquidation(_))
    }

    pub const fn is_batch(&self) -> bool {
        matches!(self, Action::Batch(_))
    }

    pub const fn is_burn(&self) -> bool {
        matches!(self, Action::Burn(_))
    }

    pub const fn is_revert(&self) -> bool {
        matches!(self, Action::Revert)
    }

    pub const fn is_mint(&self) -> bool {
        matches!(self, Action::Mint(_))
    }

    pub const fn is_transfer(&self) -> bool {
        matches!(self, Action::Transfer(_))
    }

    pub const fn is_collect(&self) -> bool {
        matches!(self, Action::Collect(_))
    }

    pub const fn is_self_destruct(&self) -> bool {
        matches!(self, Action::SelfDestruct(_))
    }

    pub const fn is_new_pool(&self) -> bool {
        matches!(self, Action::NewPool(_))
    }

    pub const fn is_pool_config_update(&self) -> bool {
        matches!(self, Action::PoolConfigUpdate(_))
    }

    pub const fn is_unclassified(&self) -> bool {
        matches!(self, Action::Unclassified(_))
    }

    pub const fn get_protocol(&self) -> Protocol {
        match self {
            Action::Swap(s) => s.protocol,
            Action::SwapWithFee(s) => s.swap.protocol,
            Action::FlashLoan(f) => f.protocol,
            Action::Batch(b) => b.protocol,
            Action::Mint(m) => m.protocol,
            Action::Burn(b) => b.protocol,
            Action::Collect(c) => c.protocol,
            Action::Liquidation(c) => c.protocol,
            Action::NewPool(p) => p.protocol,
            Action::PoolConfigUpdate(p) => p.protocol,
            Action::Aggregator(a) => a.protocol,
            _ => Protocol::Unknown,
        }
    }

    pub const fn is_eth_transfer(&self) -> bool {
        matches!(self, Action::EthTransfer(_))
    }

    pub fn is_static_call(&self) -> bool {
        if let Self::Unclassified(u) = &self {
            return u.is_static_call()
        }
        false
    }
}

macro_rules! extra_impls {
    ($(($action_name:ident, $ret:ident)),*) => {
        paste::paste!(

            impl Action {
                $(
                    pub fn [<try _$action_name:snake _ref>](&self) -> Option<&$ret> {
                        if let Action::$action_name(action) = self {
                            Some(action)
                        } else {
                            None
                        }
                    }

                    pub fn [<try _$action_name:snake _mut>](&mut self) -> Option<&mut $ret> {
                        if let Action::$action_name(action) = self {
                            Some(action)
                        } else {
                            None
                        }
                    }

                    pub fn [<try _$action_name:snake>](self) -> Option<$ret> {
                        if let Action::$action_name(action) = self {
                            Some(action)
                        } else {
                            None
                        }
                    }

                    pub fn [<try _$action_name:snake _dedup>]()
                        -> Box<dyn Fn(Action) -> Option<$ret>> {
                        Box::new(Action::[<try _$action_name:snake>])
                                as Box<dyn Fn(Action) -> Option<$ret>>
                    }
                )*
            }

            $(
                impl From<$ret> for Action {
                    fn from(value: $ret) -> Action {
                        Action::$action_name(value)
                    }
                }
            )*
        );

    };
}

extra_impls!(
    (Collect, NormalizedCollect),
    (Mint, NormalizedMint),
    (Burn, NormalizedBurn),
    (Swap, NormalizedSwap),
    (SwapWithFee, NormalizedSwapWithFee),
    (Transfer, NormalizedTransfer),
    (EthTransfer, NormalizedEthTransfer),
    (Liquidation, NormalizedLiquidation),
    (FlashLoan, NormalizedFlashLoan),
    (Aggregator, NormalizedAggregator),
    (Batch, NormalizedBatch),
    (NewPool, NormalizedNewPool)
);

/// Custom impl for itering over swaps and swap with fee
impl Action {
    /// Merges swap and swap with fee
    pub fn try_swaps_merged_ref(&self) -> Option<&NormalizedSwap> {
        match self {
            Action::Swap(action) => Some(action),
            Action::SwapWithFee(f) => Some(f),
            _ => None,
        }
    }

    /// Merges swap and swap with fee
    pub fn try_swaps_merged_mut(&mut self) -> Option<&mut NormalizedSwap> {
        match self {
            Action::Swap(action) => Some(action),
            Action::SwapWithFee(f) => Some(f),
            _ => None,
        }
    }

    /// Merges swap and swap with fee
    pub fn try_swaps_merged(self) -> Option<NormalizedSwap> {
        match self {
            Action::Swap(action) => Some(action),
            Action::SwapWithFee(f) => Some(f.swap),
            _ => None,
        }
    }

    /// Merges swap and swap with fee
    pub fn try_swaps_merged_dedup() -> Box<dyn Fn(Action) -> Option<NormalizedSwap>> {
        Box::new(Action::try_swaps_merged) as Box<dyn Fn(Action) -> Option<NormalizedSwap>>
    }
}

impl TokenAccounting for Action {
    fn apply_token_deltas(&self, delta_map: &mut AddressDeltas) {
        match self {
            Action::Swap(swap) => swap.apply_token_deltas(delta_map),
            Action::Transfer(transfer) => transfer.apply_token_deltas(delta_map),
            Action::FlashLoan(flash_loan) => flash_loan.apply_token_deltas(delta_map),
            Action::Aggregator(aggregator) => aggregator.apply_token_deltas(delta_map),
            Action::Liquidation(liquidation) => liquidation.apply_token_deltas(delta_map),
            Action::Batch(batch) => batch.apply_token_deltas(delta_map),
            Action::Burn(burn) => burn.apply_token_deltas(delta_map),
            Action::Mint(mint) => mint.apply_token_deltas(delta_map),
            Action::SwapWithFee(swap_with_fee) => swap_with_fee.swap.apply_token_deltas(delta_map),
            Action::Collect(collect) => collect.apply_token_deltas(delta_map),
            Action::EthTransfer(eth_transfer) => eth_transfer.apply_token_deltas(delta_map),
            Action::Unclassified(_) => (), /* Potentially no token deltas to apply, adjust as */
            // necessary
            Action::SelfDestruct(_self_destruct) => (),
            Action::NewPool(_new_pool) => (),
            Action::PoolConfigUpdate(_pool_update) => (),
            Action::Revert => (), // No token deltas to apply for a revert
        }
    }
}