<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dilara Hatipoğlu on Medium]]></title>
        <description><![CDATA[Stories by Dilara Hatipoğlu on Medium]]></description>
        <link>https://medium.com/@dlra.htpgl?source=rss-8048bbb30078------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O-tEzOgK0XirIp_BEaLuVA@2x.jpeg</url>
            <title>Stories by Dilara Hatipoğlu on Medium</title>
            <link>https://medium.com/@dlra.htpgl?source=rss-8048bbb30078------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:18:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dlra.htpgl/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Lifecycle of an Ethereum RPC Call: From Alloy to Reth]]></title>
            <link>https://medium.com/coinmonks/the-lifecycle-of-an-ethereum-rpc-call-from-alloy-to-reth-48f6ff25feef?source=rss-8048bbb30078------2</link>
            <guid isPermaLink="false">https://medium.com/p/48f6ff25feef</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[reth]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[alloy]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Dilara Hatipoğlu]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 10:44:29 GMT</pubDate>
            <atom:updated>2026-07-30T15:02:29.313Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Lifecycle of an Ethereum RPC Request: From Alloy to Reth</h3><pre>let logs = provider.get_logs(&amp;filter).await?;</pre><p>While using Alloy, I kept wondering what a single line like the one above actually does. So I read the relevant parts of Alloy and Reth and wrote down what I found.</p><p>We follow one call, eth_getLogs, over HTTP, from the typed Filter in your process through Reth’s log lookup and back to a Vec&lt;Log&gt;. The Alloy side of this path is shared by many ordinary request and response RPC calls, while the log search inside Reth is specific to eth_getLogs. Along the way, we see where the JSON is created, when the request is sent, and how the node finds matching logs.</p><p>Reading Rust and having used Alloy before is enough to follow along. We trace Alloy’s default provider implementation down to individual poll calls, then follow the main range query path inside Reth. The code is pinned to <a href="https://github.com/alloy-rs/alloy/tree/ffaf1da70ef3bc2f85b792257b67fce7b49999ca">Alloy 2.1.1 at </a><a href="https://github.com/alloy-rs/alloy/tree/ffaf1da70ef3bc2f85b792257b67fce7b49999ca">ffaf1da7</a> and <a href="https://github.com/paradigmxyz/reth/tree/f969bd4de34657bdea11e98c17a9fd132850d5c3">Reth 2.4.1 at </a><a href="https://github.com/paradigmxyz/reth/tree/f969bd4de34657bdea11e98c17a9fd132850d5c3">f969bd4d</a>. In some code blocks, unrelated parts have been omitted to keep the focus on the path being discussed.</p><h3>Overview</h3><p>Let’s start with an overview of what is happening in the process, so we can dive deeper later and understand the details. An Ethereum RPC call is, at its core, sending one JSON-RPC 2.0 message and receiving one in response. The node is a separate program. You can’t call its functions directly; you can only send it a message and wait for a reply. Alloy’s whole job on your side is to hide that: it takes your typed Rust values, turns them into that JSON, sends it, waits, and turns the node’s answer back into Rust types so you get a clean Vec&lt;Log&gt; instead of a blob of text.</p><p>The process overview is roughly this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ipy6NrAg20J_gMU0Z3iWA.png" /></figure><ol><li><strong>Alloy serializes:</strong> your typed call becomes the request JSON.</li><li><strong>Reth deserializes, processes, serializes:</strong> the request JSON becomes a Filter, the filter finds its logs, the logs become the response JSON.</li><li><strong>Alloy deserializes:</strong> the response JSON becomes your Vec&lt;Log&gt;.</li></ol><p>Here is the call we are going to follow, with the request details filled in:</p><pre>let filter = Filter::new()<br>    .address(address!(&quot;A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48&quot;))        // USDC<br>    .from_block(0x17d7840u64)<br>    .to_block(0x17d7842u64)<br>    .event_signature(keccak256(&quot;Transfer(address,address,uint256)&quot;));<br><br>let logs = provider.get_logs(&amp;filter).await?;</pre><p>Alloy serializes that filter into JSON-RPC parameters so the server can understand what we need. The request looks like this:</p><pre>{<br>  &quot;method&quot;: &quot;eth_getLogs&quot;,<br>  &quot;params&quot;: [<br>    {<br>      &quot;fromBlock&quot;: &quot;0x17d7840&quot;,<br>      &quot;toBlock&quot;: &quot;0x17d7842&quot;,<br>      &quot;address&quot;: &quot;0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48&quot;,<br>      &quot;topics&quot;: [<br>        &quot;0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef&quot;<br>      ]<br>    }<br>  ],<br>  &quot;id&quot;: 0,<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;<br>}</pre><p>Reth answers in the same JSON-RPC shape, including the same id and carrying either a result or an error. A successful response contains an array of logs:</p><pre>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;id&quot;: 0,<br>  &quot;result&quot;: [<br>    {<br>      &quot;address&quot;: &quot;0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48&quot;,<br>      &quot;topics&quot;: [&quot;0xddf252ad...&quot;, &quot;0x...&quot;, &quot;0x...&quot;],<br>      &quot;data&quot;: &quot;0x...&quot;,<br>      &quot;blockHash&quot;: &quot;0x...&quot;,<br>      &quot;blockNumber&quot;: &quot;0x17d7840&quot;,<br>      &quot;blockTimestamp&quot;: &quot;0x...&quot;,<br>      &quot;transactionHash&quot;: &quot;0x...&quot;,<br>      &quot;transactionIndex&quot;: &quot;0x2&quot;,<br>      &quot;logIndex&quot;: &quot;0x5&quot;,<br>      &quot;removed&quot;: false<br>    }<br>  ]<br>}</pre><p>JSONs are the only thing that travel between the two programs. Everything else is private to one side or the other.</p><h3>What the Filter Says</h3><p>Before following the code, let’s open the filter itself, because it is the payload of the whole request. In Alloy, a Filter stores three fields:</p><pre>// crates/rpc-types-eth/src/filter.rs<br>pub struct Filter {<br>    pub block_option: FilterBlockOption,<br>    pub address: FilterSet&lt;Address&gt;,<br>    pub topics: [Topic; 4],<br>}</pre><p>The block_option says which blocks to search. It can be a range (fromBlock/toBlock) or a specific blockHash. The address field says which contract address, or addresses, the logs must come from; if it is empty, logs from any address match. The topics array contains up to four topic filters; an empty slot matches anything. They are positional, so a filter can be valid while targeting the wrong topic slot.</p><p>Ethereum logs have up to four topics. For non-anonymous Solidity events, topics[0] is the hash of the event signature. For ERC-20 transfers, that is keccak256(&quot;Transfer(address,address,uint256)&quot;) -the 0xddf252ad... value in the request above. The remaining slots correspond to the indexed event arguments, in order.</p><pre>event Transfer(address indexed from, address indexed to, uint256 value);</pre><p>The layout is:</p><pre>topics[0] = keccak256(&quot;Transfer(address,address,uint256)&quot;)<br>topics[1] = from<br>topics[2] = to<br>data      = value</pre><p>value is not indexed, so it is not a topic. It lives in the log data, which means you cannot filter on it with eth_getLogs.</p><p>The topic syntax is positional:</p><pre>{<br>  &quot;topics&quot;: [<br>    &quot;0xddf252ad...&quot;,<br>    null,<br>    &quot;0x000000000000000000000000...&quot;<br>  ]<br>}</pre><p>This means: topic0 must be the Transfer signature, topic1 can be anything, topic2 must be the given address, topic3 can be anything. Get a position wrong, and the query still succeeds. It just quietly matches nothing or the wrong thing.</p><p>Now we can look at what Alloy does.</p><h3>How Alloy Serializes and Sends the Call</h3><p>Remember what we are calling the function on: Provider. But what exactly is that?</p><pre>provider.get_logs(&amp;filter).await?;</pre><p>It looks like a single function call, but several different jobs have to happen before the request reaches the node. Someone needs to provide the API you call, reuse the connection to the node, turn your function call into a JSON-RPC request, and send that request over the network.</p><p>Instead of putting all of these responsibilities into one place, Alloy splits them across four roles: Provider, RootProvider, RpcClient, and Transport:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99J0XGRVsW2vZp9_xt_-Mw.png" /></figure><h3>Provider</h3><p>The Provider is the object your application interacts with. Whenever you call methods like get_logs, get_balance, or send_transaction, you&#39;re calling methods on a Provider.</p><p>get_logs has a default implementation on the Provider trait: it obtains the shared RpcClient from the RootProvider and uses it to perform the request.</p><pre>// crates/provider/src/provider/trait.rs<br>pub trait Provider&lt;N: Network = Ethereum&gt;: Send + Sync {<br>    /// Returns the root provider.<br>    fn root(&amp;self) -&gt; &amp;RootProvider&lt;N&gt;;<br><br>    // ...<br><br>    /// Returns the RPC client used to send requests.<br>    #[inline]<br>    fn client(&amp;self) -&gt; ClientRef&lt;&#39;_&gt; {<br>        self.root().client()<br>    }<br><br>    // ...<br><br>    /// Retrieves a [`Vec&lt;Log&gt;`] with the given [`Filter`].<br>    async fn get_logs(&amp;self, filter: &amp;Filter) -&gt; TransportResult&lt;Vec&lt;Log&gt;&gt; {<br>        self.client().request(&quot;eth_getLogs&quot;, (filter,)).await<br>    }<br>}</pre><p>One scope note before we continue: this article follows this default implementation. A provider may override get_logs entirely.</p><h3>RootProvider</h3><p>The RootProvider sits at the base of every provider stack, and for our call it does exactly one thing: it holds the shared RpcClient and hands out references to it.</p><pre>// crates/provider/src/provider/root.rs<br>pub struct RootProvider&lt;N: Network = Ethereum&gt; {<br>    /// The inner state of the root provider.<br>    pub(crate) inner: Arc&lt;RootProviderInner&lt;N&gt;&gt;,<br>}<br><br>pub(crate) struct RootProviderInner&lt;N: Network = Ethereum&gt; {<br>    client: RpcClient,<br>    heart: OnceLock&lt;HeartbeatHandle&gt;,<br>    _network: PhantomData&lt;N&gt;,<br>}</pre><p>Three fields, and only the first matters to our call. client is the shared RpcClient, the next layer down. heart serves features like watching new blocks and waiting for transactions to be mined; a one-shot read like get_logs never touches it. And _network is a zero-sized PhantomData marker: it holds no data; it only pins the stack to one network&#39;s types at compile time.</p><p>Providers point back at the same root, so they all share one client and, below it, one connection pool.</p><h3>RpcClient</h3><p>The RpcClient converts your Rust function call into a JSON-RPC request: it builds the request, assigns an id, hands the finished request to the transport, and converts the reply back into Rust types.</p><p>Notice what it does <em>not</em> know: the RpcClient knows nothing about Ethereum. Its only job is to speak JSON-RPC: build a request, attach an id, read a response. It holds the transport it sends through and the counter it draws ids from. (The full type also stores is_local andpoll_interval, plus a pubsub handle when that feature is enabled -none of which our call touches.)</p><pre>// crates/rpc-client/src/client.rs<br>pub struct RpcClientInner {<br>    /// The underlying transport.<br>    pub(crate) transport: BoxTransport,<br>    /// The next request ID to use.<br>    pub(crate) id: AtomicU64,<br>    // ...<br>}</pre><p>A note on that id: over HTTP, the reply is already tied to the request by the request/response exchange itself -one POST, one response- and Alloy never even compares it; we’ll watch it get discarded on the return trip. The id becomes load-bearing on batches and on multiplexed transports like WebSocket, where many requests share one connection and responses can arrive out of order; there, the id is what routes each response back to its caller.</p><h3>Transport</h3><p>The Transport is the only layer that actually talks to the network. Its job: deliver an already-serialized JSON-RPC packet to the node and hand back the reply. It doesn&#39;t know what eth_getLogs means, and it doesn&#39;t know Ethereum. It moves packets.</p><pre>// crates/transport/src/boxed.rs<br>pub struct BoxTransport {<br>    inner: Box&lt;dyn CloneTransport&gt;,<br>}</pre><p>That is the whole reason it’s four roles and not one. The Provider speaks Ethereum, the RpcClient speaks only JSON-RPC, the RootProvider sits between them holding the client they all share, and the Transport speaks only packets. Each role strips away one concern, and the call simply descends from the one that knows the most to the one that knows the least.</p><p>Now let’s follow the call down.</p><h3>Alloy’s Serialization</h3><p>This is the overview of the function call sequence, and we will look at it in detail by reading the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vaf-C_fYzUEU4YC0SH3wog.png" /></figure><p>Let’s return to the function implementation we call:</p><pre>    /// Retrieves a [`Vec&lt;Log&gt;`] with the given [`Filter`].<br>    async fn get_logs(&amp;self, filter: &amp;Filter) -&gt; TransportResult&lt;Vec&lt;Log&gt;&gt; {<br>        self.client().request(&quot;eth_getLogs&quot;, (filter,)).await<br>    }</pre><p>self.client() borrows the shared client from the RootProvider -a ClientRef, which is simply a reference to the RpcClientInner we just saw.</p><p>request is the RpcClientInner ’s method, and does not send anything. It builds the request and wraps it in an RpcCall -a future:</p><pre>// crates/rpc-client/src/client.rs<br>/// Prepares an [`RpcCall`].<br>///<br>/// This function reserves an ID for the request, however the request is not sent.<br>/// To send a request, await the returned [`RpcCall`].<br>///<br>/// # Note<br>///<br>/// Serialization is done lazily. It will not be performed until the call is awaited.<br>pub fn request&lt;Params: RpcSend, Resp: RpcRecv&gt;(<br>    &amp;self,<br>    method: impl Into&lt;Cow&lt;&#39;static, str&gt;&gt;,<br>    params: Params,<br>) -&gt; RpcCall&lt;Params, Resp&gt; {<br>    let request = self.make_request(method, params);<br>    RpcCall::new(request, self.transport.clone())<br>}<br><br>// ...<br><br>pub fn make_request&lt;Params: RpcSend&gt;(<br>    &amp;self,<br>    method: impl Into&lt;Cow&lt;&#39;static, str&gt;&gt;,<br>    params: Params,<br>) -&gt; Request&lt;Params&gt; {<br>    Request::new(method, self.next_id(), params)<br>}</pre><p>At this point, not a single byte has gone to the network. make_request produced a Request&lt;Params&gt;: the method name, the id reserved for this call, and the params, which are still the Rust values you built. That id is the 0 you saw in the request JSON above. Serialization has not happened yet.</p><p>After RpcCall::new, an RpcCall&lt;Params, Vec&lt;Log&gt;&gt;: a future holding the request, the transport, and the response type it will eventually deserialize into.</p><h3>Sending the Request</h3><p>When you .await the RpcCall, two poll functions come into play: an outer one on the RpcCall itself, and an inner one on its state machine. The outer drives the inner and then deserializes; the inner sends the request and waits for the reply.</p><p>The outer poll, in full:</p><pre>// crates/rpc-client/src/call.rs<br>fn poll(self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut task::Context&lt;&#39;_&gt;) -&gt; task::Poll&lt;Self::Output&gt; {<br>    let this = self.get_mut();<br>    let resp = try_deserialize_ok(ready!(this.state.poll_unpin(cx)));<br>    Ready(resp.map(this.map.take().expect(&quot;polled after completion&quot;)))<br>}</pre><p>It is short because it does only two things. It polls the inner state machine (this.state) -ready! returns Pending early if the state isn&#39;t finished- and once the state returns the raw response, try_deserialize_ok turns that raw JSON into the typed Vec&lt;Log&gt;; map then applies an optional conversion, the identity for get_logs. We&#39;ll come back to the deserialize step on the return trip. First, the machine underneath.</p><p>The inner poll is the state machine that sends the request and waits for the reply. In full:</p><pre>// crates/rpc-client/src/call.rs<br>fn poll(mut self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut task::Context&lt;&#39;_&gt;) -&gt; task::Poll&lt;Self::Output&gt; {<br>    loop {<br>        match self.as_mut().project() {<br>            CallStateProj::Prepared { connection, request } =&gt; {<br>                if let Err(e) =<br>                    task::ready!(Service::&lt;RequestPacket&gt;::poll_ready(connection, cx))<br>                {<br>                    self.set(Self::Complete);<br>                    return Ready(RpcResult::Err(e));<br>                }<br><br>                let request = request.take().expect(&quot;no request&quot;);<br>                if tracing::enabled!(tracing::Level::TRACE) {<br>                    trace!(?request, &quot;sending request&quot;);<br>                } else {<br>                    debug!(method=%request.meta.method, id=%request.meta.id, &quot;sending request&quot;);<br>                }<br>                let request = request.serialize();<br>                let fut = match request {<br>                    Ok(request) =&gt; {<br>                        trace!(request=%request.serialized(), &quot;serialized request&quot;);<br>                        connection.call(request.into())<br>                    }<br>                    Err(err) =&gt; {<br>                        trace!(?err, &quot;failed to serialize request&quot;);<br>                        self.set(Self::Complete);<br>                        return Ready(RpcResult::Err(TransportError::ser_err(err)));<br>                    }<br>                };<br>                self.set(Self::AwaitingResponse { fut });<br>            }<br>            CallStateProj::AwaitingResponse { fut } =&gt; {<br>                let res = match task::ready!(fut.poll(cx)) {<br>                    Ok(ResponsePacket::Single(res)) =&gt; Ready(transform_response(res)),<br>                    Err(e) =&gt; Ready(RpcResult::Err(e)),<br>                    Ok(ResponsePacket::Batch(_)) =&gt; {<br>                        Ready(RpcResult::Err(TransportErrorKind::custom_str(<br>                            &quot;received batch response from single request&quot;,<br>                        )))<br>                    }<br>                };<br>                self.set(Self::Complete);<br>                return res;<br>            }<br>            CallStateProj::Complete =&gt; {<br>                panic!(&quot;Polled after completion&quot;);<br>            }<br>        }<br>    }<br>}</pre><p>The machine has two points where it can pause: is the transport ready, and has the node replied? Over HTTP, only the second one ever actually pauses. Everything else is serialization and bookkeeping. Let’s take the arms one by one.</p><h4>The Prepared arm</h4><p>The state machine starts here, and the arm does three things in order: ask the transport if it’s ready, serialize the request, and hand it over.</p><p>First, the readiness check:</p><pre>// crates/rpc-client/src/call.rs<br>if let Err(e) =<br>    task::ready!(Service::&lt;RequestPacket&gt;::poll_ready(connection, cx))<br>{<br>    self.set(Self::Complete);<br>    return Ready(RpcResult::Err(e));<br>}</pre><p>For an HTTP transport, this always returns Ready:</p><pre>// crates/transport-http/src/reqwest_transport.rs<br>fn poll_ready(&amp;mut self, _cx: &amp;mut task::Context&lt;&#39;_&gt;) -&gt; task::Poll&lt;Result&lt;(), Self::Error&gt;&gt; {<br>    // `reqwest` always returns `Ok(())`.<br>    task::Poll::Ready(Ok(()))<br>}</pre><p>Second, serialization: where the request becomes JSON.</p><pre>// crates/rpc-client/src/call.rs - logging trimmed<br>let request = request.take().expect(&quot;no request&quot;);<br>let request = request.serialize();<br>let fut = match request {<br>    Ok(request) =&gt; connection.call(request.into()),<br>    Err(err) =&gt; {<br>        self.set(Self::Complete);<br>        return Ready(RpcResult::Err(TransportError::ser_err(err)));<br>    }<br>};<br>self.set(Self::AwaitingResponse { fut });</pre><p>What does serialize actually do? It’s short:</p><pre>// crates/json-rpc/src/request.rs<br>pub fn serialize(self) -&gt; serde_json::Result&lt;SerializedRequest&gt; {<br>    let request = serde_json::value::to_raw_value(&amp;self)?;<br>    Ok(SerializedRequest { meta: self.meta, request })<br>}</pre><p>to_raw_value(&amp;self) hands the request to serde, which dispatches back to Request ‘s own Serialize impl. That’s where the envelope from the overview is assembled, field by field:</p><pre>// crates/json-rpc/src/request.rs<br>// manually implemented to avoid adding a type for the protocol-required<br>// `jsonrpc` field<br>impl&lt;Params&gt; Serialize for Request&lt;Params&gt;<br>where<br>    Params: RpcSend,<br>{<br>    fn serialize&lt;S&gt;(&amp;self, serializer: S) -&gt; Result&lt;S::Ok, S::Error&gt;<br>    where<br>        S: serde::Serializer,<br>    {<br>        let sized_params = std::mem::size_of::&lt;Params&gt;() != 0;<br><br>        let mut map = serializer.serialize_map(Some(3 + sized_params as usize))?;<br>        map.serialize_entry(&quot;method&quot;, &amp;self.meta.method[..])?;<br><br>        // Params may be omitted if it is 0-sized<br>        if sized_params {<br>            map.serialize_entry(&quot;params&quot;, &amp;self.params)?;<br>        }<br><br>        map.serialize_entry(&quot;id&quot;, &amp;self.meta.id)?;<br>        map.serialize_entry(&quot;jsonrpc&quot;, &quot;2.0&quot;)?;<br>        map.end()<br>    }<br>}</pre><p>There they are: method, params, id, jsonrpc: &quot;2.0&quot;; the four fields of the request JSON from the overview, written out one entry at a time. Serializing params recursively serializes your Filter, which is how the typed addresses and topics become the hex strings on the wire.</p><p>Third, the handoff. connection.call(req.into()) passes the serialized packet to the transport and returns a future. The .into() call wraps our single request in RequestPacket::Single. RequestPacket is the wire unit that can carry either a single request or a batch. But where does the returned future come from?</p><pre>// crates/transport-http/src/reqwest_transport.rs<br>impl Service&lt;RequestPacket&gt; for Http&lt;reqwest::Client&gt; {<br>    type Response = ResponsePacket;<br>    type Error = TransportError;<br>    type Future = TransportFut&lt;&#39;static&gt;;<br><br>    // poll_ready shown above<br><br>    #[inline]<br>    fn call(&amp;mut self, req: RequestPacket) -&gt; Self::Future {<br>        let this = self.clone();<br>        let span = debug_span!(&quot;ReqwestTransport&quot;, url = %this.url);<br>        Box::pin(this.do_reqwest(req).instrument(span.or_current()))<br>    }<br>}</pre><p>self.clone() copies the transport handle so the future can own it (do_reqwest takes self by value and the clone is cheap, because a reqwest::Client is itself a handle to a shared connection pool). Then this.do_reqwest(req) <em>constructs</em> its future, and Box::pin wraps it into the type the state machine stores. The span/instrument pair is observability, not control flow: it tags every log line the future emits with the transport&#39;s URL. None of it changes how the request is sent.</p><p>What does not happen in call is any networking: async functions in Rust are lazy, so at this point not a single byte has moved. The boxed future is the fut the arm stores as it moves on:</p><pre>self.set(Self::AwaitingResponse { fut });</pre><p>The POST only begins when the next arm polls it for the first time.</p><h4>The AwaitingResponse arm</h4><pre>// crates/rpc-client/src/call.rs<br>let res = match task::ready!(fut.poll(cx)) {<br>    Ok(ResponsePacket::Single(res)) =&gt; Ready(transform_response(res)),<br>    Err(e) =&gt; Ready(RpcResult::Err(e)),<br>    Ok(ResponsePacket::Batch(_)) =&gt; {<br>        Ready(RpcResult::Err(TransportErrorKind::custom_str(<br>            &quot;received batch response from single request&quot;,<br>        )))<br>    }<br>};<br>self.set(Self::Complete);</pre><p>This is the second wait, and the real one: fut.poll(cx) is where the await truly waits on the network. The future stays Pending, the task yields so the runtime can run other work, and nothing happens until the node&#39;s reply comes back. Most of that time belongs to the network and to Reth.</p><p>That first fut.poll(cx) is also what finally runs do_reqwest, a thin wrapper over reqwest:</p><pre>// crates/transport-http/src/reqwest_transport.rs - logging trimmed<br>async fn do_reqwest(self, req: RequestPacket) -&gt; TransportResult&lt;ResponsePacket&gt; {<br>    let resp = self<br>        .client<br>        .post(self.url)<br>        .json(&amp;req)<br>        .headers(req.headers())<br>        .send()<br>        .await<br>        .map_err(TransportErrorKind::custom)?;<br>    let status = resp.status();<br><br>    // Unpack data from the response body. We do this regardless of<br>    // the status code, as we want to return the error in the body<br>    // if there is one.<br>    let body = resp.bytes().await.map_err(TransportErrorKind::custom)?;<br><br>    if !status.is_success() {<br>        if let Some(response) = crate::json_rpc_error_response(&amp;body) {<br>            return Ok(response);<br>        }<br><br>        return Err(TransportErrorKind::http_error(<br>            status.as_u16(),<br>            String::from_utf8_lossy(&amp;body).into_owned(),<br>        ));<br>    }<br><br>    // Deserialize a Box&lt;RawValue&gt; from the body. If deserialization fails, return<br>    // the body as a string in the error. The conversion to String<br>    // is lossy and may not cover all the bytes in the body.<br>    serde_json::from_slice(&amp;body)<br>        .map_err(|err| TransportError::deser_err(err, String::from_utf8_lossy(&amp;body)))<br>}</pre><p>.json(&amp;req) writes the JSON body, .post(url).send() performs the HTTP POST, resp.bytes() reads the reply. This is where the request finally leaves the process. While the inner poll sits Pending here, the bytes are on the network, and control has passed to Reth.</p><p>When the reply does arrive, the arm checks its shape. We sent a single request, so a batch reply would be a protocol violation; that’s the Batch arm turning into an error. A transport failure, such as a refused connection or a timeout, surfaces as the Err arm. The normal case, Single, goes into transform_response, which turns the already-parsed reply into a Rust Result. This is the return trip. We’ll walk through its code after Reth has done its part.</p><h4>The Complete arm</h4><pre>CallStateProj::Complete =&gt; {<br>    panic!(&quot;Polled after completion&quot;);<br>}</pre><p>It’s a contract, not logic: a Rust future should not be polled again after it has returned Ready. .await respects this automatically.</p><h3>Inside Reth</h3><p>While Alloy waits in AwaitingResponse, the request is inside the node. This is the busiest of the three movements: Reth deserializes the request, does the actual work, and serializes the reply. We followed Alloy down to individual polls; here we zoom out one level and follow the main path only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8CnWiFjwZo_LIpAj4wNGaw.png" /></figure><p>Here is the whole path in outline:</p><ul><li><strong>Route.</strong> jsonrpsee parses the request and rebuilds the typed Filter, then calls the handler for eth_getLogs.</li><li><strong>Resolve.</strong> A filter names either one block hash or a range. A range may use tags like latest, so it becomes two concrete numbers that are checked against the chain head, pruned history, and the configured range cap.</li><li><strong>Search.</strong> Cheap pass first: block headers carry a bloom filter (we will see what it is) that answers “could this block match?”. Only the blocks that say yes get their receipts opened -from cache if recent, from disk if not- and only there does the exact match run.</li><li><strong>Return.</strong> Matching logs are stamped with their block and transaction context and serialized back into the response JSON.</li></ul><h3>Where the Request Arrives</h3><p>The HTTP request first reaches jsonrpsee; it is the JSON-RPC library Reth uses. It parses the JSON-RPC request and uses the method field to decide which handler receives the request. That mapping is declared by a trait:</p><pre>// reth: crates/rpc/rpc-eth-api/src/filter.rs<br>#[cfg_attr(not(feature = &quot;client&quot;), rpc(server, namespace = &quot;eth&quot;))]<br>#[cfg_attr(feature = &quot;client&quot;, rpc(server, client, namespace = &quot;eth&quot;))]<br>pub trait EthFilterApi&lt;T: RpcObject&gt; {<br>    // ...<br><br>    /// Returns logs matching given filter object.<br>    #[method(name = &quot;getLogs&quot;)]<br>    async fn logs(&amp;self, filter: Filter) -&gt; RpcResult&lt;Vec&lt;Log&gt;&gt;;<br>}</pre><p>The namespace eth and method name getLogs form eth_getLogs. The signature tells jsonrpsee what to do with the parameters: deserialize the request&#39;s filter object into a Rust Filter, then call logs.</p><p>Reth imports that Filter, along with the Log type it will return, from alloy-rpc-types-eth -the same RPC type definitions Alloy uses on the client side. The two programs hold separate Rust values, but they agree on the JSON representation, so the filter Alloy serialized is reconstructed field by field inside the node.</p><p>With the conversion done, jsonrpsee calls Reth&#39;s handler:</p><pre>// reth: crates/rpc/rpc/src/eth/filter.rs<br>#[async_trait]<br>impl&lt;Eth&gt; EthFilterApiServer&lt;RpcTransaction&lt;Eth::NetworkTypes&gt;&gt; for EthFilter&lt;Eth&gt;<br>where<br>    Eth: FullEthApiTypes + RpcNodeCoreExt + LoadReceipt + EthBlocks + &#39;static,<br>{<br>    // ...<br><br>    /// Handler for `eth_getLogs`<br>    async fn logs(&amp;self, filter: Filter) -&gt; RpcResult&lt;Vec&lt;Log&gt;&gt; {<br>        trace!(target: &quot;rpc::eth&quot;, &quot;Serving eth_getLogs&quot;);<br>        Ok(self.logs_for_filter(filter, self.inner.query_limits).await?)<br>    }<br>}</pre><p>From here on, Reth’s code works with typed Rust values rather than JSON. The block selectors, the USDC address, and the Transfer topic are typed fields inside Filter . The handler adds the node’s configured query limits and forwards the request through one small wrapper:</p><pre>async fn logs_for_filter(<br>    &amp;self,<br>    filter: Filter,<br>    limits: QueryLimits,<br>) -&gt; Result&lt;Vec&lt;Log&gt;, EthFilterError&gt; {<br>    self.inner.clone().logs_for_filter(filter, limits).await<br>}</pre><h3>Resolving the Block Range</h3><p>A filter can identify one block by hash or describe a range, and the inner logs_for_filter branches on which.</p><pre>// reth: crates/rpc/rpc/src/eth/filter.rs<br>async fn logs_for_filter(<br>    self: Arc&lt;Self&gt;,<br>    filter: Filter,<br>    limits: QueryLimits,<br>) -&gt; Result&lt;Vec&lt;Log&gt;, EthFilterError&gt; {<br>    match filter.block_option {<br>        FilterBlockOption::AtBlockHash(block_hash) =&gt; { /* single-block path omitted */ }<br>        FilterBlockOption::Range { from_block, to_block } =&gt; {<br>            if from_block.is_some_and(|b| b.is_pending()) {<br>                /* pending-block path omitted */<br>            }<br><br>            let info = self.provider().chain_info()?;<br>            let start_block = info.best_number;<br>            let from = from_block<br>                .map(|num| self.provider().convert_block_number(num))<br>                .transpose()?<br>                .flatten();<br>            let to = to_block<br>                .map(|num| self.provider().convert_block_number(num))<br>                .transpose()?<br>                .flatten();<br><br>            if let Some(t) = to &amp;&amp; t &gt; info.best_number {<br>                return Err(EthFilterError::BlockRangeExceedsHead {<br>                    requested: t, head: info.best_number,<br>                });<br>            }<br>            if let Some(f) = from &amp;&amp; f &gt; info.best_number {<br>                return Ok(Vec::new());<br>            }<br><br>            let (from_block_number, to_block_number) =<br>                logs_utils::get_filter_block_range(from, to, start_block, info)?;<br><br>            // Check if the requested range overlaps with pruned history (EIP-4444)<br>            let earliest_block = self.provider().earliest_block_number()?;<br>            if from_block_number &lt; earliest_block {<br>                return Err(EthApiError::PrunedHistoryUnavailable.into());<br>            }<br><br>            self.get_logs_in_block_range(filter, from_block_number, to_block_number, limits)<br>                .await<br>        }<br>    }<br>}</pre><p>The block-hash branch already knows its block, so it fetches that block’s receipts (cache first, storage on a miss), applies the same pruned-history check, and jumps straight to the exact-matching step every path eventually reaches. No range to resolve, no bloom scan.</p><p>The pending branch applies when fromBlock is pending, referring to a block that has not yet become part of the canonical chain. Reth uses the pending block it builds locally when one is available.</p><p>Ours is the third branch, and it is the only one with work to do before the search can start. Its problem is that “a range” arrived in an unresolved form. Both bounds are optional, and each can be a tag like latest or earliest rather than a number. So it turns the unresolved range into two concrete integers. chain_info() supplies the current head. convert_block_number resolves each bound. A number stays a number, latest becomes the head, and earliest becomes the first block the node has. Then come the boundary rules. These are worth knowing as a user because they are asymmetric:</p><ul><li>A toBlock beyond the head is an error (BlockRangeExceedsHead), you asked for blocks that don&#39;t exist yet.</li><li>A fromBlock beyond the head silently returns an empty Vec, the whole search starts past the known chain.</li><li>A range starting before the node’s earliest stored block fails with PrunedHistoryUnavailable, rather than silently searching only the part that survived pruning.</li><li>An omitted bound is not what you’d assume. get_filter_block_range fills a missing fromBlock with the current head, and a missing toBlock with the head too. A filter with no block bounds is a query over the latest block, not over all of history.</li></ul><p>Our numeric bounds pass every check unchanged:</p><pre>from_block_number = 25_000_000<br>to_block_number   = 25_000_002</pre><p>The unresolved range is now exactly three concrete blocks.</p><h3>Range Limits and a Blocking Task</h3><p>The resolved range enters get_logs_in_block_range, which does two things: checks the guardrails, and moves the work somewhere it&#39;s allowed to be slow.</p><pre>// reth: crates/rpc/rpc/src/eth/filter.rs<br>async fn get_logs_in_block_range(<br>    self: Arc&lt;Self&gt;,<br>    filter: Filter,<br>    from_block: u64,<br>    to_block: u64,<br>    limits: QueryLimits,<br>) -&gt; Result&lt;Vec&lt;Log&gt;, EthFilterError&gt; {<br>    trace!(target: &quot;rpc::eth::filter&quot;, from=from_block, to=to_block, ?filter, &quot;finding logs in range&quot;);<br><br>    // perform boundary checks first<br>    if to_block &lt; from_block {<br>        return Err(EthFilterError::InvalidBlockRangeParams);<br>    }<br><br>    if let Some(max_blocks_per_filter) =<br>        limits.max_blocks_per_filter.filter(|limit| to_block - from_block &gt; *limit)<br>    {<br>        return Err(EthFilterError::QueryExceedsMaxBlocks(max_blocks_per_filter));<br>    }<br><br>    let (tx, rx) = oneshot::channel();<br>    let this = self.clone();<br>    self.task_spawner.spawn_blocking_task(async move {<br>        let res =<br>            this.get_logs_in_block_range_inner(&amp;filter, from_block, to_block, limits).await;<br>        let _ = tx.send(res);<br>    });<br><br>    rx.await.map_err(|_| EthFilterError::InternalError)?<br>}</pre><p>The first two checks reject an inverted range and apply Reth’s configured block-range limit before the scan begins.</p><p>The scan performs synchronous provider operations such as headers_range and receipts_by_block. Since these storage reads can block, Reth runs get_logs_in_block_range_inner in a separate blocking task instead of directly in the RPC handler. The worker sends its result through tx, while rx.await keeps the handler waiting until the result arrives.</p><h3>The Scan in Three Phases</h3><p>Everything from here until the worker returns happens inside get_logs_in_block_range_inner. The complete functional path is shown below; tracing-only logging has been omitted.</p><pre>// reth: crates/rpc/rpc/src/eth/filter.rs<br>async fn get_logs_in_block_range_inner(<br>    self: Arc&lt;Self&gt;,<br>    filter: &amp;Filter,<br>    from_block: u64,<br>    to_block: u64,<br>    limits: QueryLimits,<br>) -&gt; Result&lt;Vec&lt;Log&gt;, EthFilterError&gt; {<br>    let mut all_logs = Vec::new();<br>    let mut matching_headers = Vec::new();<br><br>    // get current chain tip to determine processing mode<br>    let chain_tip = self.provider().best_block_number()?;<br><br>    // first collect all headers that match the bloom filter for cached mode decision<br>    for (from, to) in<br>        BlockRangeInclusiveIter::new(from_block..=to_block, self.max_headers_range)<br>    {<br>        let headers = self.provider().headers_range(from..=to)?;<br>        let mut headers_iter = headers.into_iter().peekable();<br><br>        while let Some(header) = headers_iter.next() {<br>            if !filter.matches_bloom(header.logs_bloom()) {<br>                continue;<br>            }<br><br>            let current_number = header.number();<br><br>            let block_hash = match headers_iter.peek() {<br>                Some(next_header) if next_header.number() == current_number + 1 =&gt; {<br>                    // Headers are consecutive, use the more efficient parent_hash<br>                    next_header.parent_hash()<br>                }<br>                _ =&gt; {<br>                    // Headers not consecutive or last header, calculate hash<br>                    header.hash_slow()<br>                }<br>            };<br><br>            matching_headers.push(SealedHeader::new(header, block_hash));<br>        }<br>    }<br><br>    // initialize the appropriate range mode based on collected headers<br>    let mut range_mode = RangeMode::new(<br>        self.clone(),<br>        matching_headers,<br>        from_block,<br>        to_block,<br>        self.max_headers_range,<br>        chain_tip,<br>    );<br><br>    // iterate through the range mode to get receipts and blocks<br>    while let Some(ReceiptBlockResult { receipts, recovered_block, header }) =<br>        range_mode.next().await?<br>    {<br>        let num_hash = header.num_hash();<br>        append_matching_block_logs(<br>            &amp;mut all_logs,<br>            recovered_block<br>                .map(ProviderOrBlock::Block)<br>                .unwrap_or_else(|| ProviderOrBlock::Provider(self.provider())),<br>            filter,<br>            num_hash,<br>            &amp;receipts,<br>            false,<br>            header.timestamp(),<br>        )?;<br><br>        // size check but only if range is multiple blocks, so we always return all<br>        // logs of a single block<br>        let is_multi_block_range = from_block != to_block;<br>        if let Some(max_logs_per_response) = limits.max_logs_per_response<br>            &amp;&amp; is_multi_block_range<br>            &amp;&amp; all_logs.len() &gt; max_logs_per_response<br>        {<br>            let retry_to_block =<br>                if num_hash.number == from_block { from_block } else { num_hash.number - 1 };<br>            return Err(EthFilterError::QueryExceedsMaxResults {<br>                max_logs: max_logs_per_response,<br>                from_block,<br>                to_block: retry_to_block,<br>            });<br>        }<br>    }<br><br>    Ok(all_logs)<br>}</pre><p>The function has three stages:</p><ol><li>Use header blooms to find candidate blocks (matching_headers).</li><li>Fetch the receipts for each candidate (range_mode.next()).</li><li>Check the real logs, build RPC Log values, and enforce the result limit (append_matching_block_logs and the check after it).</li></ol><h3>Phase 1: The bloom scan</h3><p>The first stage starts with a problem of scale. Logs live inside transaction receipts, and since this is our first mention of receipts, it’s worth saying what one is. A receipt is the record Ethereum produces for every executed transaction: whether it succeeded, how much gas it used, and -what matters here- the complete list of logs that transaction emitted. A block carries one receipt per transaction, so a busy block holds hundreds of them. Reading every receipt of every block in the range would work for our three blocks, but would be hopeless for the thousands a serious indexer asks for. The question phase 1 answers: can irrelevant blocks be eliminated without opening their receipts at all?</p><p>The block header makes that first elimination possible: it carries a 256-byte summary called the <strong>logs bloom</strong>. When a block is executed, the address and topics of every emitted log get hashed into this bloom filter. A bloom filter can answer one question, fast: “could this address or topic appear in this block’s logs?” It can produce false positives -”maybe” when the truth is no- but never false negatives. If the bloom says our USDC address isn’t in this block, it is not in this block, guaranteed, and the node never needs to open the block’s receipts.</p><p>So the scan walks headers, not receipts:</p><pre>// reth: crates/rpc/rpc/src/eth/filter.rs - the bloom scan, in get_logs_in_block_range_inner<br>for (from, to) in BlockRangeInclusiveIter::new(from_block..=to_block, self.max_headers_range) {<br>    let headers = self.provider().headers_range(from..=to)?;<br>    let mut headers_iter = headers.into_iter().peekable();<br><br>    while let Some(header) = headers_iter.next() {<br>        if !filter.matches_bloom(header.logs_bloom()) {<br>            continue;<br>        }<br><br>        let current_number = header.number();<br>        let block_hash = match headers_iter.peek() {<br>            Some(next_header) if next_header.number() == current_number + 1 =&gt; {<br>                // Headers are consecutive, use the more efficient parent_hash<br>                next_header.parent_hash()<br>            }<br>            _ =&gt; {<br>                // Headers not consecutive or last header, calculate hash<br>                header.hash_slow()<br>            }<br>        };<br><br>        matching_headers.push(SealedHeader::new(header, block_hash));<br>    }<br>}</pre><p>The whole decision for each block is one call, matches_bloom:</p><pre>// alloy: crates/rpc-types-eth/src/filter.rs<br>pub fn matches_bloom(&amp;self, bloom: Bloom) -&gt; bool {<br>    self.address_bloom_filter().matches(bloom)<br>        &amp;&amp; self.topics_bloom_filter().iter().all(|topic_bloom| topic_bloom.matches(bloom))<br>}</pre><p>The address must be possible in the bloom, and every constrained topic position must be possible too. One negative result skips the block, so its receipts are never opened. A positive result only keeps the block as a candidate; the bloom cannot confirm that a matching log exists. And it cannot confirm <em>where</em> a topic sits: the bloom records that a value appears somewhere in the block’s logs, not in which topic slot. So the positional check that phase 3 runs still has real work to do.</p><p>Two mechanical details are worth a note. First, batching. BlockRangeInclusiveIter slices the range into chunks of max_headers_range, so no single storage read is unbounded. Memory use is still not constant because every bloom-positive header is kept in matching_headers. Our request is one chunk of three.</p><p>Second, block hashes. Phase 2 fetches receipts by hash, so each surviving header has to leave the scan with its hash attached (SealedHeader::new). Computing one directly means keccak-hashing the whole header, which is the costly path. This is why the iterator is peekable: a header already stores its parent&#39;s hash, so if the next header is consecutive, its parent_hash is exactly the current block&#39;s hash, free.</p><p>The flip side of the bloom check is worth stating clearly: if the filter names no address and no topics, there is nothing to check; every bloom passes by default, and every block in the range falls through to phase 2, which is exactly why an unfiltered eth_getLogs over a wide range is such an expensive query to send a node.</p><p>Phase 1’s output is matching_headers: every block whose bloom says the filter may match, each paired with its hash. For our three-block request, this vector can contain anywhere from zero to three headers. The source code tells us how candidates are selected, but only the actual chain data can tell us which of these three blooms pass.</p><h3>Phase 2: Fetching the receipts</h3><p>A bloom-positive header is only a candidate. The actual logs remain inside the block’s receipts, so Reth must now obtain one receipt list for every candidate in matching_headers.</p><p>To see why this step has two strategies, start with where a Reth node keeps its data. Everything the node retains lives in persistent storage on disk. On top of that, Reth keeps recently touched blocks and receipts in memory, most of them near the chain tip. Memory answers immediately and disk is far slower per block. So the same request for a block’s receipts has a cheap answer for recent blocks and an expensive one for old ones, and it is worth choosing the access path explicitly.</p><p>That choice is RangeMode. It performs no additional filtering; it only decides how receipt access is managed. Two modes:</p><pre>// reth: crates/rpc/rpc/src/eth/filter.rs<br>enum RangeMode&lt;<br>    Eth: RpcNodeCoreExt&lt;Provider: BlockIdReader, Pool: TransactionPool&gt;<br>        + EthApiTypes<br>        + LoadReceipt<br>        + EthBlocks<br>        + &#39;static,<br>&gt; {<br>    /// Use cache-based processing for recent blocks<br>    Cached(CachedMode&lt;Eth&gt;),<br>    /// Use range-based processing for older blocks<br>    Range(RangeBlockMode&lt;Eth&gt;),<br>}</pre><ul><li>CachedMode, for small ranges near the chain tip. Each candidate&#39;s receipts are requested through the cache service (get_receipts_and_maybe_block): already in memory, returned immediately; on a miss, the cache service can still fall back to storage. If the full block is also cached, it comes back alongside the receipts.</li><li>RangeBlockMode, for older or larger ranges, goes to storage. It checks the cache without forcing a fetch, then reads whatever&#39;s missing straight from disk via self.provider().receipts_by_block(...). A very large candidate set is split across parallel blocking tasks that go straight to the provider, their results reassembled in block order so logs never come back out of sequence.</li></ul><p>Which mode runs is decided when the RangeMode is built. RangeMode::new computes two values from the resolved range: the number of blocks, and the distance from the range&#39;s end to the chain tip. And passes them to should_use_cached_mode:</p><pre>// reth: crates/rpc/rpc/src/eth/filter.rs<br>/// Determines whether to use cached mode based on bloom filter matches and range size<br>const fn should_use_cached_mode(<br>    headers: &amp;[SealedHeader&lt;&lt;Eth::Provider as HeaderProvider&gt;::Header&gt;],<br>    block_count: u64,<br>    distance_from_tip: u64,<br>) -&gt; bool {<br>    // Headers are already filtered by bloom, so count equals length<br>    let bloom_matches = headers.len();<br><br>    // Calculate adjusted threshold based on bloom matches<br>    let adjusted_threshold = Self::calculate_adjusted_threshold(block_count, bloom_matches);<br><br>    block_count &lt;= adjusted_threshold &amp;&amp; distance_from_tip &lt;= adjusted_threshold<br>}</pre><p>The returned boolean selects the mode: true builds Cached, false builds Range (an empty candidate list goes to Range either way).</p><p>For our query, the decision is easy: three blocks sitting far behind the chain tip, so RangeMode::new picks RangeBlockMode. Iterating it determines how the rest of the phase proceeds. Each range_mode.next() delegates to RangeBlockMode::next, which groups consecutive candidate headers and chooses how to fetch their receipts. With only three candidates, the request stays on the sequential path: check the cache first, then load whatever&#39;s missing through receipts_by_block. Whichever mode runs, next() hands back the same bundle, ReceiptBlockResult:</p><pre>// reth: crates/rpc/rpc/src/eth/filter.rs<br>/// Helper type for the common pattern of returning receipts, block and the original header that is<br>/// a match for the filter.<br>struct ReceiptBlockResult&lt;P&gt;<br>where<br>    P: ReceiptProvider + BlockReader,<br>{<br>    /// We always need the entire receipts for the matching block.<br>    receipts: Arc&lt;Vec&lt;ProviderReceipt&lt;P&gt;&gt;&gt;,<br>    /// Block can be optional and we can fetch it lazily when needed.<br>    recovered_block: Option&lt;Arc&lt;reth_primitives_traits::RecoveredBlock&lt;ProviderBlock&lt;P&gt;&gt;&gt;&gt;,<br>    /// The header of the block.<br>    header: SealedHeader&lt;&lt;P as HeaderProvider&gt;::Header&gt;,<br>}</pre><p>Two of the three fields are unconditional: the receipts and the header. The third, recovered_block, is present only when the full block was already in memory; otherwise it is None. That optional block is exactly what Phase 3 reaches for when it needs a matching log&#39;s transaction hash. So whether it arrives as Some or None sets the cost of that lookup.</p><h3>Phase 3: Exact matching, and building your Log</h3><p>Every path has now converged: for each block that made it this far, get_logs_in_block_range_inner destructures each ReceiptBlockResult that next() returns -pulling out the recovered_block we just saw- and calls the append_matching_block_logs function:</p><pre>// reth: crates/rpc/rpc/src/eth/filter.rs - the call in get_logs_in_block_range_inner<br>append_matching_block_logs(<br>    &amp;mut all_logs,<br>    recovered_block<br>        .map(ProviderOrBlock::Block)<br>        .unwrap_or_else(|| ProviderOrBlock::Provider(self.provider())),<br>    filter,<br>    num_hash,<br>    &amp;receipts,<br>    false,<br>    header.timestamp(),<br>)?;</pre><p>That second argument is the recovered_block from phase 2, mapped into an either-or: ProviderOrBlock::Block when the block came back in memory, ProviderOrBlock::Provider -a handle to storage- when it didn&#39;t. The function needs it for a single field, and the variant it gets sets the price of filling that field.</p><p>Inside, the function is two nested loops for every receipt in the block, and every log in the receipt:</p><pre>// reth: crates/rpc/rpc-eth-types/src/logs_utils.rs<br><br>/// Appends all matching logs of a block&#39;s receipts.<br>/// If the log matches, look up the corresponding transaction hash.<br>pub fn append_matching_block_logs&lt;P&gt;(<br>    all_logs: &amp;mut Vec&lt;Log&gt;,<br>    provider_or_block: ProviderOrBlock&lt;&#39;_, P&gt;,<br>    filter: &amp;Filter,<br>    block_num_hash: BlockNumHash,<br>    receipts: &amp;[P::Receipt],<br>    removed: bool,<br>    block_timestamp: u64,<br>) -&gt; Result&lt;(), ProviderError&gt;<br>where<br>    P: BlockReader&lt;Transaction: SignedTransaction&gt;,<br>{<br>    if !filter.matches_block(&amp;block_num_hash) {<br>        return Ok(());<br>    }<br><br>    // Tracks the index of a log in the entire block.<br>    let mut log_index: u64 = 0;<br><br>    // Lazy loaded number of the first transaction in the block.<br>    // This is useful for blocks with multiple matching logs because it<br>    // prevents re-querying the block body indices.<br>    let mut loaded_first_tx_num = None;<br><br>    // Iterate over receipts and append matching logs.<br>    for (receipt_idx, receipt) in receipts.iter().enumerate() {<br>        // The transaction hash of the current receipt.<br>        let mut transaction_hash = None;<br><br>        for log in receipt.logs() {<br>            if filter.matches(log) {<br>                // if this is the first match in the receipt&#39;s logs, look up the transaction hash<br>                if transaction_hash.is_none() {<br>                    transaction_hash = match &amp;provider_or_block {<br>                        ProviderOrBlock::Block(block) =&gt; {<br>                            block.body().transactions().get(receipt_idx).map(|t| *t.tx_hash())<br>                        }<br>                        ProviderOrBlock::Provider(provider) =&gt; {<br>                            let first_tx_num = match loaded_first_tx_num {<br>                                Some(num) =&gt; num,<br>                                None =&gt; {<br>                                    let block_body_indices = provider<br>                                        .block_body_indices(block_num_hash.number)?<br>                                        .ok_or(ProviderError::BlockBodyIndicesNotFound(<br>                                            block_num_hash.number,<br>                                        ))?;<br>                                    loaded_first_tx_num = Some(block_body_indices.first_tx_num);<br>                                    block_body_indices.first_tx_num<br>                                }<br>                            };<br><br>                            // This is safe because Transactions and Receipts have the same<br>                            // keys.<br>                            let transaction_id = first_tx_num + receipt_idx as u64;<br>                            let transaction =<br>                                provider.transaction_by_id(transaction_id)?.ok_or_else(|| {<br>                                    ProviderError::TransactionNotFound(transaction_id.into())<br>                                })?;<br><br>                            Some(*transaction.tx_hash())<br>                        }<br>                    };<br>                }<br><br>                let log = Log {<br>                    inner: log.clone(),<br>                    block_hash: Some(block_num_hash.hash),<br>                    block_number: Some(block_num_hash.number),<br>                    transaction_hash,<br>                    // The transaction and receipt index is always the same.<br>                    transaction_index: Some(receipt_idx as u64),<br>                    log_index: Some(log_index),<br>                    removed,<br>                    block_timestamp: Some(block_timestamp),<br>                };<br>                all_logs.push(log);<br>            }<br>            log_index += 1;<br>        }<br>    }<br>    Ok(())<br>}</pre><p>Filter::matches is where the bloom’s false positives die:</p><pre>// alloy: crates/rpc-types-eth/src/filter.rs<br>pub fn matches(&amp;self, log: &amp;alloy_primitives::Log) -&gt; bool {<br>    if !self.matches_address(log.address) {<br>        return false;<br>    }<br>    self.matches_topics(log.topics())<br>}</pre><p>The address is checked against the address set, and each topic against its positional filter -the same positional semantics from the start of the article.</p><p>Once a log clears matches, the function looks up its transaction hash. This is where the two ProviderOrBlock variants diverge. If phase 2 delivered the block, the answer is an array index: the receipt_idx-th transaction&#39;s hash. If not, storage answers in two reads.</p><p>Reth’s database numbers every transaction it stores with one global sequence, and a block’s transactions sit consecutively in it. block_body_indices fetches where the block&#39;s transactions begin (first_tx_num), and first_tx_num + receipt_idx gives the transaction&#39;s global number, which transaction_by_id resolves to the transaction itself.</p><p>Both lookups are lazy: the hash is fetched only for the first matching log in a receipt (transaction_hash starts as None, and later matches in the same receipt reuse it), while first_tx_num is fetched once per block and reused across receipts.</p><p>Once transaction_hash has been resolved, the log that passed matches becomes the RPC Log you will eventually receive. The inner loop adds it to all_logs with all_logs.push(Log { … }). Every other field comes directly from values the loop already holds:</p><ul><li>inner: the log as the contract emitted it; address, topics, data.</li><li>block_hash, block_number, block_timestamp: straight from values already in hand.</li><li>transaction_index: receipt_idx, because receipts are ordered the same way as the block’s transactions.</li><li>log_index: the log’s absolute position among all logs in the block. This is why the counter increments outside the if. Non-matching logs still occupy positions.</li><li>removed: false here; it turns true on the eth_subscribe(&quot;logs&quot;) path, where a reorg replays the logs of the blocks it undid.</li></ul><p>After append_matching_block_logs returns, the worker applies the second configured limit, max_logs_per_response:</p><pre>// reth: crates/rpc/rpc/src/eth/filter.rs<br>// size check but only if range is multiple blocks, so we always return all<br>// logs of a single block<br>let is_multi_block_range = from_block != to_block;<br>if let Some(max_logs_per_response) = limits.max_logs_per_response<br>    &amp;&amp; is_multi_block_range<br>    &amp;&amp; all_logs.len() &gt; max_logs_per_response<br>{<br>    let retry_to_block =<br>        if num_hash.number == from_block { from_block } else { num_hash.number - 1 };<br>    return Err(EthFilterError::QueryExceedsMaxResults {<br>        max_logs: max_logs_per_response,<br>        from_block,<br>        to_block: retry_to_block,<br>    });<br>}</pre><p>Three details define its behavior:</p><ul><li>It runs after each block, not each log, so a single block’s matching logs are never truncated mid-block.</li><li>A query for exactly one block is exempt entirely. The is_multi_block_range guard provides this exemption.</li><li>On overflow, Reth returns a QueryExceedsMaxResults error rather than a partial vector. The error is unusually helpful because it carries from_block and the last block number that still fit. If the very first block already overflowed, it carries that block number instead. A retry can always fetch that block because single-block queries are exempt. In either case, the client is told exactly which smaller range to try next.</li></ul><p>When the iterator runs dry, the loop ends and get_logs_in_block_range returns Ok(all_logs). For our request, every USDC Transfer log in blocks 25,000,000 through 25,000,002.</p><h3>Returning Through the Call Chain</h3><p>When the scan finishes, the result travels back through the same call chain in reverse. Because the scan ran in a separate blocking task, its first hop is through the oneshot channel: the worker sends the result through tx, and the rx.await inside get_logs_in_block_range receives it.</p><p>From there, each function that awaited the next one resumes and returns the result upward: get_logs_in_block_range returns to the inner logs_for_filter, which returns through the forwarding wrapper and finally reaches the public logs handler. An error follows the same path as a successful Vec&lt;Log&gt;.</p><p>Once the handler returns, Reth’s method-specific work is complete. jsonrpsee turns the returned value into a JSON-RPC response and writes it to HTTP, sending the call back across the boundary. Somewhere on the other side, the future we left in AwaitingResponse is about to be polled one last time.</p><h3>How Alloy Deserializes the Response</h3><p>Now the third movement reverses the first: raw JSON becomes typed Rust again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hmPStOz3QthxdnA_ecmvQA.png" /></figure><p>The reply arrives on the same HTTP connection, and we are still inside do_reqwest, parked since the POST: .send().await resolves once the response headers arrive, and resp.bytes().await reads the body:</p><pre>// crates/transport-http/src/reqwest_transport.rs<br>async fn do_reqwest(<br>    self,<br>    req: RequestPacket,<br>) -&gt; TransportResult&lt;ResponsePacket&gt; {<br>    // request sending and status handling omitted<br><br>    let body = resp.bytes().await.map_err(TransportErrorKind::custom)?;<br><br>    serde_json::from_slice(&amp;body)<br>        .map_err(|err| TransportError::deser_err(<br>            err,<br>            String::from_utf8_lossy(&amp;body),<br>        ))<br>}</pre><p>What does that parse produce? Not your logs, not yet. from_slice returns a ResponsePacket-a thin wrapper that is either Single(Response) or Batch(Vec&lt;Response&gt;):</p><pre>// crates/json-rpc/src/packet.rs<br>pub enum ResponsePacket&lt;Payload = Box&lt;RawValue&gt;, ErrData = Box&lt;RawValue&gt;&gt; {<br>    /// A single response.<br>    Single(Response&lt;Payload, ErrData&gt;),<br>    /// A batch of responses.<br>    Batch(Vec&lt;Response&lt;Payload, ErrData&gt;&gt;),<br>}</pre><p>We sent one request, so ours is Single. Here is the Response:</p><pre>// crates/json-rpc/src/response/mod.rs<br>pub struct Response&lt;Payload = Box&lt;RawValue&gt;, ErrData = Box&lt;RawValue&gt;&gt; {<br>    pub id: Id,<br>    pub payload: ResponsePayload&lt;Payload, ErrData&gt;,<br>}<br><br>// crates/json-rpc/src/response/payload.rs<br>pub enum ResponsePayload&lt;Payload = Box&lt;RawValue&gt;, ErrData = Box&lt;RawValue&gt;&gt; {<br>    Success(Payload),<br>    Failure(ErrorPayload&lt;ErrData&gt;),<br>}</pre><p>The payload is classified as Success or Failure while the response is parsed. Its default type is Box&lt;RawValue&gt;, so serde validates the result JSON but leaves it as raw text. This is the first stage of deserialization. The response structure becomes typed, while the result remains raw.</p><p>The transport cannot convert the result into Vec&lt;Log&gt; because it does not know the expected response type. RpcCall does, and try_deserialize_ok performs the second stage. Batch requests and multiplexed transports use the response id for routing. This single HTTP path discards it without checking.</p><p>This parsed ResponsePacket resolves the second wait -the fut.poll(cx) that had been sitting Pending in AwaitingResponse. From here, two transformations turn the raw reply into your Vec&lt;Log&gt;, undoing the two that built the request on the way out.</p><p><strong>First transformation:</strong> convert the response into a Result<strong>.</strong> Back in the inner poll, the resolved future hands the packet to transform_response:</p><pre>// crates/rpc-client/src/call.rs<br>CallStateProj::AwaitingResponse { fut } =&gt; {<br>    let res = match task::ready!(fut.poll(cx)) {<br>        Ok(ResponsePacket::Single(res)) =&gt; Ready(transform_response(res)),<br>        Err(e) =&gt; Ready(RpcResult::Err(e)),<br>        Ok(ResponsePacket::Batch(_)) =&gt; {<br>            Ready(RpcResult::Err(TransportErrorKind::custom_str(<br>                &quot;received batch response from single request&quot;,<br>            )))<br>        }<br>    };<br>    self.set(Self::Complete);<br>    return res;<br>}</pre><p>And transform_response is a match on the enum we just saw:</p><pre>// crates/json-rpc/src/result.rs<br>pub fn transform_response&lt;T, E, ErrResp&gt;(response: Response&lt;T, ErrResp&gt;) -&gt; RpcResult&lt;T, E, ErrResp&gt;<br>where<br>    ErrResp: RpcRecv,<br>{<br>    match response {<br>        Response { payload: ResponsePayload::Failure(err_resp), .. } =&gt; {<br>            Err(RpcError::err_resp(err_resp))<br>        }<br>        Response { payload: ResponsePayload::Success(result), .. } =&gt; Ok(result),<br>    }<br>}</pre><p>transform_response converts a failure payload into a Rust Err carrying an RpcError; a successful one stays raw JSON as Box&lt;RawValue&gt;. The .. pattern discards the response id. If Reth rejected the query, for example because the block range exceeded the node’s limit, the caller’s ? propagates that error. The inner state machine then sets itself to Complete. On success, it returns the raw result to the outer poll, where it is deserialized into Vec&lt;Log&gt;.</p><p>Second transformation: parse the payload. We now return to the outer poll, the line we set aside in “Sending the Request”:</p><pre>// crates/rpc-client/src/call.rs<br>let resp = try_deserialize_ok(ready!(this.state.poll_unpin(cx)));</pre><p>try_deserialize_ok is where the raw JSON finally becomes the type you asked for. Here is the function in full:</p><pre>// crates/json-rpc/src/result.rs<br>pub fn try_deserialize_ok&lt;J, T, E, ErrResp&gt;(<br>    result: RpcResult&lt;J, E, ErrResp&gt;,<br>) -&gt; RpcResult&lt;T, E, ErrResp&gt;<br>where<br>    J: Borrow&lt;RawValue&gt; + &#39;static,<br>    T: RpcRecv,<br>    ErrResp: RpcRecv,<br>{<br>    let json = result?;<br><br>    // Fast path: the caller wants the already-owned `Box&lt;RawValue&gt;` back unchanged. Hand it<br>    // over directly, skipping the byte copy and full JSON validation scan that<br>    // `from_str::&lt;Box&lt;RawValue&gt;&gt;` would repeat over an already-validated value.<br>    if TypeId::of::&lt;J&gt;() == TypeId::of::&lt;Box&lt;RawValue&gt;&gt;()<br>        &amp;&amp; TypeId::of::&lt;T&gt;() == TypeId::of::&lt;Box&lt;RawValue&gt;&gt;()<br>    {<br>        // SAFETY: `J` and `T` are both `Box&lt;RawValue&gt;`, so this is a no-op reinterpretation.<br>        // `transmute_copy` stands in for the unstable `transmute_unchecked` (sizes are equal).<br>        let json = std::mem::ManuallyDrop::new(json);<br>        return Ok(unsafe { std::mem::transmute_copy::&lt;J, T&gt;(&amp;json) });<br>    }<br><br>    let _guard = debug_span!(&quot;deserialize_response&quot;, ty=%std::any::type_name::&lt;T&gt;()).entered();<br>    let json = json.borrow().get();<br>    trace!(%json, &quot;deserializing&quot;);<br>    serde_json::from_str(json)<br>        .inspect(|response| trace!(?response, &quot;deserialized&quot;))<br>        .inspect_err(|err| trace!(?err, &quot;failed to deserialize&quot;))<br>        .map_err(|err| RpcError::deser_err(err, json))<br>}</pre><p>result? first propagates anything that has already gone wrong. A transport failure or an error response from the node exits here, and your ? sees it. What remains is the result payload. It is still raw JSON text that has been syntax-checked but not yet deserialized into Vec&lt;Log&gt;.</p><p>Two lines turn that text into your logs. json.borrow().get() exposes the raw value as a plain &amp;str without parsing it. serde_json::from_str then reads it as the response type get_logs declared, the Vec&lt;Log&gt; carried by RpcCall. The transport could not perform this parse because only the caller knows the expected result type. The hex strings become typed addresses, hashes, and numbers inside the same shared Log type that Reth serialized.</p><p>If the text refuses the type, the node has sent a shape that the struct cannot accept. In that case, deser_err attaches the failing JSON to the error. A deserialization failure from Alloy shows you the exact text it could not deserialize, which turns “something didn’t parse” into a bug report that writes itself.</p><p>(The fast path above serves callers that request Box&lt;RawValue&gt; directly. This is the raw, unparsed JSON. Alloy hands back the value it already owns. Our get_logs never takes this path.)</p><p>One step remains in the outer poll:</p><pre>Ready(resp.map(this.map.take().expect(&quot;polled after completion&quot;)))</pre><p>map is a final conversion applied to the response. It provides a chance to reshape the response before it reaches you. get_logs does not need this conversion. The Vec&lt;Log&gt; is already the type you want, so its map is the identity function. The value passes through unchanged.</p><p>The outer poll returns Ready, the .await inside the default get_logs completes, and get_logs returns the Vec&lt;Log&gt; to its caller.</p><p>Run against a node, our three-block request returns 187 logs. Here is an example log from the result:</p><pre>Log {<br>    inner: Log {<br>        address: 0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48,<br>        data: LogData {<br>            topics: [<br>                0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef,<br>                0x000000000000000000000000000000000004444c5dc75cb358380d2e3de08a90,<br>                0x0000000000000000000000007f54f05635d15cde17a49502fedb9d1803a3be8a,<br>            ],<br>            data: 0x00000000000000000000000000000000000000000000000000000000017d0fc6,<br>        },<br>    },<br>    block_hash: Some(<br>        0xf398976165ca4756c77fc6b61111fa1102d431eb03082417ecce38b36308d728,<br>    ),<br>    block_number: Some(<br>        25000000,<br>    ),<br>    block_timestamp: Some(<br>        1777637363,<br>    ),<br>    transaction_hash: Some(<br>        0xd019ec20783bff41af6c78575e5f1bc4018775161d1e82f7913c2c30a8369d35,<br>    ),<br>    transaction_index: Some(<br>        8,<br>    ),<br>    log_index: Some(<br>        33,<br>    ),<br>    removed: false,<br>}</pre><h3>Closing the Loop</h3><p>At the call site, all of this comes back to the line we started with:</p><pre>let logs = provider.get_logs(&amp;filter).await?;</pre><p>The path has the same shape in both directions. A typed Filter becomes JSON, crosses into another process, and becomes a typed Filter again. Reth then uses it to check block headers, load receipts, and match logs in stages. The result returns as JSON and becomes a typed Vec&lt;Log&gt;. Alloy builds and sends the call. Reth answers it.</p><p>A single .await covers this whole path. It is not one hidden operation but a series of smaller steps. Once we can see those steps, eth_getLogs no longer looks like magic. A slow query, an empty result, a range-limit error, a transport failure, and a deserialization failure can arise at different points on the same trip. Now we know where to look for each one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48f6ff25feef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/the-lifecycle-of-an-ethereum-rpc-call-from-alloy-to-reth-48f6ff25feef">The Lifecycle of an Ethereum RPC Call: From Alloy to Reth</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing an Aave V3 Indexer: Challenges and Insights]]></title>
            <link>https://medium.com/coinmonks/designing-an-aave-v3-indexer-challenges-and-insights-a15b5bcd7961?source=rss-8048bbb30078------2</link>
            <guid isPermaLink="false">https://medium.com/p/a15b5bcd7961</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[aave]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Dilara Hatipoğlu]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 14:07:25 GMT</pubDate>
            <atom:updated>2026-03-31T14:30:28.524Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VIK2fwIUyMLXcyI5QrECFQ.png" /></figure><p>I spent the last few months building an <a href="https://github.com/dlr-a/aave-v3-tracker">Aave V3 indexer</a> in Rust. It reads on-chain events from Ethereum Mainnet and writes protocol state into PostgreSQL -reserve configs, interest rate data, user supply/borrow positions, and eMode categories. The stack is Rust with Tokio for async, Alloy for Ethereum interaction, and Diesel for PostgreSQL.</p><p>It sounded straightforward at first: listen to events, decode them, write to a database. In practice, almost every assumption I started with turned out to be wrong or incomplete.</p><h3>1. Large Numbers Need the Right Type</h3><p>Solidity uses integers for everything -1.5 ETH is 1500000000000000000 on-chain. Aave&#39;s internal math goes further: it uses RAY (10^27) as a fixed-point base, so an intermediate calculation like amount × RAY, where the amount is already 10^18, produces 10^45. Rust&#39;s u128 maxes out at roughly 10^38, so it overflows. Aave itself uses uint256 in Solidity, and the Rust equivalent is Alloy&#39;s U256.</p><p>That handles the math, but U256 isn’t a storage type. For values that stay large -balances, liquidity indices, supply caps- BigDecimal maps cleanly to PostgreSQL’s NUMERIC and doesn’t lose precision.</p><h3>2. Self-Healing: What Happens When an Unknown Reserve Shows Up</h3><p>During backfill, maybe I missed an event, and I get a ReserveDataUpdated event for a reserve that didn&#39;t exist in the database yet. This can happen because we may have missed the ReserveInitialized event for that reserve.</p><p>The question was: what should the indexer do? Skipping the event because we don’t have that reserve is completely the wrong way to go, because apparently, we missed something. Throwing an error and stopping means that a single edge case blocks the entire system, which does not make sense.</p><p>I saw it as an opportunity to fix missing data, and I went with self-healing: if an event references a reserve that’s not in the database, the indexer fetches that reserve’s full config from the chain via RPC, inserts it, and then continues processing normally. It prevents a missing reserve from blocking the entire backfill.</p><p>Code is shown below:</p><pre>if !exists {<br>            warn!(<br>                asset = %asset_str,<br>                block = block_number,<br>                &quot;Reserve not found in DB — fetching from RPC&quot;<br>            );<br><br>            process_reserve(pool, &amp;provider, asset_addr, data_provider_addr, pool_addr, Some(block_number as u64))<br>                .await<br>                .wrap_err_with(|| {<br>                    format!(<br>                        &quot;Self-healing: failed to fetch reserve {} from RPC&quot;,<br>                        asset_str<br>                    )<br>                })?;<br>        }</pre><p>The same pattern applies to eMode categories -if an event references a category that doesn’t exist locally, the indexer pulls the full category definition from the chain before continuing. The idea is simple: never stop, never lose data, and recover automatically when possible.</p><h3>3. Reorg, WebSocket, and a Deliberate Tradeoff</h3><p>Ethereum can reorganize its recent history, and any events you indexed from those discarded blocks may now be invalid in a reorg -but they’re already in your database. So, processing events in real time with WebSocket is not acceptable. Because without reorg handling, a reorganization would leave stale data in the database with no way to detect or fix it.</p><p>Instead of implementing full reorg detection and rollback -which is a significant undertaking on its own- I made a deliberate tradeoff: disable WebSocket entirely and only write data through HTTP-based backfill with a 20-block confirmation delay. On Mainnet, 20 blocks are roughly 4 minutes. At that depth, a reorganization is highly unlikely. Real-time data is sacrificed, but correctness is guaranteed -and for my indexer, correctness matters more than latency.</p><h3>4. Multi-RPC Failover</h3><p>RPC providers go down, hit rate limits, or return server errors -and when your indexer depends on a single provider, any of these stops everything.</p><p>The indexer sticks with one until it starts failing. If a chunk fails and the error looks like a rate limit, timeout, or server error, the provider rotates automatically to the next one. No manual intervention, no downtime.</p><h3>5. Cold Start: Subgraph Bootstrap + Event Replay</h3><p>When you start an indexer from scratch, you need a historical state. There are two obvious approaches: replay every event since Aave V3’s deployment, or pull the current state from an external source like The Graph.</p><p>Replaying from the beginning is complete but extremely slow -Aave V3 on Ethereum has millions of events. Relying entirely on a subgraph is fast but means trusting an external source for accuracy, and subgraphs can have their own indexing issues.</p><p>I combined both: seed user positions from the subgraph at a recent block height, then switched to event replay from that block forward. The subgraph gives you speed for the initial load, and event replay gives you accuracy going forward.</p><p>I chose this approach because replaying millions of blocks is resource-intensive and time-consuming. But more importantly, I wanted to make sure my event processing and calculations were actually correct before committing to a full historical sync. If there’s an inaccuracy in how events are processed, waiting for millions of blocks to sync just to discover a bug at the end would be a waste of time.</p><p>Also, starting from a recent snapshot let me improve the design much faster -and instead of spending time waiting for a full sync, I could focus on the other parts of the system, which turned out to be much more instructive. It was a deliberate tradeoff for my own learning process.</p><p>The tradeoff is real, though: the quality of your starting state depends entirely on the external source. Any inaccuracy in the subgraph’s data propagates into every subsequent position update. I noticed some inconsistencies in practice, which is why the project’s README lists this as a known limitation.</p><h3>6. Event Replay Safety and Idempotency</h3><p>If the indexer crashes while processing a chunk of events, that chunk gets retried on restart. Without safeguards, events can be processed twice -and for events like Mint or Burn, that means double-counting a user’s balance or incorrectly reducing it.</p><p>The fix is deduplication: every event on Ethereum can be uniquely identified by its transaction hash and log index -log index is needed because a single transaction can emit multiple events. Before processing any event, the indexer records this pair. If the same pair appears again during a retry, it is skipped.</p><p>This makes the event handler idempotent. You can replay the same block range as many times as you want. If an event has already been processed, running again won’t change the database state.</p><p>Combined with checkpoint recovery -saving progress per block range so the indexer resumes from where it left off- this gives you crash safety. The indexer can be stopped and restarted at any point without data corruption or double-counting.</p><h3>7. Position Tracking: Harder Than It Looks</h3><p>I initially assumed the Pool contract was the single source of truth for user balances. But because aTokens are real ERC-20 tokens, users can transfer them directly to other addresses without going through the Pool.</p><p>This means watching Pool events alone isn’t enough -the Pool doesn’t see direct aToken transfers between users. To keep positions accurate, you also need to track events on each individual token contract.</p><p>On top of that, the balances themselves aren’t straightforward. Aave doesn’t store actual token amounts -it stores “scaled” values. The relationship looks like this:</p><p>actualBalance = scaledBalance × liquidityIndex / RAY</p><p>The liquidity index grows over time as interest accrues, which means every user’s real balance increases passively -without any individual events being emitted.</p><p>Not all token events report values the same way. I track BalanceTransfer -Aave&#39;s custom event for aToken transfers between users- rather than the standard ERC-20 Transfer event. A single user-to-user transfer can emit multiple Transfer events: one for the actual move, and up to two more from address(0) for interest that accrued on each side since their last interaction. All of them carry actual amounts, so you&#39;d need to fetch the index separately and call rayDiv on each one. BalanceTransfer sidesteps all of this: it emits exactly once per transfer, includes the scaled amount directly alongside the index, and is much simpler to track and compute with.</p><p>Mint and Burn are more involved. Both events carry a balanceIncrease field -the interest that accrued on the user&#39;s position since their last interaction. For Mint, the emitted value is amount + balanceIncrease, so you subtract the accrued interest before dividing: (value - balanceIncrease).rayDiv(index). For Burn, the emitted value is amount - balanceIncrease, so you add it back first: (value + balanceIncrease).rayDiv(index).</p><p>Due to those calculations, you may have wei drift per event. You can even see this on-chain. Here’s an example transaction where the Supply event and the Mint event in the same transaction report values <a href="https://etherscan.io/tx/0x5e9eb74f9f6130d951053c5a7fefdae88b229d28e0a53c3604fff66124319e91#eventlog">that differ by 1 wei</a> due to Aave&#39;s internal fixed-point rounding (rayDiv/rayMul). This ±1 wei drift is a protocol-level property, not a bug -but it means the indexer has to expect and handle small discrepancies in every calculation.</p><h3>What’s Still Missing</h3><p>The project is far from done. Reorg handling isn’t implemented -the 20 block delay is a workaround, not a solution. Asset prices aren’t tracked yet, which means health factor calculation isn’t possible. The Pool and PoolConfigurator addresses are hardcoded, so if Aave governance deploys new contracts, the indexer won’t notice.</p><p>There’s also the subgraph accuracy issue I mentioned: any error in the bootstrapped data carries forward into all subsequent updates.</p><p>Most of what I learned from this project didn’t come from the Rust code itself -it came from understanding how the protocol actually works and why simple assumptions break quickly when you’re dealing with real on-chain data.</p><p>This is an actively evolving project -code and design decisions may change as I learn more.</p><p>More details and known tradeoffs in the <a href="https://github.com/dlr-a/aave-v3-tracker">Repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a15b5bcd7961" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/designing-an-aave-v3-indexer-challenges-and-insights-a15b5bcd7961">Designing an Aave V3 Indexer: Challenges and Insights</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Evolution of Aave: V2, V3, and V4]]></title>
            <link>https://medium.com/coinmonks/the-evolution-of-aave-v2-v3-and-v4-77c0be252190?source=rss-8048bbb30078------2</link>
            <guid isPermaLink="false">https://medium.com/p/77c0be252190</guid>
            <category><![CDATA[aave]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Dilara Hatipoğlu]]></dc:creator>
            <pubDate>Sun, 15 Feb 2026 10:55:09 GMT</pubDate>
            <atom:updated>2026-02-16T12:39:25.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swaeXmIs64IMNfIp2VIwOg.png" /></figure><p>Aave keeps getting better with every version: V2 laid the groundwork, V3 improved risk control, and V4 increases capital efficiency while unifying liquidity. We will look at Aave’s evolution in this article, but mainly focus on V4’s design. Readers should be familiar with lending protocols and how they work.</p><h3>How Aave Works</h3><p>At its core, Aave is a lending protocol where suppliers deposit assets into liquidity pools and receive <strong>aTokens</strong> in return, which represent their deposited balance and accrue interest over time. Borrowers take loans from those pools by depositing collateral worth more than the amount they borrow (overcollateralization). Each borrower has a health factor — a ratio that represents how safe their position is, calculated from their collateral value relative to their debt. A health factor above 1 means the position is sufficiently collateralized; when it falls below 1, the protocol allows liquidators to repay part of the debt in exchange for a discounted portion of the collateral — this mechanism keeps the system solvent.</p><p>Interest rates are not fixed; they are determined by the utilization of each pool. When a pool has plenty of available liquidity, borrowing is cheaper. As utilization rises and available liquidity decreases, rates increase sharply to incentivize repayments and attract new deposits. This dynamic model helps maintain balance between supply and demand while protecting the protocol from excessive risk.</p><p>Aave is governed by its community through on-chain governance. AAVE token holders vote on protocol changes — from adding new assets and adjusting risk parameters to deploying new markets. This means that many of the risk settings and parameters discussed throughout this article — such as asset listings, LTV ratios, and supply caps — are not hardcoded; they can be adjusted by governance over time as market conditions evolve.</p><h3>V2</h3><p>V2 was a solid foundation. It was a major upgrade that made the protocol more flexible, efficient, and user-friendly. It improved capital efficiency and gave users more control over their collateral and debt management.</p><p>The key theme across V2’s features is reducing the number of steps users need to manage their positions, while opening up new possibilities through flash loans and delegation.</p><ul><li><strong>Collateral Swap:</strong> Users can swap their collateral without withdrawing it. If the collateral becomes risky, it can be exchanged for another asset (e.g., a stablecoin) in a single transaction. This helps reduce liquidation risk.</li><li><strong>Repay With Collateral:</strong> Users can repay their debt directly with their collateral in a single transaction, rather than withdrawing, swapping, and repaying in multiple steps. This saves time and gas.</li><li><strong>Debt Tokenization:</strong> V2 represents each borrower’s debt as non-transferable on-chain tokens that automatically reflect accrued interest over time.</li><li><strong>Stable/Variable Rates:</strong> Borrowers can hold both stable and variable-rate debt for the same asset from the same wallet, giving them more control over their borrowing strategy. They can also switch between stable and variable rates at any time, depending on market conditions.</li><li><strong>Batch Flash Loans:</strong> V2 allows borrowing multiple assets in a single Flash Loan, enabling more complex DeFi strategies.</li><li><strong>Flash Liquidations:</strong> Previously, a liquidator needed their own capital to repay a borrower’s debt and earn the liquidation bonus. With flash loans, Aave V2 allows liquidators to use the protocol’s own liquidity to perform liquidations without needing upfront capital.</li><li><strong>Native Credit Delegation:</strong> Users can delegate their borrowing power to someone else. The delegatee borrows without collateral, while the delegator earns additional yield but takes the risk.</li></ul><h3>V3</h3><p>V3 builds on V2’s foundation with a strong focus on risk isolation and smarter capital efficiency. Treating blue-chip and long-tail assets the same way is not feasible given their different risk profiles. Because V2 applied uniform risk parameters to all assets in a shared pool, adding volatile or illiquid tokens would expose the entire pool — including blue-chip deposits — to their downside risk. This limited the range of assets the protocol could safely list. V3 addresses this with its new features. It also deprecated stable-rate borrowing, leaving variable rates as the only borrowing mode.</p><ul><li>I<strong>solation Mode:</strong> For protocol health and protecting the protocol from a crash, new or more volatile assets can’t be added directly. Isolation mode enables long-tail assets to be supported without systemic risk to the entire protocol. When users use an asset that is listed in Isolation Mode, they can only borrow specific assets (commonly stablecoins because their price won’t fluctuate as other assets), restricted by the protocol, and they can’t use any other asset as collateral alongside that isolated asset. Each isolated asset also has a debt ceiling — a cap on the total amount that can be borrowed against it — limiting the protocol’s exposure if that asset’s price collapses.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sDz6u6tSjTOaWtXMVzBVDA.png" /><figcaption><a href="https://aave.com/docs/aave-v3/overview">https://aave.com/docs/aave-v3/overview</a></figcaption></figure><ul><li><strong>Siloed Borrowing:</strong> While Isolation Mode restricts what can be borrowed <em>against</em> risky collateral, Siloed Borrowing restricts what happens when a user borrows a risky asset itself. When a user borrows an asset that is marked as siloed, they cannot borrow any other asset in the same position — their borrowing is “siloed” to that single risky token. However, they are free to use any collateral they choose, and there is no debt ceiling. This mechanism isolates the risk of volatile or potentially manipulable assets on the borrowing side rather than the collateral side.<br>The distinction is important: Isolation Mode protects the protocol from risky <em>collateral</em>, while Siloed Borrowing protects it from risky <em>borrowed assets</em>. Together, they give V3 a layered risk framework.</li><li><strong>Efficiency Mode (E-mode):</strong> While the features above restrict riskier assets, E-Mode does the opposite for correlated assets — it loosens parameters to improve capital efficiency. When assets are correlated in price (for example, different stablecoins like USDC and DAI, or different wrapped versions of ETH), the risk of one crashing relative to the other is low. E-Mode takes advantage of this by grouping correlated assets into categories and offering users who supply and borrow within the same category a significantly higher loan-to-value (LTV) ratio than standard mode. This means users can borrow more against their collateral and face fewer unnecessary liquidations from small price fluctuations between correlated assets.</li></ul><p>Due to strong risk management, V3 also has <strong>supply and borrowing caps</strong> for assets. A supply cap limits the total amount that can be deposited, reducing overexposure. A borrow cap limits the total amount that can be borrowed, preventing a single asset from draining liquidity or creating outsized insolvency risk.</p><p>While these mechanisms operate at the asset and position level, V3 also has structural risk separation at the market level. For example, the Core market is Aave’s main general-purpose pool, but it prioritizes safety and stability — not every asset or strategy belongs there. Listing a new asset on Core means exposing the entire pool’s liquidity to that asset’s risk profile, so governance is naturally conservative about what gets in.</p><p>This is where separate market instances come in. V3’s architecture allows governance to deploy independent markets on the same network, each with its own liquidity pool, asset list, and risk parameters tailored to a specific use case. A market built around leveraged staking strategies, for example, can offer LTVs far more aggressive than Core would allow, because its entire risk model is designed around highly correlated assets. For suppliers, these specialized markets can offer more attractive yields because they serve concentrated, high-demand borrowing activity. For borrowers, they provide access to higher leverage and parameters that wouldn’t be possible in a general-purpose pool.</p><h3>V4</h3><p>Before we look at the V4’s design, let’s think about why it is needed.</p><p>Despite V3’s design, a problem persisted: liquidity fragmentation. In V3, to isolate risk, liquidity was fragmenting; it operates through separate markets on different networks. Each market — such as Core or Prime on Ethereum — has its own liquidity pool and set of supported assets; each one has a unique risk profile. When users deposit assets, they do so into a specific market; other markets can’t access that liquidity. As a result, funds supplied to one market can only be borrowed within that same market and are not shared across others.</p><p>This structural separation creates a “bootstrapping” problem: to try new things or add new assets, a new market is needed, since the core market should not take those risks. And those new markets are competing with the core market, which brings significant challenges for them.</p><p>This creates a chicken-and-egg problem: Users won’t supply their assets if liquidity is insufficient, and liquidity will be insufficient if users don’t supply their assets; thus, other users won’t be able to borrow. Also, low liquidity carries its own risks, such as sudden interest rate spikes, and can cause a market to fail to survive, even if it has potential. Because of this design, liquidity wasn’t used efficiently and was fragmented between markets. Markets compete with each other for the same users and deposits.</p><p>Users also have to compare different markets to determine where their deposits will earn higher yields, since rates vary based on each market’s liquidity and risk profile. This makes the experience more complex for end users, who must actively monitor conditions and move capital accordingly, often leading to inefficient allocation.</p><p>V3 separated liquidity to isolate risk, and V4 isolates risk while unifying liquidity. It achieves this through three core elements: Liquidity Hubs, Spokes, and Risk Premiums. Now we can look at V4’s design.</p><h3>Liquidity Hubs</h3><p>V4 unifying liquidity through Liquidity Hubs. They are the liquidity source for Aave v4, and liquidity will be collected here rather than split across markets. Each L1/L2 will have at least one Hub, with the potential for multiple Hubs if governance requires distinct risk envelopes.</p><p>The Hub is responsible for system-wide accounting and enforces global invariants — for example, total borrows can never exceed total supply, and which Spokes are authorized to access which assets. It controls Spoke access through <strong>credit lines</strong> (how much a Spoke can borrow) and <strong>debit lines</strong> (how much it can add), defined by governance and adjustable based on Spoke performance and risk. This way, no single Spoke can drain more liquidity than the system allows.</p><p>Because liquidity is no longer fragmented, utilization improves — the same assets serve borrowing demand from multiple Spokes simultaneously, unlocking better rates for both suppliers and borrowers. From a supplier’s perspective, deposits go into the Hub’s shared pool rather than a specific market. This means suppliers are no longer forced to choose between markets or monitor which one offers the best yield. Their liquidity is automatically available to all authorized Spokes, and their returns reflect the aggregate borrowing demand across the system — weighted by the risk premiums each borrower pays.</p><p>From a supplier’s perspective, deposits go into the Hub’s shared pool rather than a specific market. This means suppliers are no longer forced to choose between markets or monitor which one offers the best yield. Their liquidity is automatically available to all authorized Spokes, and their returns reflect the aggregate borrowing demand across the system — weighted by the risk premiums each borrower pays.</p><h3>Spokes</h3><p>Users won’t be able to interact directly with Hubs. They will interact with the Spokes, and Spokes will interact with the Hubs. Users will withdraw or supply to the Spokes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QpE3IX_0iqMKgwhDl1UbbA.png" /><figcaption><a href="https://aave.com/blog/understanding-aave-v4s-architecture">https://aave.com/blog/understanding-aave-v4s-architecture</a></figcaption></figure><p>Spokes operate with their own local controls, including caps, emergency stops, accountings, and customizable risk parameters tailored to specific use cases. While they can optimize these settings independently, their access to shared liquidity is still governed by the Hub. This ensures flexibility at the Spoke level without compromising system-wide stability. They are modular; they don’t affect each other when added or removed.</p><p>V4 can support V3’s functionality and risk management. Isolation Mode and E-mode can be implemented in a Spoke while accessing the Hub’s liquidity, with the necessary limits, of course.</p><p>Each Spoke will make the entire system more efficient. Liquidity is better utilized across multiple use cases, while users access specialized features without fragmenting assets to the isolated markets. Instead of starting from scratch each time, innovation builds on proven infrastructure. Each successful Spoke makes the platform more attractive to future builders, creating positive feedback loops rather than zero-sum competition.</p><h3>Risk Premiums</h3><p>In V3, borrow rates were determined by the supply and demand; fixed for the borrowed asset. The rate was the same regardless of what collateral backed the position:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*af42zQo5Gro17xMydXl0iw.png" /><figcaption><a href="https://aave.com/blog/aave-v4-risk-premiums">https://aave.com/blog/aave-v4-risk-premiums</a></figcaption></figure><p>V4 changes this: the borrowing rate no longer depends solely on supply and demand. With User Risk Premiums, users pay a borrowing rate based on the quality of their collateral; everyone pays their risk. No one subsidizes riskier borrowers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9AhBXR_5LzM8n6eeo3XMaA.png" /><figcaption><a href="https://aave.com/blog/aave-v4-risk-premiums">https://aave.com/blog/aave-v4-risk-premiums</a></figcaption></figure><p>Assets now have a Collateral Risk score: low for blue-chip assets like ETH and higher for more volatile, long-tail assets. If someone has risky collateral, then they will pay a higher rate than those who use a blue-chip asset as collateral. The Hub sets a base rate based on supply and demand, like V3, but users pay an extra rate if their collateral’s quality is low. Their borrowing cost reflects the actual risk of their collateral, so each user pays for the risk they bring to the system.</p><p>This encourages users to provide higher-quality collateral, thereby improving overall system stability. Instead of covering the risk of weaker positions, users with ETH or other top-tier assets get better rates. At the same time, suppliers earn returns that match the risk of the collateral behind each loan, making the system more balanced for both borrowers and suppliers.</p><p>Risk Premiums operate at three levels.</p><p><strong>Asset Liquidity Premiums</strong> are the foundation. When an asset is added to the protocol, it is given a risk score based on its quality and liquidity. The safest assets receive very low scores (for example, 0%), while more volatile or less liquid assets receive higher ones (for example, 200% or more). For instance, ETH may have a 0% risk score, whereas a newer token could carry a significantly higher premium. Governance can revise these scores over time as market conditions evolve.</p><p><strong>User Risk Premiums</strong> reflect a user’s overall collateral quality. When a user uses multiple assets as collateral, the protocol calculates a weighted average based on each asset’s value and risk score. A user who supplies both a low-risk and a higher-risk asset will have a User Risk Premium that falls between the two asset premiums, with greater weight given to the asset that represents a larger share of their collateral.</p><p><strong>Spoke Risk Premiums</strong> capture the average risk within a Spoke. Since different Spokes can serve different use cases and user profiles, each Spoke maintains its own aggregate risk level. This allows borrowing rates to account not only for individual risk, but also for the broader risk environment of the Spoke.</p><p>As a result, borrowing costs reflect actual risk at the asset, user, and Spoke level.</p><p>Importantly, existing positions are not affected by changes to risk parameters — users remain under their previous configuration unless they take on additional risk (e.g., by borrowing more, withdrawing collateral, or disabling collateral). This lets governance change risk settings and introduce new reserve rules only for new positions, while existing positions keep their original parameters, avoiding unnecessary liquidations for existing users.</p><h3>Liquidation In V4</h3><p>In V3, when a borrower’s health factor falls below 1, a liquidator can repay part of the borrower’s debt and receive a portion of the collateral plus a fixed liquidation bonus. The amount that can be repaid is controlled by a fixed close factor, usually 50%, but which can reach 100% when the health factor drops very low.</p><p>While this mechanism is simple and protects the protocol from bad debt, it has limitations: the fixed close factor can cause over-liquidation even when a small repayment would restore solvency, and the static liquidation bonus does not reflect how risky a position is, giving liquidators the same incentive regardless of how far underwater the position has fallen.</p><p>V4 changes this liquidation mechanism with new dynamic parameters. Instead of a fixed close factor that can liquidate half or all of the collateral, it uses a <strong>target health facto</strong>r that repays only enough debt to restore the position to a target health factor set at the Spoke level, which prevents over-liquidation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5dVysSCPZh5OMaa_g92vg.png" /><figcaption><a href="https://aave.com/blog/aave-v4-liquidations">https://aave.com/blog/aave-v4-liquidations</a></figcaption></figure><p>V4 uses a <strong>variable liquidation bonus</strong> rather than a fixed one. The liquidation bonus scales with the risk of the position: the lower the health factor falls, the higher the bonus; the closer a position is to the liquidation threshold, the lower the bonus. It encourages liquidators to close risky positions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_4aVd1TDuxWDEq8wxrIdlw.png" /><figcaption><a href="https://aave.com/blog/aave-v4-liquidations">https://aave.com/blog/aave-v4-liquidations</a></figcaption></figure><p>V4 also takes a different approach to dealing with dust debt (very small remaining debt amounts that are inefficient to keep open because liquidation is uneconomical). If, after a liquidation, the remaining debt or collateral would fall below the DUST_LIQUIDATION_THRESHOLD , the liquidator must fully clear the position. This prevents the accumulation of small leftover balances.</p><h3>Conclusion</h3><p>Aave’s evolution from V2 to V4 reflects a clear architectural shift. V2 expanded usability and flexibility. V3 strengthened risk isolation to safely support a broader range of assets. V4 takes the next step by separating risk management from liquidity fragmentation — isolating risk at the Spoke level while unifying capital at the Hub level.</p><p>By introducing shared liquidity, more precise risk pricing, and dynamic liquidation mechanics, V4 aims to create a more scalable and capital-efficient lending architecture. Instead of forcing innovation into isolated markets that compete for liquidity, V4 enables specialized environments to build on a common liquidity base. Thus, the protocol can expand without sacrificing safety — aligning incentives across suppliers and borrowers.</p><p>The following sources were helpful in preparing this article:</p><ul><li><a href="https://aave.com/blog/understanding-aave-v4s-architecture">Understanding Aave V4&#39;s Architecture</a></li><li><a href="https://aave.com/blog/aave-v4-risk-premiums">Aave V4 Risk Premiums</a></li><li><a href="https://aave.com/blog/aave-v4-unified-liquidity-thesis">Aave V4 and the Unified Liquidity Thesis</a></li><li><a href="https://aave.com/blog/defi-os">How V4 Turns Aave Into DeFi&#39;s Operating System</a></li><li><a href="https://aave.com/blog/aave-v4-risk-isolation">How Aave V4 Handles Risk Isolation Without Fragmenting Liquidity</a></li><li><a href="https://aave.com/blog/aave-v4-liquidations">Aave V4&#39;s New Liquidation Engine</a></li><li><a href="https://medium.com/aave/the-aave-protocol-v2-f06f299cee04">The Aave Protocol V2</a></li><li><a href="https://aave.com/docs/aave-v4">Aave v4 Overview</a></li><li><a href="https://aave.com/docs/aave-v3/overview">Aave V3 Overview</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77c0be252190" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/the-evolution-of-aave-v2-v3-and-v4-77c0be252190">The Evolution of Aave: V2, V3, and V4</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scammers Have Entered Their Corporate Era]]></title>
            <link>https://medium.com/@dlra.htpgl/scammers-have-entered-their-corporate-era-fe62e0bbc785?source=rss-8048bbb30078------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe62e0bbc785</guid>
            <category><![CDATA[scam]]></category>
            <category><![CDATA[scams-to-avoid]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[scammer]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[Dilara Hatipoğlu]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 11:57:56 GMT</pubDate>
            <atom:updated>2025-11-10T11:57:56.503Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*rZPgxt7Z0sjeDaEmdUZmHw.png" /></figure><p>Scams have never looked so professional. Welcome to the corporate scam age!</p><p>As developers, we’ve all seen scammers on LinkedIn sending messages like, “Hey, I have a project for you — just run it on your computer.” And we all know that they are clearly scammers. They are obvious. They probably don’t have many connections or followers, and sometimes don’t even have profile photos. They are completely fake.</p><p>But what if I say this time they came with an account that has thousands of followers, is verified on LinkedIn, and that account was an HR account that works for a real company?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*KMsf40EO1rY625vnDm8AHA.gif" /></figure><p>First, an HR representative sent me a message stating that they are starting to develop a new blockchain project and are gathering a team. I checked their profile, and the company that they claimed to work for is real. When I searched, I found that the company has been active for years and is a real company.</p><p>When I sent a reply accepting the offer, they wanted my CV. After I sent it, we talked about the position I could work on, and that was the last for that day.</p><p>Four weeks passed, and they sent another message that said, ‘You’ve been listed as a tentative candidate.’ And said there would be interviews, skill assessment, and an onboarding process, and asked if I would be available. I sent an approval message for it as well.</p><p>After a couple of days, I received a GitHub invitation email and a message at the same time. The HR was saying, “The technical team sent the skill assessment to your GitHub already. Once you’ve solved those problems, you can schedule an interview with our tech recruiter.” And sent someone’s Calendly link.</p><p>The first thing I did was check the GitHub account that invited me to the repository. It was created 4 days ago, and the repository itself was under a different GitHub account that did not have the same name as the company.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*-h7tPiZqWII2ykYnAtF5Gg.gif" /></figure><p>However, after reviewing the repository, I noticed that the account committing was a genuine and active one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*aqHZ_PBHgcwGe6PS2Bf6GQ.gif" /></figure><p>Then I looked at the project’s package.json files. The first one was completely normal and didn’t have anything weird. However, the other package.json file contained a strange package that I had never seen or heard of before, named jsonretype.</p><p>After I searched for it, all I could find about that package was at the VeraCode, which states that it is malicious, and some GitHub repositories that also indicate that the package is malicious. Yes, they were scammers and tried to scam me professionally. For a moment, I even respected them for their efforts; they were the most convincing scammers I’ve ever seen. It was so realistic that I wouldn’t be surprised if someone messages me after I’ve published this write saying, “No, we are real.”</p><p>Furthermore, the repository’s GitHub account had a site and a LinkedIn account. It appears that the company is also legitimate, but it doesn’t even mention the blockchain. Probably, as they did with the other company, they were using this company to scam people as well.</p><p>They had strong production, were professional, and were very patient in reaching their goal. I mean, what kind of scammers wait for 4 weeks to become more believable?</p><p>Additionally, I attempted to search for that tech recruiter on LinkedIn and Google, but was unable to find anyone. Was that person using a private profile, or did they never exist?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*h569ziYC1cxGIxP31X_2sQ.gif" /></figure><p>Before GitHub came into play, everything seemed very corporate and legal. However, the reality is that they were using real companies to scam people and act like professionals, giving the impression of a corporation.</p><p>Also, while researching, I found several news articles covering similar scams — <a href="https://www.reuters.com/world/asia-pacific/how-north-korean-hackers-are-using-fake-job-offers-steal-cryptocurrency-2025-09-04/">Reuters</a> and <a href="https://coinmarketcap.com/academy/article/hackers-use-fake-web3-job-interviews-to-steal-cryptocurrency-from-job-seekers">CoinMarketCap</a>, for instance, have both reported on them. According to the news, scammers impersonate recruiters from well-known companies, such as Ripple and Kraken. After a brief back-and-forth about the supposed job and compensation, scammers encourage prospective applicants to visit obscure websites to run skills tests and record videos. Some instances set up fake Web3 companies with realistic job postings to steal crypto assets from unsuspecting applicants.</p><p>Long story short, don’t trust accounts that appear real and legitimate, or even if they are indeed real and legitimate, be sure to understand what you are installing and running on your computer. It may be a good choice to use isolated environments, such as Dev Containers or virtual machines, when running code from unknown sources. You can check out <a href="https://www.youtube.com/watch?v=5p8fQ45TwUs">Patrick Collins’s video</a> to learn more about them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe62e0bbc785" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How the EVM Works]]></title>
            <link>https://coinsbench.com/how-the-evm-works-e5a866a0c9a5?source=rss-8048bbb30078------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5a866a0c9a5</guid>
            <category><![CDATA[ethereum-virtual-machine]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[evm]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Dilara Hatipoğlu]]></dc:creator>
            <pubDate>Sun, 07 Sep 2025 09:19:27 GMT</pubDate>
            <atom:updated>2025-09-10T15:45:27.487Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RErQjaySeLbBVu4azee7oA.png" /></figure><h3>Introduction</h3><p>Although this article covers EVM from scratch, readers should be familiar with core Ethereum concepts and Solidity. We will begin with account types, then move on to transactions, transaction types, and transaction calldata. After that, we will cover gas and gas calculation, contract bytecode, stack, memory, storage, and opcodes. Finally, we will look at the smart contract execution and conclude with how smart contract storage works. I’ve added sources either in the article and at the end of it that helped me understand, and I hope they can help you too!</p><p>Also, this article won’t give you all of the details about the EVM, of course. EVM is much more than this. I chose not to split this article into parts because I want to give readers the option to take a break depending on their preferences, but please don’t forget to break! It can be overwhelming for beginners to read it all at once.</p><p><strong>DISCLAIMER:</strong> I wrote this article to understand better and explain complex Ethereum concepts as clearly and accurately as I could. Despite my best efforts, there may be misunderstandings or inaccuracies, either due to my interpretation or wrong information in the sources I used. If you notice any mistakes or misleading information, I’d truly appreciate it if you let me know.</p><h3>What Is the EVM?</h3><p>The Ethereum Virtual Machine (EVM) is the decentralized computation engine that enables smart contract functionality on Ethereum. It is responsible for processing smart contract executions and applying the resulting changes to Ethereum’s state, ensuring that each transition from one state to the next is valid. It operates as a quasi–Turing–complete virtual machine, executing low-level bytecode instructions and maintaining a consistent and verifiable state across a globally distributed network.</p><p>At its core, the EVM functions as a <strong>state machine</strong>, meaning it operates on a current state (the balances, contract storage, and other blockchain data) and <strong>deterministically</strong> transitions it to a new state based on the inputs it processes (transactions).</p><p><strong>Determinism</strong> ensures that given the same initial state and the same transaction data, every EVM node in the network will compute exactly the same new state. This property is crucial for consensus, as it guarantees that all participants in the network agree on the exact state of the blockchain after each block is processed. In this article, we will examine the EVM’s components, as shown below, in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VofSLWI64FBiIAi11jLn0A.png" /><figcaption><a href="https://takenobu-hs.github.io/downloads/ethereum_evm_illustrated.pdf">https://takenobu-hs.github.io/downloads/ethereum_evm_illustrated.pdf</a></figcaption></figure><h3>Accounts</h3><p>Basically, Ethereum has two account types: EOAs and Smart Contract Accounts. Even though both of them can receive, hold, and send ETH and tokens, and they can interact with smart contracts, they have differences:</p><p><strong>EOAs</strong></p><ul><li>Can initiate transactions</li><li>Can be created without cost</li><li>By default, they don’t have additional functionality except for sending ETH/Token transfers.</li><li>It consists of two cryptographic keys — a <strong>public key</strong> and a <strong>private key</strong> — which together are used to <strong>control and manage</strong> an account’s actions.</li></ul><p><strong>Smart Contract Accounts</strong></p><ul><li>Deploying a contract incurs a cost due to the use of network storage.</li><li>Can’t initiate transactions on their own.</li><li>EOAs can trigger the contract’s code, which may execute actions like transferring tokens or even creating a new contract.</li><li>They don’t have private keys. Their behavior is fully controlled by the rules defined in their smart contract code.</li></ul><p>Both of them have states that include nonce, balance, storageHash, and codeHash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_cWBlAsdTBj5uxJgTLTjQ.png" /><figcaption><a href="https://ethereum.org/developers/docs/accounts/">https://ethereum.org/developers/docs/accounts/</a></figcaption></figure><p>nonce: The nonce is a counter that tracks the number of transactions sent from an account to ensure each one is processed only once and to prevent replay attacks where signed transactions are repeatedly broadcast and re-executed. For EOAs, it starts at 0 and increases by 1 with each transaction sent from an account. Smart Contracts’ nonces start from 1 after the EIP-161, and their nonces only increase if they create a new contract - this means that when a contract calls another contract’s function, it won’t increase.</p><p>balance: Balance of the account.</p><p>storageHash: Also known as the storage root, it is a 256-bit hash that summarizes the data stored in a smart contract’s storage. This data is organized in a special structure called a Merkle Patricia Trie, where each 256-bit key is first hashed with Keccak-256 and then mapped to its RLP-encoded value. The storage root represents the hash of the trie’s root node, which allows large data sets to be represented by a fixed 32-byte hash, keeping the global state database compact, manageable, and efficient. Any change in the storage is immediately reflected in the hash, making modifications easily detectable. This hash enables users, including light clients, to verify specific values without downloading all the data. Because the trie keeps old nodes, the network can safely reconstruct past states and handle forks. If no storage has been set, the trie (and thus its hash) is <strong>empty by default</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gu7eT8KXvUchxaDRFmiGgw.png" /><figcaption><a href="https://www.youtube.com/watch?v=kCswGz9naZg">https://www.youtube.com/watch?v=kCswGz9naZg</a></figcaption></figure><p>codeHash: It is the hash of an account&#39;s code in the EVM. For contract accounts, it is the executable code stored in the state database. This code runs when the contract receives a call and is immutable after deployment. It guarantees the smart contract’s integrity—any change in the code would change the hash. The hash also enables efficient storage, as identical code used by multiple contracts is stored only once, saving space. During execution, the EVM uses the codeHash to access the contract’s code quickly. This design ensures that contracts remain secure and verifiable across the network. For externally owned accounts (EOAs), the codeHash is simply the <strong>hash of an empty string</strong> by default.</p><p>Before the Ethereum’s Pectra Upgrade’s <a href="https://medium.com/coinmonks/what-is-eip-7702-5c3fd347107d">EIP-7702</a>, EOAs weren’t able to have code and storage. But now, they can delegate code for their accounts, and their code field can look like this: 0xef0100 || address (address is the delegated smart contract’s address). Because EIP-7702 works as an upgradable contract, now EOAs can have storage. So, it changes some rules: EOAs can execute more complex transactions if they have delegated contracts, and they can have storage. This means that the rules listed above are true for EOAs without a delegated contract, but only for <strong>default</strong> EOAs. For the rest, we will think EOAs as default EOAs.</p><h3>Transactions</h3><p>Transactions are cryptographically signed instructions from accounts. They make changes to the state of the Ethereum network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgYTgI7VjZpUll_1ijUpFQ.png" /><figcaption><a href="https://ethereum.org/developers/docs/transactions/">https://ethereum.org/developers/docs/transactions/</a></figcaption></figure><p>Transactions that modify the EVM’s state must be shared across the entire network. Once a validator executes the transaction, the updated state is then shared with all other nodes. To change the EVM’s state, a transaction must be included in the validated block; otherwise, the state won’t change.</p><p>A transaction contains the following details:</p><ul><li>from – the sender’s address that signs the transaction. This must be an EOA, since contract accounts cannot initiate transactions.</li><li>to – the recipient’s address. If it belongs to an EOA, the transaction is a simple transfer. If it’s a contract account, the transaction triggers the execution of the contract’s code.</li><li>signature – a cryptographic identifier proving the sender’s authorization. It is generated when the sender’s private key signs the transaction.</li><li>nonce - a sequential counter that tracks how many transactions have been sent from the account.</li><li>value – the amount of ETH to send from the sender to the recipient, expressed in wei (1 ETH = 1e18 wei).</li><li>calldata – an optional field for including transaction data.</li><li>gasLimit – the maximum number of gas units the transaction can consume. The EVM defines the gas cost for each computational operation.</li><li>maxPriorityFeePerGas - the highest tip per gas unit the sender is willing to give to the validator.</li><li>maxFeePerGas - the absolute maximum fee per gas unit the sender is willing to pay, which includes both baseFee and maxPriorityFeePerGas.</li></ul><p>There are different Functional Types of Transactions:</p><ul><li>Regular transactions: a transfer from one account to another.</li><li>Smart contract creation: Sending a transaction with no recipient (to field is empty) and including the contract’s bytecode in the calldata field to deploy it on-chain.</li><li>Execution of a contract: Sending a transaction to an existing contract address, often with calldata, to trigger its code. The “to” field points to the address of the smart contract.</li></ul><p>Also, we have Protocol-Defined Transaction Types.</p><h3>Transaction Types</h3><p>Ethereum supports multiple transaction types, each introduced to solve specific problems and improve the network’s usability, efficiency, or scalability. The motivation behind creating these transaction types was to make transactions cheaper, more predictable, and more flexible as the network evolved. They are helpful because they enable developers and users to leverage new features, including reduced gas costs with access lists, predictable fees, cheaper data publishing, and account abstraction compatibility.</p><p>The transaction type is defined by a leading byte (for example, 0x01, 0x02, etc.), which tells the Ethereum Virtual Machine (EVM) how to interpret and process the transaction. Formally, transactions are interpreted as TransactionType || TransactionPayload, where the TransactionType is a single byte value between 0x00 and 0x7f (allowing up to 128 different transaction types), and the TransactionPayload is the remaining byte array whose structure depends on the transaction type. Based on the TransactionType value, the EVM knows which rules to use for decoding and executing the transaction. You can check out <a href="https://eips.ethereum.org/EIPS/eip-2718">EIP-2718</a> for more details. The main transaction types are as follows:</p><h3>Legacy Transactions (Type 0x0)</h3><p>Legacy transactions are the original form of Ethereum transactions that have been used since the network was first launched. These transactions do not utilize access lists (provided with type 1 transactions), and they also don’t support the fee structure introduced by EIP-1559.</p><h3>EIP-2930 Transactions (Type 0x01)</h3><p>These transactions include an accessList parameter, which lists the addresses and storage keys the transaction intends to access. This can help reduce gas costs, especially for transactions that interact with complex smart contracts. However, these transactions do not support the fee market changes introduced by EIP-1559.</p><h3>EIP-1559 Transactions (Type 0x02)</h3><p>They have become the standard transaction type on the Ethereum network by improving fee predictability and efficiency. These transactions brought a major change to Ethereum’s fee model by splitting transaction fees into two parts: a <strong>base fee</strong>, which is burned, and a <strong>priority fee</strong> (tip) for incentivizing validators. Type 2 transactions begin with the byte 0x02 and include fields like maxPriorityFeePerGas and maxFeePerGas, giving users better control over how much they&#39;re willing to pay.</p><h3>EIP-4844 Transactions (Type 0x03)</h3><p>These transactions are optimized for handling “blob” data (Binary Large Objects), offering a more cost-effective method for Layer 2 rollups to publish their data to the Ethereum network. They include additional fields, such asmax_fee_per_blob_gas, which defines the highest blob gas fee the sender is willing to pay, while blob_versioned_hashes listing the versioned hashes of the blobs linked to the transaction. This mechanism provides a cheaper and more efficient way for rollups to post data to Layer 1, significantly reducing costs and enhancing Ethereum&#39;s scalability.</p><h3>EIP-7702 Transactions (Type 0x04)</h3><p>These transactions are designed to be forward-compatible with account abstraction. They allow EOAs to temporarily act like smart contract accounts without permanently changing the account type or losing EOA functionality. They include an authorization_list parameter, which specifies the address of the smart contract the EOA will point to for delegating its authority. After this transaction, the EOA’s code field will have the address of the delegated smart contract.</p><h3>Transaction Calldata</h3><p>As we saw above, transactions have a field named calldata. It is an unlimited byte array (if it doesn’t exceed the block gas limit) that serves as the read-only data field of a transaction, carrying the input for a message call — typically to a smart contract. This field is used to specify which function on the contract to execute and what arguments to pass to that function. You can think of this field as an instruction set, like saying, “I want to call this function with these parameters” to a smart contract call. For a smart contract call, it includes the <strong>function selector</strong> and parameters for that function.</p><p><strong>Function Selector:</strong> The First 4 bytes of the calldata tell the smart contract which function to call. It is generated by taking the first 4 bytes of the Keccak-256 hash of the function’s signature (e.g., &quot;transfer(address,uint256)&quot;).</p><p><strong>Encoded Parameters (everything after the function selector):</strong> These are the arguments for the function. Each parameter is encoded and padded to be exactly 32 bytes long, and they are appended one after another in the order they are listed in the function signature. According to ABI encoding rules, even when the actual value is smaller — like an address or a small integer — it is still padded with leading zeros to ensure it fits the fixed 32-byte format. Let’s try to decode the calldata, it looks like this:</p><p>0xa9059cbb000000000000000000000000ab4c51adf7e1824c07d4cc90ccea35947d80f20700000000000000000000000000000000000000000000000000000012dbf9ea00</p><p>The first 4 bytes, which are 0xa9059cbb for this case, are the function selector. It is ERC-20’s transfer(address,uint256) function. That function’s Keccak-256 hash is this: a9059cbb2ab09eb219583f4a59a5d0623ade346d962bcd4e46b11da047c9049b, and as you can see, calldata includes the first four bytes of it. This function accepts two parameters.</p><p>First parameter is the recipient address, 32 bytes long: 000000000000000000000000ab4c51adf7e1824c07d4cc90ccea35947d80f207. The address is the last 20 bytes: ab4c51adf7e1824c07d4cc90ccea35947d80f207, so our recipient is: 0xab4c51adf7e1824c07d4cc90ccea35947d80f207.</p><p>The second parameter is the amount. So, the next and final 32 bytes are: 00000000000000000000000000000000000000000000000000000012dbf9ea00. Our actual value is 12dbf9ea00, which, when converted from hexadecimal to decimal, equals 81,000,000,000. Because USDC has 6 decimal places, it means that someone transfers 81,000 USDC.</p><p>If we look at this transaction at <a href="https://etherscan.io/tx/0x0957637a6672e1cd1151c496f8611011426490501da32a024d0b0e241ea0ca99">Etherscan</a>, when we click to show more, it will show us this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMBILEEoXfCcRoymUAd-Fg.png" /></figure><p>You can see the original calldata by changing the view input to the original:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CRa_H-h-qnj_mQLWeguRbQ.png" /></figure><p>And if you click decode input data, it will show decoded data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wq10RZ43rZvFYcfz_Z_MvA.png" /></figure><p>Now we know what transactions, accounts, and calldata are. It’s time to understand what gas is for Ethereum, and why it matters.</p><h3>What is Gas?</h3><p>Gas is Ethereum’s unit to measure the computational and storage resources needed to execute operations on its blockchain. You can think of it as gasoline for a car. Before we dive into how gas works and calculate, let’s think about <em>why we need gas</em>.</p><h3>Why Is Gas Needed?</h3><p>Put simply, a system or programming language is considered Turing complete if it can execute any program. But this ability has a risk that some programs may run forever, and we can’t know in advance whether they will stop — this is known as the <em>halting problem</em>.</p><p>Ethereum operates as a single-threaded machine without a scheduler, meaning that if it becomes stuck in an infinite loop, it would become unusable. That’s why the EVM operates as a <strong>quasi</strong>-Turing-complete state machine; it is quasi because it won’t operate if there is not enough gas. The gas mechanism solves the halting problem.</p><p>Imagine a scenario where Ethereum doesn’t require gas for computation, and everyone can send transactions without having to pay. Someone can cause an execution that might (accidentally or maliciously) run forever, which means that it can prevent users from using Ethereum. So, besides incentivizing the validators, we need gas to address the halting problem, prevent DDoS attacks, and reduce spam transactions. It protects the network from malicious actors and prevents anyone from causing an infinite loop in Ethereum, even by mistake.</p><h3>EVM Gas Calculation</h3><h3>Setting Gas For Transaction</h3><p>Users can set the maximum amount of gas they’re willing to use for a transaction, but they should be careful while setting it because if they set gas less than needed for execution, they can cause an <strong>out-of-gas</strong> exception. In such a case, their transaction won’t end up successfully, the EVM will roll back all state changes, and gas won’t be refunded to them, which means that they will pay for the failed transaction. If they set the gas higher than needed, the remaining gas will be refunded to them at the same rate of purchase.</p><p>Let’s say 30,000 gas is required for a transaction, but you set it to 40,000. 30,000 gas will be consumed during execution, and you will get the remaining 10,000 gas in ETH. However, if you set 25,000 for the same transaction, the execution will be halted mid-execution, the state changes are discarded, consuming all 25,000 gas, and you will receive an out-of-gas error.</p><p>The gas fee formula is:</p><p>Gas fee = units of gas used * (base fee + priority fee)</p><p>The EVM determines the base fee based on the network congestion. Gas prices are typically expressed in <strong>gwei</strong>, a smaller unit of ETH. One gwei equals <strong>one-billionth of an ETH</strong> — that’s <strong>0.000000001 ETH</strong> or <strong>10⁻⁹ ETH</strong>.</p><p>Simple transfer requires 21,000 units of gas. Let’s assume that Alice wants to send Bob 1 ETH. The base fee is 5 gwei, and we added 1 gwei for priority:</p><p>21,000 * (5 + 1) = 126,000 gwei</p><p>If we <a href="https://eth-converter.com/">convert</a> it, we will see that our transaction’s fee is <strong>0.000126 ETH</strong>. Alice’s balance will decrease by <strong>1.000126 ETH,</strong> but ****Bob will receive 1 ETH. The difference (0.000126 ETH) goes to cover the transaction cost, burned base fee + validator’s tip.</p><h3>Base Fee</h3><p>For a transaction to be accepted into a block, the gas price the user offers can’t be less than the current base fee. The user must pay at least the base fee. Every block has a base fee that isn’t based on the current block itself, but is derived from the blocks that came before it, which helps make transaction costs more predictable for users. When a block is produced, its base fee is burned, meaning the base fee doesn’t go to the validators.</p><p>The base fee is determined using a formula that compares the gas used in the previous block to a target block size. If the previous block exceeds the target, the base fee increases proportionally but by no more than 12.5% per block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FPgQCmaZrKC9-IsaP5Sng.png" /><figcaption><a href="https://ethereum.org/developers/docs/gas/">https://ethereum.org/developers/docs/gas/</a></figcaption></figure><p>Similarly, if a block uses less gas than the target, the base fee will decrease proportionally but by no more than 12.5% per block. Because the increase can become very high over time, it discourages users from sending too many transactions, causing the fee to decrease again eventually. So, we probably won’t see many long periods of full blocks because the base fee rises quickly as blocks get full.</p><h3>Priority Fee</h3><p>Priority fee is a tip to incentivize validators to include a transaction in the block. If there were no tips, validators might choose to propose empty blocks since they’d still get the block reward. Even small tips encourage validators to include transactions. To expedite your transaction, you can add a higher tip to outbid competing transactions.</p><h3>Max Fee</h3><p>When users send a transaction on Ethereum, they can set an optional maximum amount they are willing to pay per unit of gas — this is called the maxFeePerGas. This value represents the highest total fee they agree to pay for the transaction&#39;s execution. This max fee must cover both the network’s <strong>base fee</strong>—a minimum fee that gets burned—and the optional <strong>tip</strong> that incentivizes validators. If the actual cost (base fee + tip) is less than the maxFeePerGas, the difference is refunded to the sender, ensuring they only pay what is necessary while still allowing flexibility to prioritize their transaction.</p><p>The maxPriorityFeePerGas is the highest tip you’re willing to pay to the validator, but they might receive less depending on the baseFee. This is because the total gas fee you’re willing to pay—maxFeePerGas—caps the combined Base Fee and Priority Fee.</p><p>For instance, if your transaction sets a maxFeePerGas of 12 gwei and a maxPriorityFeePerGas of 4 gwei, and the current baseFee is 9 gwei, then the block validator receives 3 gwei as a tip, and the 9 gwei baseFee is burned. Your transaction will only be valid in blocks where the baseFee is 12 gwei or less.</p><h3>Smart Contract Interaction Cost</h3><p>We’ve already mentioned that there is something called calldata, which we send in a transaction to tell the EVM which function we want to call with what parameters. Because of the extra computation and storage involved, interacting with a smart contract costs more gas than sending a regular transaction between accounts.</p><p>When a contract call is made, the EVM must:</p><ul><li>Read and parse the calldata.</li><li>The dispatcher sequentially compares each function selector until it finds a match</li><li>Run any required checks, such as payable restrictions.</li><li>Execute the function’s logic.</li><li>Prepare and return the result, or revert if necessary.</li></ul><p>Unlike a simple ETH transfer, which has a fixed cost of <strong>21,000 gas</strong>, contract interactions incur additional costs for every step of execution. But what do we mean by “execution”? This refers to the actual running of the compiled contract bytecode, instruction by instruction, at the opcode level (We will explain what opcodes are later). Each opcode has its own gas cost, and the total gas you pay depends on how many and which opcodes are executed during your call.</p><h3>Smart Contract Bytecode</h3><p>When we deploy a smart contract, the EVM doesn’t store the Solidity code. Instead, it stores <strong>bytecode</strong> that is interpreted as a list of opcodes by the EVM. It is a series of instructions that the EVM will interpret and execute. You can think of it as saying to EVM, “This is how we will treat calls, these are our rules and instructions for you to interpret the calls.” In other words, it is the smart contract itself.</p><p>The contract’s bytecode doesn’t fit directly in the account’s code field. We are dividing the smart contract’s bytecode into two: <strong>creation-time</strong> and <strong>runtime</strong>. Creation bytecode is the initialization code generated by the Solidity compiler that runs <em>only</em> during contract deployment. It contains both the logic to execute the constructor and the embedded runtime bytecode of the contract. When executed, it first allocates storage for state variables, runs the constructor alongside checking the payable (if defined), and applies any initial values. Then, it returns runtime bytecode. This returned runtime bytecode is what gets stored on-chain at the contract’s state, while the creation bytecode itself is discarded after deployment and never executed again.</p><p>Runtime bytecode doesn’t include the constructor. In contrast to creation bytecode, it is stored on the chain permanently and will be executed on every interaction with the contract.</p><p>A whole bytecode looks like the following. It is the bytecode of Remix’s 1_Storage.sol contract:</p><p>608060405234801561001057600080fd5b50610150806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80632e64cec11461003b5780636057361d14610059575b600080fd5b610043610075565b60405161005091906100a1565b60405180910390f35b610073600480360381019061006e91906100ed565b61007e565b005b60008054905090565b8060008190555050565b6000819050919050565b61009b81610088565b82525050565b60006020820190506100b66000830184610092565b92915050565b600080fd5b6100ca81610088565b81146100d557600080fd5b50565b6000813590506100e7816100c1565b92915050565b600060208284031215610103576101026100bc565b5b6000610111848285016100d8565b9150509291505056fea26469706673582212202d1e6a790360e1ea57d40e5b95d84472b35aeaeb43c4a9c381a5cb3f091b3f1c64736f6c63430008130033</p><p>It consists of 2 parts (creation-time and runtime).</p><p>Creation-time part is: 608060405234801561001057600080fd5b50610150806100206000396000f3. (We will look at how a creation-time bytecode works and what it does later.)</p><p>And the runtime part is: 608060405234801561001057600080fd5b50600436106100365760003560e01c80632e64cec11461003b5780636057361d14610059575b600080fd5b610043610075565b60405161005091906100a1565b60405180910390f35b610073600480360381019061006e91906100ed565b61007e565b005b60008054905090565b8060008190555050565b6000819050919050565b61009b81610088565b82525050565b60006020820190506100b66000830184610092565b92915050565b600080fd5b6100ca81610088565b81146100d557600080fd5b50565b6000813590506100e7816100c1565b92915050565b600060208284031215610103576101026100bc565b5b6000610111848285016100d8565b9150509291505056fea26469706673582212202d1e6a790360e1ea57d40e5b95d84472b35aeaeb43c4a9c381a5cb3f091b3f1c64736f6c63430008130033</p><p>It is the smart contract itself, which is stored permanently on the chain, that resides in the account’s code field, as we’ve seen before. This is the code that is executed when you call the smart contract. The EVM executes it when you send a transaction to it. These are the rules and instructions you gave the EVM.</p><p>When a Solidity contract is compiled, a small <strong>metadata</strong> section is appended to the end of the bytecode: fea26469706673582212202d1e6a790360e1ea57d40e5b95d84472b35aeaeb43c4a9c381a5cb3f091b3f1c64736f6c63430008130033 part of our contract. The metadata embedded in a contract contains information like the Solidity version, compiler settings, source files, and a hash of the metadata itself. This allows developers to verify a contract’s source code and the compilation environment. Block explorers, such as Etherscan, read the metadata hash from the bytecode and fetch the metadata (e.g., from IPFS or Swarm). Metadata allows developers to confirm that a deployed contract matches its original source code by comparing the on-chain bytecode with the compiled source code.</p><h3>Smart Contract Call Overview: From Calldata to Execution</h3><p>(I believe this part will prepare you for the more challenging part later. Keep in mind the overview, we will dive into technical details later.)</p><p>But how is this runtime code executing when we call it? Let’s assume that we paid enough for gas for our transaction. EVM starts executing the bytecode from the beginning.</p><ul><li>First, the dispatcher extracts the 4-byte function selector from calldata using opcodes. If your function selector doesn’t equal the 4-byte, it will revert.</li><li>The dispatcher starts to sequentially compare the function selector with the contract’s function selectors. If a selector matches <em>exactly</em> one of them, execution jumps to that function’s <strong>wrapper</strong> entry point. If none match, the dispatcher either jumps to the fallback() / receive() function if the contract has one; if not, it will revert.</li><li>Function Wrapper makes payable check if the function is non-payable. If msg.value is not zero, it will revert. (This is why non-payable functions cost extra gas, because they have a payable check.)</li><li>The wrapper unpacks the calldata and jumps to the function body, which is then run. All operations required by the function body, including state changes, are executed.</li><li>Once the function logic finishes, it returns to the wrapper, which prepares and sends the return data back to the caller.</li></ul><p>But <em>really</em>, <em>how</em> does EVM read the bytecode? It’s time to dive deeper technically!</p><h3>Stack, Memory, and Storage in the EVM</h3><p>When the EVM executes bytecode, it relies on stack, memory, and storage, each serving a distinct purpose and having its own gas costs.</p><p>Since we have a problem that resembles a “chicken-and-egg” scenario, I will first provide an overview of stack, memory, and storage. Don’t worry if you don’t understand them at first; we will revisit them with more detailed steps. I didn’t give all the details and how they work because it can be intangible for readers without seeing the execution and technical details, which can make it hard to understand. So, we will explain them as we continue.</p><h3>Stack</h3><p>The stack is where we perform most of our computations and operations. It is an essential component of the EVM’s execution model, and it <strong>only</strong> exists during execution. EVM instantiates a new and empty stack for every transaction, and it is cleared at the end of each transaction.</p><p>It functions as a <strong>volatile, last-in-first-out (LIFO) structure.</strong> A popular analogy for the stack is a stack of plates. You always add a new plate on top, and when you need one, you take the plate from the top as well. That’s how the stack works.</p><p>It temporarily holds data that <strong>opcodes</strong> operate on. Each element in the stack is <strong>256 bits (32 bytes)</strong>, and the stack can accommodate up to <strong>1024 items</strong>. But EVM can only reach the top 16 words of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MjwXzjX7aJgHBvYl2eZeIg.png" /><figcaption><a href="https://takenobu-hs.github.io/downloads/ethereum_evm_illustrated.pdf">https://takenobu-hs.github.io/downloads/ethereum_evm_illustrated.pdf</a></figcaption></figure><p>The cheapest places, gas-wise, to do things are going to be on the stack. Working on the stack is cheaper than working on the memory and storage. Since it cannot hold complex types such as arrays or mappings, these are stored in memory. All operations on the stack consume gas.</p><h3>Memory</h3><p><strong>Memory</strong> is temporary, volatile storage available only during the execution of a transaction; it resets at the end of each call. EVM instantiates a new and empty memory for every transaction, as it does for the stack. It is structured in 32-byte <strong>words</strong> and manipulated through opcodes like MLOAD and MSTORE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2A4i5Uc5TB0BIleXnbOT7w.png" /><figcaption><a href="https://takenobu-hs.github.io/downloads/ethereum_evm_illustrated.pdf">https://takenobu-hs.github.io/downloads/ethereum_evm_illustrated.pdf</a></figcaption></figure><p>Solidity reserves four 32-byte slots:</p><ul><li>0x00 - 0x3f (64 bytes): scratch space for temporary operations like hashing.</li><li>0x40 - 0x5f (32 bytes): free memory pointer, indicating where new memory can be allocated. It points to 0x80 initially.</li><li>0x60 - 0x7f (32 bytes): zero slot. It is used as an initial value for dynamic memory arrays and should never be written to.</li></ul><p>Storing data in memory can be costly, depending on the value being stored, but it is relatively much cheaper than storage.</p><p>We can store <strong>dynamically-sized</strong> values during execution in memory, such as arrays or strings. Unlike the stack, memory is expandable and accessible at arbitrary offsets, making it suitable for temporary data that doesn’t fit in the fixed-size stack slots. This is why we need two volatile environments: the stack is restricted in size, and memory is not. Additionally, we are working at the top of the stack, and as a result, we must always maintain our value at the top of the stack. With memory, we can read the value from memory anytime we need it. It will make sense after you see how they work.</p><h3>Storage</h3><p>Ethereum’s <strong>Storage</strong> is the blockchain’s persistent state, and it is extremely expensive. It maps 256-bit keys to 256-bit values, storing contract variables, balances, and other on-chain data. Unlike stack and memory, storage is <strong>non-volatile</strong> and is maintained in a <strong>Merkle Patricia Trie</strong> for efficient verification and global state management. Updating storage is more gas-intensive because it writes data to the blockchain’s permanent state, which must be recorded by all nodes, making it costly.</p><p>We distinguish between two types of storage access: <strong>cold</strong> and <strong>warm</strong>. Accessing a storage slot for the first time is considered a cold access and is several times more expensive than warm access. Re-accessing the same slot counts as a warm access, which incurs a lower cost. You can check out the gas cost difference from <a href="https://www.evm.codes/?fork=cancun#55">here</a>. (Don’t worry about this site or SLOAD, you will see what it is and how it works in a bit.)</p><p>If you choose the warm (without setting an input), it will show 100 gas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*8kg173G6xikpLZiRTh46Pw.png" /></figure><p>If you choose the cold, it will show 2200:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*Wt9mJrQRlAGpvzTSqYJN8A.png" /></figure><p>This is the main reason why we should be careful about storing something in the storage or accessing a storage slot in our code; we can cause costly transactions for users if we can’t manage it carefully.</p><h3>Opcodes</h3><p>We’ve seen that our smart contracts are actually bytecodes. This bytecode is made up of <strong>opcodes</strong> — low-level instructions that the EVM can execute. Basically, your Solidity code is compiled into a sequence of opcodes, and <strong>each opcode has a fixed gas cost</strong> defined by the EVM. Executing them consumes gas from the transaction’s gas limit. You can check all of the opcodes from <a href="https://www.evm.codes/">here</a>.</p><p>ADD (01): Addition operation, costs <strong>3</strong> gas.</p><p>MSTORE (52): Save word to memory, costs <strong>3</strong> gas.</p><p>SSTORE (55): Save word to storage, costs <strong>100</strong> gas.</p><p>An opcode is a single, low-level instruction that tells the EVM to perform a specific operation — this could be arithmetic, logical computation, flow control, or interacting with the stack, memory, or storage. Each opcode executes deterministically and consumes a predefined amount of gas.</p><p>Now it’s time to concretize opcodes with stack, memory, and storage! Let’s start with the stack and how it works with opcodes by adding two numbers.</p><h3>Adding Numbers With Opcodes</h3><p>To do the calculation, we will give our numbers to the stack using the PUSH1 opcode. As you can understand by its name, it pushes the value we gave it. We will use the EVM <a href="https://www.evm.codes/playground">playground</a>.</p><p>Change format to the Mnemonic and paste it:</p><p>PUSH1 0x01 PUSH1 0x02 ADD</p><p>After running, you will see that when you click the ‘Step into’ button for the first time, the stack will have just one. The second click will push 2 to the stack, and our stack will have 2 at the top (You can also check the playground’s stack). Here is the visualization of the 3 steps to understand better:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PioQqSZ2kC5YGPUNhwfPug.png" /></figure><p>Notice that we are always pushing to the top of the stack. Lastly, after executing the ADD opcode, our stack will just have 3 because the ADD opcode is taking 2 items at the top of the stack, adding them, and pushing the result to the stack. If you try to add a POP opcode at the end of our opcodes, you will see that it removes the 3 from the stack, because we are always working at the top of the stack.</p><p>Did you realize that we’ve pushed 3 opcodes to just add two numbers? Imagine a more complex function. How many opcodes and data will we push? Does that make sense to store data in the memory for you now? Since you can access up to 16 elements in the stack, repeatedly duplicating or swapping our data doesn’t make sense, as it can complicate and increase the cost of execution.</p><h3>Extracting Function Selector</h3><p>Before we look at the whole smart contract opcode, let’s take another little step by extracting the function selector from calldata! Paste the following opcodes to the playground:</p><p>PUSH0</p><p>CALLDATALOAD</p><p>PUSH1 0xE0</p><p>SHR</p><p>But this time we also should give the calldata, we can use the calldata we’ve seen in the earlier part: 0xa9059cbb000000000000000000000000ab4c51adf7e1824c07d4cc90ccea35947d80f20700000000000000000000000000000000000000000000000000000012dbf9ea00</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ItP1wogk-JK3tVf4m0u0LQ.png" /></figure><p>The first thing we did was push zero to the stack. Why? The reason is that the following opcode CALLDATALOAD. It is loading the calldata but asking for the start point, which means we should provide that opcode with a byte offset that points to where to load from. Our function selector is at the start of the calldata, so we push the zero for the start point.</p><p>After we execute theCALLDATALOAD, our calldata will be at the top of our stack. We are pushing 0xe0, but why? Similar to CALLDATALOAD, SHR requires the number of <strong>bits to</strong> shift the bits towards the least significant one to the right, and the value. e0 equals 224 in decimal, and it is equal to 28 bytes. Lastly, we are executing the SHR (shift right) instruction, which shifts bits to the right in the given value, and our stack has just a function selector! This is how we obtain the function selector from calldata.</p><h3>Deconstructing Smart Contract</h3><p>We will learn opcodes (not all of them, of course) by looking at the execution of the smart contract. This is where we will use all of the information we’ve gained from earlier parts!</p><p>To make it simpler, we have a basic smart contract:</p><pre>pragma solidity ^0.8.0;</pre><pre>contract FavoriteNumber {<br>    uint256 favoriteNumber;</pre><pre>    function setNumber(uint256 number) public payable {<br>        favoriteNumber = number;<br>    }</pre><pre>    function readNumber() public view returns(uint256) {<br>        return favoriteNumber;<br>    }<br>}</pre><p>Before we look at how it executes the functions, let’s look at the creation time. This is our contract’s full bytecode, which includes the creation time: 608060405234801561000f575f80fd5b506101438061001d5f395ff3fe608060405260043610610028575f3560e01c80633fb5c1cb1461002c578063b63d343f14610048575b5f80fd5b610046600480360381019061004191906100ba565b610072565b005b348015610053575f80fd5b5061005c61007b565b60405161006991906100f4565b60405180910390f35b805f8190555050565b5f8054905090565b5f80fd5b5f819050919050565b61009981610087565b81146100a3575f80fd5b50565b5f813590506100b481610090565b92915050565b5f602082840312156100cf576100ce610083565b5b5f6100dc848285016100a6565b91505092915050565b6100ee81610087565b82525050565b5f6020820190506101075f8301846100e5565b9291505056fea2646970667358221220d823bccee8dccf566cd706facb5ddd8ce5c41a0e75dd27a2b3b4812d92c3355164736f6c63430008140033</p><p>The fe opcode, as you can see in the <a href="https://www.evm.codes/">evm.codes</a>, is INVALID. The bytecodes until that opcode (first one to that opcode, actually) are the creation-time bytecode, so we will look at this part first: 608060405234801561000f575f80fd5b506101438061001d5f395ff3.</p><p>Let’s see this by trying to run it in Remix! Paste the contract into Remix, deploy it, and then click the <strong>debug</strong> button at the console.</p><p>Remember, creation-time bytecodes are responsible for setting the contract’s initial state (e.g, state variables or constructor) and returning the runtime code. Once it reaches the RETURN opcode, the EVM will stop executing creation-time code and store the returned bytes as the contract’s <strong>runtime code</strong>. Now we will start to look at opcodes.</p><h3>Setting the Free Memory Pointer</h3><p>The first thing it does is set the free memory pointer:</p><p>PUSH1 0x80 PUSH1 0x40 MSTORE</p><p>Now we have 0x80 in the 0x40 memory address. Our memory now looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fXAaYVguzQG2gEFVrS_0SA.png" /></figure><p>You can also verify that by looking at the Remix’s memory. Although Remix is not setting the 0x60 address in memory, we know that the slot is full of zeros; we will examine this more in detail later.</p><p>This is just creation-time bytecode, and we are not using the free memory pointer again now, but while we’re at it, let’s find out what it is.</p><h3>What Is the Free Memory Pointer?</h3><p>Firstly, <em>why</em> do we need something like that? Why are we reserving a memory address to store the next free memory address?</p><p>We are using memory to store our data, which can exceed 32 bytes. Let’s assume we don’t have any reserved addresses in memory and have stored our first data at address 0. Next time, when we need to store data, how will we know we won’t overwrite a memory address? We can just write to the 0 address again, but this will cause us to lose our first value. This is the free memory pointer’s responsibility: It always gives us the “free” memory address. Thus, we can be sure that our data storage does not lead to memory corruption. Steps look like:</p><ul><li>First free memory address is 0x80 by default (because earlier slots are reserved, we can’t use them for our data), and it is initialized at the beginning of the execution. That’s why you are seeing 6080604052 is the beginning of the bytecode.</li><li>When we need to store something, we use MLOAD opcode with 0x40 to obtain the free memory address. MLOAD reads the 0x40 address and returns the data at that address.</li><li>If we want to store something in memory starting at 0x80, the free memory pointer at 0x40 will move forward. When storing data in memory, space is always allocated in 32-byte words. Even if the value is smaller than 32 bytes, it still occupies a full word, so the free memory pointer moves to the next slot (for example, from 0x80 to 0xA0). The free memory pointer only updates when <strong>dynamic</strong> data, such as strings or arrays, is stored.</li><li>Next time we use the MLOAD with 0x40, it will give 0xA0, and this process continues each time we store data to memory.</li></ul><p>Free memory pointer says, “Here is the beginning of the free memory address. You can store your data starting from that address, and make sure you are not overwriting any data or losing your data”.</p><h3>Checking The Value</h3><p>Let’s continue to read our opcodes!</p><p>CALLVALUE DUP1 ISZERO PUSH2 0x000f JUMPI</p><ul><li>CALLVALUE opcode pushes the value sent with the transaction.</li><li>DUP1 is duplicates the first item of the stack, so our stack now has 0,0. (If you check all the opcodes, we have most DUP16.)</li><li>ISZERO is checks if it is zero or not, it pushes 1 if the value is zero, 0 if it’s not.</li><li>We are pushing 0x000f to the stack; you will see in a bit why.</li><li>JUMPI is moves execution to the destination by obtaining the destination at the top of the stack. So, we will jump to the0x000f, because this is our destination.</li></ul><h3>Program Counter</h3><p>JUMP, JUMPI, and JUMPDEST are important opcodes, and you will see them a lot. We can’t just execute all of the opcodes one by one; sometimes, we need to jump <em>over</em> them. Do you remember what we’ve said earlier? After our function selector matches (we will see these opcodes later), we need to jump to the function wrapper. We are not executing all of the opcodes one by one for each call. Let’s see how these opcodes work, but before we look at them, we need to know the <strong>program counter</strong>.</p><p>The program counter (PC) is a special register in the EVM that keeps track of <strong>which instruction in the bytecode should be executed next</strong>. Normally, it is incremented by one byte to point to the next instruction. However, some instructions modify this behavior. For example, <strong>PUSHx</strong> instructions are longer than a single byte, so the PC skips over the additional bytes that represent their parameters. You can think of PC as a directive for the EVM; it indicates the next opcode to the EVM, allowing it to execute the correct sequence.</p><ul><li>JUMP instruction does not increment the PC in the usual way; instead, it <strong>sets</strong> the PC to a new location specified by the value at the top of the stack. So, it takes the value at the top of the stack and moves execution to that point.</li><li>JUMPI is jump’s conditional version. It conditionally changes the program counter. It looks at the top 2 values of the stack: the first one is the destination, and the second one is the value which should be different than zero. If the second value is equal to zero, it won’t change the program counter, and execution won’t jump to the destination. So, it <em>jumps if</em> the second value is not zero.</li><li>JUMPDEST is the destination for JUMP and JUMPI. If their destination is <strong>not</strong> JUMPDEST, they <strong>can’t</strong> jump to the destination they obtained from the stack. Execution always jumps to the JUMPDEST.</li></ul><p>As you can see, if you click on the next step, it is the JUMPDEST.</p><h3>Deploy Code Preparation</h3><p>Before we jump to our destination, look at those 3 opcodes:</p><p>PUSH0 DUP1 REVERT</p><p>If we didn’t jump (that means if we didn’t send value), execution will revert. We jumped over them and now continue to execute.</p><p>After reaching theJUMPDEST, we are removing the first item of the stack with POP opcode. Now it’s time to prepare our runtime bytecode!</p><p>PUSH2 0x0143 DUP1 PUSH2 0x001d PUSH0 CODECOPY</p><p>First, we pushed the 0x0143 value, 323 in decimal, and duplicate it. You will see why we duplicated it later. After that, we pushed the 0x001d, 29 in decimal. And lastly, we pushed 0. Thus, we have all of the inputs for CODECOPY. It requires three inputs: the destination offset for the copy code, the byte offset within the code to copy, and the size of the data to copy. So, we are saying that opcode “here is the memory address&#39; start point you will write, this is the byte you should start to copy from bytecode, and it is the size of the bytecode you should copy”. With our items, we say “start writing to memory address 0, start from the bytecode&#39;s byte 29, and copy 323 bytes after that”. After executing that opcode, you will see our runtime in the memory.</p><p>Lastly, we have 2 opcodes to execute:</p><p>PUSH0 RETURN</p><p>We are pushing 0 to the stack, because the RETURN opcode needs 2 inputs: byte offset in memory (we just store to 0), and the size of the bytes to return, which we have 0x0143. That’s why we used it earlier DUP1 for that data, because CODECOPY receives it, and we still need that for RETURN opcode.</p><p>We’ve finished the creation-time bytecode! Now it is time to look at the runtime bytecode!</p><h3>Runtime Bytecode</h3><p>Our runtime bytecode is: 608060405260043610610028575f3560e01c80633fb5c1cb1461002c578063b63d343f14610048575b5f80fd5b610046600480360381019061004191906100ba565b610072565b005b348015610053575f80fd5b5061005c61007b565b60405161006991906100f4565b60405180910390f35b805f8190555050565b5f8054905090565b5f80fd5b5f819050919050565b61009981610087565b81146100a3575f80fd5b50565b5f813590506100b481610090565b92915050565b5f602082840312156100cf576100ce610083565b5b5f6100dc848285016100a6565b91505092915050565b6100ee81610087565b82525050565b5f6020820190506101075f8301846100e5565b9291505056fea2646970667358221220d823bccee8dccf566cd706facb5ddd8ce5c41a0e75dd27a2b3b4812d92c3355164736f6c63430008140033</p><p>As you can see in the Remix, our runtime bytecode is in the memory. Additionally, if you click on the transaction in the console and scroll to the bottom, you will see that our output is exactly the same. First, we will call the setNumber function. We will call it by just clicking the button, but as you know, calldata will be: 0x3fb5c1cb0000000000000000000000000000000000000000000000000000000000000007</p><h3>Calling the setNumber Function</h3><p>When you click debug, Remix starts at the point where we will store the number. To view all executions, drag the execution slider back to the beginning.</p><p>Like our creation bytecode, the first thing the runtime bytecode does is set up the free memory pointer to 0x80. After that, it checks our calldata’s size:</p><p>PUSH1 0x04 CALLDATASIZE LT PUSH2 0x0028 JUMPI</p><p>If calldata is less than (LT) 4, we will revert, as you can see the below opcodes. If it’s not less than 4, which it is not, we are jumping:</p><p>PUSH0 CALLDATALOAD PUSH1 0xe0 SHR</p><p>We are extracting the function selector. It is exactly the same as we did earlier! After that, we are comparing our function selector with one of the contract’s selectors:</p><p>DUP1 PUSH4 0x3fb5c1cb EQ PUSH2 0x002c JUMPI</p><p>It is the same selector with the function we want to call! So, we will jump.</p><p>The remaining opcodes are more complex and difficult to understand individually for beginners. So, we won’t examine all the opcodes individually; instead, we will focus on what the EVM aims to do. The diagram below shows all of the opcodes and is numbered by the jumps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhZqQtCZSmVFRxaFjBGbwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oU-ohEdkmvLTlyvIEDjviQ.png" /></figure><p>Before we look at our opcodes, let’s explain SWAP. This is the first time we saw it. Actually, the name tells it all; it replaces the stack’s items with each other. SWAP1 exchanges the 1st and 2nd stack items, SWAP3 exchanges the 1st and 4th items, etc. The items that will be exchanged depend on the number of the SWAP opcode. If you check out evm.codes, you will see that it is up to 16 withSWAP16, like DUP opcodes.</p><ul><li><strong>1:</strong> In this part, the contract is preparing to decode the calldata. It calculates the parameter section by subtracting 4 (the selector size) from the total calldata size (36), giving 32 bytes, which is exactly one word. Then it adds back the 4 to get 36, the endpoint of the parameters. Both values are pushed to the stack: 4 marks where the parameters begin, and 36 marks where they end, which is also useful for validation. At the same time, the contract also pushes the future jump destinations (41 and 46), setting up the flow.</li><li><strong>2:</strong> Here, the contract checks whether the calldata actually contains the expected 32-byte parameter. It does this by calculating the parameter length asend - start = 32, then using SLT to test if it’s smaller than 32. Since 32 &lt; 32 is false, the result is 0, and ISZERO turns it into 1, allowing the jump to proceed. If the calldata had been shorter, the check would fail, and execution would jump to the revert block.</li><li><strong>3–4:</strong> This block is responsible for decoding the function parameter. I want you to look carefully at the CALLDATALOAD, that&#39;s why it&#39;s underlined. Unlike our past CALLDATALOAD, this time, it is giving 4 as input, because it doesn&#39;t want the function selector; it is jumping over it. So, through stack juggling, it prepares the offset 4, which is where the parameter begins in calldata (right after the selector). The CALLDATALOAD(4) retrieves the parameter value (7 in this case). After cleaning up the stack, it pushes the return address (0x00b4) and jumps to the next block (0x0090).</li><li><strong>5–6–7–8–9–10–11:</strong> This section performs a compiler-added safety check by rearranging the stack and comparing the parameter to itself. After passing the check, it cleans up the stack and jumps to the next destination.</li><li><strong>12–13:</strong> The value 7 is then stored instorage[0], updating the contract’s state, and execution stops.</li></ul><p>Now let’s call the readNumber and see what it does!</p><h3>Calling the readNumber Function</h3><p>Before we look at the opcodes, I want you to click our transaction at the console. You will see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7obhqTT9tyav7CpAYvPB2A.png" /></figure><p>And as it says, calling a view or pure function costs gas if they called by a smart contract. They are free if they are called externally by an EOA.</p><p>Drag the execution slider to the beginning to see all executions. Like our setNumber function, it starts by setting the free memory pointer. After that, it checks the calldata size, extracts the function selector, and compares it. But unlike before, this time it doesn’t jump; it continues to check if it is equal to the second function selector. Because this time it is equal, it jumps to the function wrapper. We won’t look at them opcode by opcode this time, but you can look at them yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTg3h0_H4I_xRsoTKI0kaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSZiStUgHCui-qVDymvnIw.png" /></figure><ul><li><strong>1:</strong> The function first checks CALLVALUE, which pushes the amount of Ether (in wei) sent with the call onto the stack. Since the function is not payable, if any Ether is sent with the call, the execution will revert.</li><li><strong>2:</strong> The code then pushes the jump destinations onto the stack and jumps to one of them. This ensures the correct execution flow.</li><li><strong>3:</strong> It loads the value stored at the slot 0 in storage (SLOAD 0) and pushes it to the stack. This is our favoriteNumber.</li><li><strong>4:</strong> It reads the free memory pointer from the memory position 0x40. The address is0x80, which is where the return data will be written.</li><li><strong>5–6–7:</strong> These opcodes mainly prepare values on the stack, arranging offsets and jump destinations. In short, they push/dup/swap the needed data, remove unnecessary items, and finally jump to the correct destination.</li><li><strong>8:</strong> The loaded number is written into memory at the address 0x80 using MSTORE. This makes the value ready to be returned.</li><li><strong>9:</strong> Cleans the stack.</li><li><strong>10:</strong> It calculates the memory offset (0x80) and length (0x20 = 32 bytes), then executes the RETURN opcode, which takes the memory offset and data size as input. Sends the favorite number back to the caller.</li></ul><p>Did you realize that we didn’t update our free memory pointer even though we’ve stored our number at the memory address 0x80As we mentioned earlier, we perform free memory pointer updates if we are storing <strong>dynamic</strong> data. Let’s try to run something that will update our free memory pointer!</p><p>But before that, if you would like to read more about deconstructing a smart contract, Openzeppelin has a great series about it!</p><ol><li><a href="https://blog.openzeppelin.com/deconstructing-a-solidity-smart-contract-part-i-introduction-832efd2d7737">Deconstructing a Solidity Contract — Part I: Introduction</a></li><li><a href="https://blog.openzeppelin.com/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c">Deconstructing a Solidity Contract — Part II: Creation vs. Runtime</a></li><li><a href="https://blog.openzeppelin.com/deconstructing-a-solidity-contract-part-iii-the-function-selector-6a9b6886ea49">Deconstructing a Solidity Contract — Part III: The Function Selector</a></li><li><a href="https://blog.openzeppelin.com/deconstructing-a-solidity-contract-part-iv-function-wrappers-d8e46672b0ed">Deconstructing a Solidity Contract — Part IV: Function Wrappers</a></li><li><a href="https://blog.openzeppelin.com/deconstructing-a-solidity-contract-part-v-function-bodies-2d19d4bef8be">Deconstructing a Solidity Contract — Part V: Function Bodies</a></li><li><a href="https://blog.openzeppelin.com/deconstructing-a-solidity-contract-part-vi-the-swarm-hash-70f069e22aef">Deconstructing a Solidity Contract — Part VI: The Metadata Hash</a></li></ol><h3>Storing a String in Memory</h3><pre>pragma solidity ^0.8.0;</pre><pre>contract HelloWorld {<br>    function helloWorld() public pure returns(string memory) {<br>        return &quot;hello world&quot;;<br>    }<br>}</pre><p>This time, we won’t go into all the details; we will just see that our memory pointer is updating. If you deploy the above contract on Remix and try to call helloWorld function and click debug, and click step into continuously, you will see that our free memory pointer updates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TgjRwL8aoCM_7LZ9FWMfdQ.png" /></figure><p>And this is what you will see at the Remix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*k_nTp4qfhyN_utAr2KdVvw.png" /></figure><p>b is equal to 11, which is our string’s length, and it is at the 0x80. We are storing our string at the 0xa0. As you can see, we are not writing anything in the 0 memory address, 0x20, and 0x60. Let’s now look at how we are using them shortly!</p><h3>Memory Scratch Space</h3><p>If you don’t know how EVM stores mappings, skip this part, continue reading, read the storage part about mappings, and come back here!</p><pre>pragma solidity ^0.8.0;</pre><pre>contract MyMapping {<br>    mapping(uint256 user =&gt; uint256 level) userLevel;</pre><pre>    function store(uint256 user, uint256 level) public {<br>        userLevel[user] = level;<br>    }</pre><pre>    function getLevel(uint256 user) public view returns(uint256) {<br>        return userLevel[user];<br>    }<br>}</pre><p>I’ve deployed this contract on Remix, stored a user 1 with level 2, and called getLevel with parameter 1. If you did these steps and click the step into button repeatedly, you will see that we are storing 1 in the memory address 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*GBT4kdCEjlHI0u0rSAhviw.png" /></figure><p>For KECCAK256 opcode, we are giving it memory address 0, and 40 size. It returns a hash, which is our storage slot, and we obtain our level with SLOAD opcode. You can look at the opcodes yourself and understand the process better!</p><h3>Memory Zero Slot</h3><p>We’ve said 0x60 is our zero slot; we shouldn’t write anything there, it is reserved for the compiler’s expectations. And as we’ve seen until now, our compiler doesn’t store anything in there. Let’s prove that we are reading this slot with a dynamic array!</p><pre>contract ZeroSlotTest {<br>    <br>    function makeEmptyArray() public pure returns (uint256[] memory) {<br>        uint256[] memory arr;<br>        return arr;<br>    }<br>}</pre><p>Paste this contract, deploy it, and call the function! After clicking the step into button continuously, you will see that we have 0x60 at the top of the stack, and we are executing the MLOAD opcode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*Ccy8em0UZfuIny23j_E5Qw.png" /></figure><p>Remember, MLOAD take the item at the top of the stack (0x60 for our case), and loads the data it has, which is zero, as the slot’s name suggests. Imagine a scenario in which you would write a number in that slot. What might happen if your code reads this slot by aiming for zeros?</p><p>If you want to understand better how memory works during execution, here is a fantastic blog series:</p><ul><li><a href="https://noxx.substack.com/p/evm-deep-dives-the-path-to-shadowy?s=r">Part 1 — Function Selector Deep Dive</a></li><li><a href="https://noxx.substack.com/p/evm-deep-dives-the-path-to-shadowy-d6b?s=r">Part 2 — Memory in the EVM</a></li><li><a href="https://noxx.substack.com/p/evm-deep-dives-the-path-to-shadowy-3ea?s=r">Part 3 — Storage in the EVM</a></li><li><a href="https://noxx.substack.com/p/evm-deep-dives-the-path-to-shadowy-5a5?utm_source=%2Fprofile%2F80455042-noxx&amp;utm_medium=reader2&amp;s=r">Part 4 — Storage Opcodes In the Go Ethereum (Geth) Client</a></li><li><a href="https://noxx.substack.com/p/evm-deep-dives-the-path-to-shadowy-a5f?utm_source=%2Fprofile%2F80455042-noxx&amp;utm_medium=reader2&amp;s=r">Part 5 — Delegate Call Deep Dive</a></li></ul><h3>How Does Smart Contract Storage Work?</h3><p>You can think of a smart contract’s storage as a huge array consisting of 256-bit keys to 256-bit values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XvpoYUlWCC6C8MJ_ECJBQ.png" /><figcaption><a href="https://takenobu-hs.github.io/downloads/ethereum_evm_illustrated.pdf">https://takenobu-hs.github.io/downloads/ethereum_evm_illustrated.pdf</a></figcaption></figure><p>As we saw before, it uses <strong>Merkle Patricia Trie,</strong> and every change to the contract storage will affect the EVM state, so the block hash too. Now we will look at how EVM stores our storage variables.</p><p>If my explanation isn’t enough, Rareskills has some excellent posts on the topic, and I’ve used their visualizations, which explain smart contract storage with diagrams.</p><ol><li><a href="https://rareskills.io/post/evm-solidity-storage-layout">https://rareskills.io/post/evm-solidity-storage-layout</a></li><li><a href="https://rareskills.io/post/solidity-dynamic">https://rareskills.io/post/solidity-dynamic</a></li></ol><h3>Primitive Types</h3><p>Primitive types in Solidity, such as uint, int, bool, and address, are stored in <strong>individual 32-byte storage slots</strong>. Each slot can hold a single value up to 32 bytes. If the type is smaller than 32 bytes, multiple values may be <strong>packed into the same slot</strong> to save storage and reduce gas costs. For example, several uint8 or bool variables declared can share a single 32-byte slot if they can fit in a slot. Here is an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z9qKaKRaJnTie1LAmdZjRQ.png" /><figcaption><a href="https://rareskills.io/post/evm-solidity-storage-layout">https://rareskills.io/post/evm-solidity-storage-layout</a></figcaption></figure><p>Because addresses are 20 bytes long, we still have 12 free bytes in slot 0. So, other variables can share the same slot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vn_Rh5kAgS2tOuRZ8JqWwg.png" /><figcaption><a href="https://rareskills.io/post/evm-solidity-storage-layout">https://rareskills.io/post/evm-solidity-storage-layout</a></figcaption></figure><p>Notice that our variables are declared <strong>consecutively</strong>. If we declare a uint256 variable after the owner variable, slot 0 would only contain the 20-byte-long address. Also, packed variables cost more gas to access, since the EVM needs extra steps beyond a normal sload. Packing is only efficient if the variables are usually read together in the same transaction, so they can share cold load costs.</p><p>The EVM assigns <strong>each storage variable a slot index</strong>. All data is stored sequentially, one item after another, beginning with the first state variable, except for dynamic-sized types, which are handled differently. The first state variable declared in a contract is stored in slot 0, the second in slot 1, and so on.</p><p>Also, const and immutable variables are not stored in the contract’s storage; instead, their values are embedded directly in the runtime bytecode. This means accessing them does not require SLOAD or SSTORE operations, making them much cheaper in terms of gas.</p><h3>Dynamic-sized Types</h3><h3>Arrays</h3><p>Arrays in Solidity can be <strong>fixed-size</strong> or <strong>dynamic-size</strong>.</p><h3>Fixed-size Arrays</h3><p><strong>Fixed-size arrays</strong> store their elements consecutively in sequential storage slots. Let’s say we declared an array in our contract as the first variable, a uint256[3] array starting at slot 0, which will store its elements at slots 0, 1, and 2. But if our array were uint8[3], all of the elements would be placed in the base storage slot (in our case, slot 0) because all of them can fit in a slot. When multiple elements can fit in the same slot, the compiler will package them until there is no space to store.</p><h3>Dynamic-size Arrays</h3><p>Dynamic arrays can grow at runtime, and we can’t know how much space we should reserve for them. To prevent storage collision or overwrite, we are storing them in a different style from the fixed-size arrays. A dynamic array’s base slot only stores the <strong>length</strong> of the array. We start to store the array’s elements from the hash of the base slot. So, the first element’s slot will be the hash of the base slot, and the second element’s slot will be incremented by one from the first, and so on.</p><p>Base slot: <strong>length</strong> of the array.</p><p>Element’s slot: keccak256(base slot) + index (keccak256(0) for our case).</p><p>When you want to access an element of the array, EVM will take the hash of the base slot and add the index of the element to this hash. For example, assume that you want to access an element at index 5. EVM will first take the hash of the base slot: keccak256(base slot), and then add the index of the element: keccak256(base slot) + 5.</p><h3>Nested Arrays</h3><p>We are not using or seeing them often, but Solidity also has nested arrays. They are arrays that hold other arrays.</p><h3>Fixed-size Nested Arrays</h3><p>Fixed-size nested array looks like uint256[3][2], which means that it has two arrays, each of which holds an array that has 3 elements. It is storing like fixed-size arrays, elements placed consecutively in the slots starting from the base slot. If the elements’ types are like uint32, the compiler packages them as it did for the fixed-size arrays.</p><h3>Dynamic-size Nested Arrays</h3><p>We are repeating the dynamic-array storage process for dynamic nested arrays. First, we hash the base slot and add the sub-array’s index to it. After that, we are hashing it and adding the element’s index to it. It will be our slot.</p><p>initialHash: keccak256(base slot) + index(sub-array)</p><p>Slot: keccak(initialHash) + index(element’s index)</p><p>If we want to access uint256[1][2]:</p><p>initialHash: keccak256(base slot) + index(1)</p><p>Slot: keccak(initialHash) + index(2)</p><p>Here is the visualization of the process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPTnhGHZ-r3GeXhsaFLtUA.png" /><figcaption><a href="https://rareskills.io/post/solidity-dynamic">https://rareskills.io/post/solidity-dynamic</a></figcaption></figure><h3>Mappings</h3><p>Mappings are <strong>key-value stores</strong> that do not occupy consecutive storage slots. Instead, the key and the mapping’s slot are hashed together to obtain the slot where the value lies or write to it: keccak256(abi.encodePacked(key, base slot))</p><p>By hashing the key with the mapping’s base slot, the EVM ensures fast lookups and eliminates collisions with unrelated variables. Mappings do not store keys themselves; instead, only the values are placed in storage at the computed slot. To retrieve a value, the EVM repeats the same computation and loads the data from the resulting slot. Mappings are limited to storage-based state variables and are not allowed in memory contexts such as function arguments or return values.</p><h3>Nested Mappings</h3><p>For nested mappings, there is an extra step compared to regular mappings. First, the initial slot is computed with keccak256(abi.encodePacked(key, baseSlot)). Then, this result is combined with the second key and hashed again to derive the final storage slot:</p><ul><li><strong>initialHash</strong> = keccak256(abi.encodePacked(key, baseSlot))</li><li><strong>slot</strong> = keccak256(abi.encodePacked(secondKey, initialHash))</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71MWzM_3lV6SGmZGh7bBrA.png" /><figcaption><a href="https://rareskills.io/post/solidity-dynamic">https://rareskills.io/post/solidity-dynamic</a></figcaption></figure><h3>Strings</h3><p>We are categorizing strings into two types: <strong>short</strong> strings and <strong>long</strong> strings. If a string is equal to or less than 31 bytes, it is a short string; conversely, if it is longer than 31 bytes, it is a long string. EVM treats them differently when storing them. Let’s start with the short strings.</p><h3>Short Strings</h3><p>We store the length of the string at the lowest-order byte (right-aligned) of its slot, but then multiply it by 2. So, our lowest-order byte will be length * 2 (you will see why). Because short strings can be as long as 31 bytes, they can fit in the same slot beside their length, in other words, their base slot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2f5yWx2_pwpxSKmk2H7KA.png" /><figcaption><a href="https://rareskills.io/post/solidity-dynamic">https://rareskills.io/post/solidity-dynamic</a></figcaption></figure><p>16 is equal to 22, and if we divide it by two, we can have our actual string length: 11.</p><h3>Long Strings</h3><p>Because they are at least over 31 bytes, they can’t fit in the same slot with their length, so we need another slot or slots to store them. Unlike the short strings, the lengths of long strings multiply by two and then <strong>add one</strong>. So, their base slot’s last byte will be: (length * 2) + 1. Why don&#39;t we just store the length itself? The reason for this is that the compiler will look at the last bit and understand it is a long or short string. Short strings’ lengths are always even, and long strings’ lengths are always odd -their last bit will be <strong>one</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gLOPWB1QJbvG75JolSCqOg.png" /><figcaption><a href="https://rareskills.io/post/solidity-dynamic">https://rareskills.io/post/solidity-dynamic</a></figcaption></figure><p>Long strings don’t place in their base slot. Instead, we start to store them starting from the keccak256(base slot), and it continues like keccak256(base slot) + 1 until we store all of the string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7UcQYABNowSGw-2YYNsbw.png" /><figcaption><a href="https://rareskills.io/post/solidity-dynamic">https://rareskills.io/post/solidity-dynamic</a></figcaption></figure><h3>Bytes</h3><p>In Solidity, bytes is a dynamic type, and its storage layout is handled in the same way as a string. Short byte arrays (31 bytes or less) have their data and length packed directly into the base slot. The length is stored in the last byte of the slot as (length * 2). For long byte arrays (more than 31 bytes), the base slot contains the encoded length((length * 2) + 1), and the actual data is stored in a sequence of slots starting at keccak256(baseSlot).</p><h3>Structs</h3><p>A struct definition in Solidity is only a type declaration and does not use up a storage slot; storage is only allocated once an actual variable of that struct type is <strong>declared</strong>. So, the code below does not occupy any slot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*GIw-A9hBOMmioUXFuDhq_A.png" /></figure><p>It starts to use the slot when you declare it: User private theUser</p><p>Let’s say it is our first declared variable in our contract. Slot 0 will hold the balance, and slot 1 will hold the wallet. If we had another value, it would be at slot 2. We are storing the struct fields sequentially.</p><p>It changes when we have a dynamic type within the struct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*QSYAGpu0oSFF6g47g7SJGA.png" /></figure><p>When we declare it (assume it is the first variable), the wallet’s slot will be 0, and the mapping’s base slot will be 1. If we assign a value to the mapping, it will be stored at the keccak256(abi.encodePacked(key, baseSlot)).</p><h3>Conclusion</h3><p>In conclusion, the Ethereum Virtual Machine is a sophisticated state machine that ensures deterministic and secure execution of smart contracts. By leveraging the stack, memory, and storage, it balances efficiency and flexibility, while code and storage hashes maintain integrity and verifiability. Understanding these core mechanisms is essential for anyone building or analyzing Ethereum smart contracts, as it provides insight into gas costs, storage optimization, and contract behavior. Mastering the EVM also provides a clear understanding of how Ethereum enforces security, manages resources, and enables predictable contract execution across a decentralized network.</p><p>Here are some of the resources that I found especially helpful in understanding this topic:</p><p><a href="https://noxx3xxon.notion.site/The-EVM-Handbook-bb38e175cc404111a391907c4975426d">The EVM Handbook | Notion</a></p><p><a href="https://rareskills.io/post/evm-solidity-storage-layout">https://rareskills.io/post/evm-solidity-storage-layout</a></p><ul><li><a href="https://rareskills.io/post/solidity-dynamic">Storage Slot III (Complex Types) | By RareSkills</a></li><li><a href="https://ethereum.org/developers/docs/accounts/">Ethereum accounts | ethereum.org</a></li><li><a href="https://ethereum.org/developers/docs/transactions/">Transactions | ethereum.org</a></li><li><a href="https://ethereum.org/developers/docs/gas/">Ethereum gas and fees: technical overview | ethereum.org</a></li><li><a href="https://eips.ethereum.org/EIPS/eip-1559">EIP-1559: Fee market change for ETH 1.0 chain</a></li><li><a href="https://eips.ethereum.org/EIPS/eip-2930">EIP-2930: Optional access lists</a></li><li><a href="https://eips.ethereum.org/EIPS/eip-4844">EIP-4844: Shard Blob Transactions</a></li><li><a href="https://reth.rs/run/faq/transactions/">Transaction types</a></li><li><a href="https://www.evm.codes/about">EVM Codes</a></li><li><a href="https://www.cyfrin.io/glossary/smart-contract-metadata">Cyfrin Glossary: Smart Contract Metadata</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5a866a0c9a5" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/how-the-evm-works-e5a866a0c9a5">How the EVM Works</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is EIP-7702?]]></title>
            <link>https://medium.com/coinmonks/what-is-eip-7702-5c3fd347107d?source=rss-8048bbb30078------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c3fd347107d</guid>
            <category><![CDATA[eip-7702]]></category>
            <category><![CDATA[account-abstraction]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <dc:creator><![CDATA[Dilara Hatipoğlu]]></dc:creator>
            <pubDate>Thu, 10 Jul 2025 14:12:45 GMT</pubDate>
            <atom:updated>2025-07-11T11:32:54.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TsPERjokvBIBmm3gB9PuFA.png" /></figure><p>As we know, EOAs can initiate transactions, but smart contracts can’t; EOAs can only do simple transactions, but smart contracts can execute more complex ones. EIP-7702 combines the useful parts of these account types: EOAs can now <strong>borrow</strong> smart contracts’ code.</p><p>EIP-7702, part of Ethereum’s upcoming Pectra upgrade, introduces a new transaction type <strong>(Type 4)</strong> that lets EOAs temporarily use the logic of a smart contract, allowing them to act like smart contract wallets.</p><h3>How Will Wallets Handle EIP-7702?</h3><p>Technically, an EOA can be upgraded to <em>any</em> smart contract. However, in practice, wallets are unlikely to permit this freely, as it could introduce serious security risks. It will likely be restricted to their implementation or a limited set of approved smart accounts, as they don’t want to allow users to delegate to a malicious contract that could cause them to lose all their funds.</p><p>MetaMask supports EIP-7702 and has a Delegator Contract. Here is an example of a type 4 <a href="https://etherscan.io/tx/0x648b5f2517857cea038f917d5561caf45ed22d620521c8ad008c673d49eb3057">transaction</a> that delegates to that smart contract:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*62S1b2Pn5hLvM8AkJ34TWg.png" /><figcaption><a href="https://www.cyfrin.io/glossary/eip-7702">https://www.cyfrin.io/glossary/eip-7702</a></figcaption></figure><p>If we look at the account info, we can see the delegated address:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*RhmKMRadjtCviDfC4G9JvQ.png" /></figure><p>Also, when we look at the <a href="https://etherscan.io/address/0x63c0c19a282a1b52b07dd5a65b58948a07dae32b">address</a>, we can see that the delegated address’s Public Name Tag is <strong>MetaMask: EIP-7702 Delegator</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*gE_-DA9SGULn0IRhkynXig.png" /></figure><p>Additionally, you can check <strong>which wallets support EIP-7702 </strong><a href="https://beta.walletbeat.eth.limo/wallet/7702/"><strong>here</strong></a><strong>.</strong></p><h3>Benefits of EIP-7702</h3><ul><li>Before EIP-7702, users had to make at least two transactions for simple transactions, such as sw<em>aps or deposits,</em> because they had to <em>approve</em> them first. It makes users tired because they have to verify the correctness of all transactions and confirm them. They have to click the button for each transaction and check if it is true or not. <br>EIP-7702 enables multiple transactions to be completed in a <strong>single</strong> transaction. Due to this, users don’t have to click for each transaction and check it for correctness; they should do this just <em>once</em>. They can <em>batch</em> multiple transactions into one, such as sending funds to various users, which can save gas.</li><li>It enables sponsorship. For example, someone else can pay for a transaction on behalf of a user, and the user can then pay the sponsor in ERC-20 tokens.</li><li>It provides privilege de-escalation, which enables users to delegate limited permissions to sub-keys, rather than granting full access to their account. For example, a sub-key might be allowed to spend only ERC-20 tokens but not ETH, or limit spending to 1% of the total balance per day. This approach enhances security by limiting the actions that delegated keys can perform.</li><li>Users can perform complex operations <em>without</em> having to deploy a custom smart contract, which provides savings in gas.</li><li>Because EIP-7702 is an EIP, Ethereum and Ethereum-equivalent L2s will automatically have it. It is not required to have new infrastructure, and it can adapt quickly.</li><li>EIP-7702 can demonstrate to users the benefits of Account Abstraction, thereby helping to facilitate its adoption.</li><li>Users don’t have to migrate their funds to a newly created account. They can now have a smart account with just a single transaction — this makes EIP-7702 more desirable than ERC-4337 for users.</li><li>EIP-7702 provides an EOA that functions like a Smart Account, but it remains an EOA, allowing users to revert it to its original state. However, ERC-4337 accounts are just Smart Accounts.</li></ul><h3>Does EIP-7702 Remove the Need For ERC-4337?</h3><p><a href="https://medium.com/coinmonks/what-is-account-abstraction-35068ca401cf">ERC-4337</a> and EIP-7702 are not seen as competitors; EIP-7702 is designed to be forward-compatible with ERC-4337. While EIP-7702 enables smart account functionality, it is not enough for Account Abstraction. Even though it has advantages, it still requires <strong>storing private keys or seed phrases</strong>, which is not ideal for mainstream adoption, as users can’t keep them safe, and one of the main reasons why we need ERC-4337. So, we still need full Account Abstraction.</p><h3>How EIP-7702 Works?</h3><p>EIP-7702 enables EOAs to act like a smart contract account through a <strong>delegation indicator</strong>. Previously, EOA’s code field was empty, but now they are storing a delegation indicator (0xef0100 || address) in their code field, where the address points to a smart contract that contains features the user wants to use. Users set the delegation indicator via the setCode transaction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cktU6rs9vV1DSf9HW1b5OQ.png" /><figcaption><a href="https://decentralizedsecurity.es/eip-7702-ethereums-next-step-toward-a-more-flexible-account-model">https://decentralizedsecurity.es/eip-7702-ethereums-next-step-toward-a-more-flexible-account-model</a></figcaption></figure><p>To define this relationship, a data structure known as authorizationList is introduced:</p><p>chainId: Specifies the target blockchain network; if set to zero, it means that the transaction can be replayed on all EVM-compatible chains supporting EIP-7702. (But if nonce is different for different networks, it won’t work even if it is zero, and also, the same contract address on different chains may have different implementations, which means that it should be set carefully.)</p><p>address: Address of the smart contract EOA will point to. To delegate to a smart contract, that contract must <strong>already</strong> be deployed and available on-chain at the time of delegation.</p><p>nonce: Ensures transaction is unique and protects against replay attacks.</p><p>signature: Verifies that the EOA has authorized the action by signing it.</p><p>The user signs the hash of a message constructed by first concatenating a fixed prefix called MAGIC (0x05) with the RLP encoding of [chain_id, address, nonce], and it looks like this: MAGIC || rlp([chain_id, address, nonce]).</p><p>If the address is 0x0000000000000000000000000000000000000000, the delegation indicator is <strong>not</strong> written because it is clear that the account’s code is resetting to the empty code hash (0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470).</p><p>Additionally, the signer of an authorization tuple may differ from the tx.origin of the transaction, and a setCode transaction must include <em>at least one</em> authorization; otherwise, it will be invalid.</p><p>When a transaction targets an EOA that has a delegation indicator, the EOA runs the code located at the specified smart contract address as if the code belongs to the EOA itself, similar to the behavior of DELEGATECALL in smart contracts.</p><h3>SECURITY CONSIDERATIONS</h3><h3>Front-running initialization</h3><p>With this EIP, when delegating to a contract, there is no way to run initcode or initialize storage during the delegation process. This creates a risk: someone could try to front-run and set up the delegation using an account they control. To prevent this, developers should make sure that the initial calldata used for delegation setup is signed by the EOA’s private key. This signature can be verified using ecrecover, ensuring the delegation is only set up by the rightful account owner and with the intended values.</p><h3>Storage Collision</h3><p>As mentioned earlier, it works like a DELEGATECALL, meaning the smart contract code runs in the EOA’s context and uses the EOA’s storage instead of its own. This is similar to upgradeable smart contracts. Because of this, re-delegating must be done carefully to avoid <strong>storage collisions</strong>. To prevent such issues, using a standard like ERC-7201 is recommended. If there&#39;s any doubt, it&#39;s best to clear the account’s storage first. While Ethereum doesn&#39;t support this directly, a custom delegate contract can be created specifically to perform this operation. It’s essential to design smart contracts for EIP-7702 carefully, as they can be vulnerable to front-running attacks and storage collisions.</p><h3>Transaction Propagation</h3><p>Allowing EOAs to act like smart contracts through delegation introduces new challenges for how transactions are handled and shared across the network. Normally, EOAs can only send value, and nodes can easily check if a transaction is valid just by looking at that EOA’s state. In this setup, one transaction can only invalidate other pending transactions from the same account.</p><p>However, with this EIP, delegation allows an EOA’s code to be called by anyone, which means a transaction from one account could unexpectedly affect another. For example, an EOA’s balance might be emptied through delegated code, making it hard for nodes to predict transaction outcomes ahead of time.</p><p>To reduce the risk of this happening, it is recommended that clients only allow one pending transaction at a time for any EOA that has a non-zero delegation indicator. This limits the number of transactions that a single one can invalidate.</p><p>Another approach is to extend the EIP-7702 transaction format by including a list of accounts that the caller intends to “hydrate” during the transaction. These accounts would act as delegated code only within EIP-7702 transactions that specify them in this list, enabling clients to analyze and understand pending transactions more effectively statically.</p><h3>tx.origin After EIP-7702</h3><p>tx.origin can no longer be assumed to come from a <em>regular</em> EOA, as it may be an EOA executing delegated smart contract code. It means that contracts using checks like require(tx.origin == msg.sender, &quot;Externally owned accounts only&quot;); to make sure it’s a transaction from directly an EOA won’t work anymore because it can be an EOA with a delegation indicator, which means it can execute an intermediary smart contract but can still tx.origin == msg.sender.</p><h3>EOA Behavior Changes After EIP-7702</h3><h3>CALL</h3><p>When a transaction is sent to an EOA and it includes a delegation indicator, it will instead call the delegated smart contract. Prior to EIP-7702, it was assumed that any call to an EOA would succeed, as EOAs could not reject ETH transfers. However, what appears to be a simple ETH transfer to an EOA might now trigger a fallback function in the delegated contract, potentially consuming additional gas or even causing the transaction to revert.</p><p>For example, if a smart contract has a code like this:</p><p>(bool success, ) = recipient.call{value: amount}(&quot;&quot;);</p><p>It can revert if EOA has a delegation indicator and the smart contract doesn’t have a fallback or receive function.</p><h3>EXTCODESIZE</h3><p>Previously, EXTCODESIZE returned 0 for EOAs, but now, it will return 23 (the size of 0xef0100 || address). Checking an address with EXTCODESIZE to determine whether it is an EOA or a smart contract can cause unintended actions. However, CODESIZE will return the size of the code residing at the address. So, during delegated execution, CODESIZE and CODECOPY behave differently from EXTCODESIZE and EXTCODECOPY on the authority contract.</p><p>For more details and a better understanding, some helpful sources are here:</p><ul><li><a href="https://decentralizedsecurity.es/eip-7702-ethereums-next-step-toward-a-more-flexible-account-model">EIP-7702: Ethereum&#39;s Next Step Toward a More Flexible Account Model</a></li><li><a href="https://eips.ethereum.org/EIPS/eip-7702">EIP-7702: Set Code for EOAs</a></li><li><a href="https://www.cyfrin.io/glossary/eip-7702">Cyfrin EIP and ERC Glossary: EIP-7702</a></li><li><a href="https://beta.walletbeat.eth.limo/wallet/7702/">Walletbeat - EIP-7702 wallet adoption</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F0uy4nd8vIe8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0uy4nd8vIe8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F0uy4nd8vIe8%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4b23f60211963acb15ae268a723efb2/href">https://medium.com/media/b4b23f60211963acb15ae268a723efb2/href</a></iframe><ul><li><a href="https://safe.global/blog/eip-7702-smart-accounts-ethereum-pectra-upgrade">EIP-7702: A Win for Smart Accounts in Ethereum&#39;s Pectra Upgrade?</a></li><li><a href="https://blog.biconomy.io/le-reip-7702-the-path-to-better-blockchain-ux/">EIP-7702: How Smart Contract Powers for Existing EOA Wallets</a></li><li><a href="https://quantstamp.com/blog/will-eip-7702-affect-your-code?utm_source=chatgpt.com">Will EIP-7702 Affect Your Code?</a></li></ul><p><a href="https://docs.candide.dev/account-abstraction/7702/overview/">https://docs.candide.dev/account-abstraction/7702/overview/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c3fd347107d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/what-is-eip-7702-5c3fd347107d">What is EIP-7702?</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is Proposer-Builder Separation?]]></title>
            <link>https://coinsbench.com/what-is-proposer-builder-separation-ce4007e40e0e?source=rss-8048bbb30078------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce4007e40e0e</guid>
            <category><![CDATA[proposerbuilderseparation]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[flashbots]]></category>
            <category><![CDATA[mev-boost]]></category>
            <dc:creator><![CDATA[Dilara Hatipoğlu]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 14:26:10 GMT</pubDate>
            <atom:updated>2025-07-08T13:20:41.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3RhZK5pQrceG6Q9mhYKp3Q.jpeg" /></figure><h3>Introduction</h3><p>Proposer-Builder Separation (PBS) is designed to reduce the negative impacts of Maximal Extractable Value (MEV). To understand what Proposer-Builder Separation is and how it works, it is essential to be familiar with concepts such as <a href="https://medium.com/coinsbench/what-is-maximal-extractable-value-mev-d7315809c917">MEV</a>, mempools, blocks, and Proof-of-Stake (PoS). Also, since Proposer-Builder Separation (PBS) is still under active development, some technical details and mechanisms discussed here may be subject to change.</p><h3>Why We Need Proposer-Builder Separation?</h3><h3>Centralization Risks</h3><p>After the Merge, Ethereum’s security depends on validators who stake 32 ETH. Since not everyone can afford that, many users join staking pools instead. However, a healthy number of solo stakers is essential for keeping the network decentralized and secure.</p><p>MEV has become a key source of income for validators, especially since block rewards are lower than during mining. Large staking pools have better tools and infrastructure to extract MEV, giving them an unfair advantage. Solo stakers often miss out on these extra rewards, pushing them to join larger pools. This trend increases centralization and goes against Ethereum’s core principles of decentralization.</p><h3>Permissioned mempools</h3><p>To avoid sandwich and frontrunning attacks, traders may bypass the public mempool and send transactions directly to proposers, thereby ensuring privacy while sharing MEV profits in return.</p><p>This practice can scale into “dark pools” — private, pay-to-access mempools — which reduce Ethereum’s openness and shift it toward a “pay-to-play” system.</p><p>Such permissioned systems also deepen centralization risks, as large validator pools are best positioned to offer these services and capture more MEV, further strengthening their dominance.</p><h3>Network Health</h3><p>Attacks like frontrunning and sandwiching lead to higher gas fees as searchers compete by bidding more in <strong>priority gas auctions</strong>. They also cause network congestion by flooding the mempool with spam transactions, which can delay or prevent the confirmation of regular user transactions. This degrades network health and ultimately results in a poor user experience.</p><h3>Complexity</h3><p>Currently, running an Ethereum validator often requires specialized knowledge and expensive hardware. This complexity acts as a <strong>high barrier to entry</strong>, making it difficult for many to participate in the validator pool.</p><h3>How PBS Work?</h3><p><strong>Proposer-Builder Separation (PBS)</strong> is a protocol design introduced to reduce the harmful effects of MEV (Maximal Extractable Value), especially at the consensus layer of Ethereum. The main idea behind PBS is to <strong>separate the responsibilities of two key roles</strong>: the <strong>block proposer</strong> and the <strong>block builder</strong>.</p><p>Traditionally, validators are responsible for both selecting the transactions to include in a block (block building) and proposing the block to the network. This setup allows them to reorder or censor transactions to extract MEV, which can lead to centralization and unfair outcomes. PBS changes this by <strong>delegating the task of building the block to specialized actors called block builders</strong>, while validators (proposers) continue to propose blocks and vote in consensus.</p><p>Here’s how it works:</p><ul><li>Block builders gather transactions from the public mempool and private sources, then construct a block in a way that maximizes its value (including any MEV opportunities).</li><li>They then <strong>submit a bid</strong> (a proposed payment) to the proposer, along with a <strong>blinded block header</strong> that hides the full block content but proves its validity.</li><li>The proposer chooses the highest bid, signs the blinded block header, and commits to proposing it.</li><li>Once the builder sees the signed header, they <strong>reveal the full block</strong> (the execution payload), which is then included in the chain.</li></ul><p>Although this is the ideal approach, the current design relies on trusting intermediaries called <strong>relays</strong>. The process uses a commit-reveal scheme to protect builders from having their work stolen by proposers. It also helps create a competitive builder marketplace, which leads to better block quality and fairer MEV distribution.</p><p>While proposers still receive MEV income (through the builder’s bid), they no longer have direct control over transaction ordering. This reduces the risk of centralization, makes MEV distribution more fair, enables solo stakers to participate without requiring advanced MEV strategies, and enhances the overall security and neutrality of the Ethereum network.</p><h3>MEV-Boost: The Current PBS Implementation</h3><p>PBS hasn’t yet implemented the consensus protocol, and the MEV-Boost is a temporary solution for this. MEV-Boost is an open-source tool used by validators to connect with a competitive market of block builders. This off-chain design involves the following actors: <strong>proposers with MEV-Boost, builders</strong>, and <strong>relays</strong>.</p><h3>Proposers</h3><p>As we know, proposers are validators randomly selected by Ethereum to propose a block. They run the <strong>MEV-Boost</strong> software alongside their consensus clients, which allows them to outsource the block-building task to external parties (builders). Proposers evaluate various block offers (consisting of only “blinded headers” and the proposed payment amount) from the relays they’re connected to, selecting the offer that provides them with the highest payment. They sign the chosen block’s blinded header, committing to propose that block and accept the payment. Once they receive the whole block body (with transactions) in exchange for their signed header, they broadcast this block to the Ethereum network.</p><p>A significant portion of blocks are currently built using MEV-Boost:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0CNyNSED9qVqArZq-y-fg.png" /></figure><p>Also, a validator leveraging the Builder API is still expected to <strong>maintain a local block-building capability</strong>. This ensures they can <strong>fall back to producing a block themselves</strong> if the external block builder doesn’t respond in time. This strategy prevents them from <strong>missing block proposal rewards</strong> and helps <strong>maintain network liveness</strong> even if the MEV-Boost encounters issues.</p><h3>MEV-Boost</h3><p><strong>MEV-Boost</strong> is an open-source software run by validators that acts as an intermediary (middleware) between a validator’s consensus client and the relays. MEV-Boost aggregates block bids (blinded headers) from all connected relays and identifies the highest-paying offer to present to the validator. After the validator signs the chosen blinded block header, MEV-Boost forwards this signed header to the relevant relay. Upon receiving the whole block body from the relay, MEV-Boost verifies it for the validator and then passes it on. A key purpose of this software is to enable validators to benefit from MEV without needing to trust builders or relays with the full block content beforehand (via blinded signing).</p><h3>Relayers</h3><p><strong>Relays</strong> are trust-minimized third-party servers that act as a crucial communication bridge between builders and validators, connecting to one or many builders. They collect block bids from various builders, which include the full block bodies and proposed payments. Relays verify that the blocks submitted by builders adhere to Ethereum protocol rules (e.g., valid transactions, gas limits), but they do so without leaking the block’s contents (specifically, the MEV opportunities) to other searchers or proposers. They then forward the block header and bid amount of the most profitable and valid block offer from their connected builders to MEV-Boost. Once the validator sends back a signed blinded header, the relay reveals the full block content to the Ethereum network. Relays are designed so that validators don’t need to explicitly trust builders to pay or deliver a valid block; the payment is guaranteed once the validator signs, and if a builder’s block is invalid or unavailable, the builder bears the financial loss. Their goal is to provide a transparent and reliable marketplace between builders and validators.</p><h3>Builders</h3><p><strong>Block builders</strong> are specialized actors who optimize block content, including transaction ordering and MEV opportunities, to create the most valuable blocks. They start by gathering transactions from both the public mempool, searchers, and private order flow. Searchers can send their bundled transactions directly to the builders, and users who don’t want to front-run or be sandwiched can send their transactions through private order flow services — such as Flashbots Protect — which forward these transactions to builders, bypassing the public mempool. They arrange these collected transactions and MEV bundles within a block structure, adhering to gas limits and other rules, aiming to maximize the block’s value (and thus the payment they can offer to the validator). They set their own address as the feeRecipient in the block header and include a transaction at the end of the block that pays ETH to the proposer’s feeRecipient. These optimized blocks, along with the bid, are sent to the relayers. Builders compete in this environment to construct the most profitable blocks, allowing them to make the highest bids and win the right to have their block proposed.</p><p>Here is a diagram for a better understanding:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HDMaZKzC7ryRjmf91An-sQ.png" /><figcaption><a href="https://www.galaxy.com/insights/research/mev-the-rise-of-the-builders/">https://www.galaxy.com/insights/research/mev-the-rise-of-the-builders/</a></figcaption></figure><p>Now let’s look at the process between validators and builders step by step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYNRMYW_I5rmYOPBO3MoRQ.png" /><figcaption><a href="https://ethereum.org/content/developers/docs/mev/mev.png">https://ethereum.org/content/developers/docs/mev/mev.png</a></figcaption></figure><ol><li>Proposer Requests a Block: When it’s a validator’s turn to propose a new block, their consensus client (which has MEV-Boost integrated) sends a request to the MEV-Boost software. MEV-Boost then passes this request on to various relays it’s connected to.</li><li>Relay Sends Best Block Header: Different builders are constantly creating optimized blocks and sending their blinded block headers (a summary of the block that hides its contents, plus the builder’s bid/payment to the proposer) to the relays. The relay gathers these, picks the one with the highest payment, and sends this blinded block header to MEV-Boost, which then forwards it to the proposer.</li><li>Proposer Signs the Header: The proposer receives the blinded block header. Crucially, the proposer does not see the full block content at this stage. If satisfied, the proposer digitally signs this blinded block header, indicating their commitment to propose this block. They then send this signed blinded block header back to MEV-Boost.</li><li>MEV-Boost Identifies and Forwards: MEV-Boost recognizes the signed blinded block header and its associated builder. It then sends this signed header to the relay that originally provided the winning builder’s offer.</li><li>Relay Reveals Full Block Payload: Upon receiving the signed blinded block header, the relay performs a final verification. If everything checks out, the relay then reveals the full execution payload (the complete block content, including all transactions and MEV bundles) to MEV-Boost.</li><li>MEV-Boost Verifies and Sends to Proposer: MEV-Boost quickly verifies this complete payload to ensure it matches the previously signed header. If valid, it sends the full block to the proposer.</li><li>Proposer Shares Block with the Network: Finally, the proposer takes this fully verified block and broadcasts it to the entire Ethereum network. This block then gets added to the blockchain, and the proposer receives its payment (the builder’s bid) for proposing it.</li></ol><h3>Benefits of MEV-Boost</h3><ul><li>As we know, searchers are driving up gas fees due to the competitive MEV opportunities. MEV-Boost mitigates this through <strong>sealed-bid auctions.</strong> When a searcher sends the transaction bundle to the builder, others can’t see this bundle’s bid. So, they can’t compete through bids.</li><li>Private Order Flow offers transaction privacy to traders seeking to avoid front-running and sandwiching attacks. This differs from private mempools because the builder software is open-source, allowing anyone to run a block-building service. Additionally, having numerous block builders in the market makes censorship more difficult, thereby protecting users. In contrast, centralized private pools could give too much power to a few builders and increase the risk of censorship.</li><li>Since they are incentivized not to build blocks themselves — because doing so could cause them to lose MEV rewards — most of the MEV is no longer controlled by validators. With the separation of block building and proposing, MEV rewards are now shared with builders and searchers. Previously, validators had the ability to front-run searchers and extract MEV directly by controlling transaction order. Now, since validators no longer need to implement complex MEV strategies, solo stakers can participate more easily without joining large staking pools, improving decentralization.</li><li>The <strong>commit-reveal scheme</strong> and <strong>blinded blocks</strong> ensure that builders’ blocks cannot be front-run or stolen by validators. This security removes the need for off-chain deals with large validator pools. Without it, builders might prefer working with trusted validators to avoid losing their block content.</li><li>Use of transaction bundles give searchers important protection. By sending bundles directly to builders instead of broadcasting transactions to the public mempool, searchers can keep their strategies private. This helps prevent other searchers or validators from copying or front-running their transactions. Also, attacks like the Poisoned Sandwich, which are specifically designed to trick searchers, are no longer effective in the same way. These privacy protections improve fairness and reduce risks for searchers competing in the MEV space.</li></ul><h3>Risks of MEV-Boost</h3><p>While MEV-Boost addresses some issues, it also presents certain risks and downsides.</p><h3>Liveness Risk</h3><p>If the relayers are offline, the validator will fall back to constructing a block from the public mempool. But we still have a risk scenario: if the entire network connects to the same relay, and that relay is the highest bidding relay -which means validators will select it, and the relay remains online and provides the block header to the validator for signing, but fails to publish the complete block to the network after obtaining the signature.</p><p>This design comes with a risk called a “block withholding attack.” If that relay becomes malicious or faulty, it could trick validators into signing blocks that are never published. If it’s faulty, we can expect that it will be closed or fixed immediately. However, if it’s malicious, it can intentionally submit the highest bid so that other builders won’t be able to compete, as it’s not a genuine bid. This leads to missed slots, meaning Ethereum doesn’t produce new blocks, which is referred to as a “<a href="https://writings.flashbots.net/understanding-mev-boost-liveness-risks">liveness risk.</a>” To prevent this, validators should detect and promptly remove malicious relays.</p><p>A <a href="https://hackmd.io/@ralexstokes/SynPJN_pq"><strong>relay monitor</strong></a>, run by a trusted third party, tracks relay performance and can instruct validators to remove misbehaving relays from their configs. Since validators fall back to local block production if no relays are configured, this approach doesn’t risk missed slots and can’t force new relays into configs. However, this system is not yet fully implemented and is currently only proposed by Flashbots as a potential solution.</p><p>The <a href="https://hackmd.io/@ralexstokes/BJn9N6Thc"><strong>circuit breaker</strong></a> is built into the beacon node and doesn’t rely on third parties. If the node detects too many missed slots in a row, it disconnects from the builder network and reverts to local block production. Each consensus client implements its own threshold and behavior for this mechanism. Choosing the right threshold is key — too low risks false triggers, while too high could delay recovery.</p><h3>Relayers’ Problems</h3><p>In the current MEV-Boost model, a large portion of transaction flow is handled by just a few major relays. As the number of active relays decreases or if one or two relays become too dominant, the risk of centralization increases. This centralization can lead to serious concerns for the Ethereum network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eded9YqKMPtEze5Vbq7csA.png" /><figcaption><a href="https://www.relayscan.io/overview?t=7d">https://www.relayscan.io/overview?t=7d</a></figcaption></figure><p>One major risk is <strong>censorship</strong> — where a dominant relay might choose not to include certain transactions in blocks, either due to regulatory pressure or other motives. Another concern is the potential for <strong>MEV manipulation</strong>, where powerful relays could favor certain builders or transactions in a way that benefits a small group at the expense of the rest of the network.</p><p>Because relays occupy a critical position between block builders and validators, placing too much reliance on a few of them makes the entire MEV supply chain more fragile and less trustless. To maintain Ethereum’s core values of decentralization and neutrality, it’s vital to increase relay diversity and reduce dependence on any single entity.</p><h3>Builder Centralization</h3><p>Builder centralization poses a significant threat to Ethereum’s <strong>core principles: network neutrality and resistance to censorship</strong>. This means that every valid transaction that pays its fee should be added to the blockchain without being blocked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eded9YqKMPtEze5Vbq7csA.png" /><figcaption><a href="https://www.relayscan.io/overview?t=7d">https://www.relayscan.io/overview?t=7d</a></figcaption></figure><p>The root of this problem lies in the current MEV system’s operation. As you can see above, a small number of highly specialized builders create most of the blocks on Ethereum. This puts a lot of power in their hands. It gives these builders the authority to set their own rules for how blocks are made. As a result, they can <strong>refuse to include certain transactions</strong> in a block. This could be because a transaction isn’t profitable enough for them, or, more worryingly, it could be for <strong>censorship reasons</strong>.</p><p>Such a situation goes against Ethereum’s promise of being open to everyone and immune to censorship. It essentially means that a small group of people could decide whose transactions get on the blockchain and whose don’t. This chips away at the core idea of decentralization in Ethereum and, over time, could harm users’ trust and the network’s overall health.</p><p><strong>BuilderNet</strong> is an open-source block builder instance operated by node operators, introduced to mitigate builder centralization. These instances collaborate by sharing orderflow and coordinating their bids, fostering a cooperative environment for block building. A key advantage for orderflow providers is the ability to verify the builder software themselves and securely send orderflow to them. Due to Trusted Execution Environments (TEEs), transactions remain provably private, safeguarding sensitive information. BuilderNet also calculates and distributes refunds to orderflow providers based on the value they contribute to the block. For more information, you can visit <a href="https://buildernet.org/docs">this link</a>.</p><h3>Future of PBS: Risk Mitigations</h3><p><strong>Enshrined PBS</strong></p><p>Enshrined PBS aims to bake the separation of “block proposing” (by validators) and “block building” (by specialized builders) directly into the Ethereum protocol itself. This means the blockchain’s core protocol would enforce the rules, making the system much more secure and decentralized. It would remove the need for external, trusted intermediaries like current relays, significantly reducing censorship risks and making the entire MEV process more transparent and fair by design rather than relying on external software.</p><p><strong>SUAVE</strong></p><p>Flashbots’ vision for the future of MEV is SUAVE (Single Unifying Auction for Value Expression). This project aims to create a universal, decentralized marketplace for MEV across any blockchain, including Ethereum. Designed as a “plug-and-play” mempool and block builder, SUAVE fundamentally reshapes how transactions are ordered and included. It addresses persistent challenges, including the centralization of block builders, issues arising from exclusive order flow, and the complexities of cross-chain MEV opportunities. By creating a truly neutral marketplace, SUAVE aims to prevent power consolidation, fostering a more decentralized and fair crypto ecosystem.</p><p>SUAVE achieves its goals through a multi-component architecture. Users can express precise <em>preferences</em> for their transactions. “Executors” (specialized builders) then compete to fulfill these preferences, optimizing blocks in secure, privacy-preserving environments. These optimized blocks are integrated into the SUAVE chain before being passed to their respective target blockchains. This process democratizes MEV, offering users greater control and aiming to reduce the negative impacts of MEV extraction by making the process more transparent, equitable, and resistant to censorship across all supported chains.</p><p><strong>crList</strong></p><p>A <strong>crlist (Censorship Resistance List)</strong> is a proposed mechanism to fight against censorship in the MEV supply chain. It’s basically a list of transactions that a validator (the one proposing the block) wants to ensure are included in their block, often because they suspect builders might censor these transactions. The validator publishes this list, and any builder wishing to propose a block to that validator <em>must</em> include those specific transactions. If a builder doesn’t, their block might be rejected, making censorship economically costly for them.</p><p>For more details and a better understanding, some helpful sources are here:</p><ul><li><a href="https://docs.flashbots.net/">Welcome to Flashbots | Flashbots Docs</a></li><li><a href="https://buildernet.org/blog/introducing-buildernet">Introducing BuilderNet | BuilderNet</a></li><li><a href="https://www.galaxy.com/insights/research/mev-how-flashboys-became-flashbots/">MEV: Maximal Extractable Value Pt. 1</a></li><li><a href="https://www.galaxy.com/insights/research/mev-the-rise-of-the-builders/">MEV: Maximal Extractable Value Pt. 2</a></li><li><a href="https://writings.flashbots.net/understanding-mev-boost-liveness-risks">Understanding liveness risks from mev-boost | Flashbots Writings</a></li><li><a href="https://hackmd.io/@ralexstokes/BJn9N6Thc">mev-boost circuit breaker proposal - HackMD</a></li><li><a href="https://hackmd.io/@ralexstokes/SynPJN_pq">relay monitor design doc - HackMD</a></li><li><a href="https://docs.flashbots.net/flashbots-auction/overview">Overview | Flashbots Docs</a></li><li><a href="https://ethereum.org/en/developers/docs/mev/">Maximal extractable value (MEV)</a></li><li><a href="https://www.alchemy.com/overviews/mev-boost?utm_source=chatgpt.com">What is MEV Boost?</a></li><li><a href="https://writings.flashbots.net/why-run-mevboost">Why run mev-boost? | Flashbots Writings</a></li><li><a href="https://writings.flashbots.net/beginners-guide-mevboost">Beginner&#39;s Guide to mev-boost | Flashbots Writings</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce4007e40e0e" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/what-is-proposer-builder-separation-ce4007e40e0e">What Is Proposer-Builder Separation?</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WHAT IS MAXIMAL EXTRACTABLE VALUE (MEV)?]]></title>
            <link>https://coinsbench.com/what-is-maximal-extractable-value-mev-d7315809c917?source=rss-8048bbb30078------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7315809c917</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[mev]]></category>
            <dc:creator><![CDATA[Dilara Hatipoğlu]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 10:21:14 GMT</pubDate>
            <atom:updated>2025-06-16T11:37:32.412Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3RhZK5pQrceG6Q9mhYKp3Q.jpeg" /></figure><h3>INTRODUCTION</h3><p>In this article, we will focus on MEV in Ethereum. To follow along, you should be familiar with concepts such as transactions, gas, mempools, blocks, Proof-of-Stake (PoS), and Decentralized Finance (DeFi) — particularly DEXs and lending protocols.</p><p>Throughout the article, we refer to various MEV-related statistics and figures. Please note that these values are time-sensitive and may change significantly over time. Readers can visit live dashboards and research sites to find the most current data.</p><h3>WHAT IS MEV?</h3><p><strong>Maximal Extractable Value (MEV)</strong> refers to the additional profit that can be earned during the process of block production by strategically reordering, including, or excluding transactions within a block — beyond the standard block rewards and transaction fees that validators typically receive.</p><p>MEV is often described as an <em>invisible tax</em> on users because it extracts value from regular transactions without the users’ knowledge. When a user submits a transaction, MEV extractors — such as searchers or validators — may rearrange transactions in a way that benefits them financially, often at the expense of the original sender. As a result, users might end up paying more or receiving worse execution outcomes than expected.</p><p>Understanding how MEV works is essential for users, developers, and protocol designers alike, as it highlights hidden inefficiencies in the system and can help in developing strategies or tools to reduce its negative impacts and protect users from these unseen costs.</p><h3>How Does MEV Work?</h3><p>At first glance, it may seem like only validators and miners receive the profit. However, the blockchain’s decentralized and transparent nature allows <em>anyone</em> to extract MEV — which is also <strong>why</strong> MEV exists. Currently, independent actors known as “searchers” capture the majority of the MEV.</p><p>When you send a transaction to Ethereum, it is not included directly in a block. Before a validator picks it up and includes it in a block, it waits in the mempool. Anyone can access these mempools and see the details of the transactions.</p><p>Searchers leverage mempool visibility and extract value by running complex algorithms on blockchain data to identify profitable MEV opportunities. When they find one, their bots automatically submit a transaction to capture the value.</p><p>Searchers can’t extract MEV randomly; their transactions must be confirmed in the designated queue, which often requires paying high gas fees to validators. This is because many searchers compete for the same opportunity, and the only way to ensure inclusion is by offering a higher gas price. In highly competitive MEV scenarios, searchers may pay up to 90% or more of the total extracted value in gas fees. As a result, validators earn a significant portion of the MEV since searchers are willing to sacrifice a large share of their potential profit just to have their transaction included.</p><h3>Why Should We Care About MEV?</h3><p>MEV significantly impacts every Ethereum user and the network’s core integrity. While often unseen, MEV has evolved into a significant economic force, directly impacting transaction costs and network stability. The scale of MEV is immense, totaling <strong>billions of dollars.</strong> Here is an example from Dune, comparing the total volume to the MEV-related volume for large DEXs. We are seeing that MEV has a significant role in those DEXs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*byHNg-7wbH4CUck1qx06XQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avOru4kAFsIsVoZI-cK7Sg.png" /></figure><p>As illustrated below, one type of MEV is a sandwich — also one of the most significant ones, which affects users and transactions substantially.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*earm6H80AGFTL7GlVS9ysg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5szwb_GYfnz9pS4mlZKqOA.png" /></figure><p>The sandwich attack affected dozens of thousands of people:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZPBaQwJz3ihPeCNyMpk6A.png" /></figure><p>Also, this is just for the last 30 days of the volume of some types of MEV:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXmFJHJjruCLMm9J8UcLYA.png" /><figcaption><a href="https://eigenphi.io/">https://eigenphi.io/</a></figcaption></figure><p>MEV has a massive role in on-chain markets. It significantly affects on-chain markets and user experiences and also creates systemic risks to Ethereum. It introduces an “invisible tax” on user transactions, distorts gas markets, and incentivizes behaviors that can compromise network integrity and decentralization. Let’s look at how it works, what its types are, and the negative and positive effects of it.</p><h3>MEV TYPES</h3><h3>Arbitrage</h3><p>Because prices are determined by supply and demand at decentralized exchanges (DEXs), the value of tokens can vary across different DEXs. This creates a chance to make a profit. Searchers can buy the token on the lower-priced exchange and sell it on the higher-priced one, which helps bring the AMM’s price back in line with the actual market value.</p><p>For example, let’s assume that ETH is 1,000 dollars on DEX A and 1,050 dollars on DEX B. If the searcher buys ETH from DEX A and sells it on DEX B, their profit will be 50 dollars for 1 ETH.</p><p>This can be made with more than two tokens. Let’s look at an example with three tokens:</p><ul><li>You have USDC, and you want to buy ETH.</li><li>Then you notice that the BTC/ETH pair is giving more ETH than buying ETH directly with USDC.</li><li>First, you can buy BTC with your USDC and then sell BTC for ETH.</li></ul><p>As of the time of writing, the <strong>volume</strong> of arbitrage in Ethereum has been over $3 billion for the last 30 days, as we have seen. Below, you can see that arbitrage is the most profitable MEV compared to others. The <strong>profit</strong> from arbitrage in the same last 30 days is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGOQ0jL35OBEcxLUU2QImw.png" /></figure><p>Also, you can make a profit at the same DEX’s different liquidity pools if there is a difference between token prices. Arbitrage is the most well-known MEV opportunity, and as a result, it is also the most competitive one.</p><h3>Liquidations</h3><p>When borrowing from a DeFi lending protocol, users must provide collateral to the protocol as a security measure. Their collateral must always meet the determined threshold, or the borrower’s position will be liquidated. Because the crypto market is volatile, the collateral’s value can decrease, or the loan’s value can increase; in such situations, the borrower’s position becomes eligible for liquidity. The liquidator takes the user’s collateral and pays off the loan, but the borrower is required to pay an additional fee during liquidation. That extra fee is the liquidator’s benefit and encourages searchers to liquidate borrowers.</p><p>According to EighenPhi, liquidation profit for the last 30 days is over $48k:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-f_o48b35FKIxjiFplKWTw.png" /></figure><p>Below, you can see that liquidated positions can be pretty large, and if they can’t be covered, they have the potential to cause lending protocols to fall below their healthy thresholds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ee9BhLAip372m2m6YU6v5A.png" /></figure><h3>Front-running</h3><p>In front-running, a searcher inserts their transaction before a target transaction. For example, when a popular NFT collection opens for minting, a searcher might detect someone attempting to mint an NFT. By setting a higher gas fee and submitting their own transaction, the searcher can get their transaction included first — allowing them to mint the NFT before others.</p><p>Also, instead of writing custom logic for each MEV opportunity, some searchers use <strong>generalized frontrunner bots</strong>. These bots monitor the mempool, identify potentially profitable transactions submitted by other searchers, copy their structure, replace the recipient address with their own, and simulate the outcome locally. If it’s profitable, the bot submits the modified transaction with a higher gas fee to front-run the original — effectively taking the opportunity and stealing the MEV from the original searcher.</p><p>However, it’s important to note that with the introduction of <strong>Proposer-Builder Separation (PBS)</strong> and the use of <strong>MEV-Boost</strong>, searchers no longer rely on the public mempool in the same way. Instead, they send bundles privately to builders, which has significantly reduced the effectiveness of traditional frontrunning techniques.</p><h3>Back-running</h3><p>Back-running is also known as <strong>ethical MEV</strong> because it doesn’t affect the users, and it is the opposite of front-running. While front-running involves sending a transaction before the target transaction, back-running involves sending a transaction immediately <em>after</em> it. Assume that a user wants to buy XToken worth 10,000 ETH in DEX A, and after the user’s transaction, the price of XToken will increase distinctly at DEX A. The Searcher detects this and places a transaction immediately after the user’s transaction. That transaction buys the XToken from DEX B and sells it on DEX A. The Searcher benefits from the price differences between the two DEXs. As mentioned earlier, this helps keep the prices of the tokens at the DEXs up to date.</p><h3>Sandwich Attacks</h3><p><strong>Sandwich attacks</strong> are a combination of front-running and back-running. When a user submits a transaction, a searcher places two transactions <em>before</em> and <em>after</em> the user’s transaction — effectively “sandwiching” it.</p><p>For example, suppose a user wants to buy 10,000 ETH worth of XToken. An attacker can submit a transaction just before the user purchases a large amount of XToken, driving the price up. As a result, the user receives fewer tokens than expected due to the increased price -this is what we mentioned earlier as an “invisible tax.” Immediately after the user’s transaction, the attacker sells the tokens at the inflated price, capturing the price difference as a profit.</p><p>As we saw earlier, the Sandwich has the most volume and is one of the most profitable MEV types. The attackers’ profits can be tens of thousands of dollars:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*km-4llHWhOSWAdzrI-S69A.png" /></figure><p>According to EighenPhi, 39 thousand people have been victims of sandwich attacks in the last 30 days:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SQOKzihT0voCdDHQMu0o6w.png" /></figure><p>Some of these victims lost tens of thousands of dollars because of sandwich attacks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PowsJekrjTJNE5vk6HdD7w.png" /></figure><h3>Just In Time (JIT) Liquidity</h3><p>Because LPs receive fees if their liquidity is used in Uniswap’s concentrated liquidity feature, searchers can take advantage of this. For example:</p><ul><li>A user sends a transaction with a large amount.</li><li>The searcher detects this pending transaction and, just before it is executed, provides liquidity to the pool at the same price range.</li><li>After the user’s transaction is executed, the searcher withdraws their liquidity — hence the term “just-in-time.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYA4nE4EEy1HzZwSiyz-xw.png" /><figcaption><a href="https://blog.uniswap.org/jit-liquidity">https://blog.uniswap.org/jit-liquidity</a></figcaption></figure><p>Through this attack, the searcher earns LP fees while reducing the share of other LPs. In other words, the searcher takes a portion of the fees that would have otherwise gone to passive LPs, leading to lower earnings for them.</p><h3>Time Bandit Attacks</h3><p><strong>Time-bandit attacks</strong> occur when the MEV opportunity exceeds the block rewards, and in this scenario, validators may prefer MEV over block rewards, potentially leading to block reorganization and compromising the blockchain’s integrity.</p><p>Let’s assume that Alice and Bob are both Ethereum validators, and the network rewards $1,000 per block. Alice successfully proposes a block, and new blocks are added on top of it. However, a few blocks later, Bob noticed that Alice’s block included a transaction bundle with an MEV opportunity worth $10,000.</p><p>At this point, Bob has two choices:</p><ul><li>He can <strong>act honestly</strong>, continue building on the current chain, and receive the standard $1,000 block reward.</li><li>Or he can act <strong>rationally but selfishly</strong> and perform a <strong>time-bandit attack.</strong></li></ul><p>Bob attempts to <strong>re-mine</strong> Alice’s block (and potentially the following blocks), capturing the $10,000 MEV for himself.</p><p>Since the MEV value significantly exceeds the standard block reward, this re-org attack becomes economically rational. Bob rewinds the chain, builds a longer fork that includes his version of Alice’s block, and appends subsequent blocks on top of it. If successful, Bob’s version becomes the <strong>canonical chain</strong>.</p><h3>Poisoned Sandwich</h3><p>Due to <strong>PBS</strong>, searchers now send transaction <strong>bundles</strong>, which makes this type of attack no longer feasible as it once was. However, it’s still worth mentioning.</p><p>Unlike other types of MEV, the <strong>Poisoned Sandwich</strong> attack targets searchers themselves — it’s specifically designed to trick them.</p><p>An example scenario goes like this:</p><ul><li>To trick the searchers, someone creates a new token. But the contract of this token includes a subtle feature: if anyone buys the token, they’ll only receive a small percentage (e.g., 10%) of the amount they intended to buy, regardless of the trade size.</li><li>After creating that token, they announce a massive purchase of a newly launched, obscure token, making it appear to be a sure bet for quick profits.</li><li>As we mentioned earlier, a searcher realizes the opportunity and tries to “sandwich” this transaction.</li><li>That user’s and searcher’s buy orders go through. However, due to the hidden smart contract feature, the searchers only receive a tiny fraction of the tokens they thought they had bought.</li><li>Now, the searchers are stuck. They paid a high price for very few tokens, making it impossible to sell them for a profit. They’ve effectively lost their ETH.</li></ul><p>A blockchain developer famously showed this type of attack in March 2021. They made two special tokens, named “<a href="https://www.mev.wiki/attempts-to-trick-the-bots/salmonella">Salmonella</a>” and “Listeria,” and pretended to make huge trades with them on Uniswap. This fake activity caught the eye of other MEV searchers. These searchers attempted a “sandwich attack” by buying the tokens, which drove their prices significantly up. However, due to the secret setup of the tokens’ smart contracts, the searchers received only a small portion of the tokens they believed they had purchased. This trick cost those searchers an estimated <strong>$250,000 in ETH</strong>. This shows us that in the competitive world of blockchain, even the hunters can become the hunted.</p><h3>Uncle Bandit Attacks</h3><p>It’s not popular and doesn’t happen often, but it’s good to know. As we know, uncle blocks are not included in the canonical chain, so they are not considered valid blocks. There is a possibility that someone could take a transaction from an uncle block and <strong>include it alongside</strong> their transaction to extract MEV. You can see an example <a href="https://www.mev.wiki/attack-examples/uncle-bandit-attack">here</a>. This means that solutions like Flashbots can’t protect against this type of attack. Fortunately, uncle blocks can no longer exist on Ethereum since the transition to Proof-of-Stake.</p><h3>IMPACTS OF MEV</h3><h3>Positive Impacts of MEV</h3><ul><li>Because DEXs rely on AMMs to set token prices, those prices can sometimes differ from the broader market. Arbitrageurs help close these gaps by buying tokens where they’re undervalued and selling them where they’re overvalued. This activity keeps prices on DEXs aligned with the broader market.</li><li>In lending protocols, liquidators play an essential role in protecting the system. If a borrower’s collateral value drops too much, liquidators step in to repay the loan and claim the collateral. This mechanism prevents bad debt and ensures the protocol stays financially healthy.</li><li>The extra income validators earn from MEV is a significant incentive. Especially when market values are low or standard block rewards aren’t very appealing, MEV revenue encourages validators to stay active and continue participating in the network. Having more active validators generally boosts the overall security and resilience of the Proof-of-Stake network against attacks, as the cost of an attack becomes much higher.</li><li>MEV plays a key role in driving innovation and optimization across the network. The intense competition to capture MEV pushes block builders to create more advanced algorithms and infrastructure. As a result, block space is used more efficiently, transactions are processed faster, and new technologies continue to emerge. This constant pressure to improve benefits the entire ecosystem by advancing the limits of what’s possible in block construction.</li></ul><h3>Negative Impacts of MEV</h3><ul><li>Searchers compete with each other and send transactions with higher gas fees, leading to a phenomenon known as the <strong>priority gas auction</strong>. This drives up network fees, resulting in users paying more than they need to. Additionally, searchers may send spam transactions to capture MEV opportunities, which can lead to network congestion.</li><li>Slippage occurs due to the DeFi nature, but as we mentioned earlier, users must pay more for slippage because of front-running. This results in a poor user experience, discouraging the use of DeFi.</li><li>MEV can pose serious centralization risks alongside its other negative externalities. Large MEV opportunities may push validators to invest in specialized hardware or gain access to exclusive connections, giving them an edge over smaller, independent validators. Over time, this can lead to a validator set dominated by a few powerful players, undermining Ethereum’s core principle of decentralization. Ensuring fair access and reducing the gap between validators is crucial to preserving the health and integrity of the network.</li><li>MEV’s negative externalities also affect the consensus layer. If the MEV opportunity is higher than block rewards, validators may prefer MEV over block rewards, which can lead to block reorganization and compromise the blockchain’s integrity.</li></ul><h3>HOW CAN WE PREVENT MEV?</h3><p>MEV is an inherent part of blockchain systems, not just an exploit to eliminate. As long as transactions need to be ordered, there will always be value in that order — and opportunities to capture it. This makes MEV less of an attack to prevent and more of a reality to manage. Instead of trying to remove it entirely, the focus should be on building tools and mechanisms that minimize its negative impacts while preserving the openness and efficiency of the network.</p><p>Efforts to prevent the negative effects of MEV are ongoing, and there are ways to protect users from it. Users can set a lower slippage tolerance to protect themselves, but this can cause transactions to revert, and users will still be charged for those failed transactions. If the benefit of price slippage is lower than the gas fee, it will deter searchers; therefore, users can set higher-priority gas fees for MEV. Although, those solutions come with disadvantages and risks for users. Generally, no one wants to pay for a failed transaction or pay an extra fee for the transaction.</p><p><strong>MEV Blockers</strong> are one of the solutions to protect users from the negative impacts of MEV. An MEV blocker is a tool that protects blockchain transactions from MEV exploitation. It works through special RPC endpoints that route transactions to <strong>private mempools</strong>, keeping them hidden from searchers and sometimes providing rebates when trades leave value on the table. Thus, users are protected from front-running and sandwich attacks because searchers are not permitted to access those private mempools. Also, users can have a portion of the captured value by back-running.</p><p><strong>Proposer-builder separation</strong> is another solution, but it has not yet been implemented at the consensus layer. In this model, the block proposer delegates block construction to specialized builders who compete to produce the most valuable block. This separation helps reduce centralization risks, improves MEV management, and allows validators to maximize rewards without directly engaging in MEV extraction. <strong>MEV-Boost</strong> is an off-chain and temporary implementation of this.</p><p>Additionally, it can be beneficial to utilize DeFi protocols that incorporate built-in MEV protection. These protocols are specifically designed to prevent MEV exploitation by integrating custom logic that mitigates front-running and sandwich attacks.</p><p>For more details and a better understanding, some helpful sources are here:</p><p><a href="https://a16zcrypto.com/posts/article/mev-explained/">MEV explained</a></p><p><a href="https://www.coingecko.com/learn/what-is-mev-maximal-extractable-value-crypto">https://www.coingecko.com/learn/what-is-mev-maximal-extractable-value-crypto</a></p><p><a href="https://www.galaxy.com/insights/research/mev-how-flashboys-became-flashbots/">https://www.galaxy.com/insights/research/mev-how-flashboys-became-flashbots/</a></p><ul><li><a href="https://www.galaxy.com/insights/research/mev-the-rise-of-the-builders/">MEV: Maximal Extractable Value Pt. 2</a></li><li><a href="https://ethereum.org/en/developers/docs/mev/">Maximal extractable value (MEV)</a></li><li><a href="https://cow.fi/learn/what-is-frontrunning">What is Frontrunning - CoW DAO</a></li><li><a href="https://cow.fi/learn/mev-and-arbitrage-predatory-but-avoidable">MEV and arbitrage: predatory but avoidable - CoW DAO</a></li><li><a href="https://www.mev.wiki/">Introduction | MEV Wiki</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7315809c917" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/what-is-maximal-extractable-value-mev-d7315809c917">WHAT IS MAXIMAL EXTRACTABLE VALUE (MEV)?</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LIBRARIES IN SOLIDITY]]></title>
            <link>https://medium.com/coinmonks/libraries-in-solidity-78db4c6d8bd8?source=rss-8048bbb30078------2</link>
            <guid isPermaLink="false">https://medium.com/p/78db4c6d8bd8</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity-development]]></category>
            <category><![CDATA[solidity-tutorial]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Dilara Hatipoğlu]]></dc:creator>
            <pubDate>Fri, 21 Feb 2025 13:51:41 GMT</pubDate>
            <atom:updated>2025-02-23T07:24:34.510Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*EE9xGYNEfOq9T7bLuh9O2w.jpeg" /></figure><p>Imagine you need the same functions in dozens of contracts. Would it be efficient to rewrite all the functions for each contract? You can use inheritance, but this means that all the functions will be included in all your contracts, which is expensive. Then what should we use?</p><p>Libraries are powerful tools for code reusability. They offer significant time and effort savings when we require the same functions in multiple smart contracts. We can avoid the repetitive task of writing the same functions in all our contracts thanks to libraries.</p><p>Using libraries can be economical because a smart contract with too many functions increases its size and deployment cost. The maximum size of a smart contract is 24 kb. Therefore, it makes sense to use libraries when we need some functions repeatedly.</p><p>The difference between inheriting a smart contract and using a library is that inheriting a smart contract means copying all the code to our contract, which can be expensive. However, if we use the library, we can use the necessary functions. A library contains what we need, and we can call its functions even after they are deployed.</p><p>Libraries have some restrictions:</p><ul><li>They can’t inherit nor be inherited</li><li>They can’t be destroyed</li><li>They can’t have state variables</li><li>They can’t receive ether, so they can’t have receive and fallback functions</li></ul><h4>How do we use libraries?</h4><p>Libraries can be used in two ways: <strong>external (linked) </strong>and <strong>internal (embedded)</strong>.</p><p>In the external approach, you can use the functions you need and don’t need to deploy the library itself multiple times. Therefore, this method is cheaper in terms of deployment costs. However, executing the code is more expensive because we use delegatecall for every call.</p><p>The internal approach is more costly to deploy because it embeds the necessary library functions into the contract. But because you are directly using the function, delegatecall is not used.</p><p>Thus, deciding which one will be more efficient depends on the situation. If you only use a function a few times, it would be better to use an external library. But using an internal library would be better if you call that functions a lot. However, as mentioned earlier, the best choice depends on the situation. Now, let’s look at how to use libraries!</p><p>We can use internal functions if we include libraries within the same file or import them. Let’s look at placing the library in the same file as our contract:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AeEzxIlcE0_bsRRtcJTi6w.png" /></figure><p>If you put your library into another file, you can use it just by importing it:</p><p>import “./Math.sol”;</p><p>Also, to attach library functions to a type, we can use a statement like using &lt;libraryName&gt; for &lt;dataType&gt;. Thus, when we call a library function, we can give the first parameter of that function like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZcn-aXaTrAHDH0zrCcsZA.png" /></figure><p>Now, let’s look at the <em>external</em> approach. If the library is deployed, we call its functions using delegatecall. This method requires the library’s address.</p><p>Here is our deployed Library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*XObcP--qKyZDqa1IPFEydg.png" /></figure><p>Notice that our function’s visibility is external, not internal.</p><p>And here is how we use delegatecall:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*U40CmqImGZDPU3e2R_J0tg.png" /></figure><p>It is crucial to be careful when using a library. If you use a malicious or incorrect library, you might introduce an irreversible mistake. So, you should ensure you fully understand what it does before using it.</p><p>For more details and a better understanding, some helpful sources are here:</p><ul><li><a href="https://docs.soliditylang.org/en/latest/contracts.html#libraries">Contracts - Solidity 0.8.29 documentation</a></li><li><a href="https://solidity-by-example.org/library/">Solidity by Example</a></li><li><a href="https://www.geeksforgeeks.org/solidity-libraries/">Solidity - Libraries - GeeksforGeeks</a></li><li><a href="https://stackoverflow.com/questions/73532819/why-do-we-need-library-in-solidity">why do we need library in solidity?</a></li><li><a href="https://ethereum.stackexchange.com/questions/135747/should-i-use-embedded-library-internal-or-linked-library-external-to-save-ga">Should I use Embedded Library (Internal) or Linked Library (External) to save gas?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78db4c6d8bd8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/libraries-in-solidity-78db4c6d8bd8">LIBRARIES IN SOLIDITY</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Account Abstraction?]]></title>
            <link>https://medium.com/coinmonks/what-is-account-abstraction-35068ca401cf?source=rss-8048bbb30078------2</link>
            <guid isPermaLink="false">https://medium.com/p/35068ca401cf</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[account-abstraction]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Dilara Hatipoğlu]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 11:20:40 GMT</pubDate>
            <atom:updated>2024-09-25T12:35:51.921Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5CdULVZTh-0EYCYIJiPFNw.png" /></figure><p>Until now, if we wanted to interact with Ethereum, we had to keep our private key or seed phrases or trust a third party if we used custodial wallets. As everyone knows, we can’t lose private keys and seed phrases and must keep them safe. If someone has our private key, they can have all our assets. If we lose it, we can never take our assets.</p><p>Another option is to trust third parties if we don’t want to keep our private key. But does it make sense to trust some third parties? Our aim in the blockchain world is decentralization. We know these are not ideal options for users and are a barrier to potential users. That’s why we need to improve UX. This is where account abstraction comes into play.</p><p>Ethereum has two types of accounts: Smart Contracts and EOAs (Externally Owned Accounts). Account Abstraction reduces them to one with ERC-4337. With account abstraction, we use smart contracts instead of EOAs.</p><p>Ethereum developers have long wanted Account Abstraction. Therefore, ERC-4337 is not the first attempt to achieve this. Other attempts were not accepted because they requested core protocol changes. ERC-4337 doesn’t require core protocol changes; thus, we finally have Account Abstraction.</p><p><strong>Some of the properties that Account Abstraction gives us are:</strong></p><ul><li>Users can use various signature and nonce validation logic</li><li>Users can make their wallet quantum-safe</li><li>Users can upgrade their wallet’s public keys or code</li><li>Wallets can add various steps for execution, like atomic multi-operations</li><li>Users can make multicall. (We have to make a new transaction for each on-chain interaction. With AA, we can bundle them and send them as an atomic transaction.)</li><li>If users lose their private key, they can set it to another using various mechanisms</li><li>Users can set pre-approve rules for blockchain games and DApps with session keys</li><li>With AA, users can create a signature with multiple keys or, if they want, make a transaction only if specific requirements are provided</li><li>Users can pay gas fees with ERC20 Tokens</li><li>Sponsors can pay gas fees for users</li><li>Users can limit transactions per day, week, or month</li><li>Users can block scam addresses</li><li>Users can set multiple addresses for authorization of a transaction</li><li>Users can make small transactions with one signature and big transactions with multiple signatures</li></ul><p>Let’s now look at the maintained properties and weaknesses of Account Abstraction by <a href="https://medium.com/infinitism/erc-4337-account-abstraction-without-ethereum-protocol-changes-d75c9d94dc4a">Vitalik Buterin’s article</a>.</p><p><strong>Maintained properties with Account Abstraction:</strong></p><ul><li>We keep everything decentralized; there are no centralized actors</li><li>DoS safety: When UserOperation passes simulation checks, it is certain to be included if the sender hasn’t had another state change — in this situation, 7500+ gas is required for state changes.</li><li>It doesn’t require user-side wallet setup</li><li>It supports EIP1559: Users can set fixed and high max total fees and expect to be prioritized and charged fairly.</li><li>With the ability to replace by fee, users can send a new UserOperation—for the same transaction—with a higher gas fee, and thus, the operation can be included faster.</li></ul><p><strong>Weaknesses of Account Abstraction:</strong></p><ul><li>Slightly increased DoS vulnerability because verification logic can be more complex than single ECDSA verification -if verification logic is more complicated, it takes more computational resources, and it can open up an opportunity for attackers to exploit this and overwhelm the network.</li><li>Gas overhead: Standard transactions have a slightly higher gas cost, although, in some scenarios, this is offset by the ability to perform multiple operations in a single transaction.</li><li>One transaction at a time: Accounts can’t send multiple transactions into the mempool. However, we don’t need that too much because we can make multicall.</li></ul><h4>How Does Work Account Abstraction?</h4><p>We know that if we want to make a transaction, we need an EOA. Smart contracts can’t be triggered by themselves, so every transaction has to start with an EOA call. But we don’t want to make transactions in Ethereum through an EOA. How can we make a transaction without an EOA? With bundlers!</p><p>Bundlers are executors of our transactions. We can send them UserOperation, which they send to Ethereum with their EOAs. UserOperation includes the user’s desired action, signature, and other data for verification. Let’s look at UserOperation closer!</p><p>UserOperation has these:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*GxdePpewVxstCD7mmccnRw.png" /><figcaption><a href="https://www.erc4337.io/docs/understanding-ERC-4337/user-operation">https://www.erc4337.io/docs/understanding-ERC-4337/user-operation</a></figcaption></figure><p>An ERC-4337 contract must have contain two functions:</p><ul><li>validateUserOp: It takes UserOperation as a parameter. It validates the signature and nonce inside of UserOperation. It pays the gas fee, and if the transaction is true, it increases nonce. If it doesn’t, it returns an error.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*Lu3_VLHy6lNZz9mg1F7SaQ.png" /><figcaption><a href="https://github.com/eth-infinitism/account-abstraction/blob/develop/contracts/interfaces/IAccount.sol">https://github.com/eth-infinitism/account-abstraction/blob/develop/contracts/interfaces/IAccount.sol</a></figcaption></figure><ul><li>-Op Execution Function: It interprets calldata for the execution. How this function interprets the calldata and what it does is open-ended. However, the expected most common behavior would be to parse calldata as an instruction for the wallet to make one or more calls.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*N4JJu4shKdwido2RE87Tbw.png" /><figcaption><a href="https://github.com/eth-infinitism/account-abstraction/blob/develop/contracts/interfaces/IAccountExecute.sol">https://github.com/eth-infinitism/account-abstraction/blob/develop/contracts/interfaces/IAccountExecute.sol</a></figcaption></figure><p>Now that we know what a UserOperation is. Let’s look at how bundlers work and what an EntryPoint contract is.</p><h4>How Do Bundlers Work?</h4><p>As we know, we send the UserOperation to bundlers, and they send it to the blockchain. But why would they do that, and what are bundlers’ advantages and disadvantages? How can we protect the bundlers’ benefit and encourage them?</p><p>Bundlers can choose which transaction has priority. They have fee-prioritization logic like miners/validators to increase their gain—in addition, they may be integrated with node clients. Bundlers also have a minimum gas limit for transactions. If a transaction has too little gas, they reject it because they don’t allow DoS attacks.</p><p>Bundlers don’t want to interact with a contract they don’t know. That’s why we need an EntryPoint contract (audited, with compiled source code) so bundlers can trust the contract they will call. We want the <em>caller</em> to be the <em>entry point </em>in our contract because of its reliability.</p><p>We separate operations into two functions: validation and execution. Bundlers simulate the validationOp to see if they can receive the gas they pay for -and if it can be successful or not, of course. Some opcodes — like timestamp and blockhash — are banned because they can affect the state and cause differences between simulation and transaction. That’s why we need to separate operations into two functions -because we need those opcodes in our smart contracts. For the same reason, there are some storage limits: validationOp can access the wallet’s own storage. It can also access another contract’s storage at a slot corresponding to the wallet in a mapping(address =&gt; value). If validateOp doesn’t follow these rules, the bundle rejects it. Also, validateOp can’t make calls to contracts that we don’t ensure that are not self-destructing.</p><p>Due to bundlers’ simulations, if someone attempts to send a transaction to our contract, the bundlers can detect it during their simulations and not send the transaction to the blockchain. This way, no one can send transactions on our behalf.</p><p>EntryPoint contract includes a function: handleOps. Bundler first simulates validation and calls handleOps with the UserOperation. Then EntryPoint calls the wallet contract’s validationOp function. If it fails, it stops here. If it does not fail, EntryPoint sets aside ETH from the wallet’s deposit to pay for the maximum amount of gas it might possibly use. If that isn’t enough, it rejects. If it’s enough, it calls the execute function. When it calls the execute function, it tracks how much gas it uses, returns the remaining funds to the wallet’s deposit, and sends the gas fee to the executor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*ilIG0L-EK6BWvECDI0xPEg.png" /><figcaption><a href="https://www.alchemy.com/blog/account-abstraction">https://www.alchemy.com/blog/account-abstraction</a></figcaption></figure><p>For the gas fee, EntryPoint first looks at the user’s deposit. If that’s not enough, it sends a request to the wallet’s validationOp. We can’t know what a contract does when we send ETH to it; it can cost lots of gas. Because of this, EntryPoint has deposit and withdrawal functions.</p><p>Bundlers can send more than one operation at once. They bundle operations and send them to the blockchain, thus allowing them to save gas and earn money (Because we have to pay 21,000 gas for each transaction by default; if they bundle transactions, they don’t have to pay it for each transaction.). First, all operations’ validateOp functions are called because execution functions can change states, and changes in that state can affect validations.</p><p>Because being a bundler does not require permission, there is no centralization. Even if all bundlers want to censor a contract, other bundlers can join the network and don’t censor that contract.</p><p>Our validateOp has return data, including the time from when and until the operation is valid. The reason is that prevent bundlers can send our operation whenever they want, at a time that benefits them.</p><h4>Paymasters</h4><p>With Paymasters, DApps can pay gas fees for users, and users can pay gas fees with ERC20 Tokens — a contract can make this possible. If wallet owners aren’t familiar with blockchain, Paymasters can help them, and sponsors can be willing to pay gas fees for some users or transactions.</p><p>If UserOperation has a paymaster, EntryPoint calls a function in the paymaster contract: validatePaymasterOp. UserOperation’s paymasterAndData part is for this situation. This field includes the paymaster’s address and extra data for verification and execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*Trd0V86nzJGx_7ov7WfaPA.png" /><figcaption><a href="https://github.com/eth-infinitism/account-abstraction/blob/develop/contracts/interfaces/IPaymaster.sol">https://github.com/eth-infinitism/account-abstraction/blob/develop/contracts/interfaces/IPaymaster.sol</a></figcaption></figure><p>When users send the UserOperation, the paymaster validates that the user has enough money to refund after the transaction. However, after execution, the user balance can be zero or insufficient for the transaction gas fee because the user can spend all the money in the execution step. To protect the paymaster from these situations, the paymaster can revert transactions and thus provide gas fees for itself. But how is this possible?</p><p>Paymaster has a function: postOp. In the operation process, the entry point makes a call to the postOp function as a part of the execution function. If postOp reverts, execution functions revert, too. In this way, the user can’t spend money because the transaction reverts. After that, the entry point calls postOp again and gives the gas fee to the paymaster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*NbI3s90qfnHBXJFhfohAcg.png" /><figcaption><a href="https://github.com/eth-infinitism/account-abstraction/blob/develop/contracts/interfaces/IPaymaster.sol">https://github.com/eth-infinitism/account-abstraction/blob/develop/contracts/interfaces/IPaymaster.sol</a></figcaption></figure><p>For a better understanding, let’s look at this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*E9kZKYYLRePlCtNwMV-xXg.png" /><figcaption><a href="https://www.alchemy.com/blog/account-abstraction-paymasters">https://www.alchemy.com/blog/account-abstraction-paymasters</a></figcaption></figure><p>There is also a reputation system to prevent malicious paymasters can’t do the DoS. If a paymaster causes so many operations to fail, then bundlers can ban them.</p><p>However, the reputation system can’t prevent DoS if the same persons use various malicious paymasters. That’s why we want to stake paymasters to EntryPoint. Once they are staked, they can’t withdraw their stake until some delay has passed after calling the unlockStake function.</p><h4>Wallet Creation</h4><p>We have factory contracts for wallet creation. We can simulate factories’ functions, and thus, we can know what address our contract will be located at. Because we know the address of our contract, we can send it to ETH without deploying it. Also, if a Factory is audited, we can trust that the contract does not install a backdoor to our bytecode. If we trust some malicious tools, they can install a backdoor to our bytecode, which can be hard to notice.</p><p>Paymasters can pay deployments from certain approved factories. There are risks similar to paymasters for bundlers regarding factories. Bundlers solve this problem in the same way. They limit particular opcodes and access to storage. Factories have to stake the Entry Point, too. Despite their simulations, bundlers can ban the factories if so much failure happens in them.</p><h4>Aggregate Signatures</h4><p>With Aggregator, we can sign more than one transaction with only one signature. Bundlers send Operations with signatures to the Aggregator contract; the Aggregator implements the signature to our operations and sends it back to the bundlers. Then bundlers send this one operation -because the aggregator transformed multiple operations into one operation- to the entry point, but it calls the handleAggregatorOps function. The entry point calls the Aggregator contract for verification, and after that, it sends transactions to wallets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*N-XC3KQ1I85Jxov9Tp2r7w.png" /><figcaption><a href="https://www.alchemy.com/blog/account-abstraction-aggregate-signatures">https://www.alchemy.com/blog/account-abstraction-aggregate-signatures</a></figcaption></figure><p>Aggregator contracts have the same limitations as Paymasters and Factories.</p><h4>Conclusion</h4><p>Account Abstraction will play a big role in mainstream adaptation. We hope it will be adopted and improve UX. The codes of the concepts we discussed can be found in the <a href="https://github.com/eth-infinitism/account-abstraction">eth-infinitism</a> repository.</p><p>These sources helped me a lot to understand account abstraction. For more information and details, you can take a look at them.</p><ul><li><a href="https://www.erc4337.io/">ERC-4337</a></li><li><a href="https://www.alchemy.com/blog/account-abstraction">You Could Have Invented Account Abstraction: Part 1</a></li><li><a href="https://www.alchemy.com/blog/account-abstraction-paymasters">ERC-4337 Part 2: Sponsoring Transactions Using Paymasters</a></li><li><a href="https://www.alchemy.com/blog/account-abstraction-wallet-creation">Account Abstraction Part 3: Wallet Creation</a></li><li><a href="https://www.alchemy.com/blog/account-abstraction-aggregate-signatures">Account Abstraction Part 4: Aggregate Signatures</a></li><li><a href="https://medium.com/infinitism/erc-4337-account-abstraction-without-ethereum-protocol-changes-d75c9d94dc4a">ERC 4337: account abstraction without Ethereum protocol changes</a></li><li><a href="https://medium.com/@alex-100/what-is-account-abstraction-and-why-is-it-important-9627a4ced4f3">What is account abstraction and why is it important?</a></li><li><a href="https://medium.com/nethermind-eth/the-history-and-future-of-account-abstraction-10cb097ebdc8">The History and Future of Account Abstraction</a></li><li><a href="https://www.argent.xyz/blog/part-3-wtf-is-account-abstraction/?source=post_page-----3a74f83664e6--------------------------------">Part 3: WTF is Account Abstraction</a></li></ul><p><a href="https://docs.zerodev.app/blog/erc-4337-misconceptions-and-valid-concerns">https://docs.zerodev.app/blog/erc-4337-misconceptions-and-valid-concerns</a></p><p><a href="https://notes.ethereum.org/@yoav/unified-erc-4337-mempool?source=post_page-----3a74f83664e6--------------------------------">https://notes.ethereum.org/@yoav/unified-erc-4337-mempool?source=post_page-----3a74f83664e6--------------------------------</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35068ca401cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/what-is-account-abstraction-35068ca401cf">What is Account Abstraction?</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>