forked from flashbots/rblib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexec.rs
More file actions
812 lines (714 loc) · 24.8 KB
/
Copy pathexec.rs
File metadata and controls
812 lines (714 loc) · 24.8 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
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
use {
crate::{alloy, prelude::*, reth},
alloy::{
consensus::{crypto::RecoveryError, transaction::TxHashRef},
evm::revm::context::result::ExecutionResult as RevmExecutionResult,
primitives::{B256, TxHash},
},
reth::{
errors::ProviderError,
ethereum::primitives::SignedTransaction,
evm::{
ConfigureEvm,
Evm,
revm::{
DatabaseCommit,
DatabaseRef,
context::result::ExecResultAndState,
},
},
primitives::Recovered,
revm::{
State,
db::{
BundleState,
WrapDatabaseRef,
states::bundle_state::BundleRetention,
},
},
transaction_pool::PoolTransaction,
},
std::fmt::Debug,
};
#[derive(Debug, thiserror::Error)]
pub enum ExecutionError<P: Platform> {
#[error("Invalid signature: {0}")]
InvalidSignature(#[from] RecoveryError),
#[error("Invalid transaction: {0}")]
InvalidTransaction(types::EvmError<P, ProviderError>),
#[error("Invalid transaction {0} cannot be dropped from bundle: {1}")]
InvalidBundleTransaction(TxHash, types::EvmError<P, ProviderError>),
#[error("Transaction {0} in the bundle is not allowed to revert.")]
BundleTransactionReverted(TxHash, Option<types::EvmHaltReason<P>>),
#[error("Invalid bundle post-execution state: {0}")]
InvalidBundlePostExecutionState(types::BundlePostExecutionError<P>),
#[error("Bundle is not eligible for execution in this block")]
IneligibleBundle(Eligibility),
}
/// Describes an atomic unit of execution that can be used to create a state
/// transition checkpoint.
#[derive(Debug, Clone, PartialEq)]
pub enum Executable<P: Platform> {
// Individual transaction
Transaction(Recovered<types::Transaction<P>>),
// A bundle of transactions with context and behaviors.
Bundle(types::Bundle<P>),
}
impl<P: Platform> Executable<P> {
/// Executes this executable as a single unit of state transition and returns
/// the outcome of the execution along with all state changes. If the
/// executable is invalid, no execution result will be produced.
///
/// For details on what makes an executable invalid see the
/// [`Self::execute_transaction`] and [`Self::execute_bundle`] methods.
pub fn execute<DB>(
self,
block: &BlockContext<P>,
db: &DB,
ctx: &P::CheckpointContext,
) -> Result<ExecutionResult<P>, ExecutionError<P>>
where
DB: DatabaseRef<Error = ProviderError> + Debug,
{
match self {
Self::Bundle(bundle) => Self::execute_bundle(bundle, block, db, ctx),
Self::Transaction(tx) => Self::execute_transaction(tx, block, db, ctx)
.map_err(ExecutionError::InvalidTransaction),
}
}
/// Executes a single transaction and returns the outcome of the execution
/// along with all state changes. This output is used to create a state
/// checkpoint.
///
/// Notes:
/// - Transactions that are invalid and cause EVM failures will not produce an
/// execution result.
///
/// - Transactions that fail gracefully (revert or halt) will produce an
/// execution result and state changes. It is up to higher levels of the
/// system to decide what to do with such transactions, e.g., whether to
/// remove them from the payload or not (see
/// [`RemoveRevertedTransactions`]).
///
/// [`RemoveRevertedTransactions`]: crate::steps::RemoveRevertedTransactions
pub fn execute_transaction<DB>(
tx: Recovered<types::Transaction<P>>,
block: &BlockContext<P>,
db: &DB,
_ctx: &P::CheckpointContext,
) -> Result<ExecutionResult<P>, types::EvmError<P, ProviderError>>
where
DB: DatabaseRef<Error = ProviderError> + Debug,
{
let mut state = State::builder()
.with_database(WrapDatabaseRef(db))
.with_bundle_update()
.build();
let result = block
.evm_config()
.evm_with_env(&mut state, block.evm_env().clone())
.transact_commit(&tx)?;
state.merge_transitions(BundleRetention::Reverts);
Ok(ExecutionResult {
source: Executable::Transaction(tx),
results: vec![result],
state: state.take_bundle(),
})
}
/// Executes a bundle of transactions and returns the execution outcome of all
/// transactions in the bundle along with the aggregate of all state changes.
///
/// Notes:
/// - Bundles that are not eligible for execution in the current block are
/// considered invalid, and no execution result will be produced.
///
/// - All transactions in the bundle are executed in the order in which they
/// were defined in the bundle.
///
/// - Each transaction is executed on the state produced by the previous
/// transaction in the bundle.
///
/// - First transaction in the bundle is executed on the state of the
/// checkpoint that we are building on.
///
/// - Transactions that cause EVM errors will invalidate the bundle, and no
/// execution result will be produced (similar behavior to invalid loose
/// txs). Bundle transaction can be marked optional [`Bundle::is_optional`],
/// and invalid outcomes are handled differently:
/// - If the invalid transaction is optional, a new version of the bundle
/// will be created without the invalid transaction by removing it
/// through [`Bundle::without_transaction`].
/// - If removing the invalid optional transaction results in an empty
/// bundle, the bundle will be considered invalid and no execution
/// result will be produced.
///
/// - Transactions that fail gracefully (revert or halt) and are not optional
/// will invalidate the bundle, and no execution result will be produced.
/// Bundle transaction can be marked as allowed to fail
/// [`Bundle::is_allowed_to_fail`], and failure outcomes are handled
/// differently:
/// - If the bundle allows the failing transaction to fail, the bundle
/// will still be considered valid. The execution result will be
/// produced, including this failed transaction. State changes from the
/// failed transaction will be included in the aggregate state, e.g.,
/// gas used, nonces incremented, etc. Cleaning up transactions that are
/// allowed to fail and are optional from a bundle is beyond the scope
/// of this method. This is implemented by higher levels of the system,
/// such as the [`RemoveRevertedTransactions`] step in the pipelines
/// API.
/// - If the bundle does not allow this failed transaction to fail, but
/// the transaction is optional, then it will be removed from the
/// bundle. The bundle stays valid.
///
/// See truth table:
/// | success | `allowed_to_fail` | optional | Action |
/// | ------: | :---------------: | :------: | :------ |
/// | true | *don’t care* | *any* | include |
/// | false | true | *any* | include |
/// | false | false | true | discard |
/// | false | false | false | error |
///
/// - At the end of the bundle execution, the bundle implementation will have
/// a chance to validate any other platform-specific post-execution
/// requirements. For example, the bundle may require that the state after
/// the execution has a certain balance in some account, etc. If this check
/// fails, the bundle will be considered invalid, and no execution result
/// will be produced.
///
/// [`RemoveRevertedTransactions`]: crate::steps::RemoveRevertedTransactions
pub fn execute_bundle<DB>(
bundle: types::Bundle<P>,
block: &BlockContext<P>,
db: &DB,
checkpoint_context: &P::CheckpointContext,
) -> Result<ExecutionResult<P>, ExecutionError<P>>
where
DB: DatabaseRef<Error = ProviderError> + Debug,
{
let eligible = bundle.is_eligible(block, checkpoint_context);
if !eligible {
return Err(ExecutionError::IneligibleBundle(eligible));
}
let evm_env = block.evm_env();
let evm_config = block.evm_config();
let mut db = State::builder()
.with_database(WrapDatabaseRef(db))
.with_bundle_update()
.build();
let mut discarded = Vec::new();
let mut results = Vec::with_capacity(bundle.transactions().len());
for transaction in bundle.transactions_encoded() {
let tx_hash = *transaction.tx_hash();
let optional = bundle.is_optional(&tx_hash);
let allowed_to_fail = bundle.is_allowed_to_fail(&tx_hash);
let result = evm_config
.evm_with_env(&mut db, evm_env.clone())
.transact(&transaction);
match result {
// Valid transaction or allowed to fail: include it in the bundle
Ok(ExecResultAndState { result, state })
if result.is_success() || allowed_to_fail =>
{
results.push(result);
db.commit(state);
}
// Optional failing transaction, not allowed to fail
// or optional invalid transaction: discard it
Ok(_) | Err(_) if optional => {
discarded.push(tx_hash);
}
// Non-Optional failing transaction, not allowed to fail: invalidate the
// bundle
Ok(ExecResultAndState { result, state: _ }) => {
let halt_reason = match &result {
RevmExecutionResult::Halt { reason, .. } => Some(reason.clone()),
_ => None,
};
return Err(ExecutionError::BundleTransactionReverted(
tx_hash,
halt_reason,
));
}
// Non-Optional invalid transaction: invalidate the bundle
Err(err) => {
return Err(ExecutionError::InvalidBundleTransaction(tx_hash, err));
}
}
}
// reduce the bundle by removing discarded transactions
let bundle = discarded
.into_iter()
.fold(bundle, |b, tx| b.without_transaction(tx));
// extract all the state changes that were made by executing
// transactions in this bundle.
db.merge_transitions(BundleRetention::Reverts);
let state = db.take_bundle();
// run the optional post-execution validation of the bundle.
bundle
.validate_post_execution(&state, block)
.map_err(ExecutionError::InvalidBundlePostExecutionState)?;
Ok(ExecutionResult {
source: Executable::Bundle(bundle),
results,
state,
})
}
}
impl<P: Platform> Executable<P> {
/// Returns all transactions that make up this executable.
pub fn transactions(&self) -> &[Recovered<types::Transaction<P>>] {
match self {
Self::Transaction(tx) => std::slice::from_ref(tx),
Self::Bundle(bundle) => bundle.transactions(),
}
}
pub const fn is_transaction(&self) -> bool {
matches!(self, Self::Transaction(_))
}
pub const fn is_bundle(&self) -> bool {
matches!(self, Self::Bundle(_))
}
pub fn hash(&self) -> B256 {
match self {
Self::Transaction(tx) => *tx.tx_hash(),
Self::Bundle(bundle) => bundle.hash(),
}
}
}
/// Convenience trait that allows all types that can be executed to be used as a
/// parameter to the `Checkpoint::apply` method.
pub trait IntoExecutable<P: Platform, S = ()> {
fn try_into_executable(self) -> Result<Executable<P>, RecoveryError>;
}
/// Transactions can be converted into an executable as long as they have a
/// valid recoverable signature.
impl<P: Platform> IntoExecutable<P, Variant<0>> for types::Transaction<P> {
fn try_into_executable(self) -> Result<Executable<P>, RecoveryError> {
SignedTransaction::try_into_recovered(self)
.map(Executable::Transaction)
.map_err(|_| RecoveryError::new())
}
}
/// Transactions from the transaction pool can be converted infallibly into
/// an executable because the transaction pool discards transactions
/// that have invalid signatures.
impl<P: Platform> IntoExecutable<P, Variant<1>>
for types::PooledTransaction<P>
{
fn try_into_executable(self) -> Result<Executable<P>, RecoveryError> {
Ok(Executable::Transaction(self.into_consensus()))
}
}
/// Signature-recovered individual transactions are always infallibly
/// convertible into an executable.
impl<P: Platform> IntoExecutable<P, Variant<2>>
for Recovered<types::Transaction<P>>
{
fn try_into_executable(self) -> Result<Executable<P>, RecoveryError> {
Ok(Executable::Transaction(self))
}
}
/// Bundles are also convertible into an executable infallibly.
/// Signature recovery is part of the bundle assembly logic.
impl<P: Platform> IntoExecutable<P, Variant<3>> for types::Bundle<P> {
fn try_into_executable(self) -> Result<Executable<P>, RecoveryError> {
Ok(Executable::Bundle(self))
}
}
/// Already converted executables
impl<P: Platform> IntoExecutable<P, Variant<4>> for Executable<P> {
fn try_into_executable(self) -> Result<Executable<P>, RecoveryError> {
Ok(self)
}
}
/// Another checkpoint content
impl<P: Platform> IntoExecutable<P, Variant<5>> for Checkpoint<P> {
fn try_into_executable(self) -> Result<Executable<P>, RecoveryError> {
(&self).try_into_executable()
}
}
impl<P: Platform> IntoExecutable<P, Variant<6>> for &Checkpoint<P> {
fn try_into_executable(self) -> Result<Executable<P>, RecoveryError> {
if let Some(tx) = self.as_transaction() {
Ok(Executable::Transaction(tx.clone()))
} else if let Some(bundle) = self.as_bundle() {
Ok(Executable::Bundle(bundle.clone()))
} else {
Err(RecoveryError::new())
}
}
}
/// From EIP-2718 transaction envelope to executable.
impl<P: PlatformWithRpcTypes> IntoExecutable<P, Variant<7>>
for types::TxEnvelope<P>
{
fn try_into_executable(self) -> Result<Executable<P>, RecoveryError> {
let tx: types::Transaction<P> = self.into();
tx.try_into_executable()
}
}
/// This trait represents the overall result of executing a transaction or a
/// bundle of transactions.
///
/// Types implementing this trait provide access to the individual results of
/// transaction executions that make up this overall result.
#[derive(Debug, Clone, PartialEq)]
pub struct ExecutionResult<P: Platform> {
/// The executable used to produce this result.
pub(crate) source: Executable<P>,
/// For transactions this is guaranteed to be a single-element vector,
/// for bundles this is guaranteed to be a vector of results for each
/// transaction in the bundle.
pub(crate) results: Vec<types::TransactionExecutionResult<P>>,
/// The aggregated state executing all transactions from the source.
pub(crate) state: BundleState,
}
impl<P: Platform> ExecutionResult<P> {
/// Returns the executable used to produce this result.
pub const fn source(&self) -> &Executable<P> {
&self.source
}
/// Returns the aggregate state changes made by executing the transactions in
/// this execution unit.
pub const fn state(&self) -> &BundleState {
&self.state
}
/// Access to the individual transaction results that make up this execution
/// result.
///
/// For transactions, this will return a single-element slice containing the
/// transaction's execution result. For bundles, this will return a slice of
/// execution results for each transaction in the bundle.
pub const fn results(&self) -> &[types::TransactionExecutionResult<P>] {
self.results.as_slice()
}
/// Returns individual transactions executed as part of this execution unit.
pub fn transactions(&self) -> &[Recovered<types::Transaction<P>>] {
self.source().transactions()
}
/// Returns the cumulative gas used by the execution of this transaction or
/// bundle.
pub fn gas_used(&self) -> u64 {
self.results.iter().map(|r| r.gas_used()).sum()
}
}
#[cfg(test)]
mod tests {
use {
super::*,
crate::test_utils::{
BlockContextMocked,
TestablePlatform,
test_bundle,
test_tx,
test_txs,
},
rblib_tests_macros::rblib_test,
};
#[rblib_test(Ethereum, Optimism)]
fn test_executable_transaction_returns_single_transaction<
P: TestablePlatform,
>() {
let tx = test_tx::<P>(0, 0);
let executable = Executable::<P>::Transaction(tx.clone());
assert_eq!(executable.transactions().len(), 1);
assert_eq!(executable.transactions()[0], tx);
assert!(executable.is_transaction());
assert!(!executable.is_bundle());
}
#[rblib_test(Ethereum, Optimism)]
fn test_executable_bundle_returns_all_transactions<P>()
where
P: TestablePlatform<Bundle = FlashbotsBundle<P>>,
{
let (bundle, txs) = test_bundle::<P>(0, 0);
let executable = Executable::<P>::Bundle(bundle);
assert_eq!(executable.transactions().len(), txs.len());
assert_eq!(executable.transactions(), txs.as_slice());
assert!(!executable.is_transaction());
assert!(executable.is_bundle());
}
#[rblib_test(Ethereum, Optimism)]
fn test_execute_transaction_success<P>()
where
P: TestablePlatform,
BlockContext<P>: BlockContextMocked<P>,
{
let block = BlockContext::<P>::mocked();
let checkpoint = block.start();
let tx = test_tx::<P>(0, 0);
let result = Executable::execute_transaction(
tx.clone(),
&block,
&checkpoint,
checkpoint.context(),
);
let exec_result = result.unwrap();
assert_eq!(exec_result.results().len(), 1);
assert_eq!(exec_result.transactions().len(), 1);
assert_eq!(exec_result.transactions()[0], tx);
assert!(exec_result.results()[0].is_success());
}
#[rblib_test(Ethereum, Optimism)]
fn test_execute_transaction_produces_state_changes<P>()
where
P: TestablePlatform,
BlockContext<P>: BlockContextMocked<P>,
{
let block = BlockContext::<P>::mocked();
let checkpoint = block.start();
let tx = test_tx::<P>(0, 0);
let result = Executable::execute_transaction(
tx,
&block,
&checkpoint,
checkpoint.context(),
);
let exec_result = result.unwrap();
assert!(!exec_result.state().is_empty());
assert!(exec_result.gas_used() > 0);
}
#[rblib_test(Ethereum, Optimism)]
fn test_execute_via_execute_method<P>()
where
P: TestablePlatform,
BlockContext<P>: BlockContextMocked<P>,
{
let block = BlockContext::<P>::mocked();
let checkpoint = block.start();
let tx = test_tx::<P>(0, 0);
let executable = Executable::<P>::Transaction(tx);
let result = executable.execute(&block, &checkpoint, checkpoint.context());
assert_eq!(result.unwrap().results().len(), 1);
}
#[rblib_test(Ethereum, Optimism)]
fn test_execute_bundle_all_successful<P>()
where
P: TestablePlatform<Bundle = FlashbotsBundle<P>>,
BlockContext<P>: BlockContextMocked<P>,
{
let block = BlockContext::<P>::mocked();
let checkpoint = block.start();
let (bundle, txs) = test_bundle::<P>(0, 0);
let result = Executable::execute_bundle(
bundle,
&block,
&checkpoint,
checkpoint.context(),
);
let exec_result = result.unwrap();
assert_eq!(exec_result.results().len(), txs.len());
assert!(exec_result.results().iter().all(|r| r.is_success()));
assert_eq!(exec_result.transactions().len(), txs.len());
assert_eq!(exec_result.transactions(), txs.as_slice());
}
#[rblib_test(Ethereum, Optimism)]
fn test_execute_bundle_aggregates_gas<P>()
where
P: TestablePlatform<Bundle = FlashbotsBundle<P>>,
BlockContext<P>: BlockContextMocked<P>,
{
let block = BlockContext::<P>::mocked();
let checkpoint = block.start();
let (bundle, _) = test_bundle::<P>(0, 0);
let result = Executable::execute_bundle(
bundle,
&block,
&checkpoint,
checkpoint.context(),
);
let exec_result = result.unwrap();
let total_gas = exec_result.gas_used();
let sum_gas: u64 = exec_result.results().iter().map(|r| r.gas_used()).sum();
assert_eq!(total_gas, sum_gas);
assert!(total_gas > 0);
}
#[rblib_test(Ethereum, Optimism)]
fn test_execute_bundle_sequential_execution<P>()
where
P: TestablePlatform<Bundle = FlashbotsBundle<P>>,
BlockContext<P>: BlockContextMocked<P>,
{
// Each transaction in a bundle executes on the state from the previous
let block = BlockContext::<P>::mocked();
let checkpoint = block.start();
// Use the same account for all transactions to test sequential nonces
let txs = test_txs::<P>(0, 0, 3);
let (bundle, _) = test_bundle::<P>(0, 0);
let result = Executable::execute_bundle(
bundle,
&block,
&checkpoint,
checkpoint.context(),
);
let exec_result = result.unwrap();
assert_eq!(exec_result.results().len(), txs.len());
assert!(exec_result.results().iter().all(|r| r.is_success()));
}
#[rblib_test(Ethereum, Optimism)]
fn test_into_executable_from_recovered_transaction<P: TestablePlatform>() {
let tx = test_tx::<P>(0, 0);
let result: Result<Executable<P>, _> =
IntoExecutable::<P, Variant<2>>::try_into_executable(tx.clone());
let executable = result.unwrap();
assert!(executable.is_transaction());
assert_eq!(executable.transactions()[0], tx);
}
#[rblib_test(Ethereum, Optimism)]
fn test_into_executable_from_bundle<P>()
where
P: TestablePlatform<Bundle = FlashbotsBundle<P>>,
{
let (bundle, _) = test_bundle::<P>(0, 0);
let result: Result<Executable<P>, _> =
IntoExecutable::<P, Variant<3>>::try_into_executable(bundle);
assert!(result.unwrap().is_bundle());
}
#[rblib_test(Ethereum, Optimism)]
fn test_into_executable_from_executable<P: TestablePlatform>() {
let tx = test_tx::<P>(0, 0);
let executable = Executable::<P>::Transaction(tx);
let result: Result<Executable<P>, _> =
IntoExecutable::<P, Variant<4>>::try_into_executable(executable.clone());
assert_eq!(result.unwrap(), executable);
}
#[rblib_test(Ethereum, Optimism)]
fn test_into_executable_from_checkpoint<P>()
where
P: TestablePlatform<Bundle = FlashbotsBundle<P>>,
BlockContext<P>: BlockContextMocked<P>,
{
let block = BlockContext::<P>::mocked();
let checkpoint = block.start();
let tx = test_tx::<P>(0, 0);
let checkpoint_with_tx = checkpoint.apply(tx.clone()).unwrap();
let result: Result<Executable<P>, _> =
IntoExecutable::<P, Variant<5>>::try_into_executable(checkpoint_with_tx);
let executable = result.unwrap();
assert!(executable.is_transaction());
assert_eq!(executable.transactions()[0], tx);
}
#[rblib_test(Ethereum, Optimism)]
fn test_into_executable_from_checkpoint_ref<P>()
where
P: TestablePlatform<Bundle = FlashbotsBundle<P>>,
BlockContext<P>: BlockContextMocked<P>,
{
let block = BlockContext::<P>::mocked();
let checkpoint = block.start();
let tx = test_tx::<P>(0, 0);
let checkpoint_with_tx = checkpoint.apply(tx.clone()).unwrap();
let result: Result<Executable<P>, _> =
IntoExecutable::<P, Variant<6>>::try_into_executable(&checkpoint_with_tx);
let executable = result.unwrap();
assert!(executable.is_transaction());
assert_eq!(executable.transactions()[0], tx);
}
#[rblib_test(Ethereum, Optimism)]
fn test_into_executable_from_barrier_checkpoint_fails<P>()
where
P: TestablePlatform,
BlockContext<P>: BlockContextMocked<P>,
{
let block = BlockContext::<P>::mocked();
let checkpoint = block.start();
let barrier = checkpoint.barrier();
let result: Result<Executable<P>, _> =
IntoExecutable::<P, Variant<6>>::try_into_executable(&barrier);
assert!(result.is_err());
}
#[rblib_test(Ethereum, Optimism)]
fn test_execution_result_source<P>()
where
P: TestablePlatform,
BlockContext<P>: BlockContextMocked<P>,
{
let block = BlockContext::<P>::mocked();
let checkpoint = block.start();
let tx = test_tx::<P>(0, 0);
let executable = Executable::<P>::Transaction(tx.clone());
let result = executable
.execute(&block, &checkpoint, checkpoint.context())
.unwrap();
match result.source() {
Executable::Transaction(result_tx) => assert_eq!(*result_tx, tx),
Executable::Bundle(_) => panic!("Expected transaction source"),
}
}
#[rblib_test(Ethereum, Optimism)]
fn test_execution_result_transactions<P>()
where
P: TestablePlatform<Bundle = FlashbotsBundle<P>>,
BlockContext<P>: BlockContextMocked<P>,
{
let block = BlockContext::<P>::mocked();
let checkpoint = block.start();
let (bundle, txs) = test_bundle::<P>(0, 0);
let executable = Executable::<P>::Bundle(bundle);
let result = executable
.execute(&block, &checkpoint, checkpoint.context())
.unwrap();
assert_eq!(result.transactions(), txs.as_slice());
}
#[rblib_test(Ethereum, Optimism)]
fn test_executable_hash_transaction<P: TestablePlatform>() {
let tx = test_tx::<P>(0, 0);
let expected_hash = *tx.tx_hash();
let executable = Executable::<P>::Transaction(tx);
assert_eq!(executable.hash(), expected_hash);
}
#[rblib_test(Ethereum, Optimism)]
fn test_executable_hash_bundle<P>()
where
P: TestablePlatform<Bundle = FlashbotsBundle<P>>,
{
let (bundle, _) = test_bundle::<P>(0, 0);
let expected_hash = bundle.hash();
let executable = Executable::<P>::Bundle(bundle);
assert_eq!(executable.hash(), expected_hash);
}
#[rblib_test(Ethereum, Optimism)]
fn test_execution_error_invalid_signature_display<P: TestablePlatform>() {
let err = ExecutionError::<P>::InvalidSignature(RecoveryError::new());
let display = format!("{err}");
assert!(display.contains("Invalid signature"));
}
#[rblib_test(Ethereum, Optimism)]
fn test_execution_result_state_is_bundle_state<P>()
where
P: TestablePlatform,
BlockContext<P>: BlockContextMocked<P>,
{
let block = BlockContext::<P>::mocked();
let checkpoint = block.start();
let tx = test_tx::<P>(0, 0);
let result = Executable::execute_transaction(
tx,
&block,
&checkpoint,
checkpoint.context(),
)
.unwrap();
// State should be a BundleState with changes
assert!(!result.state().is_empty());
}
#[rblib_test(Ethereum, Optimism)]
fn test_execution_result_clone<P>()
where
P: TestablePlatform,
BlockContext<P>: BlockContextMocked<P>,
{
let block = BlockContext::<P>::mocked();
let checkpoint = block.start();
let tx = test_tx::<P>(0, 0);
let result = Executable::execute_transaction(
tx,
&block,
&checkpoint,
checkpoint.context(),
)
.unwrap();
let cloned = result.clone();
assert_eq!(result, cloned);
}
}