Skip to main content

reth_basic_payload_builder/
lib.rs

1//! A basic payload generator for reth.
2
3#![doc(
4    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
5    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
6    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
7)]
8#![cfg_attr(not(test), warn(unused_crate_dependencies))]
9#![cfg_attr(docsrs, feature(doc_cfg))]
10
11use crate::metrics::PayloadBuilderMetrics;
12use alloy_eips::merge::SLOT_DURATION;
13use alloy_primitives::{B256, U256};
14use futures_core::ready;
15use futures_util::FutureExt;
16use reth_chain_state::CanonStateNotification;
17use reth_payload_builder::{KeepPayloadJobAlive, PayloadId, PayloadJob, PayloadJobGenerator};
18use reth_payload_builder_primitives::PayloadBuilderError;
19use reth_payload_primitives::{BuiltPayload, PayloadAttributes, PayloadKind};
20use reth_primitives_traits::{HeaderTy, NodePrimitives, SealedHeader};
21use reth_revm::{cached::CachedReads, cancelled::CancelOnDrop};
22use reth_storage_api::{BlockReaderIdExt, StateProviderFactory};
23use reth_tasks::Runtime;
24use std::{
25    fmt,
26    future::Future,
27    ops::Deref,
28    pin::Pin,
29    sync::Arc,
30    task::{Context, Poll},
31    time::{Duration, SystemTime, UNIX_EPOCH},
32};
33use tokio::{
34    sync::{oneshot, Semaphore},
35    time::{Interval, Sleep},
36};
37use tracing::{debug, trace, warn};
38
39mod better_payload_emitter;
40mod metrics;
41mod stack;
42
43pub use better_payload_emitter::BetterPayloadEmitter;
44pub use stack::PayloadBuilderStack;
45
46/// Helper to access [`NodePrimitives::BlockHeader`] from [`PayloadBuilder::BuiltPayload`].
47pub type HeaderForPayload<P> = <<P as BuiltPayload>::Primitives as NodePrimitives>::BlockHeader;
48
49/// The [`PayloadJobGenerator`] that creates [`BasicPayloadJob`]s.
50#[derive(Debug)]
51pub struct BasicPayloadJobGenerator<Client, Builder> {
52    /// The client that can interact with the chain.
53    client: Client,
54    /// The task executor to spawn payload building tasks on.
55    executor: Runtime,
56    /// The configuration for the job generator.
57    config: BasicPayloadJobGeneratorConfig,
58    /// Restricts how many generator tasks can be executed at once.
59    payload_task_guard: PayloadTaskGuard,
60    /// The type responsible for building payloads.
61    ///
62    /// See [`PayloadBuilder`]
63    builder: Builder,
64    /// Stored `cached_reads` for new payload jobs.
65    pre_cached: Option<PrecachedState>,
66}
67
68// === impl BasicPayloadJobGenerator ===
69
70impl<Client, Builder> BasicPayloadJobGenerator<Client, Builder> {
71    /// Creates a new [`BasicPayloadJobGenerator`] with the given config and custom
72    /// [`PayloadBuilder`]
73    pub fn with_builder(
74        client: Client,
75        executor: Runtime,
76        config: BasicPayloadJobGeneratorConfig,
77        builder: Builder,
78    ) -> Self {
79        Self {
80            client,
81            executor,
82            payload_task_guard: PayloadTaskGuard::new(config.max_payload_tasks),
83            config,
84            builder,
85            pre_cached: None,
86        }
87    }
88
89    /// Returns the maximum duration a job should be allowed to run.
90    ///
91    /// This adheres to the following specification:
92    /// > Client software SHOULD stop the updating process when either a call to engine_getPayload
93    /// > with the build process's payloadId is made or SECONDS_PER_SLOT (12s in the Mainnet
94    /// > configuration) have passed since the point in time identified by the timestamp parameter.
95    ///
96    /// See also <https://github.com/ethereum/execution-apis/blob/431cf72fd3403d946ca3e3afc36b973fc87e0e89/src/engine/paris.md?plain=1#L137>
97    #[inline]
98    fn max_job_duration(&self, unix_timestamp: u64) -> Duration {
99        let duration_until_timestamp = duration_until(unix_timestamp);
100
101        // safety in case clocks are bad
102        let duration_until_timestamp = duration_until_timestamp.min(self.config.deadline * 3);
103
104        self.config.deadline + duration_until_timestamp
105    }
106
107    /// Returns the [Instant](tokio::time::Instant) at which the job should be terminated because it
108    /// is considered timed out.
109    #[inline]
110    fn job_deadline(&self, unix_timestamp: u64) -> tokio::time::Instant {
111        tokio::time::Instant::now() + self.max_job_duration(unix_timestamp)
112    }
113
114    /// Returns a reference to the tasks type
115    pub const fn tasks(&self) -> &Runtime {
116        &self.executor
117    }
118
119    /// Returns the pre-cached reads for the given parent header if it matches the cached state's
120    /// block.
121    fn maybe_pre_cached(&self, parent: B256) -> Option<CachedReads> {
122        self.pre_cached.as_ref().filter(|pc| pc.block == parent).map(|pc| pc.cached.clone())
123    }
124}
125
126// === impl BasicPayloadJobGenerator ===
127
128impl<Client, Builder> PayloadJobGenerator for BasicPayloadJobGenerator<Client, Builder>
129where
130    Client: StateProviderFactory
131        + BlockReaderIdExt<Header = HeaderForPayload<Builder::BuiltPayload>>
132        + Clone
133        + Unpin
134        + 'static,
135    Builder: PayloadBuilder + Unpin + 'static,
136    Builder::Attributes: Unpin + Clone,
137    Builder::BuiltPayload: Unpin + Clone,
138{
139    type Job = BasicPayloadJob<Builder>;
140
141    fn new_payload_job(
142        &self,
143        parent: B256,
144        attributes: <Self::Job as PayloadJob>::PayloadAttributes,
145        id: PayloadId,
146    ) -> Result<Self::Job, PayloadBuilderError> {
147        let parent_header = if parent.is_zero() {
148            // Use latest header for genesis block case
149            self.client
150                .latest_header()
151                .map_err(PayloadBuilderError::from)?
152                .ok_or_else(|| PayloadBuilderError::MissingParentHeader(B256::ZERO))?
153        } else {
154            // Fetch specific header by hash
155            self.client
156                .sealed_header_by_hash(parent)
157                .map_err(PayloadBuilderError::from)?
158                .ok_or_else(|| PayloadBuilderError::MissingParentHeader(parent))?
159        };
160
161        let cached_reads = self.maybe_pre_cached(parent_header.hash());
162
163        let config = PayloadConfig::new(Arc::new(parent_header), attributes, id);
164
165        let until = self.job_deadline(config.attributes.timestamp());
166        let deadline = Box::pin(tokio::time::sleep_until(until));
167
168        let mut job = BasicPayloadJob {
169            config,
170            executor: self.executor.clone(),
171            deadline,
172            // ticks immediately
173            interval: tokio::time::interval(self.config.interval),
174            best_payload: PayloadState::Missing,
175            pending_block: None,
176            cached_reads,
177            payload_task_guard: self.payload_task_guard.clone(),
178            metrics: Default::default(),
179            builder: self.builder.clone(),
180        };
181
182        // start the first job right away
183        job.spawn_build_job();
184
185        Ok(job)
186    }
187
188    fn on_new_state<N: NodePrimitives>(&mut self, new_state: CanonStateNotification<N>) {
189        let mut cached = CachedReads::default();
190
191        // extract the state from the notification and put it into the cache
192        let committed = new_state.committed();
193        let new_execution_outcome = committed.execution_outcome();
194        for (addr, acc) in new_execution_outcome.bundle_accounts_iter() {
195            if let Some(info) = acc.info.clone() {
196                // we want pre cache existing accounts and their storage
197                // this only includes changed accounts and storage but is better than nothing
198                let storage =
199                    acc.storage.iter().map(|(key, slot)| (*key, slot.present_value)).collect();
200                cached.insert_account(addr, info, storage);
201            }
202        }
203
204        self.pre_cached = Some(PrecachedState { block: committed.tip().hash(), cached });
205    }
206}
207
208/// Pre-filled [`CachedReads`] for a specific block.
209///
210/// This is extracted from the [`CanonStateNotification`] for the tip block.
211#[derive(Debug, Clone)]
212pub struct PrecachedState {
213    /// The block for which the state is pre-cached.
214    pub block: B256,
215    /// Cached state for the block.
216    pub cached: CachedReads,
217}
218
219/// Restricts how many generator tasks can be executed at once.
220#[derive(Debug, Clone)]
221pub struct PayloadTaskGuard(Arc<Semaphore>);
222
223impl Deref for PayloadTaskGuard {
224    type Target = Semaphore;
225
226    fn deref(&self) -> &Self::Target {
227        &self.0
228    }
229}
230
231// === impl PayloadTaskGuard ===
232
233impl PayloadTaskGuard {
234    /// Constructs `Self` with a maximum task count of `max_payload_tasks`.
235    pub fn new(max_payload_tasks: usize) -> Self {
236        Self(Arc::new(Semaphore::new(max_payload_tasks)))
237    }
238}
239
240/// Settings for the [`BasicPayloadJobGenerator`].
241#[derive(Debug, Clone)]
242pub struct BasicPayloadJobGeneratorConfig {
243    /// The interval at which the job should build a new payload after the last.
244    interval: Duration,
245    /// The deadline for when the payload builder job should resolve.
246    ///
247    /// By default this is [`SLOT_DURATION`]: 12s
248    deadline: Duration,
249    /// Maximum number of tasks to spawn for building a payload.
250    max_payload_tasks: usize,
251}
252
253// === impl BasicPayloadJobGeneratorConfig ===
254
255impl BasicPayloadJobGeneratorConfig {
256    /// Sets the interval at which the job should build a new payload after the last.
257    pub const fn interval(mut self, interval: Duration) -> Self {
258        self.interval = interval;
259        self
260    }
261
262    /// Sets the deadline when this job should resolve.
263    pub const fn deadline(mut self, deadline: Duration) -> Self {
264        self.deadline = deadline;
265        self
266    }
267
268    /// Sets the maximum number of tasks to spawn for building a payload(s).
269    ///
270    /// # Panics
271    ///
272    /// If `max_payload_tasks` is 0.
273    pub fn max_payload_tasks(mut self, max_payload_tasks: usize) -> Self {
274        assert!(max_payload_tasks > 0, "max_payload_tasks must be greater than 0");
275        self.max_payload_tasks = max_payload_tasks;
276        self
277    }
278}
279
280impl Default for BasicPayloadJobGeneratorConfig {
281    fn default() -> Self {
282        Self {
283            interval: Duration::from_secs(1),
284            // 12s slot time
285            deadline: SLOT_DURATION,
286            max_payload_tasks: 3,
287        }
288    }
289}
290
291/// A basic payload job that continuously builds a payload with the best transactions from the pool.
292///
293/// This type is a [`PayloadJob`] and [`Future`] that terminates when the deadline is reached or
294/// when the job is resolved: [`PayloadJob::resolve`].
295///
296/// This basic job implementation will trigger new payload build task continuously until the job is
297/// resolved or the deadline is reached, or until the built payload is marked as frozen:
298/// [`BuildOutcome::Freeze`]. Once a frozen payload is returned, no additional payloads will be
299/// built and this future will wait to be resolved: [`PayloadJob::resolve`] or terminated if the
300/// deadline is reached.
301#[derive(Debug)]
302pub struct BasicPayloadJob<Builder>
303where
304    Builder: PayloadBuilder,
305{
306    /// The configuration for how the payload will be created.
307    config: PayloadConfig<Builder::Attributes, HeaderForPayload<Builder::BuiltPayload>>,
308    /// How to spawn building tasks
309    executor: Runtime,
310    /// The deadline when this job should resolve.
311    deadline: Pin<Box<Sleep>>,
312    /// The interval at which the job should build a new payload after the last.
313    interval: Interval,
314    /// The best payload so far and its state.
315    best_payload: PayloadState<Builder::BuiltPayload>,
316    /// Receiver for the block that is currently being built.
317    pending_block: Option<PendingPayload<Builder::BuiltPayload>>,
318    /// Restricts how many generator tasks can be executed at once.
319    payload_task_guard: PayloadTaskGuard,
320    /// Caches all disk reads for the state the new payloads builds on
321    ///
322    /// This is used to avoid reading the same state over and over again when new attempts are
323    /// triggered, because during the building process we'll repeatedly execute the transactions.
324    cached_reads: Option<CachedReads>,
325    /// metrics for this type
326    metrics: PayloadBuilderMetrics,
327    /// The type responsible for building payloads.
328    ///
329    /// See [`PayloadBuilder`]
330    builder: Builder,
331}
332
333impl<Builder> BasicPayloadJob<Builder>
334where
335    Builder: PayloadBuilder + Unpin + 'static,
336    Builder::Attributes: Unpin + Clone,
337    Builder::BuiltPayload: Unpin + Clone,
338{
339    /// Spawns a new payload build task.
340    fn spawn_build_job(&mut self) {
341        trace!(target: "payload_builder", id = %self.config.payload_id(), "spawn new payload build task");
342        let (tx, rx) = oneshot::channel();
343        let cancel = CancelOnDrop::default();
344        let _cancel = cancel.clone();
345        let guard = self.payload_task_guard.clone();
346        let payload_config = self.config.clone();
347        let best_payload = self.best_payload.payload().cloned();
348        self.metrics.inc_initiated_payload_builds();
349        let cached_reads = self.cached_reads.take().unwrap_or_default();
350        let builder = self.builder.clone();
351        self.executor.spawn_blocking_task(async move {
352            // acquire the permit for executing the task
353            let _permit = guard.acquire().await;
354            let args =
355                BuildArguments { cached_reads, config: payload_config, cancel, best_payload };
356            let result = builder.try_build(args);
357            let _ = tx.send(result);
358        });
359
360        self.pending_block = Some(PendingPayload { _cancel, payload: rx });
361    }
362}
363
364impl<Builder> Future for BasicPayloadJob<Builder>
365where
366    Builder: PayloadBuilder + Unpin + 'static,
367    Builder::Attributes: Unpin + Clone,
368    Builder::BuiltPayload: Unpin + Clone,
369{
370    type Output = Result<(), PayloadBuilderError>;
371
372    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
373        let this = self.get_mut();
374
375        // check if the deadline is reached
376        if this.deadline.as_mut().poll(cx).is_ready() {
377            trace!(target: "payload_builder", "payload building deadline reached");
378            return Poll::Ready(Ok(()))
379        }
380
381        loop {
382            // Wait for any pending build to complete before polling the next tick.
383            //
384            // This avoids consuming interval ticks while a build is still in-flight,
385            // which would delay the follow-up build by a full interval even though
386            // the current attempt has already finished.
387            if let Some(mut fut) = this.pending_block.take() {
388                match fut.poll_unpin(cx) {
389                    Poll::Ready(Ok(outcome)) => match outcome {
390                        BuildOutcome::Better { payload, cached_reads } => {
391                            this.cached_reads = Some(cached_reads);
392                            debug!(target: "payload_builder", value = %payload.fees(), "built better payload");
393                            this.best_payload = PayloadState::Best(payload);
394                        }
395                        BuildOutcome::Freeze(payload) => {
396                            debug!(target: "payload_builder", "payload frozen, no further building will occur");
397                            this.best_payload = PayloadState::Frozen(payload);
398                        }
399                        BuildOutcome::Aborted { fees, cached_reads } => {
400                            this.cached_reads = Some(cached_reads);
401                            trace!(target: "payload_builder", worse_fees = %fees, "skipped payload build of worse block");
402                        }
403                        BuildOutcome::Cancelled => {
404                            unreachable!("the cancel signal never fired")
405                        }
406                    },
407                    Poll::Ready(Err(error)) => {
408                        // job failed, but we simply try again next interval
409                        debug!(target: "payload_builder", %error, "payload build attempt failed");
410                        this.metrics.inc_failed_payload_builds();
411                    }
412                    Poll::Pending => {
413                        this.pending_block = Some(fut);
414                        return Poll::Pending
415                    }
416                }
417            }
418
419            if this.best_payload.is_frozen() {
420                return Poll::Pending
421            }
422
423            // Wait for the next build interval tick.
424            //
425            // The loop is needed because `poll_tick` does not register a waker
426            // when it returns `Ready`, so we must loop back after spawning a job
427            // to reach a point that *does* register one (the pending block poll above).
428            ready!(this.interval.poll_tick(cx));
429            this.spawn_build_job()
430        }
431    }
432}
433
434impl<Builder> PayloadJob for BasicPayloadJob<Builder>
435where
436    Builder: PayloadBuilder + Unpin + 'static,
437    Builder::Attributes: Unpin + Clone,
438    Builder::BuiltPayload: Unpin + Clone,
439{
440    type PayloadAttributes = Builder::Attributes;
441    type ResolvePayloadFuture = ResolveBestPayload<Self::BuiltPayload>;
442    type BuiltPayload = Builder::BuiltPayload;
443
444    fn best_payload(&self) -> Result<Self::BuiltPayload, PayloadBuilderError> {
445        if let Some(payload) = self.best_payload.payload() {
446            Ok(payload.clone())
447        } else {
448            // No payload has been built yet, but we need to return something that the CL then
449            // can deliver, so we need to return an empty payload.
450            //
451            // Note: it is assumed that this is unlikely to happen, as the payload job is
452            // started right away and the first full block should have been
453            // built by the time CL is requesting the payload.
454            self.metrics.inc_requested_empty_payload();
455            self.builder.build_empty_payload(self.config.clone())
456        }
457    }
458
459    fn payload_attributes(&self) -> Result<Self::PayloadAttributes, PayloadBuilderError> {
460        Ok(self.config.attributes.clone())
461    }
462
463    fn payload_timestamp(&self) -> Result<u64, PayloadBuilderError> {
464        Ok(self.config.attributes.timestamp())
465    }
466
467    fn resolve_kind(
468        &mut self,
469        kind: PayloadKind,
470    ) -> (Self::ResolvePayloadFuture, KeepPayloadJobAlive) {
471        let best_payload = self.best_payload.payload().cloned();
472        if best_payload.is_none() && self.pending_block.is_none() {
473            // ensure we have a job scheduled if we don't have a best payload yet and none is active
474            self.spawn_build_job();
475        }
476
477        let maybe_better = self.pending_block.take();
478        let mut empty_payload = None;
479
480        if best_payload.is_none() {
481            debug!(target: "payload_builder", id=%self.config.payload_id(), "no best payload yet to resolve, building empty payload");
482
483            let args = BuildArguments {
484                cached_reads: self.cached_reads.take().unwrap_or_default(),
485                config: self.config.clone(),
486                cancel: CancelOnDrop::default(),
487                best_payload: None,
488            };
489
490            match self.builder.on_missing_payload(args) {
491                MissingPayloadBehaviour::AwaitInProgress => {
492                    debug!(target: "payload_builder", id=%self.config.payload_id(), "awaiting in progress payload build job");
493                }
494                MissingPayloadBehaviour::RaceEmptyPayload => {
495                    debug!(target: "payload_builder", id=%self.config.payload_id(), "racing empty payload");
496
497                    // if no payload has been built yet
498                    self.metrics.inc_requested_empty_payload();
499                    // no payload built yet, so we need to return an empty payload
500                    let (tx, rx) = oneshot::channel();
501                    let config = self.config.clone();
502                    let builder = self.builder.clone();
503                    self.executor.spawn_blocking_task(async move {
504                        let res = builder.build_empty_payload(config);
505                        let _ = tx.send(res);
506                    });
507
508                    empty_payload = Some(rx);
509                }
510                MissingPayloadBehaviour::RacePayload(job) => {
511                    debug!(target: "payload_builder", id=%self.config.payload_id(), "racing fallback payload");
512                    // race the in progress job with this job
513                    let (tx, rx) = oneshot::channel();
514                    self.executor.spawn_blocking_task(async move {
515                        let _ = tx.send(job());
516                    });
517                    empty_payload = Some(rx);
518                }
519            };
520        }
521
522        let fut = ResolveBestPayload {
523            best_payload,
524            maybe_better,
525            empty_payload: empty_payload.filter(|_| kind != PayloadKind::WaitForPending),
526        };
527
528        (fut, KeepPayloadJobAlive::No)
529    }
530}
531
532/// Represents the current state of a payload being built.
533#[derive(Debug, Clone)]
534pub enum PayloadState<P> {
535    /// No payload has been built yet.
536    Missing,
537    /// The best payload built so far, which may still be improved upon.
538    Best(P),
539    /// The payload is frozen and no further building should occur.
540    ///
541    /// Contains the final payload `P` that should be used.
542    Frozen(P),
543}
544
545impl<P> PayloadState<P> {
546    /// Checks if the payload is frozen.
547    pub const fn is_frozen(&self) -> bool {
548        matches!(self, Self::Frozen(_))
549    }
550
551    /// Returns the payload if it exists (either Best or Frozen).
552    pub const fn payload(&self) -> Option<&P> {
553        match self {
554            Self::Missing => None,
555            Self::Best(p) | Self::Frozen(p) => Some(p),
556        }
557    }
558}
559
560/// The future that returns the best payload to be served to the consensus layer.
561///
562/// This returns the payload that's supposed to be sent to the CL.
563///
564/// If payload has been built so far, it will return that, but it will check if there's a better
565/// payload available from an in progress build job. If so it will return that.
566///
567/// If no payload has been built so far, it will either return an empty payload or the result of the
568/// in progress build job, whatever finishes first.
569#[derive(Debug)]
570pub struct ResolveBestPayload<Payload> {
571    /// Best payload so far.
572    pub best_payload: Option<Payload>,
573    /// Regular payload job that's currently running that might produce a better payload.
574    pub maybe_better: Option<PendingPayload<Payload>>,
575    /// The empty payload building job in progress, if any.
576    pub empty_payload: Option<oneshot::Receiver<Result<Payload, PayloadBuilderError>>>,
577}
578
579impl<Payload> ResolveBestPayload<Payload> {
580    const fn is_empty(&self) -> bool {
581        self.best_payload.is_none() && self.maybe_better.is_none() && self.empty_payload.is_none()
582    }
583}
584
585impl<Payload> Future for ResolveBestPayload<Payload>
586where
587    Payload: Unpin,
588{
589    type Output = Result<Payload, PayloadBuilderError>;
590
591    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
592        let this = self.get_mut();
593
594        // check if there is a better payload before returning the best payload
595        if let Some(fut) = Pin::new(&mut this.maybe_better).as_pin_mut() &&
596            let Poll::Ready(res) = fut.poll(cx)
597        {
598            this.maybe_better = None;
599            if let Ok(Some(payload)) = res.map(|out| out.into_payload()).inspect_err(
600                |err| warn!(target: "payload_builder", %err, "failed to resolve pending payload"),
601            ) {
602                debug!(target: "payload_builder", "resolving better payload");
603                return Poll::Ready(Ok(payload))
604            }
605        }
606
607        if let Some(best) = this.best_payload.take() {
608            debug!(target: "payload_builder", "resolving best payload");
609            return Poll::Ready(Ok(best))
610        }
611
612        if let Some(fut) = Pin::new(&mut this.empty_payload).as_pin_mut() &&
613            let Poll::Ready(res) = fut.poll(cx)
614        {
615            this.empty_payload = None;
616            return match res {
617                Ok(res) => {
618                    if let Err(err) = &res {
619                        warn!(target: "payload_builder", %err, "failed to resolve empty payload");
620                    } else {
621                        debug!(target: "payload_builder", "resolving empty payload");
622                    }
623                    Poll::Ready(res)
624                }
625                Err(err) => Poll::Ready(Err(err.into())),
626            }
627        }
628
629        if this.is_empty() {
630            return Poll::Ready(Err(PayloadBuilderError::MissingPayload))
631        }
632
633        Poll::Pending
634    }
635}
636
637/// A future that resolves to the result of the block building job.
638#[derive(Debug)]
639pub struct PendingPayload<P> {
640    /// The marker to cancel the job on drop
641    _cancel: CancelOnDrop,
642    /// The channel to send the result to.
643    payload: oneshot::Receiver<Result<BuildOutcome<P>, PayloadBuilderError>>,
644}
645
646impl<P> PendingPayload<P> {
647    /// Constructs a `PendingPayload` future.
648    pub const fn new(
649        cancel: CancelOnDrop,
650        payload: oneshot::Receiver<Result<BuildOutcome<P>, PayloadBuilderError>>,
651    ) -> Self {
652        Self { _cancel: cancel, payload }
653    }
654}
655
656impl<P> Future for PendingPayload<P> {
657    type Output = Result<BuildOutcome<P>, PayloadBuilderError>;
658
659    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
660        let res = ready!(self.payload.poll_unpin(cx));
661        Poll::Ready(res.map_err(Into::into).and_then(|res| res))
662    }
663}
664
665/// Static config for how to build a payload.
666#[derive(Clone, Debug)]
667pub struct PayloadConfig<Attributes, Header = alloy_consensus::Header> {
668    /// The parent header.
669    pub parent_header: Arc<SealedHeader<Header>>,
670    /// Requested attributes for the payload.
671    pub attributes: Attributes,
672    /// The payload id.
673    pub payload_id: PayloadId,
674}
675
676impl<Attributes, Header> PayloadConfig<Attributes, Header>
677where
678    Attributes: PayloadAttributes,
679{
680    /// Create new payload config.
681    pub const fn new(
682        parent_header: Arc<SealedHeader<Header>>,
683        attributes: Attributes,
684        payload_id: PayloadId,
685    ) -> Self {
686        Self { parent_header, attributes, payload_id }
687    }
688
689    /// Returns the payload id.
690    pub const fn payload_id(&self) -> PayloadId {
691        self.payload_id
692    }
693}
694
695/// The possible outcomes of a payload building attempt.
696#[derive(Debug)]
697pub enum BuildOutcome<Payload> {
698    /// Successfully built a better block.
699    Better {
700        /// The new payload that was built.
701        payload: Payload,
702        /// The cached reads that were used to build the payload.
703        cached_reads: CachedReads,
704    },
705    /// Aborted payload building because resulted in worse block wrt. fees.
706    Aborted {
707        /// The total fees associated with the attempted payload.
708        fees: U256,
709        /// The cached reads that were used to build the payload.
710        cached_reads: CachedReads,
711    },
712    /// Build job was cancelled
713    Cancelled,
714
715    /// The payload is final and no further building should occur
716    Freeze(Payload),
717}
718
719impl<Payload> BuildOutcome<Payload> {
720    /// Consumes the type and returns the payload if the outcome is `Better` or `Freeze`.
721    pub fn into_payload(self) -> Option<Payload> {
722        match self {
723            Self::Better { payload, .. } | Self::Freeze(payload) => Some(payload),
724            _ => None,
725        }
726    }
727
728    /// Consumes the type and returns the payload if the outcome is `Better` or `Freeze`.
729    pub const fn payload(&self) -> Option<&Payload> {
730        match self {
731            Self::Better { payload, .. } | Self::Freeze(payload) => Some(payload),
732            _ => None,
733        }
734    }
735
736    /// Returns true if the outcome is `Better`.
737    pub const fn is_better(&self) -> bool {
738        matches!(self, Self::Better { .. })
739    }
740
741    /// Returns true if the outcome is `Freeze`.
742    pub const fn is_frozen(&self) -> bool {
743        matches!(self, Self::Freeze { .. })
744    }
745
746    /// Returns true if the outcome is `Aborted`.
747    pub const fn is_aborted(&self) -> bool {
748        matches!(self, Self::Aborted { .. })
749    }
750
751    /// Returns true if the outcome is `Cancelled`.
752    pub const fn is_cancelled(&self) -> bool {
753        matches!(self, Self::Cancelled)
754    }
755
756    /// Applies a fn on the current payload.
757    pub fn map_payload<F, P>(self, f: F) -> BuildOutcome<P>
758    where
759        F: FnOnce(Payload) -> P,
760    {
761        match self {
762            Self::Better { payload, cached_reads } => {
763                BuildOutcome::Better { payload: f(payload), cached_reads }
764            }
765            Self::Aborted { fees, cached_reads } => BuildOutcome::Aborted { fees, cached_reads },
766            Self::Cancelled => BuildOutcome::Cancelled,
767            Self::Freeze(payload) => BuildOutcome::Freeze(f(payload)),
768        }
769    }
770}
771
772/// The possible outcomes of a payload building attempt without reused [`CachedReads`]
773#[derive(Debug)]
774pub enum BuildOutcomeKind<Payload> {
775    /// Successfully built a better block.
776    Better {
777        /// The new payload that was built.
778        payload: Payload,
779    },
780    /// Aborted payload building because resulted in worse block wrt. fees.
781    Aborted {
782        /// The total fees associated with the attempted payload.
783        fees: U256,
784    },
785    /// Build job was cancelled
786    Cancelled,
787    /// The payload is final and no further building should occur
788    Freeze(Payload),
789}
790
791impl<Payload> BuildOutcomeKind<Payload> {
792    /// Attaches the [`CachedReads`] to the outcome.
793    pub fn with_cached_reads(self, cached_reads: CachedReads) -> BuildOutcome<Payload> {
794        match self {
795            Self::Better { payload } => BuildOutcome::Better { payload, cached_reads },
796            Self::Aborted { fees } => BuildOutcome::Aborted { fees, cached_reads },
797            Self::Cancelled => BuildOutcome::Cancelled,
798            Self::Freeze(payload) => BuildOutcome::Freeze(payload),
799        }
800    }
801}
802
803/// A collection of arguments used for building payloads.
804///
805/// This struct encapsulates the essential components and configuration required for the payload
806/// building process. It holds references to the Ethereum client, transaction pool, cached reads,
807/// payload configuration, cancellation status, and the best payload achieved so far.
808#[derive(Debug)]
809pub struct BuildArguments<Attributes, Payload: BuiltPayload> {
810    /// Previously cached disk reads
811    pub cached_reads: CachedReads,
812    /// How to configure the payload.
813    pub config: PayloadConfig<Attributes, HeaderTy<Payload::Primitives>>,
814    /// A marker that can be used to cancel the job.
815    pub cancel: CancelOnDrop,
816    /// The best payload achieved so far.
817    pub best_payload: Option<Payload>,
818}
819
820impl<Attributes, Payload: BuiltPayload> BuildArguments<Attributes, Payload> {
821    /// Create new build arguments.
822    pub const fn new(
823        cached_reads: CachedReads,
824        config: PayloadConfig<Attributes, HeaderTy<Payload::Primitives>>,
825        cancel: CancelOnDrop,
826        best_payload: Option<Payload>,
827    ) -> Self {
828        Self { cached_reads, config, cancel, best_payload }
829    }
830}
831
832/// A trait for building payloads that encapsulate Ethereum transactions.
833///
834/// This trait provides the `try_build` method to construct a transaction payload
835/// using `BuildArguments`. It returns a `Result` indicating success or a
836/// `PayloadBuilderError` if building fails.
837///
838/// Generic parameters `Pool` and `Client` represent the transaction pool and
839/// Ethereum client types.
840pub trait PayloadBuilder: Send + Sync + Clone {
841    /// The payload attributes type to accept for building.
842    type Attributes: PayloadAttributes;
843    /// The type of the built payload.
844    type BuiltPayload: BuiltPayload;
845
846    /// Tries to build a transaction payload using provided arguments.
847    ///
848    /// Constructs a transaction payload based on the given arguments,
849    /// returning a `Result` indicating success or an error if building fails.
850    ///
851    /// # Arguments
852    ///
853    /// - `args`: Build arguments containing necessary components.
854    ///
855    /// # Returns
856    ///
857    /// A `Result` indicating the build outcome or an error.
858    fn try_build(
859        &self,
860        args: BuildArguments<Self::Attributes, Self::BuiltPayload>,
861    ) -> Result<BuildOutcome<Self::BuiltPayload>, PayloadBuilderError>;
862
863    /// Invoked when the payload job is being resolved and there is no payload yet.
864    ///
865    /// This can happen if the CL requests a payload before the first payload has been built.
866    fn on_missing_payload(
867        &self,
868        _args: BuildArguments<Self::Attributes, Self::BuiltPayload>,
869    ) -> MissingPayloadBehaviour<Self::BuiltPayload> {
870        MissingPayloadBehaviour::RaceEmptyPayload
871    }
872
873    /// Builds an empty payload without any transaction.
874    fn build_empty_payload(
875        &self,
876        config: PayloadConfig<Self::Attributes, HeaderForPayload<Self::BuiltPayload>>,
877    ) -> Result<Self::BuiltPayload, PayloadBuilderError>;
878}
879
880/// Tells the payload builder how to react to payload request if there's no payload available yet.
881///
882/// This situation can occur if the CL requests a payload before the first payload has been built.
883#[derive(Default)]
884pub enum MissingPayloadBehaviour<Payload> {
885    /// Await the regular scheduled payload process.
886    AwaitInProgress,
887    /// Race the in progress payload process with an empty payload.
888    #[default]
889    RaceEmptyPayload,
890    /// Race the in progress payload process with this job.
891    RacePayload(Box<dyn FnOnce() -> Result<Payload, PayloadBuilderError> + Send>),
892}
893
894impl<Payload> fmt::Debug for MissingPayloadBehaviour<Payload> {
895    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
896        match self {
897            Self::AwaitInProgress => write!(f, "AwaitInProgress"),
898            Self::RaceEmptyPayload => {
899                write!(f, "RaceEmptyPayload")
900            }
901            Self::RacePayload(_) => write!(f, "RacePayload"),
902        }
903    }
904}
905
906/// Checks if the new payload is better than the current best.
907///
908/// This compares the total fees of the blocks, higher is better.
909#[inline(always)]
910pub fn is_better_payload<T: BuiltPayload>(best_payload: Option<&T>, new_fees: U256) -> bool {
911    if let Some(best_payload) = best_payload {
912        new_fees > best_payload.fees()
913    } else {
914        true
915    }
916}
917
918/// Returns the duration until the given unix timestamp in seconds.
919///
920/// Returns `Duration::ZERO` if the given timestamp is in the past.
921fn duration_until(unix_timestamp_secs: u64) -> Duration {
922    let unix_now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
923    let timestamp = Duration::from_secs(unix_timestamp_secs);
924    timestamp.saturating_sub(unix_now)
925}