Skip to content

Commit 54b51a6

Browse files
committed
fix: calculate deadline after block env changes
- calculate deadline after block env changes instead of before, so that environments aren't off-by-one - take reference to the cache after block env changes, not before, so that transactions are as fresh as possible before starting simulation
1 parent ed1a956 commit 54b51a6

File tree

1 file changed

+51
-13
lines changed

1 file changed

+51
-13
lines changed

src/tasks/block/sim.rs

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,15 @@ use init4_bin_base::{
99
};
1010
use signet_sim::{BlockBuild, BuiltBlock, SimCache};
1111
use signet_types::constants::SignetSystemConstants;
12-
use std::time::{Duration, Instant};
12+
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
1313
use tokio::{
1414
sync::{
1515
mpsc::{self},
1616
watch,
1717
},
1818
task::JoinHandle,
1919
};
20+
use tracing::trace;
2021
use trevm::revm::{
2122
context::BlockEnv,
2223
database::{AlloyDB, WrapDatabaseAsync},
@@ -34,7 +35,6 @@ pub struct Simulator {
3435
pub config: BuilderConfig,
3536
/// A provider that cannot sign transactions, used for interacting with the rollup.
3637
pub ru_provider: RuProvider,
37-
3838
/// The block configuration environment on which to simulate
3939
pub block_env: watch::Receiver<Option<BlockEnv>>,
4040
}
@@ -55,6 +55,7 @@ impl Simulator {
5555
///
5656
/// - `config`: The configuration for the builder.
5757
/// - `ru_provider`: A provider for interacting with the rollup.
58+
/// - `block_env`: A receiver for the block environment to simulate against.
5859
///
5960
/// # Returns
6061
///
@@ -79,6 +80,7 @@ impl Simulator {
7980
/// - `constants`: The system constants for the rollup.
8081
/// - `sim_items`: The simulation cache containing transactions and bundles.
8182
/// - `finish_by`: The deadline by which the block must be built.
83+
/// - `block_env`: The block environment to simulate against.
8284
///
8385
/// # Returns
8486
///
@@ -88,22 +90,34 @@ impl Simulator {
8890
constants: SignetSystemConstants,
8991
sim_items: SimCache,
9092
finish_by: Instant,
91-
block: BlockEnv,
93+
block_env: BlockEnv,
9294
) -> eyre::Result<BuiltBlock> {
95+
debug!(
96+
block_number = block_env.number,
97+
deadline = ?self.instant_to_timestamp(finish_by),
98+
tx_count= sim_items.len(),
99+
"starting block build",
100+
);
101+
93102
let db = self.create_db().await.unwrap();
103+
94104
let block_build: BlockBuild<_, NoOpInspector> = BlockBuild::new(
95105
db,
96106
constants,
97107
self.config.cfg_env(),
98-
block,
108+
block_env,
99109
finish_by,
100110
self.config.concurrency_limit,
101111
sim_items,
102112
self.config.rollup_block_gas_limit,
103113
);
104114

105115
let built_block = block_build.build().await;
106-
debug!(block_number = ?built_block.block_number(), "finished building block");
116+
debug!(
117+
tx_count = built_block.tx_count(),
118+
block_number = ?built_block.block_number(),
119+
"block simulation completed",
120+
);
107121

108122
Ok(built_block)
109123
}
@@ -152,19 +166,16 @@ impl Simulator {
152166
submit_sender: mpsc::UnboundedSender<SimResult>,
153167
) {
154168
loop {
155-
let sim_cache = cache.clone();
156-
let finish_by = self.calculate_deadline();
157-
158169
// Wait for the block environment to be set
159170
if self.block_env.changed().await.is_err() {
160171
error!("block_env channel closed");
161172
return;
162173
}
163174

164-
// If no env, skip this run
165175
let Some(block_env) = self.block_env.borrow_and_update().clone() else { return };
166-
debug!(block_env = ?block_env, "building on block env");
167176

177+
let finish_by = self.calculate_deadline();
178+
let sim_cache = cache.clone();
168179
match self.handle_build(constants, sim_cache, finish_by, block_env.clone()).await {
169180
Ok(block) => {
170181
debug!(block = ?block.block_number(), tx_count = block.transactions().len(), "built block");
@@ -187,17 +198,25 @@ impl Simulator {
187198
pub fn calculate_deadline(&self) -> Instant {
188199
// Get the current timepoint within the slot.
189200
let timepoint = self.slot_calculator().current_timepoint_within_slot();
201+
trace!(timepoint, "current timepoint within slot");
190202

191203
// We have the timepoint in seconds into the slot. To find out what's
192204
// remaining, we need to subtract it from the slot duration
193205
let remaining = self.slot_calculator().slot_duration() - timepoint;
206+
trace!(remaining, "time remaining in slot");
194207

195208
// We add a 1500 ms buffer to account for sequencer stopping signing.
196-
197-
let candidate =
209+
let deadline =
198210
Instant::now() + Duration::from_secs(remaining) - Duration::from_millis(1500);
211+
trace!(deadline = ?self.instant_to_timestamp(deadline), "calculated deadline for block simulation");
212+
213+
let buffered_deadline = deadline.max(Instant::now());
214+
trace!(?buffered_deadline, "final deadline for block simulation");
215+
216+
let timestamp = self.instant_to_timestamp(buffered_deadline);
217+
trace!(?timestamp, "deadline converted to timestamp");
199218

200-
candidate.max(Instant::now())
219+
buffered_deadline
201220
}
202221

203222
/// Creates an `AlloyDB` instance from the rollup provider.
@@ -226,4 +245,23 @@ impl Simulator {
226245
let wrapped_db: AlloyDatabaseProvider = WrapDatabaseAsync::new(alloy_db).unwrap();
227246
Some(wrapped_db)
228247
}
248+
249+
/// Converts an `Instant` to a UNIX timestamp in seconds and milliseconds.
250+
pub fn instant_to_timestamp(&self, instant: Instant) -> (u64, u128) {
251+
let now_instant = Instant::now();
252+
let now_system = SystemTime::now();
253+
254+
let duration_from_now = now_instant.duration_since(instant);
255+
256+
// Subtract that duration from the system time
257+
let target_system_time = now_system - duration_from_now;
258+
259+
let duration_since_epoch =
260+
target_system_time.duration_since(UNIX_EPOCH).expect("Time went backwards");
261+
262+
let seconds = duration_since_epoch.as_secs();
263+
let milliseconds = duration_since_epoch.as_millis();
264+
265+
(seconds, milliseconds)
266+
}
229267
}

0 commit comments

Comments
 (0)