<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Joshua Omobola - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Joshua Omobola - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 22:24:11 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/koha/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Switch Blockchains on MetaMask with JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ With over 10,000 blockchains currently operating, there are endless possibilities for deploying your smart contracts. For anybody to be able to use your Decentralized Application (DApp), they need to be connected to the blockchain where you've deploy... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-switch-blockchains-on-metamask-with-javascript/</link>
                <guid isPermaLink="false">66d45f653a8352b6c5a2aa9a</guid>
                
                    <category>
                        <![CDATA[ Blockchain ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joshua Omobola ]]>
                </dc:creator>
                <pubDate>Thu, 26 Jan 2023 23:15:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/Custom-Network--1-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>With over 10,000 blockchains currently operating, there are endless possibilities for deploying your smart contracts.</p>
<p>For anybody to be able to use your Decentralized Application (DApp), they need to be connected to the blockchain where you've deployed your smart contract.</p>
<p>This article will show you how to prompt your users to switch to your preferred blockchain using JavaScript.</p>
<p>This guide requires that you have the MetaMask extension installed. Also, I assume you have a little bit of experience connecting with MetaMask—perhaps you've previously built a DApp. If you need a quick intro, <a target="_blank" href="https://docs.metamask.io/guide/create-dapp.html#basic-action-part-1">check out this brilliant piece by MetaMask to get started</a>.</p>
<p>Alright, Let’s dig in!</p>
<h2 id="heading-step-1-check-if-the-user-has-metamask-installed">Step 1 — Check if the User Has MetaMask Installed</h2>
<p>The first thing to do is to verify if the user has installed the MetaMask extension.</p>
<p>If they have another wallet installed besides MetaMask, switching networks using the method we are about to learn might not work. So it's a good idea to check first.</p>
<p>Let's check if the <code>ethereum</code> context has been injected into the browser. The code sample below shows how to do this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { ethereum } = <span class="hljs-built_in">window</span>;

<span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> ethereum !== <span class="hljs-string">'undefined'</span> &amp;&amp; ethereum.isMetaMask) {  
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"MetaMask is installed"</span>)
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"MetaMask is not installed"</span>)
}
</code></pre>
<p>Here's what we're doing:</p>
<p>At <code>const { ethereum } = window;</code> we destructure the <code>ethereum</code> property from the windows object and assign it to a variable of the same name.</p>
<p>If you are unfamiliar with this syntax, destructuring involves simply extracting the content of an object or array and assigning it to a variable. <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Read up on this piece to learn more about destructuring</a>.</p>
<p>Then we check if <code>ethereum</code> actually does exist using the if statement. Also, in the same condition we want to verify if the wallet installed is MetaMask.</p>
<p>Good! Let's see the next step.</p>
<h2 id="heading-step-2-how-to-switch-the-active-blockchain">Step 2 — How to Switch the Active Blockchain</h2>
<p>Once we have verified that the user has MetaMask installed, the next thing to do is trigger the RPC method for switching the MetaMask active blockchain. The code looks like this:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// MetaMask Docs</span>
<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">await</span> ethereum.request({
    <span class="hljs-attr">method</span>: <span class="hljs-string">'wallet_switchEthereumChain'</span>,
    <span class="hljs-attr">params</span>: [{ <span class="hljs-attr">chainId</span>: <span class="hljs-string">'0xf00'</span> }],
  });
} <span class="hljs-keyword">catch</span> (switchError) {
<span class="hljs-comment">// This error code indicates that the chain has not been added to MetaMask.</span>
  <span class="hljs-keyword">if</span> (switchError.code === <span class="hljs-number">4902</span>) {
      <span class="hljs-comment">// Do something</span>
  }
}
</code></pre>
<p>Here's what we are doing:</p>
<p>We invoke the <code>ethereum.request</code> method, passing it an object with two properties.</p>
<p>In the method property, we specify the <code>wallet_switchEthereumChain</code> RPC method, which allows Ethereum applications (DApps) to request that MetaMask switches its active Ethereum chain.</p>
<p>Then, the params property is an array that takes an object with the chain ID of the blockchain to switch to. <code>chainId</code> must be hexadecimal, hence the 0x in the sample code.</p>
<p>We wrap our request in a try/catch block to handle errors.</p>
<p><code>null</code> is returned if the active chain is switched.</p>
<p>If the requested chain does not exist in the user's wallet, the request throws an error code <code>error.code</code> of <code>4902</code>. If this happens, you can request to add the chain to the wallet.</p>
<p>You can follow this guide to see <a target="_blank" href="https://www.freecodecamp.org/news/how-to-add-custom-network-to-metamask/">how to add a new chain to MetaMask using JavaScript.</a></p>
<p>Great! That's all it takes to switch the active chain on MetaMask with Javascript.</p>
<p>Let's have a quick demo in the next section.</p>
<h2 id="heading-demo">Demo</h2>
<p>For this example, let's write a function that, when invoked, will prompt users to switch to the Polygon chain.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> SwitchChainToPolygon = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> { ethereum } = <span class="hljs-built_in">window</span>;
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> ethereum !== <span class="hljs-string">'undefined'</span> &amp;&amp; ethereum.isMetaMask) <span class="hljs-keyword">return</span>;

    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">await</span> ethereum.request({
        <span class="hljs-attr">method</span>: <span class="hljs-string">'wallet_switchEthereumChain'</span>,
        <span class="hljs-attr">params</span>: [{ <span class="hljs-attr">chainId</span>: <span class="hljs-string">'0x89'</span> }],
      });
    } <span class="hljs-keyword">catch</span> (switchError) {
      <span class="hljs-keyword">if</span> (switchError.code === <span class="hljs-number">4902</span>) {
        <span class="hljs-comment">// You can make a request to add the chain to wallet here</span>
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Polygon Chain hasn'</span>t been added to the wallet!<span class="hljs-string">')
      }
    }
}</span>
</code></pre>
<p>In the function <code>SwitchChainToPolygon</code> above, we destructured <code>ethereum</code> from the windows object, as we learned in Step 1.</p>
<p>Next, we verified whether <code>ethereum</code> does exist or not. If the <code>ethereum</code> is unavailable, that is if MetaMask is not installed, the function will exit/break.</p>
<p>If <code>ethereum</code> exists, we call the <code>ethereum.request</code> method to make an RPC call. For the <code>method</code> property, we give it a value of <code>wallet_switchEthereumChain</code>. For the <code>params</code>, <code>chainId</code> will have the value of <code>0x89</code> ( <code>167</code> in decimal) which is the chainId for the polygon blockchain.</p>
<p>That's all folks!</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you have learned how to switch blockchains on MetaMask with JavaScript. This will help you provide a frictionless user experience for your users.</p>
<p>Thank you for taking the time to read this. I hope you found it useful. Please feel free to connect and chat with me on <a target="_blank" href="https://twitter.com/kohawithstuff">Twitter</a> and <a target="_blank" href="https://youtube.com/@kohawithstuff">YouTube</a>. See you soon in my next article!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Add a Custom Network to Metamask with JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ As a developer, you can enhance the user experience of your decentralized applications (DApps) by allowing users to easily add your network to their Metamask wallet with just one click. This simplifies the process of onboarding users to your applicat... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-add-custom-network-to-metamask/</link>
                <guid isPermaLink="false">66d45f63868774922c884fe8</guid>
                
                    <category>
                        <![CDATA[ dapps ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joshua Omobola ]]>
                </dc:creator>
                <pubDate>Mon, 02 Jan 2023 22:17:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/12/Frame-1--3--1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>As a developer, you can enhance the user experience of your decentralized applications (DApps) by allowing users to easily add your network to their Metamask wallet with just one click.</p>
<p>This simplifies the process of onboarding users to your application, since they don't have to manually add the network themselves.</p>
<p>In this article, I'll show you how to use JavaScript to programmatically add custom networks to Metamask. Let's begin!</p>
<h2 id="heading-step-1-check-if-metamask-is-installed">Step 1: Check if Metamask is Installed</h2>
<p>The first thing you need to do is check if the Metamask plugin is installed in the user's browser. Fortunately, Metamask makes this easy by injecting an <code>ethereum</code> object into websites that have it installed.</p>
<p>To check for the presence of Metamask, you can simply try to access the <code>ethereum</code> object. You can do this using the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">window</span>.ethereum !== <span class="hljs-string">'undefined'</span>) {  
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Metamask is installed"</span>)
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Metamask is not installed"</span>)
}
</code></pre>
<h2 id="heading-step-2-add-a-custom-network-to-metamask">Step 2: Add a Custom Network to Metamask</h2>
<p>To programmatically add a custom network to Metamask, you can use the <code>request</code> method of the <code>ethereum</code> object, passing it the <code>wallet_addEthereumChain</code> property.</p>
<p>For example, the following code demonstrates how to add the Matic Network (Polygon) to Metamask:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.ethereum.request({
  <span class="hljs-attr">method</span>: <span class="hljs-string">"wallet_addEthereumChain"</span>,
  <span class="hljs-attr">params</span>: [{
    <span class="hljs-attr">chainId</span>: <span class="hljs-string">"0x89"</span>,
    <span class="hljs-attr">rpcUrls</span>: [<span class="hljs-string">"https://polygon-rpc.com/"</span>],
    <span class="hljs-attr">chainName</span>: <span class="hljs-string">"Matic Mainnet"</span>,
    <span class="hljs-attr">nativeCurrency</span>: {
      <span class="hljs-attr">name</span>: <span class="hljs-string">"MATIC"</span>,
      <span class="hljs-attr">symbol</span>: <span class="hljs-string">"MATIC"</span>,
      <span class="hljs-attr">decimals</span>: <span class="hljs-number">18</span>
    },
    <span class="hljs-attr">blockExplorerUrls</span>: [<span class="hljs-string">"https://polygonscan.com/"</span>]
  }]
});
</code></pre>
<p>The <code>window.ethereum.request()</code> method takes an object as an argument with the method and params properties. The method property should be set to <code>wallet_addEthereumChain</code>, and the params property should be an array containing an object with the following properties:</p>
<ul>
<li><p><code>chainId</code>: The chain ID of the custom network which is a 0x-prefixed hexadecimal string.</p>
</li>
<li><p><code>rpcUrls</code>: An array of RPC URLs for the custom network.</p>
</li>
<li><p><code>chainName</code>: The name of the custom network.</p>
</li>
<li><p><code>nativeCurrency</code>: An object with the properties name, symbol, and decimals, representing the name, symbol, and number of decimals of the native currency of the custom network.</p>
</li>
<li><p><code>blockExplorerUrls</code>: An array of block explorer URLs for the custom network.</p>
</li>
</ul>
<p>This code will send a request to Metamask to add the Polygon (Matic) Network to the user's wallet. If the request to add the network is successful, <code>window.ethereum.request()</code> will return <code>null</code>. If not successful, it will return an error.</p>
<h3 id="heading-demo">Demo</h3>
<p>To demonstrate how you can use this code, let's write a simple function that adds the Matic network when called.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addMaticNetwork</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> <span class="hljs-built_in">window</span>.ethereum.request({
      <span class="hljs-attr">method</span>: <span class="hljs-string">"wallet_addEthereumChain"</span>,
      <span class="hljs-attr">params</span>: [{
        <span class="hljs-attr">chainId</span>: <span class="hljs-string">"0x89"</span>,
        <span class="hljs-attr">rpcUrls</span>: [<span class="hljs-string">"https://polygon-rpc.com/"</span>],
        <span class="hljs-attr">chainName</span>: <span class="hljs-string">"Matic Mainnet"</span>,
        <span class="hljs-attr">nativeCurrency</span>: {
          <span class="hljs-attr">name</span>: <span class="hljs-string">"MATIC"</span>,
          <span class="hljs-attr">symbol</span>: <span class="hljs-string">"MATIC"</span>,
          <span class="hljs-attr">decimals</span>: <span class="hljs-number">18</span>
        },
        <span class="hljs-attr">blockExplorerUrls</span>: [<span class="hljs-string">"https://polygonscan.com/"</span>]
      }]
    });
  } <span class="hljs-keyword">catch</span> (error){
    <span class="hljs-built_in">console</span>.log(error)
  }
</code></pre>
<p>The <code>addMaticNetwork</code> function, when called, will invoke the request to add the matic network. This function uses the async/await syntax to handle the request asynchronously, and includes a try/catch block to handle any errors that may occur.</p>
<p><strong>Note:</strong> It's important to note that you should never automatically prompt the user to add a network without their explicit consent. Instead, this request should only be made in response to a direct user action, such as clicking a button.</p>
<p>This ensures that the user is fully aware of the change being made to their wallet and can choose to proceed or cancel the operation as they see fit..</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this article, you have learned how to programmatically add custom networks to MetaMask using JavaScript.</p>
<p>By implementing these steps in your own DApp, you can provide a seamless onboarding experience for your users and improve their overall experience with your application.</p>
<p>I hope this article was helpful. Remember, the world is your code oyster.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
