<?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 Tushar Bhatia on Medium]]></title>
        <description><![CDATA[Stories by Tushar Bhatia on Medium]]></description>
        <link>https://medium.com/@tusharbhatia43?source=rss-d77880e966ac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3UyxQVpcbQxO-MyPHkZr_g.jpeg</url>
            <title>Stories by Tushar Bhatia on Medium</title>
            <link>https://medium.com/@tusharbhatia43?source=rss-d77880e966ac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 16:30:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tusharbhatia43/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[Solana Account Fundamentals: Part 1 -The Building Blocks]]></title>
            <link>https://tusharbhatia43.medium.com/solana-account-fundamentals-part-1-the-building-blocks-6888216bc6fe?source=rss-d77880e966ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/6888216bc6fe</guid>
            <category><![CDATA[web3-development]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[solana-network]]></category>
            <dc:creator><![CDATA[Tushar Bhatia]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 13:58:18 GMT</pubDate>
            <atom:updated>2025-01-26T13:58:18.210Z</atom:updated>
            <content:encoded><![CDATA[<p>Solana’s account system forms the backbone of its high-performance blockchain architecture. In this comprehensive guide, we’ll explore how Solana accounts work, their fundamental properties, and why they’re crucial for developing efficient blockchain applications.</p><blockquote>This article assumes that you have some prior knowledge of <strong>Rust</strong></blockquote><h3>What is a Solana Account?</h3><p>A Solana account is a fundamental data structure that stores both tokens and data on the blockchain. Every account in the Solana network has a unique 32-byte public key address and can hold SOL tokens, program code, or application data.</p><p>Think of Solana accounts as containers. Unlike your regular bank account that just holds money, Solana accounts can store both DATA and TOKENS. Pretty cool, right? Every time you interact with a Solana dApp, you’re actually working with these accounts behind the scenes.</p><p>Here’s the basic structure of a Solana account:</p><pre>pub struct Account {<br>    lamports: u64,      // Your SOL tokens (1 SOL = 1 billion lamports<br>                          // think of it like `wei`)<br>    data: Vec&lt;u8&gt;,       // Where your account stores its data (in a vector)<br>    owner: Pubkey,       // The program that controls this account<br>    executable: bool,    // Can this account run as a program?<br>    rent_epoch: u64,    // When rent is due (more on this later!)<br>}</pre><h3>Core Components of Solana Accounts</h3><h4>Public Key Address</h4><p>Every Solana account is identified by a unique public key, generated using Ed25519 cryptography. This address serves as both the identifier and the public key for verifying transactions.</p><h4>Account Ownership</h4><p>In Solana’s architecture, programs own accounts — not users. This fundamental design choice enables Solana’s high security and performance. Only the owner program can modify an account’s data, enforcing strict access control at the protocol level.</p><p>I know, I know — it sounds strange, but stick with me here. Think of it like this: <em>if accounts were safety deposit boxes, programs would be the bank, and you’d be the customer with the key</em>.</p><p>Let’s say you want to transfer some tokens. You can’t just reach in and move them — you need to ask the token program (the owner) to do it for you. This might seem like extra work, but it’s actually brilliant for security.</p><h4>Data Storage</h4><p>Accounts store data directly in a byte array, allowing for:</p><ul><li>Fast, direct access to data</li><li>Predictable storage costs</li><li>Efficient data serialization</li><li>Clear ownership boundaries</li></ul><p>Let’s say you’re building a simple game on Solana. You might need an account that stores your data like something like this:</p><pre>// Example game state stored in a PDA<br>#[account]<br>pub struct GameAccount {<br>    player: Pubkey,          // Player&#39;s wallet address<br>    score: u64,             // Current score<br>    tokens_earned: u64,     // In-game rewards<br>    last_played: i64,      // Timestamp<br>}</pre><blockquote>Please ignore the syntax right now if you are unfamiliar with Anchor basics and focus more on the concept of data storage.</blockquote><h3>Understanding Account Types in Solana</h3><h4>System Accounts</h4><p>System accounts are the most basic type of Solana account. They can hold SOL tokens and serve as user wallets. These accounts are owned by the System Program and form the foundation of user interaction with the Solana network.</p><p>Here’s a fun fact: every time you create a new Solana wallet, you’re actually creating a system account owned by the System Program.</p><h4>Program Accounts</h4><p>Program accounts store executable code (smart contracts) on the Solana blockchain. These accounts have their executable flag set to true and are owned by the BPF Loader. Program accounts are immutable by default, ensuring code security.</p><p>To understand these better think of these as the brains of the operation. We developers upload our code to program accounts. When you deploy a smart contract on Solana, you’re creating a program account that will contain the code of your program. The cool thing about program accounts is that they have their executable flag set to true, meaning they can actually run code!</p><h4>Program Derived Addresses (PDAs)</h4><p>Here’s where Solana gets really clever. PDAs are special accounts that are derived from programs — kind of like a program’s personal filing cabinet. They’re perfect for:</p><ul><li>Storing program data</li><li>Creating predictable addresses</li><li>Managing program state</li></ul><p>The neat thing about PDAs is that no one can generate their private key — they’re truly program-controlled! <a href="https://tusharbhatia43.medium.com/program-derived-addresses-pdas-in-solana-what-why-and-how-9bdc69c8d969">You can read more about them here</a></p><h4>Token Accounts</h4><p>If you’ve ever used SPL tokens (Solana’s equivalent of ERC-20), you’ve used token accounts. Each token account represents your balance of a specific token. Here’s something that might surprise you: you need a separate token account for each type of token you own! And most importantly they are owned by the <em>Token-Program </em>which is a Program Account and contains code to manage the data of <em>Token Accounts</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uKthqSc1xa2lWzjsjNQcpQ.png" /></figure><h4>Data Accounts</h4><p>Data accounts store program state and user data. They’re owned by their respective programs and can only be modified through program instructions. This design ensures data integrity and controlled access.</p><p>This means that these accounts cannot be manually modified because they have Data in them. As per Solana’s architecture, only the Program’s code is allowed to make changes to them</p><p>For example: You have a <strong>Struct</strong> to store the details of a user’s stake data. So, what you will do is store this struct in a DATA Account and in order to modify that struct, only your Program’s Instructions (The Rust Code you have written) will be able to modify this data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*VuxERzZma3hGG2ipJJCxlA.png" /><figcaption>Summarized Comparison between all Account Types</figcaption></figure><h4>The Rent System: Why Your Accounts Need “Allowance”</h4><p>Now, let’s talk about something unique to Solana — <strong>rent</strong>. Just like in the real world, storing data on Solana isn’t free. Your accounts need to pay rent to stay alive on the network. But don’t worry! If you keep enough SOL in your account (about 0.002 SOL per kilobyte), it becomes “rent-exempt” — like buying your apartment instead of renting it.</p><p>The rent calculation follows this formula:</p><pre>let rent_exempt_minimum = account_size * LAMPORTS_PER_BYTE * 2;</pre><h4>Best Practices for Account Management without Anchor</h4><p>Anchor, the popular Solana development framework, simplifies account management while enforcing best practices. In this Article we will not deep dive into anchor but understand the core model of Solana first because it will make us understand Anchor faster</p><p>If you don’t understand this right away don’t worry. We will have a Separate Anchor series soon!</p><h4><strong>Size Planning</strong>:</h4><p>Calculate account sizes carefully before initialization:</p><pre>// Calculate account size with padding<br>const ACCOUNT_DISCRIMINATOR: usize = 8;<br>const GAME_STATE_SIZE: usize = <br>    ACCOUNT_DISCRIMINATOR +  // Required prefix<br>    32 +                    // Pubkey<br>    1 +                     // game_type<br>    2 +                     // current_round<br>    4 +                     // total_players<br>    1;                      // is_active</pre><p><strong>Rent Exemption</strong>:</p><p>Always make accounts rent-exempt during creation:</p><pre>let rent = Rent::get()?;<br>let rent_exempt_lamports = rent.minimum_balance(GAME_STATE_SIZE);</pre><p><strong>Owner Validation</strong>:</p><p>Always verify account ownership in your programs:</p><pre>if account.owner != program_id {<br>    return Err(ProgramError::IncorrectProgramId);<br>}</pre><h4>Security Considerations</h4><p>When working with Solana accounts, consider these security aspects:</p><ul><li>Account ownership verification</li><li>Proper permission checks</li><li>Secure data serialization</li><li>Rent exemption status</li></ul><h4>Performance Implications</h4><p>Solana’s account model contributes to its high performance through:</p><ul><li>Direct data access</li><li>Parallel transaction processing</li><li>Efficient state management</li><li>Clear ownership boundaries</li></ul><h4>Next Steps</h4><p>Understanding Solana’s account system is essential for building efficient blockchain applications. In Parts 2 and 3, we’ll explore more about account management, interactions and their real-world usage.</p><p>Start experimenting with these concepts in your local development environment. The best way to understand Solana accounts is to build with them.</p><blockquote>Key Takeaway: Solana accounts provide a flexible, secure foundation for blockchain development through their unique ownership model and efficient data storage system.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6888216bc6fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Program Derived Addresses (PDAs) in Solana: What, Why, and How?]]></title>
            <link>https://tusharbhatia43.medium.com/program-derived-addresses-pdas-in-solana-what-why-and-how-9bdc69c8d969?source=rss-d77880e966ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bdc69c8d969</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[web3-development]]></category>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[solana-ecosystem]]></category>
            <dc:creator><![CDATA[Tushar Bhatia]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 16:11:04 GMT</pubDate>
            <atom:updated>2025-01-12T16:11:04.828Z</atom:updated>
            <content:encoded><![CDATA[<p>When learning about Solana, you’ll often hear about <strong>Program Derived Addresses (PDAs)</strong>. They’re like these — powerful, versatile, and most importantly slightly misunderstood. If you’re a developer trying to wrap your head around them, don’t worry. We’ll demystify PDAs together in this article.</p><p>In this article, I’ll break PDAs down from the ground up, assuming you’re just getting started with Solana. So, no prior knowledge is required — let’s get started.</p><h4><strong>What is a PDA?</strong></h4><p>Let’s start simple. A <strong>Program Derived Address (PDA)</strong> is a special kind of address in Solana. We all know that Solana uses Accounts to store all the data and Solana Programs are stateless by nature. Unlike regular accounts (like your wallet), PDAs don’t have a private key. Instead, they’re <strong>generated and managed by programs</strong> at runtime.</p><p>Think of PDAs as <strong>program-controlled lockers</strong>:</p><p>• Each locker (PDA) belongs to a specific program.</p><p>• Only the program can access it, control it, and use it to store data.</p><p>• No human can directly sign a transaction for a PDA, because there’s no private key to lose or steal.</p><p>PDAs are generated using:</p><p>1. <strong>Seeds</strong>: Input data (like a user ID or a custom string).</p><p>2. <strong>Program ID</strong>: The program controlling the PDA.</p><p>3. <strong>A Hashing Function</strong>: Ensures the PDA is unique and secure.</p><blockquote><strong>Important Note</strong> — A PDA is <strong>deterministic</strong>: the same input will always generate the same PDA.</blockquote><h4><strong>How are PDAs Different from Regular Accounts?</strong></h4><p>You might be wondering, “If a PDA is just an address, how’s it different from my wallet or other accounts?”</p><p>Here’s a comparison to make it clearer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*3WDFZvucEYUHXg4IttLr8A.png" /></figure><blockquote>Regular accounts are what you use for your wallet or interacting with apps. PDAs, on the other hand, are <strong>program-owned accounts</strong> — only the program can interact with them.</blockquote><h4><strong>When and How are PDAs Used?</strong></h4><p>Here’s when and how PDAs are commonly used:</p><p><strong>1. Data Storage</strong></p><p>Programs often use PDAs to store data. Since PDAs are generated in a predictable way, the program doesn’t need to keep track of their addresses</p><blockquote>It can just compute them when needed.</blockquote><p><strong>Example</strong>: A game program could create a PDA for each player to store their scores, inventory, and achievements.</p><p><strong>2. Token Accounts</strong></p><p>Many programs use PDAs to manage token accounts. For example, staking programs create PDAs to represent your stake, tied directly to your wallet and only the staking program will have authority over it.</p><blockquote><strong>Why PDAs?</strong> Because they’re safe and controlled entirely by the program — no user can tamper with them.</blockquote><p><strong>3. Escrow and Multi-Sig</strong></p><p>PDAs are perfect for holding funds temporarily (e.g., in an escrow system) or for managing multi-signature wallets. They act as impartial accounts, executing transactions only when program rules are met.</p><h4><strong>How to Create a PDA?</strong></h4><p>PDAs are created using the find_program_address function. Here’s how it works:</p><p>1. Provide <strong>seeds</strong> (like “user123” or user_pubkey).</p><p>2. Combine it with the <strong>program ID</strong>.</p><p>3. The function spits out the PDA and a <strong>bump seed</strong> (to avoid collisions).</p><p>Here’s an example in Rust:</p><pre>let (pda, bump_seed) = Pubkey::find_program_address(<br>    &amp;[b&quot;user-seed&quot;, user_pubkey.as_ref()],<br>    program_id<br>);</pre><p>This generates a PDA that only the program can control. The same input for user-seed and public key will always result in the same PDA — no surprises!</p><h4>The Problem with Static Program-Owned Accounts:</h4><p>1.<strong> Static by Nature:</strong><br> — Program-owned accounts are typically created manually at the time of program initialization.<br> — Each account needs to be explicitly funded (rent-exempt) and stored.</p><p>2. <strong>Unique Accounts for Every User or Use Case:</strong><br> — If your program needs individual accounts for many users (e.g., a user-specific escrow or staking account), using regular program-owned accounts would require:<br> — Pre-generating many accounts for each user.<br> — Tracking each account address manually.<br> — Incurring extra costs (rent exemption) for each account upfront.<br> <br>3. <strong>Limited Flexibility:</strong><br> With regular program-owned accounts, the program cannot generate new addresses dynamically based on user input or events.</p><p>These limitations make regular program-owned accounts unsuitable for dynamic, scalable applications like staking pools, liquidity protocols, or user-specific data management.</p><h4><strong>Security Implications of PDAs</strong></h4><p>PDAs are cool and powerful, but they’re not without their quirks. If used incorrectly, they can cause serious security issues. Let’s talk about a few pitfalls to watch out for.</p><p><strong>1. PDAs Shouldn’t Be Used for Authorization</strong></p><p>This is the golden rule. PDAs don’t have private keys, which means they can’t sign transactions. If you use a PDA to authorize sensitive actions (like transferring funds), you’re inviting trouble. An attacker could easily compute the PDA and bypass your checks.</p><blockquote><strong>Note</strong>: Always use cryptographic signatures for user authorization.</blockquote><p><strong>2. Unique Seeds Are Critical</strong></p><p>When generating a PDA, ensure your seeds are unique. If two PDAs end up with the same seed, you’ll overwrite data. It’s like giving two people the same locker key — chaos ensues.</p><p><strong>3. Don’t Store Sensitive Data in PDAs</strong></p><p>PDAs are public. Anyone can compute the address and see what’s inside. If you need to store sensitive data, encrypt it first.</p><h4><strong>Conclusion</strong></h4><p>Program Derived Addresses (PDAs) are a unique feature of Solana that brings deterministic control to smart contracts. They’re flexible, powerful, and secure — as long as you use them responsibly. By understanding how they work and their limitations, you can unlock a whole new level of functionality in your Solana programs.</p><p>And remember: PDAs don’t have private keys. So, if you’re waiting for one to sign something, you’ll be waiting forever. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bdc69c8d969" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Price-Tracking and Automated Trading Bot in Rust]]></title>
            <link>https://tusharbhatia43.medium.com/building-a-price-tracking-and-automated-trading-bot-in-rust-eac61e63d9fd?source=rss-d77880e966ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/eac61e63d9fd</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[cosmos-network]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <dc:creator><![CDATA[Tushar Bhatia]]></dc:creator>
            <pubDate>Fri, 27 Dec 2024 08:18:36 GMT</pubDate>
            <atom:updated>2024-12-27T08:18:36.540Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’m excited to share a project I’ve been working on: a <strong>Rust-based bot</strong> for tracking cryptocurrency prices and performing automated swaps on Ethereum. Whether you’re a blockchain developer or just starting with Rust, this bot offers a practical way to apply your skills to a real-world problem. I’ll walk you through the core components of the bot, explain the architecture, and share how you can extend it.</p><p>Link to GitHub: <a href="https://github.com/tushar1698/Rust-for-Web3/tree/main/Price_and_Swap_Bot">https://github.com/tushar1698/Rust-for-Web3/tree/main/Price_and_Swap_Bot</a></p><p><strong>Why Build This Bot?</strong></p><p>The motivation was simple: I wanted to create something that not only tracks live prices of crypto pairs like ETH/Link but also executes swaps when certain conditions are met. This bot is designed to interact with Uniswap-like decentralized exchanges, making it versatile and useful in both testnets and mainnets.</p><p><strong>The Core Features</strong></p><p>1. <strong>Fetch real-time prices of tokens.</strong></p><p>2. <strong>Perform token swaps automatically based on your preferences.</strong></p><p>3. <strong>Flexible configuration</strong> for easy customization.</p><p>4. <strong>Modular design</strong> to add more token pairs or extend functionality seamlessly.</p><p><strong>The Architecture</strong></p><p>The bot is structured in a modular way to keep things clean and manageable:</p><p>• <strong>config</strong>: Handles user configuration (e.g., RPC URL, private key, token pairs).</p><p>• <strong>client</strong>: Sets up the Ethereum client for blockchain interactions.</p><p>•<strong> price_feed:</strong> Fetches token prices using oracles like Chainlink.</p><p>• <strong>trade:</strong> Executes swaps on Uniswap-style decentralized exchanges.</p><ul><li><strong>main.rs</strong>: The entry point tying everything together.</li></ul><p><strong>Let’s Dive Into the Code</strong></p><p><strong>1. Setting Up the Ethereum Client</strong></p><p>The bot starts by setting up an Ethereum client using your RPC URL and private key stored in the .env file. Here’s the client module:</p><pre>use ethers::prelude::*;<br>use std::sync::Arc;<br><br>pub async fn create_client(<br>    rpc_url: String,<br>    private_key: String,<br>) -&gt; Result&lt;Arc&lt;SignerMiddleware&lt;Provider&lt;Http&gt;, Wallet&lt;SigningKey&gt;&gt;&gt;, Box&lt;dyn std::error::Error&gt;&gt; {<br>    let provider = Provider::&lt;Http&gt;::try_from(rpc_url.clone())?;<br>    let wallet = Wallet::from_str(&amp;private_key)?.with_chain_id(11155111); // Sepolia Testnet<br>    let client = SignerMiddleware::new(provider, wallet);<br>    Ok(Arc::new(client))<br>}</pre><p>This sets up the foundation to interact with Ethereum, enabling us to send transactions and query on-chain data.</p><p><strong>2. Fetching Real-Time Prices</strong></p><p>To get the live prices, we use Chainlink price feeds. Here’s a snippet from the price_feed module:</p><pre>pub async fn get_latest_price(<br>    client: Arc&lt;SignerMiddleware&lt;Provider&lt;Http&gt;, Wallet&lt;SigningKey&gt;&gt;&gt;,<br>    price_feed_address: Address,<br>) -&gt; Result&lt;U256, Box&lt;dyn std::error::Error&gt;&gt; {<br>    let abi = include_bytes!(&quot;../abis/PriceFeed_ABI.json&quot;);<br>    let abi = ethers::abi::Abi::load(abi.as_ref())?;<br>    let contract = Contract::new(price_feed_address, abi, client);<br>    let price: U256 = contract.method(&quot;latestAnswer&quot;, ())?.call().await?;<br>    Ok(price)<br>}</pre><p>This fetches the current price of the specified token pair from a price oracle contract.</p><p><strong>3. Executing Swaps</strong></p><p>The bot supports token swaps on decentralized exchanges. Here’s how the trade module looks:</p><pre>pub struct TradeExecutor {<br>    pub client: Arc&lt;SignerMiddleware&lt;Provider&lt;Http&gt;, Wallet&lt;SigningKey&gt;&gt;&gt;,<br>    pub router_address: Address,<br>    pub recipient: Address,<br>}<br><br>impl TradeExecutor {<br>    pub async fn execute_swap(<br>        &amp;self,<br>        token_in: Address,<br>        token_out: Address,<br>        amount_in: U256,<br>        min_amount_out: U256,<br>    ) -&gt; Result&lt;TxHash, Box&lt;dyn std::error::Error&gt;&gt; {<br>        let abi = include_bytes!(&quot;../abis/Uniswap_Router_ABI.json&quot;);<br>        let abi = ethers::abi::Abi::load(abi.as_ref())?;<br>        let contract = Contract::new(self.router_address, abi, self.client.clone());<br><br>        let tx = contract<br>            .method::&lt;_, TxHash&gt;(<br>                &quot;swapExactTokensForTokens&quot;,<br>                (amount_in, min_amount_out, vec![token_in, token_out], self.recipient, deadline),<br>            )?<br>            .send()<br>            .await?;<br>        Ok(tx)<br>    }<br>}</pre><p><strong>4. Configuration Made Simple</strong></p><p>All sensitive data like RPC URLs and private keys are stored in a .env file. Here’s an example:</p><pre>RPC_URL=https://sepolia.infura.io/v3/YOUR_PROJECT_ID<br>PRIVATE_KEY=&lt;YOUR_PRIVATE_KEY&gt;<br>LINK_ETH_PRICE_FEED=0x42585eD362B3f1BCa95c640FdFf35Ef899212734<br>UNISWAP_ROUTER=0xE592427A0AEce92De3Edee1F18E0157C05861564</pre><p>The config module then loads this data:</p><pre>pub fn load_config() -&gt; Config {<br>    dotenv::dotenv().ok();<br>    Config {<br>        rpc_url: std::env::var(&quot;RPC_URL&quot;).expect(&quot;RPC_URL not found in .env&quot;),<br>        private_key: std::env::var(&quot;PRIVATE_KEY&quot;).expect(&quot;PRIVATE_KEY not found in .env&quot;),<br>        link_eth_price_feed: std::env::var(&quot;LINK_ETH_PRICE_FEED&quot;).unwrap(),<br>        uniswap_router: std::env::var(&quot;UNISWAP_ROUTER&quot;).unwrap(),<br>    }<br>}</pre><p><strong>Customizing the Bot</strong></p><p>Adding new functionality, such as supporting more tokens, is straightforward:</p><p>1. <strong>Add the token contract addresses to the </strong>.env<strong> file.</strong></p><p>2. <strong>Update the </strong>config<strong> and </strong>price_feed<strong> modules accordingly.</strong></p><p>You can even extend the TradeExecutor struct to include more swap methods for ETH-based pairs or other assets.</p><p><strong>Lessons Learned</strong></p><p>Building this bot taught me how to:</p><p>• Use <strong>ethers-rs</strong> to interact with Ethereum.</p><p>• Handle <strong>smart contract calls</strong> in Rust.</p><p>• Write modular, maintainable code.</p><ul><li>Work with Chainlink oracles and Uniswap-like DEXs.</li></ul><p><strong>Final Thoughts</strong></p><p>This project is a great starting point for anyone looking to dive into blockchain development with Rust. Feel free to clone the repository and experiment with the code. Remember, <strong>use it at your own risk</strong> — this is for educational purposes!</p><p>If you found this helpful or have ideas for improvement, let me know in the comments or reach out. Let’s build together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eac61e63d9fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under the Hood of Solana Transactions: From PoH to BPF Execution]]></title>
            <link>https://tusharbhatia43.medium.com/under-the-hood-of-solana-transactions-from-poh-to-bpf-execution-34206ce8441c?source=rss-d77880e966ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/34206ce8441c</guid>
            <category><![CDATA[evm]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[ethereum-virtual-machine]]></category>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <dc:creator><![CDATA[Tushar Bhatia]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 09:27:53 GMT</pubDate>
            <atom:updated>2024-11-05T09:27:53.190Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back! If you read my <a href="https://tusharbhatia43.medium.com/exploring-solanas-consensus-what-makes-proof-of-stake-and-proof-of-history-so-fast-5e44aac81456">last article</a> on Solana’s Proof of History (PoH), you know PoH is like the backstage manager, ensuring transactions are timestamped and in order. But what happens next? How does Solana actually execute a transaction? And what’s this “BPF Loader” anyway? Where is the Compiler?</p><p>Today, we’re going to break down what really happens under the hood when you send a transaction on Solana. From PoH to the BPF Loader, we’ll cover the entire journey in a way that’s easy to digest. Let’s get started!</p><p><strong>1. Solana Transaction Lifecycle: It All Starts with a Click</strong></p><p>Imagine you’re sending SOL to a friend, buying an NFT, or swapping tokens. You hit <em>Send</em>, and here’s what happens:</p><p><strong>Transaction Creation</strong>: You specify details like sender, receiver, and any instructions (perhaps a message like “Here’s for coffee!”).</p><p><strong>Proof of History (PoH)</strong>: PoH timestamps and sequences the transaction, ensuring it’s processed in the right order. <a href="https://docs.solana.com/proposals/poh">Learn more about PoH here</a>.</p><p><strong>Validation through Proof of Stake (PoS)</strong>: Solana’s <strong>Proof of Stake (PoS)</strong> consensus mechanism empowers validators to verify transactions. Validators, chosen based on the amount of SOL they’ve staked, confirm the transaction’s integrity by checking signatures and using PoH’s sequence for order. This dual system allows Solana to maintain ultra-fast speeds with high security. <a href="https://docs.solana.com/cluster/stake-delegation-and-rewards">More on PoS in Solana</a>.</p><p><strong>2. What Happens Under the Hood?</strong></p><p>Once validated, the transaction moves on to Solana’s processing engine. Here’s where Solana’s unique <strong>account-based model</strong> comes in:</p><p>• <strong>Accounts as State Machines</strong>: Every piece of information (from user balances to smart contract data) is stored in “accounts.” Transactions interact with these accounts, updating their state in real time. Check out Solana’s <a href="https://docs.solana.com/developing/programming-model/accounts">account model here</a>.</p><p>• <strong>Parallel Processing</strong>: Solana’s transactions run in parallel, allowing it to handle thousands at once. Unlike blockchains that process transactions one by one, Solana groups and processes non-overlapping transactions simultaneously.</p><p><strong>3. The BPF Loader:</strong></p><p>If PoH is the bouncer, the <strong>BPF Loader</strong> is the chef in Solana’s kitchen, handling smart contract execution. Here’s what you need to know:</p><p>• <strong>What’s BPF?</strong> BPF (Berkeley Packet Filter) originally came from Linux for network packet filtering. Solana adapted it to efficiently execute smart contracts in a resource-friendly way. <a href="https://docs.solana.com/developing/programming-model/overview#berkeley-packet-filter">More on BPF here</a>.</p><p>• <strong>The BPF Loader’s Role</strong>: Solana compiles its smart contracts into BPF bytecode, which the BPF Loader then interprets and runs. It’s like loading a mini program, executing each instruction step-by-step.</p><p>• <strong>Efficiency and Security</strong>: The BPF Loader isolates each program’s execution, enhancing security and keeping fees low. Because it’s built for speed, the BPF Loader is a key reason why Solana can handle complex applications without slowing down.</p><p><strong>4. From Start to Finish:</strong></p><p>Let’s put it all together with an example.</p><p>Imagine you’re transferring tokens to a friend:</p><p><strong>Initiate the Transfer</strong>: You click <em>Send</em>. The transaction specifies the sender, receiver, and instructions.</p><p><strong>PoH Timestamps</strong>: PoH sequences the transaction.</p><p><strong>Validators Verify</strong>: Using PoS, validators confirm the transaction details based on the PoH sequence.</p><p><strong>Execution with BPF Loader</strong>: The BPF Loader loads the smart contract program and executes it, transferring tokens from your account to your friend’s.</p><p><strong>Account Updates</strong>: Solana’s account model records the transaction and updates balances, making it official!</p><p><strong>5. Why the BPF Loader Matters for Solana</strong></p><p>The BPF Loader isn’t just an executor — it’s what makes Solana so unique:</p><p>• <strong>Multi-Program Execution</strong>: BPF allows multiple programs to run in a single transaction, critical for DeFi and complex applications.</p><p>• <strong>Low Fees and High Efficiency</strong>: BPF’s optimized execution keeps fees low while ensuring speed.</p><ul><li><strong>Security through Isolation</strong>: Each program runs in isolation, so an issue with one program doesn’t affect the others.</li></ul><p><strong>EVM vs. Solana Transactions: A Quick Comparison</strong></p><p>Now that we know how a transaction typically works in Solana, let’s compare it to how EVM (Ethereum Virtual Machine) blockchains like Ethereum handle transactions. This way, we’ll get a better sense of what makes Solana so unique!</p><p><strong>1. Execution Environment: EVM vs. BPF Loader</strong></p><p><strong>EVM</strong>: In EVM-based blockchains, like Ethereum, smart contracts are written in Solidity (or Vyper) and then run directly in the EVM, which is basically Ethereum’s smart contract engine. Transactions are executed one at a time, so they wait in line until it’s their turn. Plus, each transaction needs gas (a.k.a. fees) based on its complexity. This can lead to high fees, especially when the network is busy.</p><p><strong>Solana’s BPF Loader</strong>: Solana’s programs (a.k.a. smart contracts) are written in Rust or C, then compiled into BPF bytecode, which the <strong>BPF Loader</strong> interprets and executes. This system is designed for super-fast processing, so it’s a big reason why Solana fees stay low. Solana also processes transactions in <strong>parallel</strong>, which lets it handle thousands at once, unlike the EVM’s single-file-line approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*6y2qEgtkiYWOiekRBbrX1w.png" /></figure><p><strong>2. Sequential vs. Parallel Processing</strong></p><p>• <strong>EVM</strong>: EVM processes transactions sequentially, like a single-lane road. Each transaction has to wait for the previous one to complete before moving ahead. This setup can cause bottlenecks and high fees during peak times.</p><p>• <strong>Solana</strong>: Solana’s parallel processing is like a multi-lane highway. Transactions that don’t interact with the same accounts can be processed at the same time, so it can handle tons of transactions without slowing down. This is one of the main reasons Solana can keep fees low and speeds high, even with lots of users on the network.</p><p><strong>3. Stateless vs. Stateful Programs</strong></p><p><strong>EVM (Stateful)</strong>: On Ethereum, contracts hold their own data and state (memory), which can be convenient but can also limit scalability. Each transaction modifies this “state” directly, which means it can only handle one change at a time per contract. If you’re interacting with a popular smart contract, get ready for potential congestion.</p><p><strong>Solana (Stateless)</strong>: Solana takes a different approach. Programs are <strong>stateless</strong>, meaning they don’t store data themselves. Instead, all data and state info is held in separate “accounts” that the programs interact with. This design allows more flexibility and enables Solana’s parallelism magic since programs don’t have to worry about keeping track of their own state — everything they need to read or write is external.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*J8y0nUw0HCzXGvtm7dy1xQ.png" /></figure><p><strong>Wrapping Up:</strong></p><p>So, from PoH keeping things in order to the BPF Loader making sure smart contracts run smoothly, you can see that Solana’s design is all about speed and efficiency. Every part: PoH, PoS validation, accounts, and the BPF Loader plays a role in making sure your transactions are fast, secure, and cheap.</p><p>Now, we’ve touched on accounts here, but Solana’s account and ownership system is unique and deserves its own spotlight. Stay tuned for a future article where we’ll break down how accounts and ownership actually work in Solana — because understanding that piece really brings the whole system together. In the meantime, check out <a href="https://docs.solana.com/">Solana’s docs</a> if you’re curious, and feel free to drop questions in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34206ce8441c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Solana’s Consensus- What Makes Proof of Stake and Proof of History So Fast?]]></title>
            <link>https://tusharbhatia43.medium.com/exploring-solanas-consensus-what-makes-proof-of-stake-and-proof-of-history-so-fast-5e44aac81456?source=rss-d77880e966ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e44aac81456</guid>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[crypto-education]]></category>
            <category><![CDATA[proof-of-stake]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Tushar Bhatia]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 12:20:15 GMT</pubDate>
            <atom:updated>2024-11-01T12:20:15.198Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re curious about what makes Solana stand out in the blockchain world, you’re not alone. Honestly, when I first dug into it, I was surprised at just how different it is from other blockchains. Solana doesn’t just rely on Proof of Stake (PoS) like most blockchains — it adds this unique system called Proof of History (PoH) into the mix. And these two together? They’re what give Solana its speed and affordability. Let’s unpack this together.</p><p><strong>Starting with Solana’s Foundation: Proof of Stake (PoS)</strong></p><p>So, a quick refresher on PoS. In Solana’s network, validators secure everything by staking SOL tokens — essentially locking them in as a “deposit” to show they’re committed. The more SOL they stake, the better their chances of getting chosen to validate transactions and earn rewards. It’s a bit like earning trust points, keeping everyone honest and motivated to keep the network safe.</p><p>But here’s where it gets interesting: Solana didn’t stop there. Instead, they added this layer called Proof of History, and that’s where the magic really starts.</p><p><strong>Proof of History (PoH)</strong></p><p>Now, PoH might sound fancy, but it’s actually super straightforward once you get it. Think of it like a built-in timer. Every transaction gets its own timestamp right when it comes in, so everything’s already in order by the time validators see it. This makes Solana crazy efficient — validators don’t have to stop and ask each other about the order because it’s all pre-organized. It saves so much time!</p><p>Let me give you a few examples to make PoH really click:</p><p>• <strong>A Digital Stopwatch for Transactions</strong>: Picture PoH as Solana’s own stopwatch, ticking away as each transaction arrives. Every one of them gets a timestamp, like marking splits on a stopwatch. Because of that, validators don’t have to figure out what came first — it’s already clear. When I first got this, it made total sense why Solana’s so fast.</p><p>• <strong>The Warehouse Barcode Scanner</strong>: PoH is like a barcode scanner in a busy warehouse. Every transaction has a unique “arrival time,” so validators can just scan it and know exactly where it fits. Without PoH, they’d have to constantly double-check with each other. Instead, PoH does the work, speeding things up and cutting out any back-and-forth.</p><p><strong>Why the PoH + PoS Combo Sets Solana Apart?</strong></p><p>1. <strong>Transaction Speed</strong></p><p>Most blockchains feel like single-lane roads, with each transaction waiting its turn. But PoH lets Solana act more like an expressway, with everything queued up in order. Validators don’t have to slow down; they just confirm each transaction as they come. This setup is why Solana can process over 65,000 transactions per second — pretty incredible if you think about it.</p><p>2. <strong>Efficiency in Reaching Consensus</strong></p><p>PoH acts like a universal clock that all validators follow. It’s almost like they’re working from the same synced calendar, eliminating any need for constant checking. This keeps things efficient and helps avoid the usual slowdowns. It’s faster and more efficient than a lot of other systems, and it’s a big reason why Solana can handle so much traffic.</p><p>3. <strong>Low Costs and High Throughput</strong></p><p>Since PoH lines everything up in advance, validators can process many transactions at once. Imagine it like a bulk-processing line where everything is ready and waiting. This keeps transaction costs low even when there’s a lot going on, making Solana a very cost-effective option.</p><p><strong>Why/How Solana’s PoS + PoH Design is Changing the Game?</strong></p><p>Solana’s combination of PoS and PoH has created a unique edge in the blockchain world. This setup is ideal for applications that rely on fast, low-cost transactions—like DeFi, gaming, and NFTs. By streamlining transaction processing with PoH’s pre-ordered timestamps, Solana makes it easy for developers to build responsive, affordable applications.</p><p>For users, this means a smoother experience without delays or high fees, regardless of network traffic. Solana’s ability to sidestep the usual bottlenecks has made it a popular choice for high-performance blockchain projects. With PoS and PoH working together, Solana is shaping up to be a powerful tool for the next generation of decentralized apps.</p><p>This version highlights the impact of Solana’s design on performance and accessibility without directly repeating the developer and user appeal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e44aac81456" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Huff vs Yul: Mastering EVM Storage Optimization for Gas Efficiency]]></title>
            <link>https://tusharbhatia43.medium.com/huff-vs-yul-mastering-evm-storage-optimization-for-gas-efficiency-8af053d28ef1?source=rss-d77880e966ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/8af053d28ef1</guid>
            <category><![CDATA[solidity-tutorial]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[evm]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Tushar Bhatia]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 16:06:40 GMT</pubDate>
            <atom:updated>2024-09-28T16:06:40.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ce6P8RfnEB-yT6X1c3PYA.png" /></figure><p>When optimizing <strong>Ethereum Virtual Machine (EVM)</strong> storage and gas efficiency, two low-level programming languages are like the Batman and Superman of the blockchain world: <strong>Huff</strong> and <strong>Yul</strong>. Both can save your smart contract from the evils of high gas fees, but they each have their own unique superpowers (and weaknesses). In this article, we’ll break down their differences, share some pro tips, and help you decide which hero is right for your project. ⚡️</p><h4><strong>What is Huff?</strong></h4><p><strong>Huff</strong> is the hardcore, no-nonsense hero of gas optimization. It’s like the martial artist who can pinpoint every single gas unit in your smart contract and cut it down with precision. This low-level language allows direct access to the EVM, making it perfect for creating highly optimized code. But, just like learning to fight crime, it’s not for the faint of heart.</p><p><strong>Pros of Huff</strong></p><p>• <strong>Ultimate Control</strong>: Huff gives you the steering wheel. Every single instruction you write is executed exactly as you intended. Want control over every gas unit? Huff’s your guy.</p><p>• <strong>Best for Gas Savings</strong>: Huff gets deep into the nuts and bolts of the EVM, letting you optimize your contract like a gas-saving ninja.</p><p><strong>Cons of Huff</strong></p><p>• <strong>Steep Learning Curve</strong>: Let’s face it, Huff is not easy. Writing code in Huff is like trying to read an ancient scroll — it takes time to understand and master.</p><p>• <strong>Tough to Maintain</strong>: Huff can optimize your contract down to the last byte, but maintaining it later? Well, that’s a whole other story. You’ll need a decoder ring just to figure out what you wrote six months ago. 😅</p><p><strong>Code Example:</strong></p><p>Here’s an example of how you can manually define a storage slot in Huff to optimize gas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osf9a3ChvxUoDRplgTQlWg.png" /></figure><p>In this example, we define a storage slot at 0x00 and create a macro function LOAD_SLOT to access this value directly. Huff gives you fine-grained control over storage assignment, which can help with <strong>EVM storage optimization</strong>.</p><p><strong>Pro Tip: </strong>If you’re using Huff, plan your EVM storage slots carefully. Think of it like packing for a trip — only bring what you need and make sure you’re not wasting gas on unnecessary storage.</p><p><strong>What is Yul?</strong></p><p><strong>Yul</strong>, on the other hand, is more like the friendly neighbourhood superhero. It’s still low-level enough to optimize gas, but it won’t make your head explode trying to understand it. Think of Yul as your trusty sidekick that makes optimization more approachable while still keeping things efficient.</p><p><strong>Pros of Yul</strong></p><p>• <strong>Easy to Read</strong>: Compared to Huff, Yul is like reading a comic book instead of an encyclopedia. It’s easier to understand and write while still giving you some solid optimizations.</p><p>• <strong>Works Well with Solidity</strong>: Yul plays nicely with Solidity, making it a good choice if you want to optimize specific parts of your smart contract without going full assembly mode.</p><p><strong>Cons of Yul</strong></p><p>• <strong>Less Fine-Grained Control</strong>: Yul doesn’t give you the same fine-tuned control over EVM storage as Huff does. It’s great for optimization, but if you’re looking to squeeze out every last drop of gas, you might hit a ceiling.</p><p>• <strong>Smaller Ecosystem</strong>: Yul doesn’t have as many libraries or tools available as Solidity, so you may need to build some custom logic from scratch.</p><p><strong>Code Example:</strong></p><p>Here’s how Yul can be used to write optimized loops to reduce gas consumption:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*Z7eUJ84sKNWl-9z7TnHTvQ.png" /></figure><p>This loop example is straightforward and clean compared to Solidity’s equivalent, making it ideal for <strong>batch transactions</strong> where optimization is critical.</p><p><strong>Pro Tip: </strong>Use Yul when you’re dealing with batch transactions. Its loop capabilities can help you cut down on redundant external calls, saving a nice chunk of gas without diving too deep into the EVM’s inner workings.</p><p><strong>Tooling and Ecosystem</strong></p><p>When it comes to tooling, <strong>Huff</strong> and <strong>Yul</strong> both have their own sets of resources, but they are quite different in scope.</p><p><strong>Huff Tooling:</strong></p><p>• <strong>Huff Compiler</strong>: The <a href="https://docs.huff.sh/get-started/installing/"><strong>Huff compiler</strong></a> is lightweight but does the job of compiling Huff contracts. You’ll need to be comfortable with the command line for deploying and testing your contracts.</p><p>• <a href="https://github.com/huff-language/huffmate"><strong>Huffmate</strong></a>: An emerging IDE tool to help with writing and compiling Huff contracts more efficiently.</p><p>• <strong>Testing Frameworks</strong>: Currently, you’ll need to rely on Solidity-based testing frameworks like <strong>Hardhat</strong> or <strong>Foundry</strong> to integrate your Huff code with larger Solidity projects.</p><p><strong>Yul Tooling:</strong></p><p>• <strong>Solidity Compiler Support</strong>: The <strong>Solidity compiler</strong> (solc) comes with built-in support for Yul, making it easy to compile and deploy. Just switch to Yul in your Solidity project.</p><p>• <strong>Integration</strong>: Yul integrates smoothly with Solidity and other Ethereum developer tools, so you can use <strong>Hardhat</strong>, or <strong>Foundry</strong> (RIP Truffle) without any extra setup.</p><p>• <strong>Testing</strong>: Testing Yul contracts is as simple as testing Solidity code, making it a more accessible option for developers already familiar with the Ethereum development environment.</p><p><strong>Huff vs Yul: How to Choose?</strong></p><p>So, which superhero do you call when it’s time to optimize your smart contracts? It all depends on your mission.</p><p>If you’re a gas-saving perfectionist who loves getting into the weeds of EVM storage, <strong>Huff</strong> is the way to go. But if you want a more balanced approach with easier readability and still plenty of optimizations, <strong>Yul</strong> is your go-to sidekick.</p><p><strong>When to Use Huff:</strong></p><p>• You want to go all-in on gas optimization and don’t mind the challenge.</p><p>• You need full control over EVM storage and are ready to write low-level code.</p><p>• You love assembly (or at least, you tolerate it). 🛠️</p><p><strong>When to Use Yul:</strong></p><p>• You want a balance between optimization and readability.</p><p>• You’re working on a contract with lots of batch transactions or repetitive actions.</p><p>• You want to integrate with Solidity but need to optimize specific sections.</p><h4><strong>Pro Tips for Working with Huff and Yul</strong></h4><p>1. <strong>Batch Operations in Yul</strong>: If you’re working with loops or batch processes, Yul’s ability to handle repetitive tasks efficiently will save you a ton of gas.</p><p>2. <strong>Storage Planning in Huff</strong>: In Huff, plan out your <strong>EVM storage slots</strong> carefully — organizing storage upfront will pay off in gas savings later.</p><p>3. <strong>Hybrid Approach</strong>: Use Solidity for most of your logic, and drop into Yul or Huff for gas-heavy sections. It’s the best of both worlds!</p><p>4. <strong>Start with Yul</strong>: If you’re new to EVM optimization, start with Yul to get comfortable. Once you feel more confident, dive into Huff for maximum efficiency.</p><h4><strong>Conclusion</strong></h4><p>Both <strong>Huff</strong> and <strong>Yul</strong> are powerful tools for mastering <strong>EVM storage optimization </strong>in my opinion. Huff is the go-to if you’re looking to push the limits of gas savings and have the patience for low-level coding. Yul, on the other hand, offers a more readable, balanced approach to optimizing specific sections of your contract.</p><p>Whichever path you choose, mastering these languages will level up your <strong>smart contract development skills</strong> and help you write efficient, scalable applications on the <strong>Ethereum blockchain</strong>. Good luck, and may your gas fees be low! 💸</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8af053d28ef1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum Virtual Machine (EVM) vs Traditional Operating Systems: A Simple Guide (Part 3)]]></title>
            <link>https://tusharbhatia43.medium.com/ethereum-virtual-machine-evm-vs-traditional-operating-systems-a-simple-guide-part-3-1572bd716ffe?source=rss-d77880e966ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/1572bd716ffe</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[gas-fees]]></category>
            <category><![CDATA[evm]]></category>
            <category><![CDATA[solidity-development]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <dc:creator><![CDATA[Tushar Bhatia]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 06:52:16 GMT</pubDate>
            <atom:updated>2024-09-23T06:52:16.802Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back to the final chapter of our Ethereum Virtual Machine (EVM) deep dive. So far, we’ve explored <a href="https://tusharbhatia43.medium.com/ethereum-virtual-machine-evm-vs-traditional-operating-systems-a-simple-guide-part-1-6b0ec23ca8d1">Part 1</a> and <a href="https://tusharbhatia43.medium.com/ethereum-virtual-machine-evm-vs-traditional-operating-systems-a-simple-guide-part-2-1578498c678b">Part 2</a>, how the EVM stacks up against traditional OS sandboxes and why its design shapes decentralized applications. Now, it’s time to crack open the mechanics of gas, storage, and efficiency on Ethereum — key ingredients to building better smart contracts.</p><p><strong>Why Does Gas Matter?</strong></p><p>Ethereum runs on gas, plain and simple. Every action, whether it’s transferring tokens or interacting with smart contracts, needs gas to get from point A to point B. And just like a car on the road, the more complex the journey (more contract operations), the more fuel (gas) you burn.</p><p><strong>Understanding Gas: The Backbone of Ethereum</strong></p><p>Imagine gas as Ethereum’s toll system. You pay for every computation your contract makes. If you run out of gas mid-operation, the transaction fails. Think of it as your car breaking down halfway through a trip because the tank ran empty.</p><p><strong>Gas Costs: The Hidden Pain of Developers and Users</strong></p><p>Gas is more than just a small annoyance for users. High gas fees can make your decentralized application (dApp) expensive, alienating users. From a developer’s perspective, inefficient code not only wastes gas but creates hurdles for adoption and scalability.</p><p>Let’s break it down. Why does gas efficiency matter?</p><p><strong>Three Key Gas Optimization Strategies</strong></p><p>1. <strong>Minimizing State Changes</strong></p><p>Modifying the state is one of the most expensive things you can do in Ethereum because it involves writing data to the blockchain. Aim to batch state changes wherever possible.</p><p><strong>Example</strong>: Instead of updating user balances every time a transaction happens, accumulate these updates and make one final state change at the end. This reduces gas by consolidating multiple operations into a single write.</p><p><strong>Analogy</strong>: Think of it like closing your cash register at the end of the day rather than ringing up each sale as it happens. Fewer entries, less work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*uakYfl5XX5fUI9TWMWbOdQ.png" /></figure><p>2. <strong>Efficient Function Design</strong></p><p>The structure of your functions matters more than you think. Large loops or excessive calls inside a single function can eat up gas fast. Using call data instead of memory for function inputs can also help save gas.</p><p><strong>Pro Tip</strong>: Avoid unnecessary looping. Breaking down large operations into smaller, more manageable chunks will minimize gas consumption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*RFAc9xFUnj1g4y36CuNNDw.png" /></figure><p>3. <strong>Stay Updated with Solidity</strong></p><p>Solidity’s new versions often include gas optimizations under the hood. Keeping your smart contract code updated is a low-effort way to reap these efficiency rewards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynZtCxiY8DJvmsLztP2iOQ.png" /></figure><h4><strong>Storage: On-Chain vs. Off-Chain</strong></h4><p>One of the biggest decisions you’ll make as a developer is where to store your data — on-chain or off-chain. On-chain storage is secure and immutable, but it comes at a premium. Meanwhile, off-chain storage offers cost benefits but sacrifices some transparency.</p><h4><strong>On-Chain Storage in EVM: How is Data Physically Stored?</strong></h4><p>One of the fundamental differences between the Ethereum Virtual Machine (EVM) and traditional operating systems is how they handle storage, particularly on-chain data. In a traditional OS, data is typically stored in local file systems, databases, or external storage drives, which are structured in a hierarchical directory tree. By contrast, the EVM operates on a decentralized network of nodes, with each node contributing to the collective ledger of data.</p><p>So, how is EVM data physically stored on the node, and how does that differ from traditional OS storage?</p><p><strong>Data Structure in EVM</strong></p><p>In Ethereum, all on-chain data is stored in key-value pairs using <strong>Merkle Patricia Trie</strong> (MPT). This cryptographic data structure helps verify the integrity of transactions and states efficiently. Unlike a traditional OS where files are stored in folders, Ethereum stores everything in a shared global state where each contract and account has an associated state root, mapping directly to its data on the blockchain.</p><p>• <strong>State Trie:</strong> The EVM keeps track of the entire state of the system using a structure called the “state trie.” Each account or contract has its own unique address, and this trie is used to track balances, contract code, and storage variables. Each node in the Ethereum network has a copy of the State Trie, and this trie is updated every time a new transaction is executed, such as when ether is sent or when smart contract code is called.</p><p>• <strong>Storage Trie:</strong> Each smart contract or account has its own storage trie. When a contract stores data, such as token balances or critical contract variables, that data is saved in this storage trie, which is unique to that specific contract address.</p><p>This structure is highly efficient for decentralized systems but significantly different from how traditional OS storage works. In traditional OS storage, data retrieval and updates are faster and more direct due to centralized access.</p><h4><strong>Physical Storage on Ethereum Nodes</strong></h4><p>When you deploy a smart contract or store any data on the blockchain, that information is propagated across all full nodes in the Ethereum network. Each full node keeps a copy of the blockchain, which includes transaction data, the state trie, and storage tries for every account. This data is stored physically on hard drives or SSDs of the nodes, but unlike a traditional OS that stores files locally for private use, blockchain data is replicated across thousands of nodes globally.</p><p>• <strong>Distributed Nature:</strong> Traditional OS data is usually centralized, stored on a local machine or a specific server. In contrast, EVM data is decentralized and replicated across many Ethereum nodes. Each node has a copy of the same data, ensuring redundancy and security.</p><p>• <strong>Immutable and Public:</strong> Once data is written to the blockchain, it becomes immutable and public. While traditional OS systems allow for private data storage with the option to modify or delete files, EVM data is permanent and cannot be tampered with.</p><p>• <strong>Use Cases</strong>: Token balances, critical contract data.</p><p>• <strong>Example</strong>: An ERC-20 token’s balance mapping is stored on-chain to maintain transparency and security.</p><p><strong>Gas Cost</strong>: Each storage write can consume up to 20,000 gas.</p><p><strong>Analogy</strong>: Think of it as renting a safe deposit box. It’s secure and accessible, but space is limited, and the cost is high.</p><h4><strong>Off-Chain Storage</strong></h4><p>Data that doesn’t require on-chain storage can be offloaded to cheaper solutions like IPFS or Arweave. These systems provide decentralized storage without clogging up Ethereum’s space, but you’ll need to store a reference (hash) on-chain to access it.</p><p>• <strong>Use Cases</strong>: Large files, media, or non-critical data.</p><p>• <strong>Example</strong>: An NFT’s artwork is stored off-chain, with the hash on-chain as a reference.</p><p><strong>Gas Cost</strong>: A fraction of the cost of on-chain storage since you’re only saving a hash.</p><p><strong>Analogy</strong>: Imagine storing your photo albums in the attic and just keeping a note of where they are—safe but cost-effective.</p><h4><strong>Practical Tips for Developers: Boosting Efficiency in Smart Contracts</strong></h4><p>1. <strong>Batch Transactions</strong></p><p>Instead of processing each transaction individually, consider batching them. This approach can reduce gas consumption by consolidating multiple operations into a single call.</p><p><strong>Example</strong>: A payout contract can batch payments, processing multiple users’ payouts in one function call.</p><p>2. <strong>Leverage Solidity Libraries</strong></p><p><strong>Solidity’s built-in libraries</strong>, such as <a href="https://docs.openzeppelin.com/contracts/4.x/api/utils#SafeMath">SafeMath</a>, <a href="https://docs.openzeppelin.com/contracts/4.x/api/security#ReentrancyGuard">ReentrancyGuard</a>, <a href="https://docs.openzeppelin.com/contracts/4.x/api/utils#ECDSA">ECDSA</a>, <a href="https://docs.openzeppelin.com/contracts/4.x/api/utils#Strings">Strings</a>, and <a href="https://docs.openzeppelin.com/contracts/4.x/api/utils#SafeCast">SafeCast</a>, offer optimized solutions that reduce gas and improve security.</p><p>3. <strong>Avoid Redundancy</strong></p><p>Functions that perform repetitive checks or unnecessary operations can become a gas sink. Streamline your logic to ensure efficiency.</p><p><strong>Example</strong>: A function that checks the same condition multiple times can consolidate checks at the start, reducing computational load.</p><h4><strong>Real-World Case Study: Optimizing a Crowdfunding Contract</strong></h4><p>Consider a crowdfunding contract where users contribute funds and can claim refunds if the project goal isn’t met.</p><p>In the initial design:</p><p>• Each contribution updates the contract’s total funds (on-chain).</p><p>• Refunds are processed individually, involving multiple state changes.</p><p><strong>The Problem</strong></p><p>• Frequent updates to the contract’s state lead to excessive gas costs.</p><p>• Processing refunds for each contributor adds further complexity.</p><p><strong>The Optimization</strong></p><p>• Instead of updating the total funds after every contribution, batch the updates at the end of the campaign.</p><p>• Process refunds in a single transaction for all users, minimizing costly state changes.</p><h4><strong>Conclusion: Balancing Gas, Storage, and Efficiency for Smarter dApps</strong></h4><p>The EVM’s decentralized nature means that all storage is distributed across multiple nodes, relying on cryptographic structures to ensure security and immutability. In contrast, traditional OS storage systems are centralized, faster, and more flexible, but they don’t offer the same level of decentralization or trustlessness. As a developer, understanding how EVM handles data storage can help you design smarter, more efficient contracts while minimizing gas costs, an essential factor for building scalable decentralized applications.</p><p>Remember, gas is finite, storage is costly, and efficiency is key. Keep these factors in mind, and you’ll create decentralized applications that are not only scalable but also sustainable in the long run.</p><h4>External Links For Reference and Further Studies</h4><blockquote>• For a deeper dive into how Ethereum’s gas system functions, check out the <a href="https://ethereum.org/en/developers/docs/gas/">official Ethereum gas documentation</a>.</blockquote><blockquote>• Keeping your contracts up to date with the latest version of Solidity can significantly reduce gas consumption. Learn more in the <a href="https://docs.soliditylang.org/en/v0.8.27/">Solidity official documentation</a>.</blockquote><blockquote>• For more information on how off-chain storage solutions like IPFS can reduce on-chain gas costs, visit the <a href="https://ipfs.tech/">IPFS website</a>.</blockquote><blockquote>• To ensure your smart contract is secure and gas-efficient, check out ConsenSys’ <a href="https://consensys.github.io/smart-contract-best-practices/">Smart Contract Best Practices</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1572bd716ffe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum Virtual Machine (EVM) vs Traditional Operating Systems: A Simple Guide (Part 2)]]></title>
            <link>https://tusharbhatia43.medium.com/ethereum-virtual-machine-evm-vs-traditional-operating-systems-a-simple-guide-part-2-1578498c678b?source=rss-d77880e966ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/1578498c678b</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[evm]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Tushar Bhatia]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 09:07:16 GMT</pubDate>
            <atom:updated>2024-09-12T14:03:56.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*DaO6xsK7nt-iMnEU.png" /></figure><p>In the <a href="https://tusharbhatia43.medium.com/ethereum-virtual-machine-evm-vs-traditional-operating-systems-a-simple-guide-part-1-6b0ec23ca8d1">first part</a> of this series, we explored the key differences between Ethereum’s Virtual Machine (EVM) and traditional operating systems (OS) like Linux and Windows. We touched on topics like how smart contracts are executed, how hardware interacts with the EVM, and what “sandboxing” means in both environments.</p><p>In this second part, we’ll dive deeper into <strong>how Ethereum’s EVM interacts with hardware, reaches consensus, and executes smart contracts across multiple nodes</strong>. Along the way, we’ll introduce new real-world examples and provide a deeper understanding of the unique architecture of Ethereum. Let’s jump in!</p><p><strong>How Ethereum’s EVM Manages Hardware Interaction</strong></p><p>In traditional operating systems, the kernel manages hardware, controlling things like memory, CPU, and file systems. But the EVM, running across decentralized nodes, abstracts the hardware layer.</p><p><strong>How does this work?</strong></p><p>Every Ethereum node has its own operating system (like Linux), which handles hardware. The EVM sits on top of this, operating independently of the actual hardware. This ensures that the smart contracts run consistently across different machines, even if the underlying hardware differs.</p><p>In both systems, resource allocation plays a crucial role, but in Ethereum’s case, gas fees ensure fair use of resources across nodes.</p><p><strong>Reaching Consensus: How Ethereum Executes Smart Contracts Across Multiple Nodes</strong></p><p>In a traditional operating system, when you perform a task, it happens on a single machine. But in Ethereum, every smart contract execution must reach consensus across thousands of decentralized nodes.</p><p><strong>Real-World Analogy: The Jury System</strong></p><p>Imagine you’re in a courtroom, and a jury must unanimously agree on a verdict before a decision is final. Similarly, Ethereum nodes must come to an agreement on the state of the blockchain and smart contract execution.</p><p>When you send a transaction to Ethereum (say, swapping tokens on Uniswap), it gets propagated across the network. Every node runs the EVM and verifies that your transaction is valid. After reaching a consensus, the transaction is finalized and added to the blockchain.</p><p><strong>The Role of Gas in Ethereum: A Unique Resource Allocation Mechanism</strong></p><p>In the EVM, the concept of <strong>gas</strong> acts like a metered service that limits how much computation can be done in each transaction. Gas ensures that no single transaction consumes too many resources and halts the entire network.</p><p><strong>Real-World Example: Paying for Utilities</strong></p><p>Think of gas as a utility bill. Just like electricity or water, you pay for what you use. In Ethereum, gas fees are paid to miners (now validators in Proof of Stake) to incentivize the processing of transactions. The more complex your smart contract, the more gas is needed to run it.</p><h4><strong>Gas Costs in Solidity Code</strong></h4><p>Consider the following Solidity code. Each operation inside the smart contract has a gas cost associated with it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0EvKLtNW-PHPZvTjIGM4eA.png" /></figure><p>The <strong>setData</strong> function changes the state of the contract, so it requires more gas. The <strong>getData</strong> function, on the other hand, is just a read operation and is less gas-intensive.</p><h4><strong>Sandboxing in Ethereum vs. Traditional OS: Why Security Matters</strong></h4><p>In both Ethereum’s EVM and traditional operating systems (OS), sandboxing plays a crucial role in ensuring security, isolation, and smooth operation. While the general concept is the same — separating processes to prevent interference — how it works in these two environments is quite different.</p><p><strong>What Is Sandboxing?</strong></p><p>Sandboxing is a technique that isolates programs or smart contracts to ensure that they don’t interfere with one another. In both traditional OS and the EVM, sandboxing is essential for preventing potential bugs or malicious actions in one program from affecting the rest of the system.</p><p>In Ethereum, each smart contract is isolated within its own “sandbox.” This means that each contract operates with its own set of data and resources, making sure that no external contract or account can interfere with it unless explicitly allowed. Even if a smart contract contains bugs or vulnerabilities, the damage remains contained within that specific contract, and other contracts are unaffected.</p><p>In a <strong>traditional OS</strong>, sandboxing is used to isolate applications (like a browser or a game) to protect the system and other applications from potential harm. For example, if a malicious app were to crash or attempt to access sensitive parts of the system, the OS would isolate it to prevent widespread damage.</p><p><strong>Ethereum’s Sandbox: Decentralization and Security</strong></p><p>In Ethereum, sandboxing is more complex because the EVM runs across thousands of decentralized nodes. The primary goal is to ensure that smart contracts run securely and independently on every node, without any external influences or interference.</p><p><strong>Why Is This Crucial?</strong></p><p>Smart contracts handle valuable assets and execute critical functions in decentralized finance (DeFi) platforms. If sandboxing were not in place, vulnerabilities in one contract could lead to catastrophic losses across the entire network. Sandboxing protects the integrity of Ethereum’s decentralized nature by ensuring that no single smart contract can bring down the entire network.</p><p><strong>Example: The DAO Hack</strong></p><p>One of the most well-known incidents in Ethereum’s history is <strong>The DAO hack</strong>. In 2016, a vulnerability in The DAO smart contract was exploited, leading to the loss of millions of dollars’ worth of Ether. While the vulnerability was specific to The DAO contract, other contracts remained unaffected because they were sandboxed. This isolation prevented further losses and safeguarded the integrity of the Ethereum network.</p><p><strong>Traditional OS Sandboxing: Protecting Your System</strong></p><p>In traditional OS environments, sandboxing is primarily about keeping your system secure from potentially harmful applications. When you download an app or run a browser, the operating system uses sandboxing to restrict the app’s access to sensitive parts of your system, like your files or network.</p><p>For example, when you open a webpage that contains malicious code, the browser’s sandbox ensures that the malicious code stays within the browser and doesn’t spread to other parts of the system. If sandboxing weren’t in place, this code could affect your files, steal sensitive information, or crash your entire system.</p><h4><strong>Security Comparisons</strong></h4><p>• <strong>Ethereum (EVM)</strong>: Sandboxing ensures that each smart contract is isolated from others. This prevents cross-contract interference and secures the network from widespread vulnerabilities. It’s particularly important in DeFi, where financial contracts control large sums of money.</p><p>• <strong>Traditional OS</strong>: Sandboxing protects the system from external threats and malicious programs. It keeps rogue apps from accessing system files or interfering with other applications, thus maintaining the system’s overall stability and security.</p><p><strong>The Role of Smart Contracts in Ethereum’s Security Model</strong></p><p>Ethereum smart contracts run autonomously and can be interacted with by any external user or contract. This openness requires a robust security model where every contract is guaranteed to run in isolation. Sandboxing ensures that a faulty or malicious contract can’t manipulate or interfere with other contracts running on the network. This containment mechanism is fundamental to maintaining trust in decentralized applications (DApps) and preventing large-scale hacks or exploits.</p><p><strong>Traditional OS vs. EVM: Handling Failures</strong></p><p>In a traditional OS, if an application fails (due to bugs or malware), the OS ensures that the failure remains confined to that application through sandboxing mechanisms. Similarly, in Ethereum, if a smart contract fails or is exploited, the failure is confined to that specific contract, and the rest of the network remains unaffected.</p><p>In both cases, sandboxing is critical for mitigating risks and ensuring that failures don’t escalate into system-wide vulnerabilities. However, the key difference is that Ethereum’s sandboxing operates in a decentralized environment, which requires consensus across multiple nodes to execute and validate transactions.</p><p><strong>Ethereum 2.0 and Future Scalability: The Next Evolution of the EVM</strong></p><p>As Ethereum transitions into its <strong>Proof of Stake</strong> (PoS) consensus mechanism, the role of the EVM will evolve. <strong>Sharding</strong>, one of the key features of Ethereum 2.0, will split the network into smaller, more manageable sections, enabling greater scalability without compromising security.</p><p><strong>How Sharding Affects the EVM:</strong></p><p>In a traditional OS, scaling requires better hardware (more RAM, CPUs, etc.). In Ethereum, scaling happens through software improvements like sharding. This allows Ethereum to process more transactions simultaneously by spreading them across different shards.</p><p><strong>Expanding Smart Contract Efficiency: Tips for Developers</strong></p><p>Optimizing gas usage is a crucial skill for Ethereum developers. Here are a few tips for writing more gas-efficient smart contracts:</p><p>• <strong>Use Fixed-Size Data Types</strong>: Opt for smaller integer types like <strong>uint8</strong> instead of <strong>uint256</strong> when possible.</p><p>• <strong>Avoid Loops with High Iterations</strong>: Loops can quickly consume gas, especially if they iterate over large arrays.</p><p>• <strong>Minimize Storage Writes</strong>: Writing data to the blockchain is one of the most expensive operations, so store only necessary data and use memory variables where applicable.</p><p><strong>Part 3 Teaser: Breaking Down Gas, Storage, and Efficiency in Ethereum</strong></p><p>In the final part of this series, we’ll explore:</p><p>• <strong>Gas optimization techniques</strong>: How you can reduce costs in smart contract execution.</p><p>• <strong>On-chain vs. off-chain storage</strong>: Where is the data really stored?</p><ul><li><strong>Practical examples for developers</strong>: Best practices for making smart contracts more efficient and cost-effective.</li></ul><blockquote>What’s your take on Ethereum’s sandboxing model compared to traditional operating systems? Do you think Ethereum’s decentralized approach adds extra layers of security, or do you see potential challenges?</blockquote><blockquote><strong>Let’s discuss!</strong> Drop your comments below, and don’t forget to share this article with others who are curious about the technical side of blockchain technology.</blockquote><blockquote>Also, what specific topic would you like me to dive into next? More on Ethereum’s consensus mechanism, gas optimization, or maybe how smart contracts handle memory? Let me know!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1578498c678b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum Virtual Machine (EVM) vs Traditional Operating Systems: A Simple Guide (Part 1)]]></title>
            <link>https://tusharbhatia43.medium.com/ethereum-virtual-machine-evm-vs-traditional-operating-systems-a-simple-guide-part-1-6b0ec23ca8d1?source=rss-d77880e966ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b0ec23ca8d1</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[evm]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Tushar Bhatia]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 16:19:45 GMT</pubDate>
            <atom:updated>2024-09-07T16:19:45.693Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-b5Ml-2r3iBWhNUy65QGGg.png" /></figure><p>In the world of decentralized finance (DeFi), understanding how Ethereum’s virtual machine (EVM) compares to traditional operating systems (OS) is key. While both play an important role in managing and running applications, their architecture and functionality are quite different.</p><p>This article will break down the differences in a clear, engaging way, and help you understand how smart contracts execute on Ethereum in comparison to how applications run on a traditional OS like Windows or Linux. To make things more interesting, we’ll also take a look at how hardware interacts with the EVM. But first, let’s get into the basics!</p><p><strong>What’s the Job of an OS?</strong></p><p>An operating system is the backbone of your computer. Imagine it as the manager of all the programs (applications) running on your device. When you open an app on your phone, the OS ensures that each app gets its own space and doesn’t interfere with others. It also manages interactions with hardware components like your computer’s CPU, memory, and storage.</p><p>Example: You’re listening to music on Spotify while browsing the internet. The OS ensures that both apps run smoothly without clashing, by separating their activities and allocating resources like memory to each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*mNsW37OlDnaqwzsS" /></figure><h4><strong>Enter the EVM: Ethereum’s OS</strong></h4><p>Now, Ethereum operates a bit differently. While traditional OS deals with apps, Ethereum operates on smart contracts — self-executing pieces of code that live on the blockchain. The Ethereum Virtual Machine (EVM) is like Ethereum’s own operating system. It runs these smart contracts in a sandbox environment, ensuring that each contract is isolated and secure, much like how your OS handles different apps.</p><p>But here’s where the EVM stands out: It’s decentralized. Instead of one computer running the show, thousands of nodes worldwide participate in executing smart contracts. So, unlike a traditional OS, which has central control, the EVM operates across a network of nodes.</p><p><strong>Example Time: Sandboxing</strong></p><blockquote>Think of sandboxing like running different apps on your phone. If Spotify crashes, your browser continues to work fine because the OS ensures they don’t interfere with each other.</blockquote><p>In the EVM, each smart contract is “sandboxed.” This means it operates in isolation, with its own set of rules and memory. If one contract has a bug or fails, it won’t affect other contracts running on the network. This is key to maintaining Ethereum’s security.</p><h4><strong>How Does the EVM Interact with Hardware?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*KgEA_UDcOv6vkOjV" /></figure><p>You might be wondering, “How does the EVM handle physical hardware, since it’s a virtual machine?” While traditional OS manages hardware directly (like when your OS sends instructions to your computer’s CPU), the EVM does something different. It operates on top of the hardware of each Ethereum node running the Ethereum software.</p><blockquote>Think of each Ethereum node as having its own small OS (like Linux) that handles the hardware. The EVM, in turn, runs on top of this OS, abstracting the actual hardware details. This separation helps maintain the security and integrity of the blockchain.</blockquote><p><strong><em>Real-World Comparison:</em></strong> Imagine renting a car. You don’t need to know how the engine works; you just need to drive. Similarly, the EVM runs contracts without needing direct access to the underlying hardware of the node, which is managed by the Ethereum node software.</p><p>To better understand the execution layer of the EVM, here’s a simple Solidity smart contract:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYHklhEOQeyK1pNr3kNCkA.png" /></figure><p>In this contract, the function store() allows anyone to input a number, while the function retrieve() allows them to read the stored number. This basic example shows how decentralized applications interact with the Ethereum blockchain, updating and retrieving data that is globally accessible.</p><h4>Ethereum Node Software: The Real Worker Behind the Scenes</h4><p>To better understand how the EVM works, let’s quickly talk about Ethereum nodes. These nodes are the real workers that execute the EVM and run the Ethereum blockchain. Each node operates Ethereum’s software, such as Geth or OpenEthereum, to manage interactions with the blockchain and keep the network synchronized.</p><p><strong>Nodes are responsible for:</strong></p><p>• Validating transactions</p><p>• Executing smart contracts (via the EVM)</p><p>• Storing blockchain data</p><p>In a way, Ethereum node software is the foundation, while the EVM is the building that sits on top of it, running decentralized applications and contracts.</p><p><strong>Example: Sending a Transaction</strong></p><p>Let’s imagine you send a transaction to a smart contract to swap tokens on Uniswap. Your transaction goes to the Ethereum network and is picked up by a node. The EVM on that node executes the contract’s logic in a sandboxed environment, independent of other contracts. Once executed, the node helps verify and propagate the result across the network. Every node agrees on the same result, thanks to Ethereum’s consensus mechanism.</p><h3>Key Differences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M16pZkRE2CExnuN1XkRucg.png" /></figure><p><strong>1. Application Layer</strong></p><p>• <strong>Traditional OS:</strong> Think of applications running on your laptop or desktop. These can include web browsers, games, or word processors. They are user-facing and rely on the OS to handle background tasks like file management and memory allocation.</p><p>• <strong>EVM:</strong> In Ethereum, the “application layer” consists of smart contracts. Smart contracts are pieces of code that automatically execute when triggered. These are crucial for decentralized applications (DApps) like DeFi platforms, NFT marketplaces, etc.</p><p>2. <strong>User Mode vs. Execution Layer (EVM)</strong></p><p>•<strong> Traditional OS</strong>: Users interact with the operating system through shells (command-line or GUI). In the background, the OS ensures that applications receive the correct amount of memory, CPU power, and other resources.</p><p>• <strong>EVM:</strong> In Ethereum, smart contracts run on the EVM, which ensures that all instructions are executed consistently. The EVM checks and enforces gas limits, making sure that transactions don’t drain excessive resources.</p><p><strong>3. Kernel vs. Consensus Laye</strong>r</p><p><strong>• Traditional OS:</strong> The kernel is the core of the operating system that controls hardware interaction. It manages everything from memory allocation to process scheduling.</p><p><strong>• EVM:</strong> Instead of a kernel, Ethereum relies on a consensus mechanism (Proof of Stake) to ensure the accuracy of the state across all nodes. Multiple nodes must agree on the result of transactions to maintain security and integrity.</p><p><strong>4. Hardware Interaction vs. Node Communication</strong></p><p>• Traditional OS: The operating system kernel directly communicates with the CPU, RAM, and other hardware devices. It allocates CPU cycles to processes and handles network input/output.</p><p><strong>• EVM:</strong> In Ethereum, instead of hardware communication, nodes in the Ethereum network interact in a peer-to-peer manner. These nodes validate transactions, communicate with each other, and reach consensus to secure the network.</p><p><strong>5. Physical Storage vs. Blockchain Storage</strong></p><p>• Traditional OS: Data is stored on local disks and managed by file systems. For example, documents, apps, and system files all sit on a hard drive or SSD.</p><p><strong>• EVM:</strong> In Ethereum, all smart contract data is stored in a globally shared state (a distributed ledger). This data is replicated across all nodes in the network, ensuring transparency and security.</p><h4><strong>Part 2 Teaser: </strong>How Ethereum’s EVM Handles Hardware and Consensus</h4><p>In the next part of this series, we’ll dive deeper into how Ethereum’s EVM interacts with hardware when executing smart contracts. We’ll explore:</p><p>• How sandboxing ensures security in Ethereum.</p><p>• How consensus is reached across nodes during transaction execution.</p><p>• How hardware and memory interact to run Ethereum smart contracts.</p><p>These topics will give you a more in-depth understanding of how the EVM operates under the hood.</p><h4><strong>Part 3 Teaser:</strong> Breaking Down Gas, Storage, and Efficiency in Ethereum</h4><p>In the final part of this series, we’ll uncover the mysteries behind gas fees, how smart contracts store data on-chain, and how to write more efficient smart contracts. We will cover:</p><p>• Understanding gas fees and optimizing them.</p><p>• On-chain vs. off-chain storage: where data is really stored.</p><p>• Practical tips for developers to make smart contracts more cost-effective.</p><h3>Conclusion</h3><p>The Ethereum Virtual Machine may seem complex at first, but when we break it down layer by layer, we can see the parallels and differences with traditional operating systems. From executing smart contracts to managing global consensus, the EVM offers a fascinating blend of decentralized technology and computation.</p><p>Stay tuned for Parts 2 and 3, where we’ll explore how Ethereum works under the hood and how you can optimize your smart contract development for a decentralized future.</p><blockquote>“What aspect of the Ethereum Virtual Machine do you find the most fascinating? Share your thoughts and questions in the comments below, and let’s dive deeper into the world of decentralized technology together!”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b0ec23ca8d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XXE, how did a feature become a critical vulnerability?]]></title>
            <link>https://tusharbhatia43.medium.com/xxe-how-did-a-feature-become-a-critical-vulnerability-e34091a21e33?source=rss-d77880e966ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/e34091a21e33</guid>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[ethical-hacking]]></category>
            <category><![CDATA[owasp-top-10]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[cyber]]></category>
            <dc:creator><![CDATA[Tushar Bhatia]]></dc:creator>
            <pubDate>Mon, 25 Oct 2021 12:23:42 GMT</pubDate>
            <atom:updated>2021-10-25T12:23:42.287Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDAQVehkG4RqIf-2Y0EASw.jpeg" /></figure><p>This is my take on XML External Entities and how a feature of this front-end language intrigued the security researchers and how it was proved to be a vulnerability if XML is not implemented properly.</p><p><strong>The process to analyze or understand any vulnerability:</strong></p><p>1. What it is?</p><p>2. Why does it exist (basic and specific reasons)?</p><p>3. Impacts (the damage it can cause)</p><p>4. Mitigation (ways to prevent it)</p><p><strong>Description:</strong></p><p><strong>What is XML?</strong></p><p>It stands for Extensible Markup Language and is described as a metalanguage meaning that XML is used to describe other languages. It was developed to fulfill the shortcomings of the HTML because it could only define how the data will be displayed. However, XML defines the structure of data as well.</p><p>Differences between HTML and XML:</p><p>1. HTML has predefined tags (some of them need to be closed while some don’t) but XML has no predefined tags. Instead, tags are user-defined and unlike HTML, XML tags always require a closing tag.</p><p>2. <strong>Example:</strong></p><blockquote>1st. &lt;?xml version=”1.0&quot; encoding=”UTF-8&quot;?&gt;</blockquote><blockquote>2nd. &lt;Hi&gt;</blockquote><blockquote>3rd. &lt;Hello&gt;</blockquote><blockquote>4th. &lt;Title&gt;Bug Bounty&lt;/Title&gt;</blockquote><blockquote>5th. &lt;Compensation&gt;1000000&lt;/Compensation&gt;</blockquote><blockquote>6th. &lt;Responsibility fundamental=”1&quot;&gt;Shot web&lt;/Responsibility&gt;</blockquote><blockquote>7th. &lt;/Hello&gt;</blockquote><blockquote>8th. &lt;/Hi&gt;</blockquote><p>Look closely here, because all of the tags are user-defined so it’s impossible to know how this data will look on a web page.</p><p>Note: “1st” line is the declaration header of XML indicating the version and the type of Unicode encoding.</p><p>Now, before getting into basic XML syntax in order to fathom and create an attack, let’s understand why is the XML vulnerable?</p><p>Moreover, in layman’s terms, XML is used to fetch some data from the Back-End to the Front-End in order to increase the application’s speed and efficiency. However, if we look at it from an attacker’s perspective then this feature could be a disastrous vulnerability.</p><p>In fact, if XML is not implemented properly<strong> </strong>then the attacker can abuse its feature in order to fetch sensitive data from the Back-End.</p><h3><strong>Basics of XML:</strong></h3><p><strong>Document Type Definition (DTD):</strong></p><p>It defines the structure, the legal elements, and the attributes of an XML document. In other words, because all the tags are user-defined then, in order to work an XML document must follow this set of general rules known as DTD.<br> DTD is a set of declarations that decides the elements, structure and attributes as explained above. For a better understanding of these terms consider the following example:</p><p>&lt;address category = “residence”&gt;</p><p>&lt;name&gt;name content&lt;/name&gt;</p><p>&lt;company&gt;company content&lt;/company&gt;</p><p>&lt;phone&gt;(011) 123–4567&lt;/phone&gt;</p><p>&lt;/address&gt;</p><p>Here, “address” is the element, and “category” is the attribute. However, “name” is a tag because it marks the start and end of an element without any attributes i.e. for empty elements, by an empty-element tag.</p><p>On the other hand, DTDs are of two types: Internal and External.</p><p><strong>Internal DTD</strong>: This DTD is defined within the XML document.</p><p><strong>External DTD</strong>: This is actually an external <em>.dtd </em>file from which the XML document fetches and references.</p><p><strong>Note:</strong> All the elements used in the XML document are defined in the external <em>.dtd</em> file using the keyword “!Element”.</p><p>Moreover, before moving on to entities and parsable character data let’s understand the meaning of “parsing” in XML.</p><h3><strong>XML Parser:</strong> In computing, a parser is a program (or a piece of code or API that you can reference inside your own programs) which analyses files to identify the component parts. All applications that read input have a parser of some kind, otherwise they’d never be able to figure out what the information means. It also verifies that the XML document is in a suitable format and may also validate the XML documents.</h3><p><strong><em>There is also one more use of parser that is it converts an XML document into an XML DOM object so that it can then be manipulated with JavaScript</em></strong>.</p><p><strong>Parsable Character Data (#PCDATA)</strong>:</p><p>This type of data tells the parser about the data in the elements that are going to be parsed. Similarly, CDATA means that a particular element contains unparsable character data.</p><p><strong>XML Entities (Finally!)</strong>:</p><p>XML Documents consist of a set of storage units called Entities. They act as a replacement mechanism and placeholders for information.</p><p>For Example: Creating a database of names, addresses, and attaching them to a word document, and then storing the document in the form of an Entity to be accessible by the parser.</p><p>Nevertheless, entities can be used as a shortcut that allows us to embed blocks of text or even entire documents and files into an XML document as it makes updating documents across networks really convenient.</p><p><strong>Sample XML Document</strong>:</p><blockquote>&lt;?xml version=”1.0&quot; encoding=”UTF-8&quot;?&gt;</blockquote><blockquote>&lt;!DOCTYPE Jobs [</blockquote><blockquote>&lt;!ATTLIST Responsibility fundamental CDATA “0”&gt;</blockquote><blockquote>➊ &lt;!ELEMENT Website ANY&gt;</blockquote><blockquote>➋ &lt;!ENTITY url SYSTEM “website.txt”&gt;</blockquote><blockquote>]&gt;</blockquote><blockquote>&lt;Jobs&gt;</blockquote><blockquote>&lt;Job&gt;</blockquote><blockquote>&lt;Title&gt;Hacker&lt;/Title&gt;</blockquote><blockquote>&lt;Compensation&gt;1000000&lt;/Compensation&gt;</blockquote><blockquote>&lt;Responsibility fundamental=”1&quot;&gt;Shot web&lt;/Responsibility&gt;</blockquote><blockquote>➌ &lt;Website&gt;&amp;url;&lt;/Website&gt;</blockquote><blockquote>&lt;/Job&gt;</blockquote><blockquote>&lt;/Jobs&gt;</blockquote><p>Notice that I’ve added a Website “!ELEMENT”, but instead of (#PCDATA), I’ve used <strong>ANY</strong> (it refers to literally anything at all as long as rules are followed) because it is useful when you have yet to decide the allowable contents of the element ➊.</p><p>➋ This data definition means the Website tag can contain any combination of parsable data. I’ve also defined an !ENTITY with a SYSTEM attribute, telling the parser to get the contents of the website.txt file wherever the placeholder name URL is inside a website tag.</p><p>At ➌ I use the website tag, and the contents of website.txt would be fetched in the place of “&amp;url;” Note the &amp; in front of the entity name. Whenever you reference an entity in an XML document, you must precede it with &amp;.</p><p>To sum it up, we can make use of these External Entities to fetch data from the Back-End like the contents of “/etc/passwd” etc.</p><p><strong>XXE Vulnerability:</strong></p><p>In an XXE attack, an attacker abuses a goal software in order that it consists of outside (external) entities in its XML parsing. In different words, the software expects a few XML, and it isn’t always validating what it is receiving; it simply parses something it gets. For instance, let’s say the job board in the previous example lets you register and upload jobs via XML.</p><p>The job board might make its DTD file available to you and assume that you’ll submit a file matching the requirements. Instead of having the !ENTITY retrieve the contents of “website.txt”, you could have it retrieve the contents of “/etc/passwd”.</p><p>Retrieving the contents of “/etc/passwd” is the best way to prove that this vulnerability exists.</p><p>We should submit something like this in the XML document:</p><p>&lt;?xml version=”1.0&quot; encoding=”UTF-8&quot;?&gt;</p><p>➊ &lt;!DOCTYPE foo [</p><p>➋ &lt;!ELEMENT foo ANY &gt;</p><p>➌ &lt;!ENTITY xxe SYSTEM “file:///etc/passwd” &gt;</p><p>]&gt;</p><p>➍ &lt;foo&gt;&amp;xxe;&lt;/foo&gt;</p><p>➊The parser receives this code and recognizes an internal DTD defining a foo document type.</p><p>➋The DTD tells the parser that foo can include any parsable data; then there’s an entity xxe that should read my /etc/passwd file (file:// denotes a full URI path to the /etc/passwd file) when the document is parsed.</p><p>➌The parser should replace &amp;xxe; elements with those file contents.</p><p>➍Then, you finish it off with XML defining a &lt;foo&gt; tag that contains “&amp;xxe;”, which prints my server info.</p><p><strong>Note</strong>: <em>The above example has been taken from “REAL-WORLD BUG HUNTING by Peter Yaworski”</em></p><p><strong>Bonus: A little tip to find Hidden Attack Vectors for XXE</strong></p><p>Sometimes the attack vectors are less visible than the common ones. It happens because some apps receive client-submitted data, embed it server-side in an XML document, and then parse the document.</p><h3><strong>Mitigation:</strong></h3><p>1. First and foremost protection from XXE attacks would be to disable DTD and External Entities Completely.</p><p>2. The XML Processor must be given many little features. For example, it should not be allowed to retrieve contents of the /etc/passwd or any kind of backend file on the client-side.</p><p>3. User Input, File Upload, and all the URLs must be sanitized, validated, and whitelisted.</p><p><strong>For Practice:</strong> I would personally recommend <a href="https://portswigger.net/web-security/xxe"><em>Portswigger Labs</em></a> for the basic practice of XXE as it accumulates the real environments really well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e34091a21e33" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>