Skip to main content

revm_context/
local.rs

1//! Local context that is filled by execution.
2use context_interface::LocalContextTr;
3use core::cell::RefCell;
4use std::{rc::Rc, string::String, vec::Vec};
5
6/// Local context that is filled by execution.
7#[derive(Clone, Debug)]
8pub struct LocalContext {
9    /// Interpreter shared memory buffer. A reused memory buffer for calls.
10    pub shared_memory_buffer: Rc<RefCell<Vec<u8>>>,
11    /// Optional precompile error message to bubble up.
12    pub precompile_error_message: Option<String>,
13    /// EIP-8037 `cost_per_state_byte` cached for the current transaction.
14    ///
15    /// Populated at transaction start from `cfg.cpsb(block.gas_limit())`
16    /// (honoring `cpsb_override`). Read by the hot-path `Host::cpsb`.
17    pub cpsb: u64,
18}
19
20impl Default for LocalContext {
21    fn default() -> Self {
22        Self {
23            shared_memory_buffer: Rc::new(RefCell::new(Vec::with_capacity(1024 * 4))),
24            precompile_error_message: None,
25            cpsb: 0,
26        }
27    }
28}
29
30impl LocalContextTr for LocalContext {
31    fn clear(&mut self) {
32        // Sets len to 0 but it will not shrink to drop the capacity.
33        unsafe { self.shared_memory_buffer.borrow_mut().set_len(0) };
34        self.precompile_error_message = None;
35        self.cpsb = 0;
36    }
37
38    fn shared_memory_buffer(&self) -> &Rc<RefCell<Vec<u8>>> {
39        &self.shared_memory_buffer
40    }
41
42    fn set_precompile_error_context(&mut self, output: String) {
43        self.precompile_error_message = Some(output);
44    }
45
46    fn take_precompile_error_context(&mut self) -> Option<String> {
47        self.precompile_error_message.take()
48    }
49
50    fn cpsb(&self) -> u64 {
51        self.cpsb
52    }
53
54    fn set_cpsb(&mut self, cpsb: u64) {
55        self.cpsb = cpsb;
56    }
57}
58
59impl LocalContext {
60    /// Creates a new local context with default values.
61    ///
62    /// Initializes a shared memory buffer with 4KB capacity and no precompile error message.
63    pub fn new() -> Self {
64        Self::default()
65    }
66}