<?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>Forem: Venkatesh R</title>
    <description>The latest articles on Forem by Venkatesh R (@venkatesh_rajendran).</description>
    <link>https://forem.com/venkatesh_rajendran</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%2F944755%2F4d774245-2ff7-456f-9fd9-7d134d444f48.jpeg</url>
      <title>Forem: Venkatesh R</title>
      <link>https://forem.com/venkatesh_rajendran</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/venkatesh_rajendran"/>
    <language>en</language>
    <item>
      <title>All About EVM Instructions And Opcodes:</title>
      <dc:creator>Venkatesh R</dc:creator>
      <pubDate>Sun, 06 Nov 2022 10:29:55 +0000</pubDate>
      <link>https://forem.com/venkatesh_rajendran/all-about-evm-instructions-and-opcodes-1hon</link>
      <guid>https://forem.com/venkatesh_rajendran/all-about-evm-instructions-and-opcodes-1hon</guid>
      <description>&lt;h2&gt;
  
  
  EVM Instructions and Opcodes:
&lt;/h2&gt;

&lt;p&gt;Do you want to gain a deep understanding about EVM Instructions and Opcodes? Or Do you want to become Senior Smart Contract developer?&lt;/p&gt;

&lt;p&gt;Well, good news! you're in the right place.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is EVM ?
&lt;/h2&gt;

&lt;p&gt;The Ethereum Virtual Machine or EVM is a piece of software that executes smart contracts and computes the state of the Ethereum network after each new block is added to the chain&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Assembly ?
&lt;/h2&gt;

&lt;p&gt;Assembly refers to any low-level programming language that is converted to machine code using an assembler. Assembler languages are tied to either a physical or a virtual machine, because they implement its instruction set. An instruction tells simply the CPU to do some fundamental task, such as adding two numbers, etc. &lt;/p&gt;

&lt;p&gt;Yul language is being used as low level Assembly Language for the Ethereum. &lt;/p&gt;

&lt;h2&gt;
  
  
  Getting Started:
&lt;/h2&gt;

&lt;p&gt;EVM is a &lt;strong&gt;stack&lt;/strong&gt; based virtual machine which uses few instruction set to perform its fundamental tasks.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--9LYV0Q3Q--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dj854y97mpk5efokqadi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--9LYV0Q3Q--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dj854y97mpk5efokqadi.png" alt="Image description" width="553" height="288"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;EVM instruction sets:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Stack Instruction Set&lt;/li&gt;
&lt;li&gt;Arthmetic Instruction Set&lt;/li&gt;
&lt;li&gt;Comparision Instruction Set&lt;/li&gt;
&lt;li&gt;Memory Instruction Set&lt;/li&gt;
&lt;li&gt;Storage / Context Instruction Set&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Stack Instruction Set:
&lt;/h3&gt;

&lt;p&gt;Stack Instruction is being used to push / pop the one or more values into the stack to perform its fundamental tasks.&lt;/p&gt;

&lt;p&gt;Stack Instructions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;PUSHN&lt;/strong&gt; - pushes a value into the top of the stack where N is the byte size of value Example: PUSH1, PUSH2, PUSH3, etc.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;POP&lt;/strong&gt; - pops out a value from the top of the stack&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;SWAPN&lt;/strong&gt; - swaps a value from the top of the stack at the index N&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;DUPN&lt;/strong&gt; - duplicate the value from the stack at the position N and push the duplicated value to the top of the stack.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;There are many instructions available on the Stack Instruction Set.&lt;/p&gt;

&lt;p&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;PUSH1 0x01 // pushes 1 [1]
PUSH1 0x02 // pushes 2 [2, 1]
PUSH1 0x02 // pushes 2 [2, 2, 1]

POP // pops out the value 2 [2, 1]

DUP1 // duplicates the value 2 and push the value [2, 2, 1]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Arthmetic Instruction Set:
&lt;/h3&gt;

&lt;p&gt;Arthmetic Instruction takes two / more values from the top of the stack and performs arthmetic operation and push the resultant value into the top of the stack&lt;/p&gt;

&lt;p&gt;Arthmetic Instructions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;ADD&lt;/strong&gt; - Add two values from the top of the stack and pushes to the stack.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;SUB&lt;/strong&gt; - Subtract two values from the top of the stack and pushes to the stack.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;DIV&lt;/strong&gt; - Divide two values from the top of the stack and pushes to the stack.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;MUL&lt;/strong&gt; - Multiplies two values from the top of the stack and pushes to the stack.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;There are many instructions available on the Arthmetic Instruction Set.&lt;/p&gt;

&lt;p&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;PUSH1 0x01 // pushes 1 [1]
PUSH1 0x02 // pushes 2 [2, 1]

ADD // Adds two values from top of the stack [3]

PUSH1 0x01 // pushes 1 [1, 3]

SUB // Subtract the two value [2]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Comparision Instruction Set:
&lt;/h3&gt;

&lt;p&gt;Comparision Instruction takes two / more values from the top of the stack and performs comparision operation and push the resultant value into the top of the stack&lt;/p&gt;

&lt;p&gt;Comparision Instructions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;LT&lt;/strong&gt; - Compares the top value from stack with second top value and pushes the result into the top of the stack.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;GT&lt;/strong&gt; - Compares the top value from stack with second top value and pushes the result into the top of the stack.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;EQ&lt;/strong&gt; - Pushes true if the top two values are equal&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;ISZERO&lt;/strong&gt; - Pushes true if the top value of the stack is 0&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;There are many instructions available on the Comparision Instruction Set.&lt;/p&gt;

&lt;p&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;// false = 0 and true = 1

PUSH1 0x01 // pushes 1 [1]
PUSH1 0x01 // pushes 2 [1, 1]

EQ // stores the result [1] / [true]

ISZERO // stores the result [0] / [false]

POP // pops out the values []
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Memory Instruction Set:
&lt;/h3&gt;

&lt;p&gt;Memory Instruction are used to read and write the chunks of values into the memory.&lt;/p&gt;

&lt;p&gt;Memory Instructions&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;MSTORE&lt;/strong&gt; -  writes a value into the memory &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;MLOAD&lt;/strong&gt; - reads a value from the memory&lt;/li&gt;
&lt;/ol&gt;

&lt;p&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;PUSH1 0x01 // pushes 1 [1]
PUSH1 0x00 // pushes 0 [0, 1]

// Stores the value 1 into the memory slot zero

MSTORE 

PUSH1 0x00 // pushes 0 [0]

// Loads the value from the memory at slot zero

MLOAD // [O]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Context Instruction Set:
&lt;/h3&gt;

&lt;p&gt;Context Instruction are used to read and write the data from the global state / execution context.&lt;/p&gt;

&lt;p&gt;Context Instructions (READ):&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;SLOAD&lt;/strong&gt; - Loads the values from the storage with respect to the pointer value&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;CALLER&lt;/strong&gt; - Loads the caller of the contract context&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;TIMESTAMP&lt;/strong&gt; - Loads the current block's timestamp&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;There are many instructions available on the Context Instruction Set (READ).&lt;/p&gt;

&lt;p&gt;Context Instructions (WRITE):&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;SSTORE&lt;/strong&gt; - Stores the values into the storage with respect to the pointer&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;CALL&lt;/strong&gt; - Used to make a call to external contract and update the global state&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;CREATE&lt;/strong&gt; - Used to deploy the contract in the blockchain state&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;LOGN&lt;/strong&gt; - Used to log the contract's execution data, where N is the number of indexed Topics.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;There are many instructions available on the Context Instruction Set (WRITE).&lt;/p&gt;

&lt;p&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;CALLER // pushes contract caller [caller_address]
PUSH1 0x00 // pushes 0 [0, caller_address]

// Loads the caller_address into the first storage slot

SSTORE // []

PUSH1 0x00 // pushes 0 [0]

// Loads the caller_address from the first storage slot

SLOAD // [caller_address]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Conslusion:
&lt;/h3&gt;

&lt;p&gt;It is very important for the smart contract developers and auditors to undertand that how solidity based smart contracts/EVM executes its fundamental tasks behind the scenes to get deep foundation of EVM. To know more about the other EVM opcodes, please visit &lt;a href="https://github.com/crytic/evm-opcodes"&gt;Here&lt;/a&gt; and if you want to play with these opcodes in the real time playground, please visit &lt;a href="https://www.evm.codes/playground"&gt;EVM codes playground website &lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Hope you guys have learnt something new today, do follow me to get more exiting contents on #blockchain #Web3 #SmartContracts #Solidity #Rust #Solana &lt;/p&gt;

&lt;p&gt;You can reach out to me via &lt;a href="https://www.linkedin.com/in/venkatesh16031999/"&gt;LinkedIn&lt;/a&gt;, &lt;a href="https://github.com/venkatesh16031999"&gt;Github&lt;/a&gt;&lt;/p&gt;

</description>
      <category>blockchain</category>
      <category>web3</category>
      <category>solidity</category>
      <category>smartcontract</category>
    </item>
    <item>
      <title>Mainnet Forking and Crypto Wallet Impersonation:</title>
      <dc:creator>Venkatesh R</dc:creator>
      <pubDate>Sat, 22 Oct 2022 11:05:20 +0000</pubDate>
      <link>https://forem.com/venkatesh_rajendran/mainnet-forking-and-wallet-impersonation-5bj9</link>
      <guid>https://forem.com/venkatesh_rajendran/mainnet-forking-and-wallet-impersonation-5bj9</guid>
      <description>&lt;h1&gt;
  
  
  Mainnet Forking and Wallet Impersonation:
&lt;/h1&gt;

&lt;p&gt;Do you want to fork the Mainnet Blockchain into your local development network? Or Do you want to simulate mainnet blockchain and build your own Defi projects? Or Do you want to become a Senior Web3 Developer by learning complex blockchain concepts?&lt;/p&gt;

&lt;p&gt;Well, good news! you're in the right place.&lt;/p&gt;

&lt;h3&gt;
  
  
  Mainnet Forking:
&lt;/h3&gt;

&lt;p&gt;Mainnet Forking means we simulate mainnet blockchain to have the same state as mainnet, but it will work as a local development network. You can simulate the Ethereum blockchain into your local network and build your next Defi project.&lt;/p&gt;

&lt;h3&gt;
  
  
  Wallet Impersonation:
&lt;/h3&gt;

&lt;p&gt;Wallet Impersonation is a process of unlocking an access to any wallet which exists in the blockchain network by wallet address. This lets you send transactions from that account even if you don't have access to its private key.&lt;/p&gt;

&lt;h3&gt;
  
  
  Benefits:
&lt;/h3&gt;

&lt;p&gt;Benefits of forking the mainnet and wallet impersonation are&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Write real-time unit tests for your smart contracts&lt;/li&gt;
&lt;li&gt;Build your own Defi smart contracts based on other complex protocols such as Uniswap, Compound, Curve, etc.&lt;/li&gt;
&lt;li&gt;Learn and get comfortable with your own cryptocurrency arbitrage strategies by mocking the Mainnet protocols&lt;/li&gt;
&lt;li&gt;Test your new protocols against your previously deployed smart contracts.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Getting Started:
&lt;/h3&gt;

&lt;p&gt;Before starting you need to setup your Hardhat Smart contract development environment. Please refer to this &lt;a href="https://hardhat.org/hardhat-runner/docs/getting-started#quick-start"&gt;hardhat docs&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  How to fork the blockchain network:
&lt;/h3&gt;

&lt;p&gt;To fork the mainnet blockchain you need a RPC node provider.&lt;/p&gt;

&lt;p&gt;You can use these RPC providers such as&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Infura - Follow &lt;a href="https://docs.infura.io/infura/tutorials/ethereum/fork-ethereum-with-ganache"&gt;this docs&lt;/a&gt; to get a RPC endpoint forking the Mainnet&lt;/li&gt;
&lt;li&gt;Alchemy - Follow &lt;a href="https://docs.alchemy.com/docs/how-to-fork-ethereum-mainnet"&gt;this docs&lt;/a&gt; to get a RPC endpoint forking the Mainnet&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;After completing the RPC endpoint setup process, you need to goto your Hardhat development environment and check for the &lt;strong&gt;Hardhat config file&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Inside the &lt;code&gt;hardhat.config.js&lt;/code&gt; file, paste your RPC endpoint to setup the mainnet forking.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;require("@nomicfoundation/hardhat-toolbox");

/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  solidity: "0.7.6",
  networks: {
    hardhat: {
      forking: {
        url: "https://eth-mainnet.g.alchemy.com/v2/&amp;lt;API_KEY&amp;gt;"
      }
    }
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Tada! From now whenever you start your hardhat local network / run your unit tests, hardhat environement will automatically fork the mainnet into your local network.&lt;/p&gt;

&lt;h3&gt;
  
  
  Wallet Impersonation:
&lt;/h3&gt;

&lt;p&gt;We can use the hardhat built-in features to impersonate any wallet account in the mainnet blockchain using the address. &lt;/p&gt;

&lt;p&gt;Use this code snippet to impersonate any wallet&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;await network.provider.request({
   method: "hardhat_impersonateAccount",
   params: [WALLET_ADDRESS],
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Example:
&lt;/h4&gt;

&lt;p&gt;Do you want to impersonate and gain access to one of the top bitcoin holder's wallet and transfer all the bitcoin to your own wallet in your local network?&lt;/p&gt;

&lt;h4&gt;
  
  
  Steps:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Go to &lt;strong&gt;etherscan&lt;/strong&gt; and pick your favourite account which you want to impersonate. Let's say we impersonate the bitcoin holder's wallet, &lt;/li&gt;
&lt;li&gt;Goto WBTC contract in etherscan, navigate to holders tab and pick one of the account from there&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;WBTC Address: &lt;code&gt;0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599&lt;/code&gt;&lt;br&gt;
WBTC Whale Address: &lt;code&gt;0x28c6c06298d514db089934071355e5743bf21d60&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Since bitcoin is a cryptocurrency of different blockchain, so we use a &lt;strong&gt;Wrapped BTC (ERC20 token)&lt;/strong&gt; to represent the bitcoin in Ethereum blockchain&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Use the impersonate built in feature provided by hardhat to unlock the account.&lt;/li&gt;
&lt;li&gt;Get the access to the whale's wallet account in your local network by getting the signer.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;await network.provider.request({
   method: "hardhat_impersonateAccount",
   params: [WBTC_WHALE],
});

const whaleAccount = await ethers.getSigner(WBTC_WHALE);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;You can transfer the WBTC from whale's wallet account to your account with the help of ERC20 utility methods
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const whaleWalletBalance = await wbtc.balanceOf(whaleAccount.address);

await wbtc.connect(whaleAccount).transfer(yourWallet.address, whaleWalletBalance);

const yourWalletBalance = await wbtc.balanceOf(yourWallet.address);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Full Sample Code Snippet:
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { ethers, network } = require("hardhat");

const WBTC_WHALE = "0x28c6c06298d514db089934071355e5743bf21d60";
const WBTC_TOKEN = "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599";


describe("Wallet Impersonation code snippet", () =&amp;gt; {
   let wbtc;
   let accounts;

   before(async ()=&amp;gt; {
      accounts = await ethers.getSigners();
      wbtc = await ethers.getContractAt('IERC20', WBTC_TOKEN);
   })  

   it("Impersonate any wallet", async () =&amp;gt; {
      const userAccount = accounts[0];

      await network.provider.request({
         method: "hardhat_impersonateAccount",
         params: [WBTC_WHALE],
      });

      const whaleAccount = await ethers.getSigner(WBTC_WHALE);

      const whaleTokenBalance = await wbtc.balanceOf(whaleAccount.address);
      await wbtc.connect(whaleAccount).transfer(userAccount.address, whaleTokenBalance);

      const userTokenBalance = await wbtc.balanceOf(userAccount.address);
        console.log("User Token Balance", userTokenBalance);
   })
}) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hope you guys have learnt something new today, do follow me to get more exiting contents on #blockchain #Web3 #SmartContracts #Solidity #Rust #Solana &lt;/p&gt;

&lt;p&gt;You can reach out to me via &lt;a href="https://www.linkedin.com/in/venkatesh16031999/"&gt;LinkedIn&lt;/a&gt;, &lt;a href="https://github.com/venkatesh16031999"&gt;Github&lt;/a&gt;&lt;/p&gt;

</description>
      <category>web3</category>
      <category>blockchain</category>
      <category>smartcontract</category>
      <category>defi</category>
    </item>
    <item>
      <title>Upgradable Proxy Contracts 101 (Advanced)</title>
      <dc:creator>Venkatesh R</dc:creator>
      <pubDate>Sun, 16 Oct 2022 11:37:50 +0000</pubDate>
      <link>https://forem.com/venkatesh_rajendran/upgradable-proxy-contracts-101-3d0g</link>
      <guid>https://forem.com/venkatesh_rajendran/upgradable-proxy-contracts-101-3d0g</guid>
      <description>&lt;h1&gt;
  
  
  Upgradable Proxy Contract Advanced Concepts:
&lt;/h1&gt;

&lt;p&gt;Do you want to learn how proxy upgradable contracts work? Or Do you want to create your own proxy contract? Or Do you want to become a Senior Blockchain Developer by learning complex concepts?&lt;/p&gt;

&lt;p&gt;Well, good news! you're in the right place.&lt;/p&gt;

&lt;p&gt;If you are already familiar with proxy upgradable contracts and want to know more about its internal concepts ? Directly jump to the &lt;strong&gt;Getting Started&lt;/strong&gt; section. &lt;/p&gt;

&lt;h3&gt;
  
  
  What is Upgradable Proxy Contracts ?
&lt;/h3&gt;

&lt;p&gt;In the software development industry, software quality and stability heavily depend on software enhancements or bug fixes on the time to time basis. Since smart contracts are immutable in nature, we need advanced techniques to make our smart contracts upgradable while maintaining considerable immutability.&lt;/p&gt;

&lt;p&gt;Proxy Upgradable Contract is a advanced technique which is being used for updating the existing smart contract in the event of bug fixes, new features, update the existing business logic etc..&lt;/p&gt;

&lt;h3&gt;
  
  
  Getting Started:
&lt;/h3&gt;

&lt;p&gt;To upgrade the smart contract, we need to have a sample smart contract to get started with it. We got you covered, use the &lt;strong&gt;Counter&lt;/strong&gt; 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 CounterV1 {
    uint public count;

    function inc() external {
        count += 1;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Upgradable proxy contract technique/approach is achieved with the help of&lt;br&gt;
&lt;strong&gt;1. Proxy Contract&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;2. Storage Layout Library Contract&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;3. Proxy Admin Contract&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--DJA5087G--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qzosp9916m48sk6vnl0q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--DJA5087G--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qzosp9916m48sk6vnl0q.png" alt="Image description" width="880" height="219"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EaSawq0u--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1jaz9jskjnh2oluft7tq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EaSawq0u--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1jaz9jskjnh2oluft7tq.png" alt="Image description" width="880" height="605"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--DmAno-BO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ji9u4ngs91axpg383bg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--DmAno-BO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ji9u4ngs91axpg383bg.png" alt="Image description" width="880" height="577"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  1. Proxy Contract:
&lt;/h3&gt;

&lt;p&gt;Proxy contract is contract which is responsible for communicating with the implementation contract, maintaining storage layout and contract's state.&lt;/p&gt;

&lt;p&gt;Proxy contract will communicate with the implementation contract via &lt;strong&gt;Delegate Call&lt;/strong&gt; using the &lt;strong&gt;Yul Assembly Language&lt;/strong&gt; (a low level inline language which will directly interact with EVM) which will execute the contract logic and updates the storage layout of the calling contract.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Delegate Call:&lt;/strong&gt; delegatecall is a low level function call similar to call. When contract A executes delegatecall to contract B, B's code is executed with contract A's storage&lt;br&gt;
&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;contract Proxy {
    address public admin;
    address public implementation;

    constructor() {
        admin = msg.sender;
    }

    modifier ifAdmin() {
        if (msg.sender == admin) {
            _;
        } else {
            _fallback();
        }
    }

    function upgradeTo(address _implementation) external ifAdmin {
        implementation = _implementation;
    }

    function _delegate(address _implementation) internal virtual {
        assembly {
            // Copy msg.data. We take full control of memory in this inline assembly
            // block because it will not return to Solidity code. We overwrite the
            // Solidity scratch pad at memory position 0.

            // calldatacopy(t, f, s) - copy s bytes from calldata at position f to mem at position t
            // calldatasize() - size of call data in bytes
            calldatacopy(0, 0, calldatasize())

            // Call the implementation.
            // out and outsize are 0 because we don't know the size yet.

            // delegatecall(g, a, in, insize, out, outsize) -
            // - call contract at address a
            // - with input mem[in…(in+insize))
            // - providing g gas
            // - and output area mem[out…(out+outsize))
            // - returning 0 on error (eg. out of gas) and 1 on success
            let result := delegatecall(gas(), _implementation, 0, calldatasize(), 0, 0)

            // Copy the returned data.
            // returndatacopy(t, f, s) - copy s bytes from returndata at position f to mem at position t
            // returndatasize() - size of the last returndata
            returndatacopy(0, 0, returndatasize())

            switch result
            // delegatecall returns 0 on error.
            case 0 {
                // revert(p, s) - end execution, revert state changes, return data mem[p…(p+s))
                revert(0, returndatasize())
            }
            default {
                // return(p, s) - end execution, return data mem[p…(p+s))
                return(0, returndatasize())
            }
        }
    }

    function _fallback() private {
        _delegate(_getImplementation());
    }

    fallback() external payable {
        _fallback();
    }

    receive() external payable {
        _fallback();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will always start interacting with the proxy contracts which will perform a delegatecall to implementation contract to execute the contract's logic. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;function _delegate()&lt;/strong&gt; is resposible for performing a delegate call. We will be initiating the contract call with the help of the &lt;strong&gt;Function Signature&lt;/strong&gt; (eg. &lt;code&gt;function inc()&lt;/code&gt;) which will be sent as &lt;strong&gt;msg.data&lt;/strong&gt; to the contract via transaction. The &lt;strong&gt;receive()&lt;/strong&gt; / &lt;strong&gt;fallback()&lt;/strong&gt; function will be triggered when the transaction doesn't matches any other function signatures in the proxy contract, which will executes the &lt;code&gt;function _delegate()&lt;/code&gt; function.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;receive()&lt;/strong&gt; - The receive function is executed on a call to the contract with empty calldata. This is the function that is executed on plain Ether transfers (e.g. via .send() or .transfer()).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;fallback()&lt;/strong&gt; - If no receive function exists, the fallback function will be called on a plain Ether transfer. If neither a receive Ether nor a payable fallback function is present, the contract cannot receive Ether through regular transactions and throws an exception.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;calldatacopy()&lt;/strong&gt; - It will copy the calldata to the memory address 0 till the size of the calldata&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;calldatasize()&lt;/strong&gt; - It is used to determine the size of the calldata in the executing transaction&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;returndatacopy()&lt;/strong&gt; - It will copy the return data to the memory address 0 till the size of the result of the function call&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;returndatasize()&lt;/strong&gt; - It is used to determine the size of the return data in the executing transaction&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  2. Storage Layout Library Contract:
&lt;/h3&gt;

&lt;p&gt;Storage layout library contract is used to store and maintain the contract state variables without any collision/conflicts between each other. This is achieved by storing the contract's state variables in the different EVM sotrage slots with the help of Yul assembly language.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;library StorageSlot {
    struct AddressSlot {
        address value;
    }

    function getAddressSlot(bytes32 slot)
        internal
        pure
        returns (AddressSlot storage r)
    {
        assembly {
            r.slot := slot
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;EVM consist of a storage slots which can store upto &lt;strong&gt;256 bits&lt;/strong&gt; of data in it. We are generating a &lt;strong&gt;hash&lt;/strong&gt; based on the function signature which determines the location of the data to be stored in the storage slot.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;contract TestProxy {
    bytes32 public constant slot = keccak256("SAMPLE_SLOT");

    function getSlot() external view returns (address) {
        return StorageSlot.getAddressSlot(slot).value;
    }

    function writeSlot(address _addr) external {
        StorageSlot.getAddressSlot(slot).value = _addr;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;slot&lt;/strong&gt; - Smart contract values are stored in slots, starting from slot 0 and so on. Elementary fixed-size value types occupy one slot. Moreover, they sometimes can be packed into one slot and unpacked on the fly&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  3. Proxy Admin Contract:
&lt;/h3&gt;

&lt;p&gt;Proxy Admin Contract is used for managing the proxy contract. Using the Proxy Admin Contract we can look up, change, or upgrade the contract and its ownership such as&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Upgrade Implementation Contract&lt;/li&gt;
&lt;li&gt;Change Proxy Admin
&lt;/li&gt;
&lt;li&gt;Lookup proxy admin and implementation contract
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;contract ProxyAdmin {
    address public owner;

    constructor() {
        owner = msg.sender;
    }

    modifier onlyOwner() {
        require(msg.sender == owner, "not owner");
        _;
    }

    function getProxyAdmin(address proxy) external view returns (address) {
        (bool ok, bytes memory res) = proxy.staticcall(
            abi.encodeCall(Proxy.implementation, ())
        );
        require(ok, "call failed");
        return abi.decode(res, (address));
    }

    function getProxyImplementation(address proxy) external view returns (address) {
        (bool ok, bytes memory res) = proxy.staticcall(abi.encodeCall(Proxy.admin, ()));
        require(ok, "call failed");
        return abi.decode(res, (address));
    }

    function changeProxyAdmin(address payable proxy, address admin) external onlyOwner {
        Proxy(proxy).changeAdmin(admin);
    }

    function upgrade(address payable proxy, address implementation) external onlyOwner {
        Proxy(proxy).upgradeTo(implementation);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Upgrade The Contract:
&lt;/h3&gt;

&lt;p&gt;To upgrade a smart contract, we need a V2 implementation &lt;strong&gt;Counter&lt;/strong&gt; 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 CounterV2 {
    uint public count;

    function inc() external {
        count += 1;
    }

    function dec() external {
        count -= 1;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can use the above contract to upgrade the existing V1 Counter contract using proxy upgradable technique.&lt;/p&gt;

&lt;p&gt;Deploy the V2 contract in the blockchain and use the deployed V2 contract address to upgrade the old version.&lt;/p&gt;

&lt;p&gt;To upgrade the V1 Counter contract, we need to trigger the &lt;code&gt;function upgrade()&lt;/code&gt; in the &lt;strong&gt;Proxy Admin Contract&lt;/strong&gt; by pointing the &lt;strong&gt;proxy contract's&lt;/strong&gt; address. The Proxy Admin Contract will replace the V1 implementation contract address with the V2 contract address without affecting the contract's state. While upgrading the implementation contract, the address of the proxy contract will never change. Hence the proxy contract will now get a new implementation contract with new features/bug fixes.&lt;/p&gt;

&lt;p&gt;Hope you guys have learnt something new today, do follow me to get more exiting contents on #blockchain #Web3 #SmartContracts #Solidity #Rust #Solana &lt;/p&gt;

&lt;p&gt;You can reach out to me via &lt;a href="https://www.linkedin.com/in/venkatesh16031999/"&gt;LinkedIn&lt;/a&gt;, &lt;a href="https://github.com/venkatesh16031999"&gt;Github&lt;/a&gt;&lt;/p&gt;

</description>
      <category>blockchain</category>
      <category>web3</category>
      <category>smartcontracts</category>
      <category>contract</category>
    </item>
  </channel>
</rss>
