<?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 SHUAIB GANIYAT on Medium]]></title>
        <description><![CDATA[Stories by SHUAIB GANIYAT on Medium]]></description>
        <link>https://medium.com/@shuaibganiyat20?source=rss-2ce36021829a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WcfavQw6-FjOXjin</url>
            <title>Stories by SHUAIB GANIYAT on Medium</title>
            <link>https://medium.com/@shuaibganiyat20?source=rss-2ce36021829a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:18:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shuaibganiyat20/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[Review: Yearn Finance’s BaseStrategy Contract]]></title>
            <link>https://medium.com/@shuaibganiyat20/review-yearn-finances-basestrategy-contract-85654fa79007?source=rss-2ce36021829a------2</link>
            <guid isPermaLink="false">https://medium.com/p/85654fa79007</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[yield-aggregator]]></category>
            <dc:creator><![CDATA[SHUAIB GANIYAT]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 22:53:27 GMT</pubDate>
            <atom:updated>2026-04-18T17:20:16.031Z</atom:updated>
            <content:encoded><![CDATA[<p>Yearn Finance is one of the most battle-tested yield aggregators in DeFi. At the core of how it works is a contract called <em>BaseStrategy</em>, a shared foundation that every Yearn yield strategy is built on.<br> <br>This article walks through what the contract does, why it’s structured the way it is, and what the key pieces mean.</p><h3>What the Contract Does</h3><p>When a user deposits funds into a Yearn Vault, the Vault doesn’t sit on those funds. It delegates them to one or more <em>strategies</em> contracts that put the capital to work (lending, liquidity provision, staking, etc.) to earn yield.<br><strong>BaseStrategy</strong> is the abstract contract every strategy inherits from. It handles:<br>- The relationship between a strategy and its Vault<br>- Access control (who can call what)<br>- Harvest and reporting logic<br>- Emergency mechanisms<br>This contract should be inherited and the abstract methods implemented to adapt the Strategy to the particular needs it has to create a return.</p><h3>The Imports</h3><pre>import {IERC20} from &quot;@openzeppelin/contracts/token/ERC20/IERC20.sol&quot;;<br>import {ERC20} from &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br>import {SafeERC20} from &quot;@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol&quot;;</pre><p>Three imports, all from OpenZeppelin:<br> <br><strong>IERC20</strong>: is the standard ERC-20 interface. The strategy uses it to type the <em>want</em> token the token the strategy manages and to interact with arbitrary tokens in the sweep() rescue function.<br> <br><strong>ERC20</strong>: is imported but not directly used in <em>BaseStrategy</em>. It’s available for concrete implementations that may need it.<br> <br><strong>SafeERC20</strong>: Some tokens like USDT don’t return a boolean on <em>transfer()</em> and <em>approve()</em>, which causes a raw <em>IERC20</em> call to revert unexpectedly. <em>SafeERC20</em> wraps those calls with low-level checks that handle non-standard tokens safely.</p><pre>using SafeERC20 for IERC20;<br><br>// This single line activates `SafeERC20` for all `IERC20` variables throughout<br>// the contract. Every `want.safeTransfer()` and `want.safeApprove()` call you <br>//see later flows through it.</pre><h3>Key Interfaces</h3><p>Before the main contract, four interfaces define the external contracts this strategy talks to.</p><h4>VaultAPI</h4><pre>interface VaultAPI is IERC20 {<br>    function name() external view returns (string calldata);<br>    function symbol() external view returns (string calldata);<br>    function decimals() external view returns (uint256);<br>    function apiVersion() external pure returns (string memory);<br>    function permit(<br>        address owner,<br>        address spender,<br>        uint256 amount,<br>        uint256 expiry,<br>        bytes calldata signature<br>    ) external returns (bool);<br>    function deposit() external returns (uint256);<br>    function deposit(uint256 amount) external returns (uint256);<br>    function deposit(uint256 amount, address recipient) external returns (uint256);<br>    function withdraw() external returns (uint256);<br>    function withdraw(uint256 maxShares) external returns (uint256);<br>    function withdraw(uint256 maxShares, address recipient) external returns (uint256);<br>    function token() external view returns (address);<br>    function strategies(address _strategy) external view returns (StrategyParams memory);<br>    function pricePerShare() external view returns (uint256);<br>    function totalAssets() external view returns (uint256);<br>    function depositLimit() external view returns (uint256);<br>    function maxAvailableShares() external view returns (uint256);<br>    function creditAvailable() external view returns (uint256);<br>    function debtOutstanding() external view returns (uint256);<br>    function expectedReturn() external view returns (uint256);<br>    function report(<br>        uint256 _gain,<br>        uint256 _loss,<br>        uint256 _debtPayment<br>    ) external returns (uint256);<br>    function revokeStrategy() external;<br>    function governance() external view returns (address);<br>    function management() external view returns (address);<br>    function guardian() external view returns (address);<br>}</pre><p><strong>VaultAPI</strong> extends <em>IERC20 </em>because Vault shares are themselves ERC-20 tokens. This interface is how the strategy talks to its Vault checking how much debt it owes, how much new credit is available, and most importantly, reporting back profits and losses via <em>report()</em>.</p><h4>StrategyAPI</h4><pre>interface StrategyAPI {<br>    function name() external view returns (string memory);<br>    function vault() external view returns (address);<br>    function want() external view returns (address);<br>    function apiVersion() external pure returns (string memory);<br>    function keeper() external view returns (address);<br>    function isActive() external view returns (bool);<br>    function delegatedAssets() external view returns (uint256);<br>    function estimatedTotalAssets() external view returns (uint256);<br>    function tendTrigger(uint256 callCost) external view returns (bool);<br>    function tend() external;<br>    function harvestTrigger(uint256 callCost) external view returns (bool);<br>    function harvest() external;<br>    event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);<br>}</pre><p>This is the interface keeper bot use. It intentionally exposes only execution and trigger functions, no admin controls. A keeper can call <em>harvest()</em> but cannot change strategy parameters.</p><h4>HealthCheck and IBaseFee</h4><pre>interface HealthCheck {<br>    function check(<br>        uint256 profit,<br>        uint256 loss,<br>        uint256 debtPayment,<br>        uint256 debtOutstanding,<br>        uint256 totalDebt<br>    ) external view returns (bool);<br>}<br><br>interface IBaseFee {<br>    function isCurrentBaseFeeAcceptable() external view returns (bool);<br>}</pre><p><strong>HealthCheck</strong> is an optional external contract that validates harvest results, if the numbers look wrong, the harvest reverts. <strong>IBaseFee</strong> is a gas oracle that blocks harvests when network fees are too high to make harvesting economical.</p><h3>The Abstract Contract</h3><h4>State Variables</h4><pre>VaultAPI public vault;<br>address public strategist;<br>address public rewards;<br>address public keeper;<br>IERC20 public want;<br>// The core variables</pre><p><em>vault</em> is the Vault this strategy serves. <br><em>want</em> is the token being managed, resolved from vault.token() at initialization. <br><em>strategist</em>, <em>rewards</em>, and <em>keeper</em> are the three human/bot roles with different levels of access.</p><pre>uint256 public minReportDelay;<br>uint256 public maxReportDelay;<br>bool public emergencyExit;<br>address public baseFeeOracle;<br>uint256 public creditThreshold;<br>bool public forceHarvestTriggerOnce;<br>bool public doHealthCheck;<br>address public healthCheck;</pre><p>These control <strong>when</strong> the strategy harvests, <strong>whether</strong> it’s in emergency mode, and <strong>how</strong> it validates results.</p><h4>Access Control</h4><p>The contract defines seven modifiers with distinct permission levels:</p><pre>modifier onlyAuthorized()          // governance or strategist<br>modifier onlyEmergencyAuthorized() // governance, strategist, guardian, or management<br>modifier onlyStrategist()          // strategist only<br>modifier onlyGovernance()          // vault governance only<br>modifier onlyRewarder()<br>modifier onlyKeepers()             // keeper, strategist, governance, guardian, or management<br>modifier onlyVaultManagers()       // vault management or governance</pre><p>The pattern is deliberate. A keeper bot can trigger yield operations but cannot touch configuration. A strategist can tune parameters but cannot act as governance. Emergency powers are intentionally wider because emergencies need fast, multi-party response.</p><h4>Initialization</h4><pre> function _initialize(<br>        address _vault,<br>        address _strategist,<br>        address _rewards,<br>        address _keeper<br>    ) internal {<br>        require(address(want) == address(0), &quot;Strategy already initialized&quot;);<br><br>        vault = VaultAPI(_vault);<br>        want = IERC20(vault.token());<br>        want.safeApprove(_vault, type(uint256).max); // Give Vault unlimited access (might save gas)<br>        strategist = _strategist;<br>        rewards = _rewards;<br>        keeper = _keeper;<br><br>        // initialize variables<br>        maxReportDelay = 30 days;<br>        creditThreshold = 1_000_000 * 10**vault.decimals(); // set this high by default so we don&#39;t get tons of false triggers if not changed<br><br>        vault.approve(rewards, type(uint256).max); // Allow rewards to be pulled<br>    }</pre><p>The <em>require(address(want) == address(0))</em> line is the initialization lock. Since <em>want</em> is set here, calling <em>_initialize</em> a second time always fails. No separate <em>initialized</em> boolean needed.<br> <br>The contract grants the Vault and rewards address unlimited approval upfront , a gas optimization that avoids repeated approval transactions. It also sets <em>maxReportDelay</em> to 30 days and <em>creditThreshold </em>to 1 million tokens as high defaults, so freshly deployed strategies don’t get bombarded with spurious keeper triggers.</p><h4>The Abstract Methods</h4><pre>function prepareReturn(uint256 _debtOutstanding)<br>    internal virtual<br>    returns (uint256 _profit, uint256 _loss, uint256 _debtPayment);<br> <br>function adjustPosition(uint256 _debtOutstanding) internal virtual;<br> <br>function liquidatePosition(uint256 _amountNeeded)<br>    internal virtual<br>    returns (uint256 _liquidatedAmount, uint256 _loss);<br> <br>function liquidateAllPositions()<br>    internal virtual<br>    returns (uint256 _amountFreed);</pre><p><strong>prepareReturn<em> </em></strong>— called during a normal harvest. Claim rewards, sell them, calculate net profit or loss against total debt, and prepare any debt repayment.<br> <br><strong>adjustPosition</strong>— called after reporting to redeploy idle capital. If the Vault sent new funds, put them to work. If debt is due, start unwinding.<br> <br><strong>liquidatePosition</strong>— called when a user withdraws. Liquidate up to <em>_amountNeeded</em> of the strategy’s positions. The <em>_loss</em> return distinguishes between a realized loss and a temporary lock (e.g., funds still in a time-locked contract).<br> <br><strong>liquidateAllPositions</strong> — called during an emergency exit. No amount limit. Get out as fast as possible.</p><h3>The Key Functions</h3><h4>harvest()</h4><pre>function harvest() external onlyKeepers {<br>        uint256 profit = 0;<br>        uint256 loss = 0;<br>        uint256 debtOutstanding = vault.debtOutstanding();<br>        uint256 debtPayment = 0;<br>        if (emergencyExit) {<br>            // Free up as much capital as possible<br>            uint256 amountFreed = liquidateAllPositions();<br>            if (amountFreed &lt; debtOutstanding) {<br>                loss = debtOutstanding - amountFreed;<br>            } else if (amountFreed &gt; debtOutstanding) {<br>                profit = amountFreed - debtOutstanding;<br>            }<br>            debtPayment = debtOutstanding - loss;<br>        } else {<br>            // Free up returns for Vault to pull<br>            (profit, loss, debtPayment) = prepareReturn(debtOutstanding);<br>        }<br><br>        // we&#39;re done harvesting, so reset our trigger if we used it<br>        forceHarvestTriggerOnce = false;<br>        emit ForcedHarvestTrigger(false);<br><br>        // Allow Vault to take up to the &quot;harvested&quot; balance of this contract,<br>        // which is the amount it has earned since the last time it reported to<br>        // the Vault.<br>        uint256 totalDebt = vault.strategies(address(this)).totalDebt;<br>        debtOutstanding = vault.report(profit, loss, debtPayment);<br><br>        // Check if free returns are left, and re-invest them<br>        adjustPosition(debtOutstanding);<br><br>        // call healthCheck contract<br>        if (doHealthCheck &amp;&amp; healthCheck != address(0)) {<br>            require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), &quot;!healthcheck&quot;);<br>        } else {<br>            emit SetDoHealthCheck(true);<br>            doHealthCheck = true;<br>        }<br><br>        emit Harvested(profit, loss, debtPayment, debtOutstanding);<br>    }</pre><p><strong>harvest()</strong> is the heartbeat of any strategy. Its flow:<br> <br>1. Check if emergency exit is active. If so, liquidate everything. Otherwise, call `preparbehavior)`.<br>2. Reset the <em>forceHarvestTriggerOnce</em> flag.<br>3. Snapshot <em>totalDebt</em> <strong>before</strong> calling <em>vault.report()</em> because <em>report()</em> modifies Vault state and the health checker needs the pre-report value.<br>4. Report to the Vault. The Vault settles accounting and returns a new <em>debtOutstanding()</em>.<br>5. Redeploy idle capital through <em>adjustPosition()</em>.<br>6. Run the health check if enabled. If it fails, the entire harvest reverts.<br>Note: if <em>doHealthCheck</em> is false (the initial state), the <em>else</em> branch silently sets it to <em>true</em>. The first harvest after deployment always enables health checks going forward a default-to-safe behavior.</p><h4>harvestTrigger()</h4><pre>   function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {<br>        // Should not trigger if strategy is not active (no assets or no debtRatio)<br>        if (!isActive()) return false;<br><br>        // check if the base fee gas price is higher than we allow. if it is, block harvests.<br>        if (!isBaseFeeAcceptable()) return false;<br><br>        // trigger if we want to manually harvest, but only if our gas price is acceptable<br>        if (forceHarvestTriggerOnce) return true;<br><br>        // Should trigger if hasn&#39;t been called in a while<br>        StrategyParams memory params = vault.strategies(address(this));<br>        if ((block.timestamp - params.lastReport) &gt;= maxReportDelay) return true;<br><br>        // harvest our credit if it&#39;s above our threshold or return false<br>        return (vault.creditAvailable() &gt; creditThreshold);<br>    }</pre><p>This is what keeper bots call to decide whether to harvest. It returns <em>true</em> when the strategy is active, gas is acceptable, and one of three conditions is met: a manual override is set, enough time has passed since the last harvest, or available credit exceeds the threshold.<br> <br>The order matters: <em>isActive()</em> is checked first to avoid unnecessary external calls for strategies that aren’t running.</p><h4>withdraw()</h4><pre>function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {<br>        require(msg.sender == address(vault), &quot;!vault&quot;);<br>        // Liquidate as much as possible to `want`, up to `_amountNeeded`<br>        uint256 amountFreed;<br>        (amountFreed, _loss) = liquidatePosition(_amountNeeded);<br>        // Send it directly back (NOTE: Using `msg.sender` saves some gas here)<br>        want.safeTransfer(msg.sender, amountFreed);<br>        // NOTE: Reinvest anything leftover on next `tend`/`harvest`<br>    }</pre><p>Called by the Vault when a user withdraws. Only the Vault can call this. Any funds freed above <em>_amountNeeded</em> stay in the strategy and get reinvested on the next <em>tend()</em> or <em>harvest()</em></p><h4>setEmergencyExit()</h4><pre>function setEmergencyExit() external onlyEmergencyAuthorized {<br>        emergencyExit = true;<br>        if (vault.strategies(address(this)).debtRatio != 0) {<br>            vault.revokeStrategy();<br>        }<br><br>        emit EmergencyExitEnabled();<br>    }</pre><p>A one-way switch, there is no way to unset it. Calling this tells the Vault to stop sending new capital through <em>revokeStrategy()</em>, and ensures the next <em>harvest()</em> call fully liquidates all positions back to the Vault. The liquidation is deferred to the next harvest intentionally, so it happens in an orderly, observable way. This may only be called by governance or the strategist.</p><h3>Cloning</h3><pre>abstract contract BaseStrategyInitializable is BaseStrategy {<br>    bool public isOriginal = true;<br>    event Cloned(address indexed clone);<br><br>    constructor(address _vault) BaseStrategy(_vault) {}<br><br>    function initialize(<br>        address _vault,<br>        address _strategist,<br>        address _rewards,<br>        address _keeper<br>    ) external virtual {<br>        _initialize(_vault, _strategist, _rewards, _keeper);<br>    }<br><br>    function clone(address _vault) external returns (address) {<br>        return clone(_vault, msg.sender, msg.sender, msg.sender);<br>    }<br><br>    function clone(<br>        address _vault,<br>        address _strategist,<br>        address _rewards,<br>        address _keeper<br>    ) public returns (address newStrategy) {<br>        require(isOriginal, &quot;!clone&quot;);<br>        // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol<br>        bytes20 addressBytes = bytes20(address(this));<br><br>        assembly {<br>            // EIP-1167 bytecode<br>            let clone_code := mload(0x40)<br>            mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)<br>            mstore(add(clone_code, 0x14), addressBytes)<br>            mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)<br>            newStrategy := create(0, clone_code, 0x37)<br>        }<br><br>        BaseStrategyInitializable(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);<br><br>        emit Cloned(newStrategy);<br>    }<br>}</pre><p><strong>BaseStrategyInitializable </strong>extends <em>BaseStrategy</em> with <strong>EIP-1167 minimal proxy cloning</strong>. Instead of deploying a full strategy contract each time, <em>clone()</em> deploys a ~45-byte proxy that forwards all calls to the original. Deployment gas is cut significantly.<br> <br>The <em>isOriginal = true</em> flag prevents clones-of-clones. A clone starts with zero storage, so <em>isOriginal</em> is <em>false</em> in any clone, the <em>require(isOriginal)</em> guard blocks it from being cloned again.</p><h3>Key Security Observations</h3><p><strong>Unlimited approvals</strong>: Both <em>want.safeApprove(_vault, type(uint256).max)</em> and <em>vault.over-prioritize, type(uint256).max)</em> are granted at initialization. This is a deliberate gas optimization, but it means the security of these funds is entirely dependent on the correctness of the Vault and rewards contracts. A compromised Vault contract could drain all strategy funds.</p><p><strong>One-way emergency exit:</strong> <em>emergencyExit</em> cannot be unset. This is intentional, an emergency exit is a serious event and reversing it could be exploited. The tradeoff is that a falsely triggered exit requires deploying a new strategy.</p><p><strong>No reentrancy guard</strong>: <em>harvest()</em> and <em>withdraw()</em> interact with external contracts (<em>vault.report()</em>, <em>liquidatePosition()</em>, <em>adjustPosition()</em>) without an explicit reentrancy guard. The contract relies on the Vault’s own guards and the assumption that <em>want</em> is a non-reentrant ERC-20. Concrete strategies using tokens with transfer hooks (e.g., ERC-777) should add their own guards.</p><p><strong>Health check opt-out</strong>: Setting <em>healthCheck = address(0)</em> effectively disables the health check, even if <em>doHealthCheck = true</em>. The <em>if (doHealthCheck &amp;&amp; healthCheck != address(0))</em> condition silently passes. This is noted as a potential gotcha, the check being <em>true</em> may give a false sense of security if the oracle address was never set.</p><p><strong>ethToWant():</strong> is virtual and unimplemented. Concrete strategies must implement this to convert gas cost estimates into <em>want</em> terms for keeper incentive calculations. A buggy implementation here doesn’t break execution but can cause keepers to under- or over-prioritize harvesting.</p><h3>Summary</h3><p><em>BaseStrategy</em> separates concerns: the Vault manages capital allocation, each strategy manages yield generation, and <em>BaseStrategy</em> handles all the shared infrastructure in between. Access control, harvest orchestration, emergency exits, health checks — all handled here so strategy developers only need to implement four methods.<br> <br>If you’re building a Yearn strategy or studying how serious DeFi protocols manage complexity, this contract is worth reading carefully. <a href="https://github.com/yearn/yearn-vaults-v2/blob/master/contracts/BaseStrategy.sol">The Link to the code on github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85654fa79007" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[50 EVM Opcodes Explained]]></title>
            <link>https://medium.com/@shuaibganiyat20/50-evm-opcodes-explained-6f8fe3a5226a?source=rss-2ce36021829a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f8fe3a5226a</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[evm]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[opcodes]]></category>
            <dc:creator><![CDATA[SHUAIB GANIYAT]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 15:41:02 GMT</pubDate>
            <atom:updated>2026-03-31T15:56:26.275Z</atom:updated>
            <content:encoded><![CDATA[<p>Opcodes (operation codes) are the low-level machine instructions that define how the Ethereum Virtual Machine (EVM) executes smart contracts. When a contract is written in Solidity and compiled, it becomes bytecode — a sequence of hexadecimal values where each byte represents a specific opcode. <br>The EVM, being a stack-based virtual machine, processes these opcodes one at a time, manipulating data on its stack to perform computations, control flow, and interact with blockchain state. Understanding opcodes is essential for writing gas-efficient smart contracts, performing security audits, and gaining deeper insight into how high-level Solidity code actually behaves when executed on-chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4_Fb4ulbe9EpXdepgO2Ww.png" /><figcaption>EVM Opcodes</figcaption></figure><h3>How Does EVM Opcodes Works</h3><p>The EVM operates using a Last-In, First-Out (LIFO) structure, similar to a stack of plates. Data is pushed onto the top of the stack using opcodes like PUSH, and most operations work by popping their required inputs from the stack, performing a computation, and then pushing the result back onto it. The stack has a maximum depth of 1024 items, with each item being a 256-bit (32-byte) word. <br>In this guide, we explore 50 EVM opcodes, organized by category, with each entry detailing the opcode’s hexadecimal value, a clear explanation, gas cost and a practical Solidity example demonstrating its use.</p><h4>Arithmetic Operations</h4><p><strong>0x01 — ADD:</strong> Adds two numbers.<br>Pops the top two values off the stack, adds them together, and pushes the result back. All arithmetic in the EVM is modular, if the sum overflows 256 bits, it wraps back to 0.<br><strong>Gas cost:</strong> 3</p><pre>uint256 a = 3;<br>uint256 b = 5;<br>uint256 c = a + b; // compiles to ADD → result is 8</pre><p><strong>0x02 -MUL: </strong>Multiply two numbers.<br>Pops two values, multiplies them, pushes the result. Slightly more expensive than ADD because multiplication is more complex.<br><strong>Gas cost:</strong> 5</p><pre>uint256 a = 7;<br>uint256 b = 6;<br>uint256 c = a * b; // compiles to MUL → result is 42</pre><p><strong>0x03 — SUB:</strong> Subtract one number from another.<br>Pops the top value (a) and the second value (b), then pushes a - b. The top of the stack is always the first operand. If the result would go below zero, it wraps around to a very large number (unsigned underflow).<br><strong>Gas cost:</strong> 3</p><pre>uint256 a = 10;<br>uint256 b = 3;<br>uint256 c = a - b; // compiles to SUB → result is 7</pre><p><strong>0x04 — DIV: </strong>Divide two numbers (unsigned).<strong><br></strong>Pops numerator (a) and denominator (b), pushes floor(a / b)meaning it truncates decimals. Importantly, <strong>dividing by zero does not revert, </strong>it returns 0. <br><strong>Gas cost:</strong> 5</p><pre>uint256 a = 6;<br>uint256 b = 2;<br>uint256 c = a / b; // compiles to DIV → result is 3</pre><pre>uint256 d = 7 / 2; // → result is 3 (not 3.5, decimals truncated)</pre><p><strong>0x05 — SDIV: </strong>Divide two numbers (signed).<br>Same as DIV, but treats both values as <strong>signed</strong> 256-bit integers (two’s complement). This is used when Solidity works with int256 types instead of uint256. Negative numbers are represented with the highest bit set to 1.<br><strong>Gas cost:</strong> 5</p><pre>int256 a = -10;<br>int256 b = 3;<br>int256 c = a / b; // compiles to SDIV → result is -3 (truncated toward zero)</pre><p><strong>0x06 — MOD: </strong>Modulo (remainder after division).<br>Pops two values and pushes the remainder of a / b. If the denominator is 0, the result is 0 (no revert). Useful for cycling through ranges, checking even/odd, or limiting values.<br><strong>Gas cost:</strong> 5</p><pre>uint256 a = 15;<br>uint256 b = 4;<br>uint256 c = a % b; // compiles to MOD → result is 3</pre><pre>bool isEven = (n % 2 == 0); // → MOD then ISZERO</pre><p><strong>0x07 — SMOD: </strong>Signed modulo.<br>Like MOD, but treats operands as signed integers. The result takes the sign of the dividend (first operand). Used when working with int256 in Solidity.<br><strong>Gas cost:</strong> 5</p><pre>int256 a = -13;<br>int256 b = 5;<br>int256 c = a % b; // compiles to SMOD → result is -3 (sign follows a)</pre><p><strong>0x08 — ADDMOD: </strong>Modular addition without overflow.<br>Pops three values: a, b, and N. Computes (a + b) % N in <strong>arbitrary precision, </strong>meaning the intermediate sum is NOT cut off at 256 bits before taking the modulus. This makes it safe for cryptographic math.<br><strong>Gas cost:</strong> 8</p><pre>assembly {<br>    // Safe even if a + b would overflow a normal uint256<br>    let result := addmod(a, b, N)<br>}</pre><p><strong>0x09 — ADDMOD: </strong>Modular multiplication without overflow.<br>Like ADDMOD but for multiplication. Pops a, b, N and pushes (a * b) % N using arbitrary precision. If N is 0, the result is 0.<br><strong>Gas cost:</strong> 8</p><pre>uint256 a = 15;<br>uint256 b = 3;<br>uint256 N = 8;<br>// (15 * 3) % 8 = 45 % 8 = 5<br>uint256 c = mulmod(a, b, N); // → MULMOD opcode</pre><p><strong>0x0A — EXP: </strong>Exponentiation (power).<br>Pops base and exponent, pushes base ** exponent. This is the most variable-cost arithmetic opcode, the gas cost depends on the size of the exponent in bytes.<br><strong>Gas cost:</strong> 10 base + 50 per byte of the exponent</p><pre>uint256 result = 2 ** 10;  // exponent is 1 byte → 10 + 50 = 60 gas<br>uint256 big    = 2 ** 256; // exponent is 2 bytes → 10 + 100 = 110 gas</pre><p><strong>0x0B — SIGNEXTEND: </strong>Extend the sign of a smaller integer to 256 bits.<br>Pops b (byte size indicator) and x (value), and sign-extends the value from b+1 bytes to 256 bits. Used when casting smaller signed integers like int8 or int32 to int256.<br><strong>Gas cost:</strong> 5</p><pre>// When casting int8 to int256, Solidity uses SIGNEXTEND<br>// -1 as int8 = 0xFF → sign-extended to 0xFFFF...FFFF in int256<br>int8 small = -1;<br>int256 big = int256(small); // SIGNEXTEND ensures -1 stays -1</pre><h4>Comparison &amp; Bitwise Logic Operations</h4><p><strong>0x10 — LT: </strong>Less than (unsigned).<br>Pops two values and pushes 1 if a &lt; b, otherwise pushes 0. The EVM has no boolean type, true is 1, false is 0. Operates on unsigned integers.<br><strong>Gas cost:</strong> 3</p><pre>uint256 a = 3;<br>uint256 b = 7;<br>bool result = a &lt; b; // compiles to LT → pushes 1 (true)</pre><p><strong>0x11-GT: </strong>Greater than (unsigned).<br>Mirror of LT. Pushes 1 if a &gt; b, otherwise pushes0 . Unsigned comparison.<br><strong>Gas cost:</strong> 3</p><pre>require(msg.value &gt; minDeposit, &quot;Too little&quot;);<br>// → CALLVALUE, PUSH minDeposit, GT, ISZERO, JUMPI(revert)</pre><p><strong>0x12 — SLT: </strong>Signed less than.<br>Like LT but both values are treated as <strong>signed</strong> integers. The bit pattern 0xFF...FF means -1 in signed math, unsigned LT would call it huge, but SLT correctly identifies it as less than 1.<br><strong>Gas cost:</strong> 3</p><pre>int256 a = -1;<br>int256 b = 1;<br>bool result = a &lt; b; // compiles to SLT → true</pre><p><strong>0x13 — SGT: </strong>Signed greater than.<br>Signed version of GT. Used automatically when Solidity compares int256 values with &gt;.<br><strong>Gas cost:</strong> 3</p><pre>int256 a = 5;<br>int256 b = -3;<br>bool result = a &gt; b; // compiles to SGT → true</pre><p><strong>0x14 — EQ: </strong>Equality check.<br>Pops two values and pushes 1 if they are exactly equal, 0 if not. Works on any 256-bit value — numbers, addresses, hashes.<br><strong>Gas cost:</strong> 3</p><pre>require(msg.sender == owner, &quot;Not owner&quot;);<br>// → CALLER, PUSH owner_address, EQ, ISZERO, JUMPI(revert)</pre><p><strong>0x15 — ISZERO: </strong>Check if a value is zero (logical NOT).<br>Pops one value. Pushes 1 if it is 0, pushes 0 if it is anything else. This is how the EVM does logical NOT — flipping a boolean result.<br><strong>Gas cost:</strong> 3</p><pre>// require(x != 0) becomes:<br>// PUSH x → ISZERO → JUMPI(revert if zero)</pre><pre>// Double ISZERO normalizes any nonzero value to exactly 1:<br>bool isActive = someValue != 0;<br>// internally: PUSH someValue, ISZERO, ISZERO</pre><p><strong>0x16 — AND: </strong>Bitwise AND.<strong><br></strong>Pops two 256-bit values and pushes the result where each bit is 1 only if <strong>both</strong> corresponding input bits were 1. Used to mask and extract specific bits.<br><strong>Gas cost:</strong> 3</p><pre>assembly {<br>    // Extract the lower 20 bytes (an address) from a packed uint256<br>    let addr := and(packed, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)<br>}</pre><p><strong>0x17 — OR: </strong>Bitwise OR.<br>Pops two values, pushes the result where each bit is 1 if <strong>either</strong> input bit is 1. Used to combine or set bits, often when packing multiple values into one storage slot.<br><strong>Gas cost:</strong> 3</p><pre>assembly {<br>    // Pack two uint128 values into a single uint256 storage slot<br>    let packed := or(upper128, shl(128, lower128))<br>}</pre><p><strong>0x18 — XOR: </strong>Bitwise exclusive OR.<br>Pops two values, pushes the result where each bit is 1 only if the two input bits are <strong>different</strong>. Key property: a XOR a = 0 and a XOR 0 = a. Used in cryptography and simple equality checks.</p><p><strong>Gas cost:</strong> 3</p><pre>assembly {<br>    // Swap two variables without a temp variable<br>    a := xor(a, b)<br>    b := xor(a, b)<br>    a := xor(a, b)<br>}</pre><p><strong>0x19 — NOT: Bitwise NOT (flip all bits).<br></strong>Pops one value and flips every single one of its 256 bits. NOT(0) gives the maximum uint256 value (all ones). Used to create bitmasks.<br><strong>Gas cost:</strong> 3</p><pre>// Create a mask for everything EXCEPT the lowest byte<br>uint256 mask = ~uint256(0xFF);<br>// Result: 0xFFFFFFFF...FFFFFF00<br>// Solidity&#39;s ~ operator compiles to NOT</pre><p><strong>0x1A — BYTE: </strong>Extract a single byte from a 256-bit word.<br>Pops i (byte index from the left, 0–31) and x (the value), pushes the single byte at position i. Byte 0 is the most significant (leftmost) byte.<br><strong>Gas cost:</strong> 3</p><pre>assembly {<br>    // Extract the 5th byte (index 4) from a packed word<br>    let b := byte(4, someWord)<br>}</pre><p><strong>0x1B — SHL: </strong>Shift left (cheap multiplication by powers of 2).<br>Pops shift amount and value, pushes value &lt;&lt; shift. Shifting left by N is the same as multiplying by 2ᴺ. Bits that shift past position 255 are discarded.<br><strong>Gas cost:</strong> 3</p><pre>uint256 x = 1 &lt;&lt; 10; // SHL: 3 gas → result is 1024<br>uint256 y = 2 ** 10; // EXP: 60 gas → same result 1024<br>// SHL is ~20x cheaper for powers of 2</pre><p><strong>0x1C — SHR: Shift right (cheap division by powers of 2).<br></strong>Pops shift amount and value, pushes value &gt;&gt; shift (logical shift — zeros fill from the left). Used to extract upper bytes from packed values or divide by powers of 2.<br><strong>Gas cost:</strong> 3</p><pre>// Extract the upper 128 bits from a packed uint256<br>uint128 upper = uint128(packed &gt;&gt; 128); // → SHR</pre><pre>// Fast integer divide by 4<br>uint256 quarter = x &gt;&gt; 2; // same as x/4, but 3 gas vs 5 gas</pre><p><strong>0x1D — SAR: Arithmetic shift right (signed).<br></strong>Like SHR but for signed values. Instead of filling with zeros from the left, it fills with the <strong>sign bit</strong> (1 for negative numbers). This correctly preserves the sign when right-shifting a negative int256.<br><strong>Gas cost:</strong> 3</p><pre>assembly {<br>    // Signed divide int256 by 2 (preserves sign)<br>    let result := sar(1, signedValue)<br>}<br>// -8 &gt;&gt; 1 = -4 with SAR (correct)<br>// -8 &gt;&gt; 1 = a huge positive number with SHR (wrong for signed)</pre><h4>Memory &amp; Storage</h4><p><strong>0x51 — MLOAD: </strong>Load 32 bytes from memory.<strong><br></strong>Pops a byte offset and reads the 32-byte word starting at that offset from memory, pushing it onto the stack. If the offset exceeds current memory size, memory expands automatically (extra gas cost).<br><strong>Gas cost:</strong> 3 (plus memory expansion cost if needed)</p><pre>assembly {<br>    // The free memory pointer is always stored at slot 0x40<br>    let freePtr := mload(0x40)<br>    // freePtr now holds the address of the next free memory byte<br>}</pre><p><strong>0x52 — MSTORE: </strong>Write 32 bytes to memory.<br>Pops an offset and a 32-byte value, then writes the full word to memory at that offset. Always writes exactly 32 bytes, use MSTORE8 if you only want one byte.<br><strong>Gas cost:</strong> 3 (plus memory expansion cost if needed)</p><pre>assembly {<br>    let ptr := mload(0x40)      // get free memory pointer<br>    mstore(ptr, 0x1234)         // write value at ptr<br>    mstore(0x40, add(ptr, 32))  // advance the free pointer by 32 bytes<br>}</pre><p><strong>0x53 — MSTORE8: </strong>Write exactly 1 byte to memory.<br>Like MSTORE but writes only the <strong>lowest byte</strong> of the value to the given offset, leaving surrounding bytes unchanged. Useful when building byte arrays character by character.<br><strong>Gas cost:</strong> 3</p><pre>assembly {<br>    mstore8(0, 0x41) // writes &#39;A&#39; (ASCII 65) to memory byte 0<br>    mstore8(1, 0x42) // writes &#39;B&#39; to memory byte 1<br>}</pre><p><strong>0x54 — SLOAD: </strong>Load a value from permanent storage.<br>Pops a storage slot key and pushes the 32-byte value stored there. Contract storage survives across transactions. The first time you read a slot in a transaction (cold), it costs 2100 gas. If you read it again (warm), it’s only 100 gas.<br><strong>Gas cost:</strong> 2100 (cold) / 100 (warm)</p><pre>// Bad: reads storage 3 times (2100 + 100 + 100 gas)<br>if (balances[user] &gt; 0) emit Transfer(balances[user]);</pre><p><strong>0x55 — SSTORE: </strong>Write a value to permanent storage.<br>Pops a slot key and a value, permanently writes it to the contract’s storage. This is the most expensive opcode in normal contract execution.</p><p><strong>Gas cost:</strong> 20,000 (writing to a new/zero slot) / 5,000 (modifying an existing value) / gas refund for zeroing a slot</p><pre>// Every state variable assignment is an SSTORE<br>totalSupply += amount; // SLOAD + ADD + SSTORE</pre><pre>// Gas tip: pack small types to share one storage slot<br>struct Packed {<br>    uint128 a; // \<br>    uint128 b; //  → both fit in one 32-byte slot, saving 20,000 gas<br>}</pre><p><strong>0x35 — CALLDATALOAD: </strong>Read 32 bytes from the transaction’s input data.<br>Pops a byte offset and pushes the 32-byte chunk of calldata starting there. Calldata is the raw input sent with a transaction — the first 4 bytes are the function selector, the rest are ABI-encoded arguments.<br><strong>Gas cost:</strong> 3</p><pre>// Calldata layout for: transfer(address to, uint256 amount)<br>// [0-3]:   function selector (4 bytes)<br>// [4-35]:  address `to`      (32 bytes)<br>// [36-67]: uint256 `amount`  (32 bytes)</pre><pre>assembly {<br>    let to     := calldataload(4)  // skip 4-byte selector<br>    let amount := calldataload(36) // 4 + 32<br>}</pre><p><strong>0x36 — CALLDATASIZE: </strong>Get the total size of calldata in bytes.<br>Pushes the byte length of the current call’s input data onto the stack. No stack inputs needed. Commonly used in fallback functions and proxy contracts to forward the full calldata.<br><strong>Gas cost:</strong> 2</p><pre>// Proxy pattern: forward all calldata to implementation<br>fallback() external payable {<br>    assembly {<br>        calldatacopy(0, 0, calldatasize()) // copy all input to memory[0]<br>        let ok := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)<br>    }<br>}</pre><p><strong>0x39 — CODECOPY: </strong>Copy this contract’s bytecode into memory.<br>Pops three values: destination memory offset, source byte offset within the bytecode, and length. Copies that slice of the contract’s own bytecode into memory. Mainly used during contract deployment.<br><strong>Gas cost:</strong> 3 per word copied</p><pre>// During deployment, the constructor uses CODECOPY to place<br>// the runtime bytecode in memory, then RETURN to deploy it<br>assembly {<br>    let size := codesize()<br>    codecopy(0, 0, size)  // copy full bytecode to memory<br>    return(0, size)        // return it → this becomes the deployed contract<br>}</pre><h4>Stack Operations</h4><p><strong>0x60 — PUSH: </strong>Push a 1-byte value onto the stack.<br>The only opcode family that reads data directly from the bytecode stream rather than from the stack. PUSH1 reads the next 1 byte after itself in the bytecode and pushes it. There are PUSH1 through PUSH32, pushing 1 to 32 bytes respectively.</p><p><strong>Gas cost:</strong> 3</p><pre>// Every literal constant in Solidity compiles to a PUSH<br>uint256 x = 5;<br>// Bytecode: PUSH1 0x05</pre><pre>// A full address needs PUSH20, a keccak256 hash needs PUSH32</pre><p><strong>0x50 — POP: </strong>Remove and discard the top stack item.<br>Pops and throws away the top value. This is needed when a function returns a value you don’t use, Solidity’s compiler emits POP to keep the stack clean.<br><strong>Gas cost:</strong> 2</p><pre>// When you ignore a return value, the compiler emits POP<br>function getValue() internal returns (uint256) { return 42; }</pre><pre>getValue(); // return value ignored → compiler inserts POP</pre><p><strong>0x80 — DUP1: </strong>Duplicate the top stack item.<br>Copies the top item and pushes the copy. The original stays in place — so you end up with two copies. DUP1 through DUP16 let you copy the 1st through 16th item from the top.<br><strong>Gas cost:</strong> 3</p><pre>// Using a value twice forces a DUP<br>uint256 a = 100;<br>uint256 b = a * a; // compiler: PUSH a, DUP1, MUL</pre><p><strong>0x90 — SWAP1:</strong> Swap the top two stack items.<br>Exchanges the top item with the second item. SWAP1 through SWAP16 swap the top with the 2nd through 17th item. Used to reorder operands for opcodes that require a specific argument order.<br><strong>Gas cost:</strong> 3</p><pre>// Before: stack = [B, A, ...]<br>// After SWAP1: stack = [A, B, ...]</pre><pre>// Solidity uses SWAP when operand order matters<br>// e.g., SUB pops a then b → if you need b - a, compiler inserts a SWAP1</pre><p><strong>0x59 — MSIZE: </strong>Push the current memory size in bytes.<br>Pushes the size of the highest touched memory address, rounded up to the nearest 32 bytes. Memory starts at size 0 and grows as needed.<br><strong>Gas cost:</strong> 2</p><pre>assembly {<br>    let currentSize := msize() // how many bytes of memory have been used?<br>    mstore(currentSize, 0x42)  // write at the end of currently used memory<br>}</pre><h4>Control Flow</h4><p><strong>0x00 — STOP: </strong>Halt execution successfully (no return data).<br>Ends execution successfully without returning any data. It’s opcode 0x00 — literally the zero byte. Costs zero gas. An empty contract (all zero bytes) is valid because STOP is a complete program.</p><p><strong>Gas cost:</strong> 0</p><pre>// Solidity appends STOP at the end of functions that return nothing<br>function doSomething() external {<br>    counter++;<br>    // compiler appends STOP here automatically<br>}</pre><p><strong>0x56 — JUMP: </strong>Unconditional jump.<br>Pops a destination byte offset and sets the program counter (PC) to it — execution continues from there. The destination <strong>must</strong> have a JUMPDEST opcode at that exact position, otherwise the transaction reverts.<br><strong>Gas cost:</strong> 8</p><pre>// Pseudo-bytecode for a loop:<br>// offset 10: JUMPDEST   ← valid jump target<br>// ...loop body...<br>// PUSH1 0x0A            ← push offset 10<br>// JUMP                  ← go back to offset 10</pre><p><strong>0x57 — JUMPI: </strong>Conditional jump.<strong><br></strong>Pops two values: destination and condition. If the condition is any nonzero value (true), it jumps to the destination. If condition is 0 (false), execution continues to the next opcode. This is the foundation of every if, require, and loop in Solidity.<br><strong>Gas cost:</strong> 10</p><pre>require(x &gt; 0, &quot;x must be positive&quot;);<br>// Compiled roughly as:<br>// PUSH x<br>// PUSH 0<br>// GT                      // x &gt; 0?<br>// JUMPI continue_offset   // if true, skip revert<br>// PUSH error_data<br>// REVERT<br>// JUMPDEST                // ← continue_offset lands here</pre><p><strong>0x58 — JUMPDEST: </strong>Mark a position as a valid jump target.<br>Does nothing computationally, it’s purely a marker. Before executing, the EVM scans the bytecode and records every JUMPDEST position. JUMP and JUMPI can only land here. This prevents jumping into the middle of PUSH data (which would execute arbitrary bytes as opcodes).<br><strong>Gas cost:</strong> 1</p><pre>// Every function in compiled Solidity bytecode starts with a JUMPDEST<br>// so that function dispatch (via the selector routing in the fallback) <br>// can jump to it safely.</pre><p><strong>0x58 — PC: </strong>Push the current program counter.<br>Pushes the byte index of the PC opcode itself within the bytecode. Rarely used in typical contracts but appears in advanced meta-programming and position-independent code.<br><strong>Gas cost:</strong> 2</p><pre>assembly {<br>    let myOffset := pc() // byte position of this instruction in the bytecode<br>}</pre><h4>Environmental Information</h4><p><strong>0x30 — ADDRESS: </strong>Push this contract’s own address.<br>Pushes the 20-byte address of the currently executing contract. During a DELEGATECALL, this returns the caller’s address not the implementation contract’s address.<br><strong>Gas cost:</strong> 2</p><pre>address self = address(this); // → ADDRESS opcode</pre><p><strong>0x31 — BALANCE: </strong>Push an address’s ETH balance.<br>Pops an address and pushes its current ETH balance in wei. Accessing an address for the first time in a transaction (cold) costs more gas than re-accessing it (warm).<br><strong>Gas cost:</strong> 2600 (cold) / 100 (warm)</p><pre>uint256 contractBal = address(someContract).balance; // → PUSH addr, BALANCE</pre><p><strong>0x32 — ORIGIN: </strong>Push the original transaction sender (tx.origin).<br>Always pushes the EOA (externally owned account) that signed and sent the original transaction, no matter how many contract hops the call has gone through.<br><strong>Gas cost:</strong> 2</p><pre>address originalSender = tx.origin; // → ORIGIN opcode</pre><p><strong>0x33 — CALLER: </strong>Push the direct caller’s address (msg.sender).<br>Pushes the address of whoever called this contract in the current call frame. This is msg.sender in Solidity. During a DELEGATECALL, this returns the original caller transparently.<br><strong>Gas cost:</strong> 2</p><pre>modifier onlyOwner() {<br>    require(msg.sender == owner, &quot;Not owner&quot;); // → CALLER, PUSH owner, EQ<br>    _;<br>}</pre><p><strong>0x34 — CALLVALUE: </strong>Push the ETH sent with this call (msg.value).<br>Pushes the amount of ETH (in wei) attached to the current call. For non-payable functions, Solidity automatically generates code that checks this is zero and reverts if not.<br><strong>Gas cost:</strong> 2</p><pre>function deposit() external payable {<br>    require(msg.value &gt;= 0.01 ether, &quot;Too little&quot;); // → CALLVALUE, PUSH, LT<br>    balances[msg.sender] += msg.value;<br>}</pre><p><strong>0x3A — GASPRICE: </strong>Push the gas price of the current transaction.<br>Pushes the effective gas price in wei per gas unit. After EIP-1559 this is the base fee plus the priority tip, the actual price paid per unit of gas.<br><strong>Gas cost:</strong> 2</p><pre>uint256 price = tx.gasprice; // → GASPRICE opcode<br>// Useful for MEV-aware contracts or gas subsidy calculations</pre><p><strong>0x40 — BLOCKHASH: </strong>Push the hash of a recent block.<br>Pops a block number and pushes its 32-byte block hash. Only works for the <strong>256 most recent blocks, </strong>beyond that it returns zero.<strong>Gas cost:</strong> 20</p><pre>bytes32 prevHash = blockhash(block.number - 1); // → BLOCKHASH</pre><p><strong>0x42 — TIMESTAMP: </strong>Push the current block’s Unix timestamp.<br>Pushes the timestamp of the current block in seconds since the Unix epoch. In Proof-of-Stake Ethereum, blocks come every 12 seconds, making timestamps more predictable than before, but validators still have a small window to manipulate it.<br><strong>Gas cost:</strong> 2</p><pre>require(block.timestamp &gt;= unlockTime, &quot;Too early&quot;);<br>// → TIMESTAMP, PUSH unlockTime, LT, ISZERO, JUMPI</pre><h4>System / Call Operations</h4><p><strong>0xF0 — CREATE: </strong>Deploy a new contract.<br>Pops three values: ETH to send (value), memory offset and length of the constructor bytecode. Runs the bytecode as a constructor and deploys whatever it returns as a new contract. The new address is computed from keccak256(deployer, nonce). Pushes the new contract&#39;s address, or 0 on failure.<br><strong>Gas cost:</strong> 32,000 base + execution costs</p><pre>// Factory pattern<br>contract Factory {<br>    function deploy() external returns (address) {<br>        return address(new MyContract()); // → CREATE<br>    }<br>}</pre><p><strong>0xF1 — CALL: </strong>Call another contract or send ETH.<br>The primary way to interact with other contracts. Takes 7 stack arguments: gas limit, target address, ETH value, input data offset and length, return data offset and length. Pushes 1 on success, 0 on failure. <strong>Does NOT automatically revert on failure, </strong>you must check the return value.<br><strong>Gas cost:</strong> ~700 base + execution costs</p><pre>// Safest ETH transfer pattern:<br>(bool ok, ) = recipient.call{value: amount}(&quot;&quot;);<br>require(ok, &quot;Transfer failed&quot;);</pre><p><strong>0xF3 — RETURN: </strong>Halt successfully and return data.<br>Pops offset and length, halts execution successfully, and returns the memory slice as output data. All state changes are permanently committed. Every function that returns a value uses this.<br><strong>Gas cost:</strong> 0 (plus memory expansion if needed)</p><pre>function getAmount() external view returns (uint256) {<br>    return amount;<br>    // → PUSH amount, MSTORE, PUSH 32, PUSH 0, RETURN<br>}</pre><p><strong>0xF4 — DELEGATECALL: </strong>Run another contract’s code in your own context.<br>Like CALL, but the called contract’s code executes <strong>inside the calling contract’s context, </strong>storage, address, and ETH balance all remain the caller’s. This is the foundation of upgradeable proxy contracts.<br><strong>Gas cost:</strong> ~700 base + execution costs</p><pre>// How a proxy contract forwards calls to its implementation:<br>fallback() external payable {<br>    address impl = implementation;<br>    assembly {<br>        calldatacopy(0, 0, calldatasize())<br>        // impl&#39;s code runs, but reads/writes THIS proxy&#39;s storage<br>        let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)<br>    }<br>}</pre><p><strong>0xF5 — CREATE2: </strong>Deploy a contract at a predictable address.<br>Like CREATE, but the deployed address is determined by keccak256(0xFF, deployer, salt, keccak256(bytecode)). You can calculate where a contract will live <strong>before deploying it</strong>. <br><strong>Gas cost:</strong> 32,000 base + execution costs</p><pre>// Deploy at a pre-computable address<br>bytes32 salt = keccak256(abi.encode(token0, token1));<br>address pair = address(new UniswapPair{salt: salt}()); // → CREATE2</pre><p><strong>0xFA — STATICCALL: </strong>Read-only call, reverts if target modifies state.<br>Like CALL but prohibits any state modification inside the called contract, no SSTORE, no events, no CREATE, no sending ETH. If the target tries any of those, the whole call reverts. Solidity uses this automatically for view and pure function calls.<br><strong>Gas cost:</strong> ~700 base + execution costs</p><pre>// Calling a view function → compiler automatically uses STATICCALL<br>uint256 bal = ERC20Token(addr).balanceOf(user);<br>// balanceOf is view → this compiles to STATICCALL, not CALL</pre><p><strong>0xFD — REVERT: </strong>Abort execution and undo all state changes.<br>Pops offset and length, halts execution with failure, and <strong>reverts every state change</strong> made in this call, storage writes, ETH transfers, event emissions are all undone. The memory slice is returned as the error data. Remaining gas is <strong>refunded</strong> to the caller.<br><strong>Gas cost:</strong> 0 (plus memory expansion if needed)</p><pre>require(amount &gt; 0, &quot;Zero amount&quot;);<br>// Roughly compiles to:<br>// check condition → if false:<br>// PUSH error_string_offset<br>// PUSH error_string_length<br>// REVERT  ← reverts all state, refunds remaining gas</pre><h4>Logging (Events)</h4><p><strong>0xA0 — LOG0: </strong>Emit a log with no indexed topics.<br>Pops offset and length, emits a transaction log entry with only raw data and no searchable topics. The cheapest log opcode but the least filterable off-chain.<br><strong>Gas cost:</strong> 375 base + 8 per byte of data</p><pre>assembly {<br>    // Emit raw bytes from memory[0..31] as a log with no topics<br>    log0(0, 32)<br>}</pre><p><strong>0xA1 to 0xA4 — LOG1, LOG2, LOG3, LOG4</strong>:Emit a log with 1 to 4 indexed topics.<br>Each LOGn opcode pops (offset, length, topic1, ..., topicN). Topics are 32-byte searchable values. The <strong>first topic is always the event signature hash</strong> for non-anonymous events. Indexed parameters in Solidity events become additional topics. Non-indexed parameters go into the data payload.<br><strong>Gas cost:</strong> 375 base + 375 per topic + 8 per byte of data</p><pre>event Transfer(address indexed from, address indexed to, uint256 value);<br>emit Transfer(sender, receiver, amount);</pre><pre>// Compiles to LOG3 (3 topics):<br>// topic[0] = keccak256(&quot;Transfer(address,address,uint256)&quot;)  ← event signature<br>// topic[1] = from   (indexed)<br>// topic[2] = to     (indexed)<br>// data     = abi.encode(value)  ← NOT indexed, goes in data payload</pre><p><strong>0x20 — KECCAK256:</strong>Hash a memory region with Keccak-256.<br>Pops offset and length, hashes that region of memory, and pushes the 32-byte hash. This is the cryptographic backbone of Ethereum — used to compute mapping slot addresses, event topic signatures, CREATE2 addresses, function selectors, and more.</p><p><strong>Gas cost:</strong> 30 base + 6 per 32-byte word hashed</p><pre>// How Solidity computes mapping slot addresses:<br>// slot = keccak256(abi.encodePacked(key, mappingSlotNumber))<br>assembly {<br>    mstore(0, user)          // store key at memory[0]<br>    mstore(32, 1)            // store slot number at memory[32]<br>    let slot := keccak256(0, 64)  // hash 64 bytes<br>    let balance := sload(slot)    // read from that storage slot<br>}</pre><pre>// Function selector = first 4 bytes of keccak256(&quot;transfer(address,uint256)&quot;)<br>// = 0xa9059cbb</pre><h3>Summary</h3><p>Understanding EVM opcodes is a key step toward mastering how smart contracts truly behave under the hood. While high-level languages like Solidity abstract away complexity, it’s the opcodes that ultimately define execution, gas consumption, and security at the lowest level.</p><p>By learning how opcodes manipulate the stack, interact with memory and storage, and control execution flow, developers gain the ability to:</p><ul><li>Write more gas-efficient contracts</li><li>Debug and trace low-level behavior</li><li>Identify subtle vulnerabilities that aren’t obvious in Solidity</li></ul><p>For auditors and advanced developers, opcode-level knowledge is not optional, it’s essential. It provides the clarity needed to reason about edge cases, optimize performance, and build safer systems on Ethereum.</p><p>In short, if Solidity is the “what,” opcodes are the “how.” Mastering them gives you full visibility into the EVM and a significant edge in smart contract development and security.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f8fe3a5226a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum Wallet Protocols: From window.ethereum to Agentic Payments]]></title>
            <link>https://medium.com/@shuaibganiyat20/ethereum-wallet-protocols-from-window-ethereum-to-agentic-payments-45356e444a71?source=rss-2ce36021829a------2</link>
            <guid isPermaLink="false">https://medium.com/p/45356e444a71</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[wallet]]></category>
            <category><![CDATA[eip-4337]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[SHUAIB GANIYAT]]></dc:creator>
            <pubDate>Fri, 20 Mar 2026 10:52:27 GMT</pubDate>
            <atom:updated>2026-03-20T13:01:56.343Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What started as a simple JavaScript trick has quietly grown into the infrastructure for AI agents that pay for things on their own.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7tVs_Qljy_xqzaRzqUbUQ.png" /><figcaption>Ethereum Wallet Protocols</figcaption></figure><p>You’ve probably connected a wallet to a website before. You clicked “Connect Wallet,” a MetaMask popup appeared, you approved it, and suddenly the site knew who you were.</p><p>That felt simple. Under the hood, six different standards made it work.</p><p>Here’s what they are, why they exist, and why the last one involves AI agents paying for things on your behalf — automatically.</p><h3>It started with a hack</h3><p>When MetaMask (or any wallet) installs itself as a browser extension, it injects a JavaScript object called window.ethereum directly into every webpage. Any dApp can call window.ethereum.request({ method: &#39;eth_requestAccounts&#39; }) to connect.</p><p>Any website could then check:</p><pre>if (window.ethereum) {<br>  // a wallet is here, let&#39;s connect<br>}</pre><p>Simple. Clever. And it worked — until people started installing more than one wallet.</p><p>Here’s the problem: window.ethereum is a single slot. One value. When MetaMask loads, it writes itself there. When Coinbase Wallet loads next, it overwrites MetaMask. Completely. Silently. No warning.</p><p>The website ends up seeing whichever wallet loaded last. The other one just… disappears.</p><h3>EIP-1193 — teaching wallets to speak the same language</h3><p>Different wallets didn’t just fight over the same slot. They also spoke different dialects. MetaMask used one method name, other wallets used different ones entirely.</p><p>EIP-1193 fixed that by defining one universal interface. Every wallet that wants to play nicely has to speak it.</p><p>The whole thing boils down to one method:</p><pre>await window.ethereum.request({<br>  method: &#39;eth_requestAccounts&#39;<br>})<br>// → your wallet address</pre><p>Connect, send, sign, switch networks — everything goes through .request(). One shape, every wallet. Think of it like USB. Before USB, every device had its own plug. After it, they all fit the same port.</p><p>EIP-1193 also defines standard events — so your app knows when the user switches accounts or changes network — and standard error codes, so you always know <em>why</em> something failed.</p><p>What it doesn’t fix: the single-slot problem. That needed its own solution.</p><h3>EIP-6963 — the wallet picker, finally</h3><p>EIP-6963 (2023) doesn’t patch window.ethereum. It sidesteps it entirely.</p><p>Instead of wallets fighting over one slot, they now <em>announce</em> themselves using browser events. The dApp listens, collects every announcement, and shows you a proper wallet picker.</p><p>The whole protocol is two events:</p><pre>eip6963:announceProvider  →  wallets say &quot;I&#39;m here&quot;<br>eip6963:requestProvider   →  dApps say &quot;anyone there?&quot;</pre><p>Each wallet announces its name, icon, and a unique ID. The dApp collects them all. You see a list. You pick one. Done.</p><p>No more last-writer-wins. No more invisible wallets. Just a clean list of everything you’ve actually installed.</p><h3>EIP-4337 — Smart Contract Wallets Without Protocol Changes</h3><p>This is a bigger architectural shift. Normally in Ethereum, only <strong>Externally Owned Accounts (EOAs)</strong> — accounts controlled by a private key — can initiate transactions. EIP-4337 introduces <strong>smart contract wallets</strong> as first-class citizens.</p><p>Instead of a transaction, you submit a <strong>UserOperation</strong> (a pseudo-transaction) to a separate <strong>mempool</strong>. Special nodes called <strong>Bundlers</strong> pick these up, bundle them, and submit them on-chain through a global <strong>EntryPoint</strong> contract. This enables:</p><ul><li><strong>Gas sponsorship</strong> (paymasters pay fees for users)</li><li><strong>Session keys</strong> (limited-permission keys for dApps)</li><li><strong>Social recovery</strong> (recover wallet without seed phrase)</li><li><strong>Batched transactions</strong> (multiple actions in one)</li><li><strong>No ETH required</strong> to pay gas (any token via paymaster)</li></ul><p>The tradeoff? You’d need a new wallet address. For many existing users, that’s a dealbreaker.</p><h3>EIP-7702 — upgrade what you already have</h3><p>EIP-4337 is powerful, but it has an adoption problem. To use it, you need a <em>new</em> smart contract wallet at a <em>new</em> address. That means migrating from your existing 0x... address, your identity, your reputation, your NFTs, your DeFi positions to a new one. For most users, that&#39;s a non-starter.</p><p><strong>EIP-7702</strong>, proposed by Vitalik Buterin and shipped as part of the Pectra upgrade, solves this with a more pragmatic approach: <em>don’t make users migrate</em>. Instead, let their existing EOA temporarily borrow smart contract logic for the duration of a transaction.<br>How it works</p><p>EIP-7702 introduces a new transaction type. In it, you sign an authorization saying: “For this transaction, treat my EOA as if it has the code at <em>this</em> smart contract address.”</p><pre>// An EIP-7702 transaction<br>const tx = {<br>  type: &#39;0x04&#39;,    // new transaction type<br>  authorizationList: [{<br>    chainId: 1,<br>    address: smartWalletImplementationAddress,  // the code to borrow<br>    nonce: currentNonce,<br>    // signed by the EOA owner<br>    v, r, s<br>  }],<br>  // ... the actual calls to execute<br>}</pre><p>During this transaction, your EOA behaves exactly like the smart wallet at that address. It can batch calls, use a Paymaster, honour session keys — all the EIP-4337 features. When the transaction completes, the EOA returns to normal. Same address. Same history. No migration.</p><h3>X402 — the internet starts charging, automatically</h3><p>Here’s where it gets interesting.</p><p>HTTP has had a 402 Payment Required status code since 1991. The idea was that servers could charge for content. But nobody ever defined <em>how</em> to pay, so it sat unused for over 30 years.</p><p>X402 activates it — and it’s specifically designed for AI agents.</p><p>An AI agent calls an API. The server responds with 402 and says: &quot;it costs $0.001, pay this address in USDC.&quot; The agent pays on-chain, sends proof, and gets the data. No human involved. No account needed. No credit card on file.</p><pre>Agent → GET /data<br>Server → 402: pay 0.001 USDC to 0x...<br>Agent → pays on-chain, sends proof<br>Server → 200 OK, here&#39;s your data</pre><p>Combined with EIP-4337 smart wallets, an AI agent can have its own wallet, its own spending limits, and full autonomy to pay for whatever it needs to get its job done.</p><h3>The stack, plain and simple</h3><p>Each standard solved one specific problem:Standard What it fixed window.ethereum Wallets became findable EIP-1193 All wallets speak the same language EIP-6963 Multiple wallets can coexist EIP-4337 Wallets became programmable EIP-7702 Existing wallets got upgraded X402 The web became payable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45356e444a71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Hooks: useState, useEffect, useCallback, useMemo, useRef, and useContext]]></title>
            <link>https://medium.com/@shuaibganiyat20/react-hooks-usestate-useeffect-usecallback-usememo-useref-and-usecontext-1def8b4da536?source=rss-2ce36021829a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1def8b4da536</guid>
            <dc:creator><![CDATA[SHUAIB GANIYAT]]></dc:creator>
            <pubDate>Wed, 18 Mar 2026 09:14:42 GMT</pubDate>
            <atom:updated>2026-03-18T09:15:22.266Z</atom:updated>
            <content:encoded><![CDATA[<p>React Hooks transformed how we write React applications by enabling functional components to manage state, side effects, and more without needing class-based components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*deup_rWJVKy9Hy-nAThQcg.png" /><figcaption>React Hooks</figcaption></figure><h3>useState</h3><p>useState Hook lets you add a <a href="https://react.dev/learn/state-a-components-memory">state variable</a> to your component, update a value that persists across renders and triggers a re-render whenever that value changes.</p><h4>Syntax</h4><pre>const [state, setState] = useState(initialState)</pre><h4>Example</h4><pre>import { useState } from &quot;react&quot;;<br><br>function Counter() {<br>  const [count, setCount] = useState(0);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>useEffect</h3><p>useEffect Hook synchronizes your component with an external system like data fetching, a DOM API, a timer, or a subscription. It replaces componentDidMount, componentDidUpdate, and componentWillUnmount from class components.</p><h4>Syntax</h4><pre>useEffect(() =&gt; {<br>  // side effect logic<br>// dependency is optional<br>}, [dependencies]);</pre><ul><li>No dependency — It runs on every render</li><li>[ ] — Runs only on the first render with empty dependency array</li><li>[prop, state] — Runs on the first render and anytime any depency value changes</li></ul><h4>Example</h4><pre>import { useState, useEffect } from &quot;react&quot;;<br><br>function Users() {<br>  const [users, setUsers] = useState([]);<br><br>  useEffect(() =&gt; {<br>    fetch(&quot;https://jsonplaceholder.typicode.com/users&quot;)<br>      .then(res =&gt; res.json())<br>      .then(data =&gt; setUsers(data));<br>  }, []);<br><br>  return (<br>    &lt;ul&gt;<br>      {users.map(user =&gt; (<br>        &lt;li key={user.id}&gt;{user.name}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}</pre><h3>useCallback</h3><p>useCallback Hook memoizes a callback function to ensure that it is not recreated on every render unless its dependencies change.</p><h4>Syntax</h4><pre>const memoizedFn = useCallback(() =&gt; {}, [dependencies]);</pre><h4>Example</h4><pre>function useSearch(baseUrl: string) {<br>  const [results, setResults] = useState([])<br><br>  // Without useCallback, every consumer&#39;s useEffect that lists<br>  // &#39;search&#39; as a dep would re-run on every parent render<br>  const search = useCallback(async (query: string) =&gt; {<br>    const res = await fetch(`${baseUrl}?q=${query}`)<br>    setResults(await res.json())<br>  }, [baseUrl])  // recreate only if baseUrl changes<br><br>  return { results, search }<br>}</pre><h3>useMemo</h3><p>useMemo Hook lets you cache the result of a calculation between re-renders. It returns a memoized value.</p><h4>Syntax</h4><pre>const memoizedValue = useMemo(() =&gt; computeValue(), [dependencies]);</pre><h4>Example</h4><pre>import { useState, useMemo } from &quot;react&quot;;<br><br>function ExpensiveComponent() {<br>  const [count, setCount] = useState(0);<br><br>  const expensiveCalculation = (num) =&gt; {<br>    console.log(&quot;Calculating...&quot;);<br>    return num * 1000;<br>  };<br><br>  const result = useMemo(() =&gt; expensiveCalculation(count), [count]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Result: {result}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increase&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>useRef</h3><p>useRef Hook provides a way to persist values across renders without causing re-renders.. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.</p><h4>Syntax</h4><pre>const ref = useRef(initialValue);</pre><h4>Example</h4><pre>import { useRef } from &quot;react&quot;;<br><br>function InputFocus() {<br>  const inputRef = useRef(null);<br><br>  const focusInput = () =&gt; {<br>    inputRef.current.focus();<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input ref={inputRef} /&gt;<br>      &lt;button onClick={focusInput}&gt;Focus Input&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>useContext</h3><p>useContext Hook allows you to share data across components without prop drilling. It can be used together with the useState Hook to share state between deeply nested components more easily than with useState alone.</p><h4>Step 1: Create Context</h4><pre>import { createContext } from &quot;react&quot;;<br><br>export const ThemeContext = createContext();</pre><h4>Step 2: Provide Context</h4><pre>function App() {<br>  return (<br>    &lt;ThemeContext.Provider value=&quot;dark&quot;&gt;<br>      &lt;Child /&gt;<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>}</pre><h4>Step 3: Consume Context</h4><pre>import { useContext } from &quot;react&quot;;<br>import { ThemeContext } from &quot;./ThemeContext&quot;;<br><br>function Child() {<br>  const theme = useContext(ThemeContext);<br><br>  return &lt;p&gt;Current theme: {theme}&lt;/p&gt;;<br>}</pre><h4>Example</h4><pre>import { createContext, useContext, useState } from &#39;react&#39;<br><br>type Theme = &#39;light&#39; | &#39;dark&#39;<br>type ThemeCtx = { theme: Theme; toggle: () =&gt; void }<br><br>const ThemeContext = createContext&lt;ThemeCtx | undefined&gt;(undefined)<br><br>export function ThemeProvider({ children }: { children: React.ReactNode }) {<br>  const [theme, setTheme] = useState&lt;Theme&gt;(&#39;light&#39;)<br>  const toggle = () =&gt; setTheme(t =&gt; t === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;)<br><br>  return (<br>    &lt;ThemeContext.Provider value={{ theme, toggle }}&gt;<br>      {children}<br>    &lt;/ThemeContext.Provider&gt;<br>  )<br>}<br><br>export function useTheme(): ThemeCtx {<br>  const ctx = useContext(ThemeContext)<br>  if (!ctx) throw new Error(&#39;useTheme must be used inside ThemeProvider&#39;)<br>  return ctx<br>}<br><br>function SettingsPage() {<br>  const { theme, toggle } = useTheme()<br>  return (<br>    &lt;button onClick={toggle}&gt;<br>      Current theme: {theme} — click to switch<br>    &lt;/button&gt;<br>  )<br>}</pre><p>React Hooks have fundamentally reshaped how we build modern React applications. By moving away from class-based components to a more functional approach, hooks like useState, useEffect, useCallback, useMemo, useRef, and useContext give developers the tools to write cleaner, more reusable, and highly efficient code.</p><p>Understanding <strong>when and why</strong> to use each hook is just as important as knowing their syntax. While useState and useEffect form the backbone of most components, optimization hooks like useCallback and useMemo help you fine-tune performance. Meanwhile, useRef and useContext unlock more advanced patterns like direct DOM interaction and global state management without unnecessary complexity.</p><p>As your React applications grow, these hooks become essential for maintaining scalability and readability. The key is not to overuse them, but to apply them thoughtfully where they provide real value.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1def8b4da536" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inheritance is one of the most important features of the object-oriented programming language.]]></title>
            <link>https://medium.com/@shuaibganiyat20/inheritance-is-one-of-the-most-important-features-of-the-object-oriented-programming-language-b06b70916a61?source=rss-2ce36021829a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b06b70916a61</guid>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[SHUAIB GANIYAT]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 20:37:46 GMT</pubDate>
            <atom:updated>2026-02-14T21:02:19.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPJElQyBAzgt9VAbQ_foOw.png" /></figure><p>Inheritance is one of the most important features of the object-oriented programming language. It is a way of extending the functionality of a program, used to separate the code, reduces the dependency, and increases the re-usability of the existing code. This article explores how inheritance works in Solidity, why it matters for smart contract architecture, and how to implement it effectively while avoiding common pitfalls.</p><h3>What Is Inheritance in Solidity?</h3><p>Inheritance allows you to create a new contract (derived contract) that inherits functionalities and state variables from an existing contract (base contract). Smart contracts can inherit other contracts by using the <strong>is</strong> keyword. More specifically, a contract that inherits is the <strong>child</strong>, and the contract being inherited is the <strong>parent</strong>. Using the <strong>is</strong> keyword in Solidity establishes a parent-to-child chain.<br>Think of inheritance as a way to create contract hierarchies. A base contract (parent) defines core functionality, while derived contracts (children) extend or modify that functionality for specific use cases.</p><h3>Why Inheritance Matters in Smart Contract Development</h3><ul><li><strong>Code Reusability:</strong> Instead of rewriting common functionalities in every new contract, developers can define them once in a base contract and reuse them across multiple derived contracts. This saves time and reduces the likelihood of introducing errors.</li><li><strong>Modularity:</strong> Inheritance promotes breaking down large, complex contracts into smaller, more manageable, and focused modules. Each module can handle a specific aspect of the contract’s functionality, making development, testing, and auditing significantly easier.</li><li><strong>Upgradeability and Maintenance:</strong> While true upgradeability in smart contracts is a complex topic, inheritance can contribute to easier maintenance. If a bug is found in a base contract’s common functionality, fixing it there can propagate the fix to all derived contracts (though deploying new versions of child contracts is still required).</li><li><strong>Standardization:</strong> Implementing standards like ERC20, ERC721 often involves inheriting from base contracts that provide required functionality.</li></ul><h3>How Inheritance Works in Solidity</h3><h4>Single Inheritance</h4><p>In Single inheritance the functions and variables of one base contract are inherited to only one derived contract.</p><pre>// Basecontract<br>contract Ownable {<br>    address public owner;<br><br>    constructor() {<br>        owner = msg.sender;<br>    }<br><br>    modifier onlyOwner() {<br>        require(msg.sender == owner, &quot;Not owner&quot;);<br>        _;<br>    }<br>}<br><br>// Derived contract inheriting Ownable<br>contract MyContract is Ownable {<br>    function restrictedAction() public onlyOwner {<br>        // function logic<br>    }<br>}</pre><p>Here, MyContract inherits the owner variable, onlyOwner modifier, and transferOwnership function from Ownable. It adds its own state variable and function.</p><h4>Multiple Inheritance</h4><p>In Multiple Inheritance, a single contract can be inherited from many contracts. A parent contract can have more than one child while a child contract can have more than one parent.</p><pre>contract Student{<br>    string public name;<br>    <br>    constructor(string memory _name) {<br>        name = _name;<br>    }<br>}<br><br>contract Timestamped {<br>    uint256 public createdAt;<br>    <br>    constructor() {<br>        createdAt = block.timestamp;<br>    }<br>}<br><br>contract Class is Student, Timestamped {<br>    string public gender;<br>    <br>    constructor(string memory _name, string _gender) <br>        Named(_name) <br>        Timestamped() <br>    {<br>        gender= _gender;<br>    }<br>}</pre><h4>Multi-Level Inheritance</h4><p>It is very similar to single inheritance, but the difference is that it has levels of the relationship between the parent and the child. The child contract derived from a parent also acts as a parent for the contract which is derived from it.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>// LEVEL 1: The Base Layer<br>contract Account {<br>    string public username;<br>    uint256 public accountCreated;<br><br>    constructor(string memory _name) {<br>        username = _name;<br>        accountCreated = block.timestamp;<br>    }<br>}<br><br>// LEVEL 2: The Administrative Layer<br>// Inherits from Account<br>contract Admin is Account {<br>    address public admin;<br>    uint256 public playerLevel;<br><br>    constructor(string memory _name) Account(_name) {<br>        admin = msg.sender;<br>        playerLevel = 1; // Everyone starts at Level 1<br>    }<br><br>    modifier onlyAdmin() {<br>        require(msg.sender == admin, &quot;Only the admin can boost levels!&quot;);<br>        _;<br>    }<br><br>    // A virtual function intended to be modified by the next level<br>    function getStatus() public virtual view returns (string memory) {<br>        return &quot;Basic Player&quot;;<br>    }<br>}<br><br>// LEVEL 3: The Final Layer (The one we deploy)<br>// Inherits from Admin (which already inherited from Account)<br>contract GameProfile is Admin {<br>    uint256 public highscore;<br><br>    constructor(string memory _name) Admin(_name) {}<br><br>    // Function to update highscore (available to anyone)<br>    function updateScore(uint256 _score) public {<br>        if (_score &gt; highscore) {<br>            highscore = _score;<br>        }<br>    }<br><br>    // Admin-only function inherited from Level 2<br>    function boostLevel() public onlyAdmin {<br>        playerLevel += 1;<br>    }<br><br>    // Overriding the status function from Level 2<br>    function getStatus() public override view returns (string memory) {<br>        if (playerLevel &gt; 10) {<br>            return &quot;Pro Gamer&quot;;<br>        }<br>        return &quot;Amateur&quot;;<br>    }<br>}</pre><h3>Practical Use Case: Building an ERC Token Standard</h3><pre>// Step 1: The Interface - defines what the token must do<br>interface IERC20 {<br>    function totalSupply() external view returns (uint256);<br>    function balanceOf(address account) external view returns (uint256);<br>    function transfer(address recipient, uint256 amount) external returns (bool);<br>    function allowance(address owner, address spender) external view returns (uint256);<br>    function approve(address spender, uint256 amount) external returns (bool);<br>    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);<br>    <br>    event Transfer(address indexed from, address indexed to, uint256 value);<br>    event Approval(address indexed owner, address indexed spender, uint256 value);<br>}<br><br>// Step 2: Abstract contract with basic implementation<br>abstract contract ERC20 is IERC20 {<br>    mapping(address =&gt; uint256) internal _balances;<br>    mapping(address =&gt; mapping(address =&gt; uint256)) internal _allowances;<br>    uint256 internal _totalSupply;<br>    string internal _name;<br>    string internal _symbol;<br>    uint8 internal _decimals;<br>    <br>    constructor(string memory name_, string memory symbol_) {<br>        _name = name_;<br>        _symbol = symbol_;<br>        _decimals = 18;<br>    }<br>    <br>    function name() public view virtual returns (string memory) {<br>        return _name;<br>    }<br>    <br>    function symbol() public view virtual returns (string memory) {<br>        return _symbol;<br>    }<br>    <br>    function decimals() public view virtual returns (uint8) {<br>        return _decimals;<br>    }<br>    <br>    function totalSupply() public view virtual override returns (uint256) {<br>        return _totalSupply;<br>    }<br>    <br>    function balanceOf(address account) public view virtual override returns (uint256) {<br>        return _balances[account];<br>    }<br>    <br>    function allowance(address owner, address spender) public view virtual override returns (uint256) {<br>        return _allowances[owner][spender];<br>    }<br>    <br>    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {<br>        _transfer(msg.sender, recipient, amount);<br>        return true;<br>    }<br>    <br>    function approve(address spender, uint256 amount) public virtual override returns (bool) {<br>        _approve(msg.sender, spender, amount);<br>        return true;<br>    }<br>    <br>    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {<br>        _transfer(sender, recipient, amount);<br>        <br>        uint256 currentAllowance = _allowances[sender][msg.sender];<br>        require(currentAllowance &gt;= amount, &quot;ERC20: transfer amount exceeds allowance&quot;);<br>        unchecked {<br>            _approve(sender, msg.sender, currentAllowance - amount);<br>        }<br>        <br>        return true;<br>    }<br>    <br>    // Internal functions for derived contracts<br>    function _transfer(address sender, address recipient, uint256 amount) internal virtual {<br>        require(sender != address(0), &quot;ERC20: transfer from zero address&quot;);<br>        require(recipient != address(0), &quot;ERC20: transfer to zero address&quot;);<br>        <br>        uint256 senderBalance = _balances[sender];<br>        require(senderBalance &gt;= amount, &quot;ERC20: transfer amount exceeds balance&quot;);<br>        <br>        unchecked {<br>            _balances[sender] = senderBalance - amount;<br>            _balances[recipient] += amount;<br>        }<br>        <br>        emit Transfer(sender, recipient, amount);<br>    }<br>    <br>    function _mint(address account, uint256 amount) internal virtual {<br>        require(account != address(0), &quot;ERC20: mint to zero address&quot;);<br>        <br>        _totalSupply += amount;<br>        _balances[account] += amount;<br>        emit Transfer(address(0), account, amount);<br>    }<br>    <br>    function _burn(address account, uint256 amount) internal virtual {<br>        require(account != address(0), &quot;ERC20: burn from zero address&quot;);<br>        <br>        uint256 accountBalance = _balances[account];<br>        require(accountBalance &gt;= amount, &quot;ERC20: burn amount exceeds balance&quot;);<br>        <br>        unchecked {<br>            _balances[account] = accountBalance - amount;<br>            _totalSupply -= amount;<br>        }<br>        <br>        emit Transfer(account, address(0), amount);<br>    }<br>    <br>    function _approve(address owner, address spender, uint256 amount) internal virtual {<br>        require(owner != address(0), &quot;ERC20: approve from zero address&quot;);<br>        require(spender != address(0), &quot;ERC20: approve to zero address&quot;);<br>        <br>        _allowances[owner][spender] = amount;<br>        emit Approval(owner, spender, amount);<br>    }<br>}</pre><h4>Extending with Mintable Feature</h4><pre>// Access control base<br>contract Ownable {<br>    address public owner;<br>    <br>    constructor() {<br>        owner = msg.sender;<br>    }<br>    <br>    modifier onlyOwner() {<br>        require(msg.sender == owner, &quot;Ownable: caller is not owner&quot;);<br>        _;<br>    }<br>    <br>    function transferOwnership(address newOwner) public virtual onlyOwner {<br>        require(newOwner != address(0), &quot;Ownable: new owner is zero address&quot;);<br>        owner = newOwner;<br>    }<br>}<br><br>// Mintable token combining ERC20 and Ownable<br>contract ERC20Mintable is ERC20, Ownable {<br>    constructor(string memory name, string memory symbol) ERC20(name, symbol) {}<br>    <br>    function mint(address to, uint256 amount) public onlyOwner {<br>        _mint(to, amount);<br>    }<br>}</pre><h3>Best Practices</h3><ol><li><strong>Keep inheritance shallow</strong>: Deep hierarchies become hard to understand and audit. Prefer composition over inheritance when possible.</li><li><strong>Mark functions appropriately</strong>: Use virtual for functions meant to be overridden and override explicitly when overriding.</li><li><strong>Document inheritance intentions</strong>: Use NatSpec comments to explain why inheritance is used and how functions should be overridden.</li><li><strong>Test inherited functionality</strong>: Verify that base contract behavior integrates correctly with child contracts.</li><li><strong>Consider storage layout</strong>: Inherited contracts append their state variables in order. Be careful with upgrades.</li></ol><h3>Common Pitfalls</h3><ol><li><strong>Storage Collisions</strong></li></ol><pre>contract A {<br>    uint256 public x;<br>}<br><br>contract B {<br>    uint256 public x; // Collision! Both try to use slot 0<br>}<br><br>contract C is A, B { // Danger: storage collision<br>    // Both A.x and B.x would share slot 0<br>}</pre><p>2. <strong>Constructor Order Issues</strong></p><pre>contract Parent {<br>    uint256 public value;<br>    <br>    constructor(uint256 _value) {<br>        value = _value;<br>    }<br>}<br><br>contract Child is Parent {<br>    constructor(uint256 _value) <br>        Parent(_value * 2) // Parent constructor runs first<br>    {<br>        // value is already set to _value * 2<br>    }<br>}</pre><p>3. <strong>Overlooking Function Shadowing</strong></p><pre>contract Parent {<br>    function getData() public pure returns (uint256) {<br>        return 42;<br>    }<br>}<br><br>contract Child is Parent {<br>    uint256 public data; // No relation to getData()<br>    <br>    function getData() public pure override returns (uint256) {<br>        return 100; // Overrides parent function<br>    }<br>}</pre><h3>Conclusion</h3><p>Inheritance in Solidity isn’t just a technical feature, it’s one of the main ways developers keep smart contracts organized, reusable, and easier to manage. Instead of rewriting the same logic over and over, contracts can build on shared functionality, customize behavior when needed, and grow into well-structured systems that are easier to understand and maintain.</p><p>That said, it has to be used carefully. Things like storage layout, constructor setup, and function overrides can introduce subtle issues if they’re not handled properly. When developers apply inheritance thoughtfully and follow solid design practices, it becomes a powerful tool that improves both the reliability and scalability of smart contract architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b06b70916a61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ERC-5564: Stealth Addresses]]></title>
            <link>https://medium.com/@shuaibganiyat20/erc-5564-stealth-addresses-628d42da98aa?source=rss-2ce36021829a------2</link>
            <guid isPermaLink="false">https://medium.com/p/628d42da98aa</guid>
            <dc:creator><![CDATA[SHUAIB GANIYAT]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 11:48:03 GMT</pubDate>
            <atom:updated>2026-02-06T17:06:26.615Z</atom:updated>
            <content:encoded><![CDATA[<p>Ethereum is a public blockchain, meaning that every transaction, token holding, and interaction with a smart contract leaves a public, traceable record linked directly to a user’s main wallet address. This transparency sacrifices user privacy. The problem is: how can I make a transaction without it being linked to me?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBW6PM1pdt20o2Ic2SOyRw.png" /></figure><h3>The Privacy Problem</h3><p>Alice wants to transfer funds to Bob, but since they are using a public ledger, every transaction between them is visible to anyone monitoring the network. Alice values her privacy and wants to avoid creating a permanent, public link between her wallet and Bob’s.</p><p>To solve this manually, Alice could ask Bob to generate a fresh, one-time address for their specific interaction. Bob would create a new wallet, Alice would send the funds there, and Bob would then receive the money without exposing his primary personal address. This works, but it is tedious and requires “out-of-band” private communication (like a phone call or encrypted chat) every time they want to transact.</p><p>The real question is: <strong>How can this privacy be achieved automatically, without any direct private interaction between them?</strong> This is where <strong>Stealth Addresses (ERC-5564)</strong> come in.</p><h3>What are Stealth Addresses?</h3><p><strong>Stealth Address</strong> is a one-time destination address generated non-interactively by a sender that only the intended recipient can control, providing <strong>unlinkability</strong> between transactions.</p><p>It is important to note that stealth addresses do not “erase” the blockchain’s inherent <strong>traceability</strong>; rather, they prevent the public linking of a transaction to a user’s main identity. However, linking can still occur if the recipient later “sweeps” funds from multiple stealth addresses into a single, known public address.</p><p>When Alice sends funds to Bob using a stealth address, she does not send them directly to his public address. Instead, she derives a brand-new, unique address that only Bob can access. This process is standardized by <strong>ERC-5564</strong> (for announcement and discovery) and <strong>ERC-6538</strong> (the Stealth Meta-Address Registry). These standards typically use <strong>secp256k1 ECDH</strong> (Elliptic Curve Diffie-Hellman) to establish the shared secret required to derive these private, one-time addresses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ua06aQRBGSky3nYKg9xiAA.png" /></figure><h3>The Implementation of ERC-5564</h3><ul><li>A “stealth meta-address” is a set of one or two public keys that can be used to compute a stealth address for a given recipient.</li><li>A “spending key” is a private key that can be used to spend funds sent to a stealth address. A “spending public key” is the corresponding public key.</li><li>A “viewing key” is a private key that can be used to determine if funds sent to a stealth address belong to the recipient who controls the corresponding spending key. A “viewing public key” is the corresponding public key.</li></ul><p>ERC-5564 defines three essential functions that must be implemented (either in Solidity or via SDKs) for any stealth scheme:</p><ul><li><strong>generateStealthAddress</strong>: Called by the <strong>sender</strong>. It takes the recipient&#39;s meta-address and returns a unique stealth address, an ephemeral public key, and a <strong>view tag</strong>.</li></ul><pre>/// @notice Generates a stealth address from a stealth meta address.<br>/// @param stealthMetaAddress The recipient&#39;s stealth meta-address.<br>/// @return stealthAddress The recipient&#39;s stealth address.<br>/// @return ephemeralPubKey The ephemeral public key used to generate the stealth address.<br>/// @return viewTag The view tag derived from the shared secret.<br>function generateStealthAddress(bytes memory stealthMetaAddress)<br>  external<br>  view<br>  returns (address stealthAddress, bytes memory ephemeralPubKey, bytes1 viewTag);</pre><ul><li><strong>checkStealthAddress</strong>: Called by the <strong>recipient</strong> during the scanning process. It uses the viewing key to determine if a specific stealth address belongs to them.</li></ul><pre>/// @notice Returns true if funds sent to a stealth address belong to the recipient who controls<br>/// the corresponding spending key.<br>/// @param stealthAddress The recipient&#39;s stealth address.<br>/// @param ephemeralPubKey The ephemeral public key used to generate the stealth address.<br>/// @param viewingKey The recipient&#39;s viewing private key.<br>/// @param spendingPubKey The recipient&#39;s spending public key.<br>/// @return True if funds sent to the stealth address belong to the recipient.<br>function checkStealthAddress(<br>  address stealthAddress,<br>  bytes memory ephemeralPubKey,<br>  bytes memory viewingKey,<br>  bytes memory spendingPubKey<br>) external view returns (bool);</pre><ul><li><strong>computeStealthKey</strong>: Called by the <strong>recipient</strong> to derive the actual private key needed to spend the funds.</li></ul><pre>/// @notice Computes the stealth private key for a stealth address.<br>/// @param stealthAddress The expected stealth address.<br>/// @param ephemeralPubKey The ephemeral public key used to generate the stealth address.<br>/// @param viewingKey The recipient&#39;s viewing private key.<br>/// @param spendingKey The recipient&#39;s spending private key.<br>/// @return stealthKey The stealth private key corresponding to the stealth address.<br>/// @dev The stealth address input is not strictly necessary, but it is included so the method<br>/// can validate that the stealth private key was generated correctly.<br>function computeStealthKey(<br>  address stealthAddress,<br>  bytes memory ephemeralPubKey,<br>  bytes memory viewingKey,<br>  bytes memory spendingKey<br>) external view returns (bytes memory);</pre><h4>Announcement Mechanism</h4><p>ERC-5564 defines a singleton <strong>ERC5564Announcer</strong> contract (one per chain) that emits an Announcement event whenever funds are sent to a stealth address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4FePCM2GfkvZSk-_xaoBA.png" /></figure><h3>Challenges with ERC-5564</h3><p><strong>1. Scanning Overhead<br></strong>Wallets must scan many on-chain events to detect payments.<br> This increases: Computation cost, sync time, battery and bandwidth usage</p><p><strong>2. Wallet Adoption<br></strong>ERC-5564 requires wallet support, UX improvements, Developer tooling. Without adoption, privacy remains theoretical.</p><p><strong>3. Gas Costs<br></strong>Extra events and cryptographic operations increase gas usage, especially for senders.</p><p><strong>4. UX Complexity<br></strong>Users must understand Meta-addresses, Viewing vs spending keys, Wallet scanning behavior. Poor UX can discourage use.</p><h4>Solutions to These Challenges</h4><ol><li><strong>Efficient Indexing<br></strong>Use off-chain indexers, batch event scanning, and light-client friendly designs to reduce overhead.</li></ol><p><strong>2. Wallet-Level Abstraction<br></strong>Hide cryptographic complexity, auto-detect stealth payments, and present them like normal transfers.</p><p><strong>3. Optional Privacy<br></strong>ERC-5564 is opt-in, users choose when privacy matters, reducing unnecessary overhead.</p><p><strong>4. Ecosystem Standards<br></strong>Standardization enables wallet interoperability and composable privacy solutions.</p><h3>Conclusion: The Long Term</h3><p>ERC-5564 shows that privacy <em>can</em> exist on Ethereum without sacrificing transparency or requiring disruptive protocol forks. It proves that privacy can be <strong>composable, auditable, and optional</strong>, rather than hidden or forced. This standard is a meaningful step toward a future where payments don’t automatically expose identities, where on-chain activity doesn’t feel like constant surveillance, and where Ethereum is practical not just for developers, but for everyday users, businesses, and institutions alike. In the long run, ERC-5564 moves Ethereum closer to being a truly open financial system, one that respects both transparency and personal privacy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=628d42da98aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum:The World Computer]]></title>
            <link>https://medium.com/@shuaibganiyat20/ethereum-the-world-computer-a892983ea814?source=rss-2ce36021829a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a892983ea814</guid>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[SHUAIB GANIYAT]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 11:48:17 GMT</pubDate>
            <atom:updated>2026-02-05T11:48:17.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nnPfjg_hjTrx4itSjnIsDw.png" /></figure><p>Imagine transacting in a world where no one has control over your money except you because of it’s decentralized network, that world is Ethereum. Ethereum is more than just a cryptocurrency; it is a ‘world computer,’ meaning it executes both transactions and complex smart contract logic. To truly understand how Ethereum operates, there are a few core concepts you should know: the <strong>EVM</strong>, <strong>blocks</strong>, <strong>gas</strong>, <strong>accounts</strong>, and <strong>transactions</strong>.</p><h3>Ethereum Virtual Machine (EVM)</h3><figure><img alt="Ethereum Virtual Machine" src="https://cdn-images-1.medium.com/max/1024/1*BTZEUcoZnCiK0E68okBRdg.jpeg" /></figure><p>The EVM is the part of Ethereum that handles smart contract deployment and execution. Think of it as a single, global computer whose state is maintained by thousands of connected nodes (computers) around the world. Every node runs the EVM to execute the same instructions, ensuring consensus.</p><p>The EVM is “quasi-Turing-complete,” meaning it can solve any computational problem given enough resources. This is what allows for the immense flexibility of Ethereum smart contracts, which can automate complex agreements and power decentralized applications (dApps) from finance to gaming. The EVM’s state is updated with every new block, providing a constantly evolving, globally agreed upon digital ledger.</p><h3>Blocks</h3><p>Data on Ethereum is batched into blocks. A new block is created roughly every 12 seconds and contains a collection of transactions, along with important metadata such as the block number, timestamp, and the hash of the previous block.</p><figure><img alt="Block" src="https://cdn-images-1.medium.com/max/833/1*sn1Y40Hi9WMbEgjYHMOh6A.jpeg" /></figure><h4>How blocks work</h4><p>To preserve the transaction history, blocks are strictly ordered (every new block created contains a reference to its parent block), and transactions within blocks are strictly ordered as well. Except in rare cases, at any given time, all participants on the network are in agreement on the exact number and history of blocks, and are working to batch the current live transaction requests into the next block.<br>Once a block is put together by a randomly selected validator on the network, it is propagated to the rest of the network; all nodes add this block to the end of their blockchain, and a new validator is selected to create the next block. The exact block-assembly process and commitment/consensus process is currently specified by Ethereum’s “proof-of-stake” protocol.</p><h3>Gas</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-v0UeNH7pvqlHs9Kau33Q.jpeg" /></figure><p>Gas refers to the unit that measures the amount of computational effort required to execute specific operations on the Ethereum network. Every transaction or smart contract interaction consumes gasto execute. Those gas have to be paid for to ensure Ethereum is not vulnerable to spam and cannot get stuck in infinite computational loops. Payment for computation is made in the form of a gas fee.<br><strong>Gas Fee</strong> is the amount of gas used to do some operation, multiplied by the cost per unit gas.</p><h4>How are gas fees calculated?</h4><p><strong>Gas fees on Ethereum</strong> are calculated based on how much computation a transaction uses and how much you’re willing to pay per unit of gas. When you submit a transaction, you choose how much gas you’re willing to offer, effectively bidding for inclusion in the next block — too low and validators may ignore it, too high and you risk overpaying.</p><blockquote>An ETH transfer requires 21,000 units of gas</blockquote><blockquote>Total fee = units of gas used * (base fee + priority fee)</blockquote><p>The total gas fee has two parts: the <strong>base fee</strong> and the <strong>priority fee (tip)</strong>. The base fee is set by the protocol and must be paid for a transaction to be valid, while the priority fee is an optional tip added by the user to incentivize validators to include the transaction faster. A transaction that only pays the base fee is technically valid but unlikely to be included because it offers no incentive to the validators to choose it over any other transaction.</p><h3>Accounts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TpAT_LevJ-TtUR_pjake_Q.png" /></figure><p>Ethereum has two account types:</p><ul><li><strong>Externally owned accounts (EOAs)</strong> are accounts that are controlled by users with the private key. EOAs can receive, hold and send ETH and tokens.</li><li><strong>Contract accounts </strong>are owned by smart contracts and can be used to interact with the Ethereum blockchain. Contract addresses are unique addresses that are associated with smart contracts deployed on the Ethereum blockchain.</li></ul><h4>Difference Between EOAs and Contract Accounts</h4><h4>Externally Owned Accounts (EOAs)</h4><ul><li>Creating an accout costs nothing</li><li>Can initiate transactions on the network</li><li>Transactions between EOAs can only be ETH and token transfers</li><li>Made up of a cryptographic pair of keys (Private and Public keys) that control account activities.</li></ul><h4>Contract Accounts(CAs)</h4><ul><li>They don’t have private keys, Instead they are controlled by the logic of the smart contract code.</li><li>Creating a CA has a cost because they use on-chain storage</li><li>Cannot initiate transactions on their own</li><li>Can only respond to transactions or messages sent to them</li><li>Can execute complex logic such as, Transferring tokens, Interacting with other contracts, Creating new contracts</li></ul><h3>Transaction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txdUdBDBg4_GXljKswDjwQ.jpeg" /></figure><p>A transaction is a cryptographically signed instruction from an EOA that initiates a state change on the Ethereum network. The main types are:</p><ul><li>Regular transactions: a transaction from one account to another.</li><li>Contract Deployment: Publishing a new smart contract to the blockchain.</li><li>Contract Interaction: Calling a function in a deployed contract (e.g., swapping tokens on Uniswap, minting an NFT).</li></ul><p>A transaction specifies the recipient, the amount of ETH to transfer, the gas parameters, the nonce, and is secured by the sender’s digital signature. Once broadcast to the network, it is picked up by validators, executed inside the EVM within a block, and irrevocably alters the global state.</p><h4>The Anatomy of a Transaction</h4><ul><li>from – the address of the sender, that will be signing the transaction. This will be an externally-owned account as contract accounts cannot send transactions</li><li>to – the receiving address (if an externally-owned account, the transaction will transfer value. If a contract account, the transaction will execute the contract code)</li><li>signature – the identifier of the sender. This is generated when the sender&#39;s private key signs the transaction and confirms the sender has authorized this transaction</li><li>nonce - a sequentially incrementing counter which indicates the transaction number from the account</li><li>value – amount of ETH to transfer from sender to recipient (denominated in WEI, where 1ETH equals 1e+18wei)</li><li>input data – optional field to include arbitrary data</li><li>gasLimit – the maximum amount of gas units that can be consumed by the transaction. The <a href="https://ethereum.org/developers/docs/evm/opcodes/">EVM</a> specifies the units of gas required by each computational step</li><li>maxPriorityFeePerGas - the maximum price of the consumed gas to be included as a tip to the validator</li><li>maxFeePerGas - the maximum fee per unit of gas willing to be paid for the transaction (inclusive of baseFeePerGas and maxPriorityFeePerGas)</li></ul><h3>Conclusion</h3><p>Ethereum can be challenging at first, just like it was for me before, but now i’m able to put out what i know and understand, it takes time but you will get it. Now we’ve explored how <strong>accounts</strong> act as the starting point for activity, how <strong>transactions</strong> move value and instructions across the network, and how <strong>gas</strong> ensures that every operation has a cost, keeping the system efficient and secure. Behind the scenes, the <strong>EVM</strong> does the heavy lifting, executing code and enforcing rules, before everything is finally recorded inside a <strong>block</strong> on the blockchain. Whether your goal is to create, invest, or simply understand what’s happening under the hood, grasping these fundamentals puts you on the right path forward.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a892983ea814" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum’s Evolution: Through The Impact Of Its Upgrades And How They Positioned Ethereum As A…]]></title>
            <link>https://medium.com/@shuaibganiyat20/ethereums-evolution-through-the-impact-of-its-upgrades-and-how-they-positioned-ethereum-as-a-c703b8766660?source=rss-2ce36021829a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c703b8766660</guid>
            <category><![CDATA[ethereum-upgrade]]></category>
            <dc:creator><![CDATA[SHUAIB GANIYAT]]></dc:creator>
            <pubDate>Wed, 04 Feb 2026 11:46:11 GMT</pubDate>
            <atom:updated>2026-02-11T11:46:57.372Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ethereum’s Evolution: Through The Impact Of Its Upgrades And How They Positioned Ethereum As A Leading Blockchain</h3><figure><img alt="Ethereum Upgrades" src="https://cdn-images-1.medium.com/max/1024/1*EmZrgQ13Ew1sfkWiCqW9OA.png" /></figure><h3>Introduction</h3><p>Ethereum is a blockchain with a computer embedded in it. It is the foundation for building apps and organizations in a decentralized, permissionless, censorship-resistant way. As its usage grew, Ethereum faced several challenges such as high transaction fees, scalability issues, and energy consumption concerns. To address these problems, the network introduced a series of upgrades.<br>These upgrades have played a crucial role in strengthening Ethereum’s performance, security, and usability. Through continuous improvement, Ethereum has positioned itself as one of the most reliable and widely used blockchain platforms, supporting decentralized finance (DeFi), NFTs, DAOs, and countless Web3 applications.</p><h3>The Upgrades and The Impact</h3><h4>Frontier(July 30, 2015)</h4><p>Ethereum started with <strong>Frontier</strong>, the network’s very first release. The goal was simple: provide a live blockchain for developers to experiment with smart contracts and mining.</p><p><strong>Implementation:</strong> A minimal network with basic transaction capabilities, a 5,000 gas limit per block, and no advanced safety features.<br><strong>Impact:</strong> Allowed developers to start building decentralized applications (dApps) and miners to join the network, essentially “kickstarting” Ethereum.<br><strong>Challenges:</strong> Frontier was highly experimental and risky for general users, with limited security and reliability.</p><h4>Homestead(March 14, 2016)</h4><p>The goal of Homestead was to transition Ethereum from an experimental network into a stable, usable blockchain.</p><p><strong>Implementation:</strong> It included several protocol changes and a networking change that gave Ethereum the ability to do further network upgrades.<br><strong>Impact:</strong> Gave developers confidence to build more complex applications and increased network stability.<br><strong>Challenges:</strong> Security vulnerabilities and performance issues still needed careful monitoring as adoption increased.</p><h4>The DAO Fork (July 20, 2016)</h4><p>The DAO fork was in response to the <a href="https://www.coindesk.com/learn/understanding-the-dao-attack/">2016 DAO attack</a> where an insecure DAO contract was drained of over 3.6 million ETH in a hack.</p><p><strong>Implementation:</strong> The network underwent a hard fork, The fork moved the funds from the faulty contract to a new contract with a single function: withdraw. Anyone who lost funds could withdraw 1 ETH for every 100 DAO tokens in their wallets. Those opposing the fork continued on Ethereum Classic.<br><strong>Impact:</strong> Restored trust in the network and demonstrated Ethereum’s ability to govern itself in emergencies.<br><strong>Challenges:</strong> Raised debates about blockchain immutability versus community intervention.</p><h4>Byzantium (October 16, 2017)</h4><p>With increasing usage, Ethereum needed better efficiency, security, and support for Layer 2 solutions.</p><p><strong>Implementation:</strong> Reduced block mining rewards from 5 to 3 ETH, delayed the difficulty bomb by a year, Added ability to make non-state-changing calls to other contracts, and added cryptographic features like zk-SNARKs to allow for layer 2 scaling.<br><strong>Impact:</strong> Improved transaction efficiency, lowered inflation, and prepared Ethereum for more complex applications.<br><strong>Challenges:</strong> Balancing decentralization, security, and efficiency while reducing miner rewards.</p><h4>Constantinople (February 28, 2019)</h4><p>Ethereum continued to optimize gas costs and prepare for Proof of Stake.</p><p><strong>Implementation:</strong> Reduced block miningrewards from 3 to 2 ETH, ensured the blockchain didn’t freeze before proof-of-stake was implemented, optimised the gas cost of certain actions in the EVM and added the ability to interact with addresses that haven’t been created yet.<br><strong>Impact:</strong> Lowered transaction costs, improved efficiency, and ensured the network would remain functional during the transition to Proof of Stake.<br><strong>Challenges:</strong> Any change to gas costs and block rewards required careful testing to prevent disruptions.</p><h4>Istanbul (December 8, 2019)</h4><p>Scalability and Layer 2 compatibility became crucial as Ethereum’s ecosystem expanded.</p><p><strong>Implementation:</strong> Optimized gas costs, strengthened the network against denial-of-service attacks, and improved support for SNARKs/STARKs and other Layer 2 solutions.<br><strong>Impact:</strong> Faster, cheaper transactions and better security for decentralized applications.<br><strong>Challenges:</strong> Integrating Layer 2 improvements without compromising mainnet stability.</p><h4>Beacon Chain (December 1, 2020)</h4><p>Ethereum introduced <strong>Proof of Stake</strong> while the main network still ran Proof of Work.</p><p><strong>Implementation:</strong> Launched a parallel chain where validators could stake ETH and participate in network consensus.<br><strong>Impact:</strong> Allowed Ethereum to test PoS securely, reduce energy use, and prepare for the Merge.<br><strong>Challenges:</strong> Running two consensus systems in parallel required careful coordination.</p><h4>London (August 5, 2021)</h4><p>High gas fees and unpredictable transaction costs were frustrating users.<br><strong>Implementation:</strong> Introduced <strong>EIP-1559</strong>, creating a base fee that is burned and optional tips for validators, and adjusted gas refund rules.<br><strong>Impact:</strong> More predictable fees, improved user experience, and a deflationary effect on ETH supply.<br><strong>Challenges:</strong> Developers had to update wallets and tooling to handle the new fee system.</p><h4>Altair (October 27, 2021)</h4><p>The first upgrade to the Beacon Chain, aimed at preparing for The Merge.<br><strong>Implementation:</strong> Added support for sync committees for light clients, increased validator penalties for inactivity and slashing, and improved network efficiency.<br><strong>Impact:</strong> Strengthened PoS security and prepared validators for The Merge.<br><strong>Challenges:</strong> Validators had to adjust to stricter protocol rules.</p><h4>The Merge (Paris + Bellatrix, 2022)</h4><p>Ethereum’s biggest upgrade transitioned the network fully to Proof of Stake.<br><strong>Implementation:</strong> Replaced miners with validators, coordinated execution and consensus layers via the Engine API, and switched off Proof of Work.<br><strong>Impact:</strong> Energy consumption dropped by over 99%, network security improved, and Ethereum became environmentally sustainable.<br><strong>Challenges:</strong> Coordinating such a large-scale change without breaking the network was extremely complex.</p><h4>Shanghai–Capella (Shapella, 2023)</h4><p>Staking withdrawals became possible for the first time.</p><p><strong>Implementation:</strong> Enabled stakers to withdraw rewards or exit fully, automated validator reward processing, and improved account management.<br><strong>Impact:</strong> Increased trust, flexibility, and usability for staking participants.<br><strong>Challenges:</strong> Ensuring smooth withdrawals without introducing bugs or risks.</p><h4>Cancun–Deneb (Dencun, March 13, 2024)</h4><p>Ethereum needed better scaling and lower transaction fees.</p><p><strong>Implementation:</strong> Introduced <strong>Proto-Danksharding (EIP-4844)</strong> for cheaper Layer 2 rollup transactions, capped validator churn, and improved staking exit safety.<br><strong>Impact:</strong> Lower fees, faster Layer 2 operations, and improved decentralization.<br><strong>Challenges:</strong> Safely implementing sharding without compromising security.</p><h4>Prague–Electra (Pectra, May 7, 2025)</h4><p>Ethereum improved both staking efficiency and user functionality.</p><p><strong>Implementation:</strong> Added compounding validator balances, more control over staked funds, and enabled smart-account features for regular wallets, like transaction batching, programmable spending, and gas sponsorship<br><strong>Impact:</strong> Increased staking efficiency and unlocked more advanced features for ordinary users.<br><strong>Challenges:</strong> Securing new functionalities for non-smart-contract accounts without opening vulnerabilities.</p><h4>Fulu–Osaka (Fusaka, 2025)</h4><p>The latest upgrade continues Ethereum’s evolution.</p><p><strong>Implementation:</strong> Refined consensus operations, validator efficiency, and protocol performance, while strengthening Layer 2 compatibility.<br><strong>Impact:</strong> Makes Ethereum more scalable, efficient, and reliable as the base layer for Web3 applications.<br><strong>Challenges:</strong> Balancing new improvements with ecosystem stability and backward compatibility.</p><h3><strong>How Upgrades Position Ethereum as a Leading Blockchain</strong></h3><p>Ethereum’s ability to upgrade continuously without sacrificing security, decentralization, or developer trust has positioned it as a leading blockchain. Through carefully planned improvements, such as the shift from Proof of Work to Proof of Stake in The Merge, the introduction of EIP-1559 for predictable fees, and scalability-focused upgrades like proto-danksharding, Ethereum has addressed its biggest limitations while preparing for future growth. These upgrades have reduced energy consumption, improved network efficiency, enhanced user experience, and strengthened economic sustainability, all while maintaining backward compatibility for existing applications. By constantly adapting to real-world demands and prioritizing long-term scalability, Ethereum has remained the most robust and widely adopted smart contract platform in the blockchain ecosystem.</p><h3>Conclusion</h3><p>Ethereum’s journey shows that evolution is essential for long-term success in blockchain technology. Each upgrade has addressed real-world challenges while preparing the network for future growth. As Ethereum continues to improve scalability, efficiency, and usability, it remains well-positioned to power the next generation of decentralized applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c703b8766660" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparing Frontend Technologies: React vs. Next.js]]></title>
            <link>https://medium.com/@shuaibganiyat20/comparing-frontend-technologies-react-vs-next-js-f92186989ee1?source=rss-2ce36021829a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f92186989ee1</guid>
            <dc:creator><![CDATA[SHUAIB GANIYAT]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 13:22:56 GMT</pubDate>
            <atom:updated>2024-06-28T13:22:56.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aESIRFAYek8y8JmicX5Crw.png" /></figure><p>Frontend development is an exciting and ever-evolving field, with numerous technologies vying for our attention. Among them, React and Next.js are particularly notable for building dynamic, modern web applications. In this article, I’ll share my personal insights into React and Next.js, what makes each unique, and why you might choose one over the other.</p><h3>ReactJS</h3><p>ReactJS is a declarative, efficient, and flexible JavaScript library for building user interfaces. It is an open-source, component-based front-end library responsible for the view layer of applications. Developed by Facebook, ReactJS addresses common challenges in building complex user interfaces by introducing several key concepts:</p><p>1. <strong>Single-Page Applications (SPAs):</strong> ReactJS excels in creating SPAs where the entire application loads once, and subsequent interactions update the view dynamically without a full page reload. This results in a smoother, more responsive user experience.</p><p>2. <strong>Component-Based Development:</strong> React promotes the development of reusable UI components. Each component encapsulates its own structure, style, and behavior, making the code more modular, maintainable, and easier to test.</p><p>3. <strong>Virtual DOM for Efficient Updates:</strong> React employs a Virtual DOM to optimize rendering performance. It updates only the parts of the DOM that have changed, minimizing expensive DOM manipulations and improving application performance.</p><p>4. <strong>Declarative Syntax:</strong> React’s declarative syntax makes it straightforward to describe how the UI should look at any given time. This approach simplifies the process of designing and debugging user interfaces.</p><p>5. <strong>React Native for Mobile App Development: </strong>Leveraging React’s component-based architecture, React Native extends the capability to build mobile applications for iOS and Android using JavaScript and React.</p><p>6. <strong>State Management:</strong> React manages the state of components efficiently, allowing for dynamic and interactive UIs. The introduction of hooks in React 16.8 has further simplified state management within functional components.</p><p>7. <strong>Reusable UI Components:</strong> React’s emphasis on reusability promotes the development of a consistent look and feel across the application. Components can be easily shared and reused across different parts of the application.</p><h3><strong>Next.js</strong></h3><p>Next.js, created by Vercel, is an open-source React-based framework known for its powerful features that extend the capabilities of React applications:</p><p>1. <strong>Server-Side Rendering (SSR): </strong>Next.js supports server-side rendering, which improves initial load times and enhances SEO by rendering pages on the server before sending them to the client.</p><p>2. <strong>Static Site Generation (SSG): </strong>Next.js allows for static site generation, where pages are pre-rendered at build time. This approach combines the performance benefits of static sites with the dynamic capabilities of React.</p><p>3. <strong>Automatic Code Splitting: </strong>Next.js automatically splits the code into smaller chunks, loading only the necessary code for the current page. This results in faster load times and better performance.</p><p>4. <strong>Next.js Pages and Routing: </strong>Next.js simplifies routing with a file-based routing system. Each file in the pages directory automatically becomes a route, making it easier to manage and scale application routes.</p><p>5. <strong>Data Fetching Methods: </strong>Next.js provides built-in methods like getStaticProps and getServerSideProps for fetching data during build time and request time, respectively. These methods streamline the data-fetching process and improve performance.</p><p>6. <strong>API Routes: </strong>Next.js includes support for API routes, allowing developers to create API endpoints within the same project. This simplifies the development process by keeping the frontend and backend logic together.</p><p>7. <strong>Next.js Image Optimization: </strong>Next.js includes an image optimization feature that automatically optimizes images for faster load times and better performance. This feature supports resizing, lazy loading, and more.</p><p>8. <strong>Custom Document and Head Components: </strong>Next.js provides customization options for the HTML document and head tags, allowing for advanced configurations and better control over the document structure.</p><h3>Comparing React and Next.js</h3><p>While React and Next.js share the same foundational library, they cater to different aspects of frontend development:</p><ul><li><strong>Use Case</strong>: React is ideal for building dynamic user interfaces where client-side rendering suffices. It excels in applications requiring frequent updates and interactive components.</li><li><strong>Performance Optimization</strong>: Next.js extends React’s capabilities by offering SSR and SSG, optimizing performance through faster initial loads and improved SEO. This makes it suitable for content-heavy sites or applications prioritizing SEO.</li><li><strong>Development Workflow</strong>: React provides a flexible framework for frontend development, while Next.js enhances it with additional features like automatic code splitting and integrated backend API support, streamlining development and deployment.</li></ul><h3>My Expectations with HNG and React</h3><p>As an aspiring frontend developer, I am thrilled to participate in the HNG Internship. This program provides an incredible opportunity to deepen my understanding of React while working on real-world projects. Through collaboration with experienced mentors and fellow interns, I aim to enhance my skills and build dynamic, user-friendly applications.</p><p>Moreover, being part of the HNG community means access to a wealth of resources and support, which will be invaluable as I navigate the challenges of frontend development. I’m particularly eager to apply my knowledge in practical scenarios, gain hands-on experience, and contribute to meaningful projects.</p><p>For anyone interested in the <a href="https://hng.tech/internship">HNG Internship</a>, whether to hire talented developers or participate in the program, I highly recommend checking out the <a href="https://hng.tech/hire">HNG Hire</a> and <a href="https://hng.tech/premium">HNG Premium</a> pages for more information.</p><p><strong>Conclusion</strong></p><p>Both ReactJS and Next.js offer unique strengths that cater to different aspects of frontend development. ReactJS provides a solid foundation for building dynamic and reusable UI components, while Next.js enhances React applications with powerful features like server-side rendering, static site generation, and optimized performance.</p><p>For organizations already using ReactJS, incorporating Next.js can bring additional benefits, such as improved SEO, faster initial load times, and streamlined data fetching. Together, these technologies enable developers to create highly efficient, scalable, and maintainable web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f92186989ee1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>