Skip to content

Commit 9223ea4

Browse files
authored
Order -> Arc<Order> (#871)
## 📝 Summary To avoid expensive clones, replaced Order with Arc<Order> in almost all the code. Notice that the Arc also enforces immutability, which is something good for the Orders. ## ✅ I have completed the following steps: * [X] Run `make lint` * [X] Run `make test` * [ ] Added tests (if applicable)
1 parent 7302972 commit 9223ea4

37 files changed

+167
-152
lines changed

crates/rbuilder-operator/src/clickhouse.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,7 @@ impl BidObserver for BuiltBlocksWriter {
337337
let mut used_bundle_hashes = Vec::new();
338338
let mut used_bundle_uuids = Vec::new();
339339
for res in &built_block_trace.included_orders {
340-
if let Order::Bundle(bundle) = &res.order {
340+
if let Order::Bundle(bundle) = res.order.as_ref() {
341341
used_bundle_hashes
342342
.push(bundle.external_hash.unwrap_or(bundle.hash).to_string());
343343
used_bundle_uuids.push(bundle.uuid.to_string());

crates/rbuilder-primitives/src/lib.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1011,13 +1011,25 @@ impl SimValue {
10111011
/// Order simulated (usually on top of block) + SimValue
10121012
#[derive(Debug, Clone, PartialEq, Eq)]
10131013
pub struct SimulatedOrder {
1014-
pub order: Order,
1014+
pub order: Arc<Order>,
10151015
pub sim_value: SimValue,
10161016
/// Info about read/write slots during the simulation to help figure out what the Order is doing.
10171017
pub used_state_trace: Option<UsedStateTrace>,
10181018
}
10191019

10201020
impl SimulatedOrder {
1021+
pub fn new(
1022+
order: Arc<Order>,
1023+
sim_value: SimValue,
1024+
used_state_trace: Option<UsedStateTrace>,
1025+
) -> Self {
1026+
Self {
1027+
order,
1028+
sim_value,
1029+
used_state_trace,
1030+
}
1031+
}
1032+
10211033
pub fn id(&self) -> OrderId {
10221034
self.order.id()
10231035
}

crates/rbuilder/src/backtest/build_block/backtest_build_block.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ fn print_orders_with_tx_hash(
219219
.iter()
220220
.map(|order_with_timestamp| &order_with_timestamp.order)
221221
.filter(|order| order.list_txs().iter().any(|(tx, _)| tx.hash() == tx_hash))
222-
.for_each(print_order);
222+
.for_each(|order| print_order(order));
223223
println!("\nSIM ORDERS:");
224224
sim_orders
225225
.iter()
@@ -241,7 +241,7 @@ fn print_order_execution_result(order_result: &ExecutionResult) {
241241
order_result.space_used.gas,
242242
format_ether(order_result.coinbase_profit),
243243
);
244-
if let Order::Bundle(_) = order_result.order {
244+
if let Order::Bundle(_) = order_result.order.as_ref() {
245245
for tx in order_result.tx_infos.iter().map(|info| &info.tx) {
246246
println!(" ↳ {:?}", tx.hash());
247247
}

crates/rbuilder/src/backtest/build_block/synthetic_orders.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use rbuilder_primitives::{
55
Bundle, MempoolTx, Metadata, Order, TransactionSignedEcRecoveredWithBlobs, LAST_BUNDLE_VERSION,
66
};
77
use reth_provider::test_utils::MockNodeTypesWithDB;
8+
use std::sync::Arc;
89
use uuid::Uuid;
910

1011
use super::backtest_build_block::{run_backtest_build_block, BuildBlockCfg, OrdersSource};
@@ -75,7 +76,7 @@ impl<ConfigType: LiveBuilderConfig> SyntheticOrdersSource<ConfigType> {
7576
)));
7677
orders.push(OrdersWithTimestamp {
7778
timestamp_ms: 0,
78-
order,
79+
order: Arc::new(order),
7980
});
8081
}
8182

@@ -106,7 +107,7 @@ impl<ConfigType: LiveBuilderConfig> SyntheticOrdersSource<ConfigType> {
106107
bundle.hash_slow();
107108
orders.push(OrdersWithTimestamp {
108109
timestamp_ms: 0,
109-
order: Order::Bundle(bundle),
110+
order: Arc::new(Order::Bundle(bundle)),
110111
});
111112
}
112113

crates/rbuilder/src/backtest/execute.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use crate::{
1010
};
1111
use alloy_eips::BlockNumHash;
1212
use alloy_primitives::U256;
13-
use rbuilder_primitives::{OrderId, SimulatedOrder};
13+
use rbuilder_primitives::{Order, OrderId, SimulatedOrder};
1414
use reth_chainspec::ChainSpec;
1515
use serde::{Deserialize, Serialize};
1616
use std::sync::Arc;
@@ -95,10 +95,10 @@ pub fn backtest_prepare_orders_from_building_context<P>(
9595
where
9696
P: StateProviderFactory + Clone + 'static,
9797
{
98-
let orders = available_orders
98+
let orders: Vec<Arc<Order>> = available_orders
9999
.iter()
100-
.map(|order| order.order.clone())
101-
.collect::<Vec<_>>();
100+
.map(|order| Arc::clone(&order.order))
101+
.collect();
102102
for order in &orders {
103103
ctx.mempool_tx_detector.add_tx(order);
104104
}

crates/rbuilder/src/backtest/fetch/data_source.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use crate::{
77
};
88
use alloy_primitives::B256;
99
use async_trait::async_trait;
10+
use std::sync::Arc;
1011

1112
#[derive(Debug, Clone)]
1213
pub struct DatasourceData {
@@ -45,7 +46,7 @@ pub async fn get_full_slot_data_from_data(
4546
.into_iter()
4647
.map(|o| ReplaceableOrderPoolCommandWithTimestamp {
4748
timestamp_ms: o.timestamp_ms,
48-
command: ReplaceableOrderPoolCommand::Order(o.order),
49+
command: ReplaceableOrderPoolCommand::Order(Arc::clone(&o.order)),
4950
})
5051
.collect(),
5152
built_block_data: data.built_block_data,

crates/rbuilder/src/backtest/fetch/mempool.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use rbuilder_primitives::{
1414
Order,
1515
};
1616
use sqlx::types::chrono::DateTime;
17+
use std::sync::Arc;
1718
use std::{
1819
fs::create_dir_all,
1920
path::{Path, PathBuf},
@@ -52,7 +53,7 @@ pub fn get_mempool_transactions(
5253

5354
Some(OrdersWithTimestamp {
5455
timestamp_ms,
55-
order,
56+
order: Arc::new(order),
5657
})
5758
})
5859
.collect())

crates/rbuilder/src/backtest/full_slot_block_data.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ impl From<OrdersWithTimestamp> for ReplaceableOrderPoolCommandWithTimestamp {
2929
fn from(order: OrdersWithTimestamp) -> Self {
3030
ReplaceableOrderPoolCommandWithTimestamp {
3131
timestamp_ms: order.timestamp_ms,
32-
command: ReplaceableOrderPoolCommand::Order(order.order),
32+
command: ReplaceableOrderPoolCommand::Order(Arc::clone(&order.order)),
3333
}
3434
}
3535
}
@@ -116,7 +116,7 @@ impl FullSlotBlockData {
116116
if included_orders_ids.remove(&order.id()) {
117117
Some(OrdersWithTimestamp {
118118
timestamp_ms: command_ts.timestamp_ms,
119-
order: order.clone(),
119+
order: Arc::clone(order),
120120
})
121121
} else {
122122
None
@@ -167,7 +167,7 @@ impl FullSlotBlockData {
167167
match command_ts.command {
168168
ReplaceableOrderPoolCommand::Order(order) => {
169169
order_id_to_timestamp.insert(order.id(), command_ts.timestamp_ms);
170-
order_manager.insert_order(order);
170+
order_manager.insert_order(Arc::clone(&order));
171171
}
172172
ReplaceableOrderPoolCommand::CancelBundle(replacement_data) => {
173173
order_manager.remove_bundle(replacement_data);
@@ -181,7 +181,7 @@ impl FullSlotBlockData {
181181
.iter()
182182
.map(|o| OrdersWithTimestamp {
183183
timestamp_ms: *order_id_to_timestamp.get(&o.id()).unwrap(),
184-
order: o.clone(),
184+
order: Arc::clone(o),
185185
})
186186
.collect();
187187

crates/rbuilder/src/backtest/mod.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ mod store;
1212
use ahash::HashMap;
1313
pub use backtest_build_range::run_backtest_build_range;
1414
use std::collections::HashSet;
15+
use std::sync::Arc;
1516

1617
use crate::{mev_boost::BuilderBlockReceived, utils::offset_datetime_to_timestamp_ms};
1718
use alloy_consensus::Transaction as TransactionTrait;
@@ -38,15 +39,15 @@ impl From<OrdersWithTimestamp> for RawOrdersWithTimestamp {
3839
fn from(orders: OrdersWithTimestamp) -> Self {
3940
Self {
4041
timestamp_ms: orders.timestamp_ms,
41-
order: orders.order.into(),
42+
order: (*orders.order).clone().into(),
4243
}
4344
}
4445
}
4546

4647
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4748
pub struct OrdersWithTimestamp {
4849
pub timestamp_ms: u64,
49-
pub order: Order,
50+
pub order: Arc<Order>,
5051
}
5152

5253
/// Historic data for a block.
@@ -171,7 +172,7 @@ impl BlockData {
171172
let mempool_txs = self
172173
.available_orders
173174
.iter()
174-
.filter_map(|o| match &o.order {
175+
.filter_map(|o| match o.order.as_ref() {
175176
Order::Tx(tx) => Some(tx.tx_with_blobs.hash()),
176177
_ => None,
177178
})

crates/rbuilder/src/backtest/redistribute/mod.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ where
312312
let mut txs = 0;
313313
let mut bundles = 0;
314314
for ts_order in &block_data.available_orders {
315-
match &ts_order.order {
315+
match ts_order.order.as_ref() {
316316
Order::Bundle(_) => bundles += 1,
317317
Order::Tx(_) => txs += 1,
318318
}
@@ -449,7 +449,7 @@ struct AvailableOrders {
449449
included_orders_by_address: Vec<(Address, Vec<OrderId>)>,
450450
all_orders_by_address: HashMap<Address, Vec<OrderId>>,
451451
orders_id_to_address: HashMap<OrderId, Address>,
452-
all_orders_by_id: HashMap<OrderId, Order>,
452+
all_orders_by_id: HashMap<OrderId, Arc<Order>>,
453453
bundle_hash_by_id: HashMap<OrderId, B256>,
454454
order_sender_by_id: HashMap<OrderId, Address>,
455455
}
@@ -550,7 +550,7 @@ fn split_orders_by_identities(
550550

551551
for order in &block_data.available_orders {
552552
let id = order.order.id();
553-
if let Order::Bundle(bundle) = &order.order {
553+
if let Order::Bundle(bundle) = order.order.as_ref() {
554554
bundle_hash_by_id.insert(id, bundle.external_hash.unwrap_or(bundle.hash));
555555
};
556556
order_sender_by_id.insert(id, order_sender(&order.order));
@@ -603,7 +603,7 @@ fn split_orders_by_identities(
603603
all_orders_by_id: block_data
604604
.available_orders
605605
.iter()
606-
.map(|order| (order.order.id(), order.order.clone()))
606+
.map(|order| (order.order.id(), Arc::clone(&order.order)))
607607
.collect(),
608608
bundle_hash_by_id,
609609
order_sender_by_id,

0 commit comments

Comments
 (0)