<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Deep Patel on Medium]]></title>
        <description><![CDATA[Stories by Deep Patel on Medium]]></description>
        <link>https://medium.com/@pateldeep-eth?source=rss-36b5aa8ffc91------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9IScjccOCiP_LVju45MHWQ.png</url>
            <title>Stories by Deep Patel on Medium</title>
            <link>https://medium.com/@pateldeep-eth?source=rss-36b5aa8ffc91------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 16:49:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pateldeep-eth/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Next.js v13 brings the most awaited feature]]></title>
            <link>https://pateldeep-eth.medium.com/next-js-v13-brings-the-most-awaited-feature-521196efb6e6?source=rss-36b5aa8ffc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/521196efb6e6</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[usability]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextjs-tutorial]]></category>
            <dc:creator><![CDATA[Deep Patel]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 14:27:00 GMT</pubDate>
            <atom:updated>2023-01-27T14:27:00.655Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Issue</h3><p>If you have ever used <strong>getServerSideProps </strong>in Next.js you must have faced the issue when the page takes almost a few seconds to load or to redirect, that too without any indication of loading on the screen.</p><p>While building <a href="https://realnifty.xyz/">RealNifty</a> we faced the same issue, <br>It almost takes 7–8 seconds to load the page after clicking on the element</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XzoZXQLiptSFDsxD0EF1A.gif" /></figure><h3>How does Next.js 13 solve it?</h3><blockquote><strong>Note:</strong> If you are using Next.js version ≤ 12, the solution for you is <a href="https://www.npmjs.com/package/nextjs-progressbar">https://www.npmjs.com/package/nextjs-progressbar</a></blockquote><p>Next.js 13 introduced a new file-system based router built on top of <a href="https://beta.nextjs.org/docs/rendering/server-and-client-components">React Server Components</a> with support for layouts, nested routing, loading states, error handling, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*9pIAQ7Kd0orpg-HvvUdKEQ.png" /></figure><p>In your app directory, you can add a loading.tsx file <br>where you can define the content you want to show while the page is being rendered.</p><p>For this particular example, we added this code in loading.tsx</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z7X7TZUv4a-FYbBQHeDp8g.png" /></figure><p>This is how it looks at run time,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gq1idu1FGgVlvHAjtxNDnQ.gif" /></figure><p>With this convention, you can show an <a href="https://beta.nextjs.org/docs/routing/loading-ui#instant-loading-states">instant loading state</a> from the server while the content of a route segment loads, the new content is automatically swapped in once rendering is complete.</p><p><strong>Resources:</strong><br><a href="https://beta.nextjs.org/docs/routing/loading-ui">https://beta.nextjs.org/docs/routing/loading-ui</a></p><p>Want to connect? DM me on twitter @<a href="https://twitter.com/pateldeep_eth">pateldeep_eth</a> or <a href="https://www.linkedin.com/in/patel-deep-dev/">Linkedin</a></p><h3>Also, Read</h3><ul><li><a href="https://medium.com/@pateldeep-eth/rescue-assets-from-a-compromised-wallet-f32ae3f25edd">Rescue Assets From a Compromised Wallet</a></li><li><a href="https://medium.com/better-programming/in-the-world-of-javascript-finding-the-length-of-string-is-such-an-easy-thing-just-do-str-length-4b4b33dbed09">How to Find Length of String in Solidity — From the Smart Contract of “ens”</a></li><li><a href="https://medium.com/better-programming/permanent-file-storage-for-web3-apps-with-arweave-bundlr-next-js-rainbowkit-and-wagmi-18aa1506fa6e">Permanent File Storage for Web3 Apps With Arweave, Bundlr, Next.js, RainbowKit, and Wagmi</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=521196efb6e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Users don’t give a fu*k if you use blockchain/ web3 in your app]]></title>
            <link>https://pateldeep-eth.medium.com/users-dont-give-a-fu-k-if-you-use-blockchain-web3-in-your-app-65d472c821b1?source=rss-36b5aa8ffc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/65d472c821b1</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[newbie]]></category>
            <dc:creator><![CDATA[Deep Patel]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 12:15:03 GMT</pubDate>
            <atom:updated>2023-01-26T12:15:03.005Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been developing in web3 for more than one year, during this time I’ve explored many products, gotten a chance to interact with many developers, founders, and explore crypto Twitter and communities.</p><p>The one common thing I’ve noticed in “Entry level” developers and a few experience devs as well is they want to build everything in a decentralized manner don’t get me wrong here all of them are amazing people &amp; great developers.</p><p>But one thing they tend to forget is,</p><p>Blockchain can also be used as a part of your application, you don’t need to build your whole application on top of Blockchain or use blockchain at all places.</p><p>Not all apps, especially basic apps need Blockchain or can benefit from it.</p><blockquote>Let’s be honest regular users (for example my parents) don’t give shit if your app is decentralized, or if it’s using blockchain and web3, for them all that matters is if it’s solving a problem for them.</blockquote><figure><img alt="problems with web3" src="https://cdn-images-1.medium.com/max/1024/1*3YFxmQWIeNExhAUHBANXCg.png" /><figcaption>problems with web3 — monkey og [web3isgoinggreat]</figcaption></figure><p>The underline here is</p><p>Don’t build to build on blockchain, build something which provides a solution to a problem blockchain might or might not be a part of your solution.</p><p>Use blockchain where it provides actual value, and not for just the sake of it or because it is fancy.</p><p>You might be thinking where can we use blockchain/ web3 in apps?</p><p>I’ve already written my thoughts on this in this thread here</p><h3>Tushar is hiring on Twitter: &quot;According to you, where is blockchain tech required in a basic app? I mean which aspect of app generally requires blockchain tech? And why? / Twitter&quot;</h3><p>According to you, where is blockchain tech required in a basic app? I mean which aspect of app generally requires blockchain tech? And why?</p><blockquote><em>Want to connect? DM me on twitter @</em><a href="https://twitter.com/pateldeep_eth"><em>pateldeep_eth</em></a><em> or </em><a href="https://www.linkedin.com/in/patel-deep-dev/"><em>Linkedin</em></a></blockquote><h3>Also, Read</h3><ul><li><a href="https://medium.com/@pateldeep-eth/rescue-assets-from-a-compromised-wallet-f32ae3f25edd">Rescue Assets From a Compromised Wallet</a></li><li><a href="https://medium.com/better-programming/in-the-world-of-javascript-finding-the-length-of-string-is-such-an-easy-thing-just-do-str-length-4b4b33dbed09">How to Find Length of String in Solidity — From the Smart Contract of “ens”</a></li><li><a href="https://medium.com/better-programming/permanent-file-storage-for-web3-apps-with-arweave-bundlr-next-js-rainbowkit-and-wagmi-18aa1506fa6e">Permanent File Storage for Web3 Apps With Arweave, Bundlr, Next.js, RainbowKit, and Wagmi</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65d472c821b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Must-Know Features in JavaScript ES2022: Enhance Your Code and Boost Your Productivity]]></title>
            <link>https://javascript.plainenglish.io/5-must-know-features-in-javascript-es2022-enhance-your-code-and-boost-your-productivity-8181eebdffbd?source=rss-36b5aa8ffc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/8181eebdffbd</guid>
            <category><![CDATA[es2022]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Deep Patel]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 18:14:12 GMT</pubDate>
            <atom:updated>2023-01-16T18:14:12.354Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript is constantly evolving, and the latest version, ES2022, introduces some exciting new features that can make your coding life easier and more efficient. In this post, we’ll take a look at five must-know features in JavaScript ES2022 that you can start using today to enhance your code and boost your productivity.</p><h4><strong>List of features we are going to discuss:</strong></h4><p>1. Optional chaining<br>2. Nullish coalescing<br>3. Dynamic imports<br>4. Promise.allSettled<br>5. String.prototype.matchAll</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ScnqUg9KbpJ4ewAO" /><figcaption>Photo by <a href="https://unsplash.com/@blakeconnally?utm_source=medium&amp;utm_medium=referral">Blake Connally</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Feature 1: Optional chaining</h4><p>Optional chaining is a new operator that allows you to access an object’s properties without having to check for null or undefined first. This can be especially useful when working with complex data structures, as it allows you to access deeply nested properties without having to worry about intermediate values being null or undefined.</p><p>Here’s an example of how optional chaining works:</p><pre>Copy code<br>const data = {<br>  user: {<br>    name: &#39;John&#39;,<br>    age: 30,<br>    address: {<br>      street: &#39;123 Main St&#39;,<br>      city: &#39;New York&#39;,<br>      state: &#39;NY&#39;,<br>      zip: 10001<br>    }<br>  }<br>};<br>// Without optional chaining<br>let zip;<br>if (data &amp;&amp; data.user &amp;&amp; data.user.address &amp;&amp; data.user.address.zip) {<br>  zip = data.user.address.zip;<br>}<br>// With optional chaining<br>const zip = data?.user?.address?.zip;</pre><p>As you can see, optional chaining allows you to access nested properties without having to write long, nested if statements. This can make your code cleaner and easier to read.</p><h4>Feature 2: Nullish coalescing</h4><p>Nullish coalescing is another new operator that allows you to specify a default value for a variable if it’s null or undefined. This can be useful when working with variables that might be falsy (e.g., 0, “”, false), as the nullish coalescing operator only returns the default value if the variable is strictly null or undefined.</p><p>Here’s an example of how nullish coalescing works:</p><pre>const data = {<br>  user: {<br>    name: &#39;John&#39;,<br>    age: 30,<br>    address: {<br>      street: &#39;123 Main St&#39;,<br>      city: &#39;New York&#39;,<br>      state: &#39;NY&#39;,<br>      zip: 10001<br>    }<br>  }<br>};<br><br>// Without nullish coalescing<br>let zip;<br>if (data &amp;&amp; data.user &amp;&amp; data.user.address &amp;&amp; data.user.address.zip) {<br>  zip = data.user.address.zip;<br>} else {<br>  zip = 0;<br>}<br><br>// With nullish coalescing<br>const zip = data?.user?.address?.zip ?? 0;</pre><p>As you can see, nullish coalescing allows you to specify a default value in a concise and easy-to-read way.</p><h4>Feature 3: Dynamic imports</h4><p>Dynamic imports allow you to load JavaScript modules asynchronously, which can be useful when you only need to load certain modules on demand. This can improve the performance of your application by reducing the amount of code that needs to be downloaded and parsed by the browser.</p><p>Here’s an example of how dynamic imports work:</p><pre>// Without dynamic imports<br>import MyModule from &#39;./my-module&#39;;<br><br>// With dynamic imports<br>const MyModule = await import(&#39;./my-module&#39;);</pre><h4>Feature 4: Promise.allSettled</h4><p>Promise.allSettled is a new method that allows you to wait for a group of Promises to either resolve or reject. This can be useful when you want to handle the results of multiple Promises at the same time, regardless of whether they resolve or reject.</p><p>Here’s an example of how Promise.allSettled works:</p><pre>const promise1 = Promise.resolve(1);<br>const promise2 = Promise.reject(new Error(&#39;Error&#39;));<br>const promise3 = Promise.resolve(3);<br>Promise.allSettled([promise1, promise2, promise3]).then(results =&gt; {<br>  results.forEach(result =&gt; {<br>    if (result.status === &#39;fulfilled&#39;) {<br>      console.log(result.value);<br>    } else {<br>      console.error(result.reason);<br>    }<br>  });<br>});<br>// Output: 1, Error: Error, 3</pre><p>As you can see, Promise.allSettled allows you to handle the results of multiple Promises in a single callback, making it easier to manage asynchronous code. Instead of waiting for all Promises to resolve or rejecting as soon as any of the Promises reject, Promise.allSettled waits for all Promises to settle (i.e., either resolve or reject) before running the callback. This can be useful if you want to handle the results of all Promises, regardless of whether they resolve or reject.</p><h4>Feature 5: String.prototype.matchAll</h4><p>String.prototype.matchAll is a new method that allows you to find all matches of a regular expression in a string, rather than just the first match. This can be useful when you need to extract multiple pieces of data from a string, or when you want to perform more advanced string manipulation.</p><p>Here’s an example of how String.prototype.matchAll works:</p><pre>const str = &#39;Hello World&#39;;<br>const regex = /l/g;<br><br>// Without String.prototype.matchAll<br>const matches = str.match(regex);<br><br>// With String.prototype.matchAll<br>const matches = [...str.matchAll(regex)];<br>console.log(matches); // [&#39;l&#39;, &#39;l&#39;]</pre><p>As you can see, String.prototype.matchAll allows you to find all matches of a regular expression in a string, making it easier to extract multiple pieces of data from a string.</p><h3>Best practices for using these new features</h3><p>Now that we’ve covered the new features in JavaScript ES2022, let’s talk about some best practices for using them.</p><p>First and foremost, it’s important to keep in mind that not all of these features are fully supported in all browsers. Therefore, you should check the browser compatibility of each feature before using it in your projects.</p><p>Additionally, it’s a good idea to use these features sparingly and only when they provide a clear benefit. While they can be useful in certain situations, they can also make your code more complex and harder to understand if used excessively.</p><p>Finally, be sure to test your code thoroughly after using these new features to ensure that everything is working as expected.</p><p>By following these best practices, you can take full advantage of the new features in JavaScript ES2022 while avoiding any potential pitfalls.</p><blockquote><strong><em>Want to connect? DM me on twitter @</em></strong><a href="https://twitter.com/pateldeep_eth"><strong><em>pateldeep_eth</em></strong></a><strong><em> or </em></strong><a href="https://www.linkedin.com/in/patel-deep-dev/"><strong><em>Linkedin</em></strong></a></blockquote><h4>Also, Read</h4><ul><li><a href="https://medium.com/better-programming/in-the-world-of-javascript-finding-the-length-of-string-is-such-an-easy-thing-just-do-str-length-4b4b33dbed09">How to Find Length of String in Solidity — From the Smart Contract of “ens”</a></li><li><a href="https://medium.com/better-programming/permanent-file-storage-for-web3-apps-with-arweave-bundlr-next-js-rainbowkit-and-wagmi-18aa1506fa6e">Permanent File Storage for Web3 Apps With Arweave, Bundlr, Next.js, RainbowKit, and Wagmi</a></li></ul><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em>, and</em></strong><em> </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Build awareness and adoption for your tech startup with </em></strong><a href="https://circuit.ooo/?utm=publication-post-cta"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8181eebdffbd" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/5-must-know-features-in-javascript-es2022-enhance-your-code-and-boost-your-productivity-8181eebdffbd">5 Must-Know Features in JavaScript ES2022: Enhance Your Code and Boost Your Productivity</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rescue Assets From a Compromised Wallet]]></title>
            <link>https://pateldeep-eth.medium.com/rescue-assets-from-a-compromised-wallet-f32ae3f25edd?source=rss-36b5aa8ffc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/f32ae3f25edd</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[flashbots]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[wallet]]></category>
            <dc:creator><![CDATA[Deep Patel]]></dc:creator>
            <pubDate>Sat, 31 Dec 2022 12:26:11 GMT</pubDate>
            <atom:updated>2023-01-01T03:43:12.779Z</atom:updated>
            <content:encoded><![CDATA[<p>Flashbots can actually be a lifesaver sometimes.</p><p>One of our wallets had been hacked some time back, and all the Ether in that wallet was taken out, it was an issue but the bigger issue was this wallet was the owner of a contract we deployed. it still had the ownership, but it didn’t have any Ether left, so we can’t transfer the Ownership to another wallet as we don’t have any Ether left to pay the gas fees.</p><p>Well, just load the wallet with some Ether and transfer the tokens it’s so easy, well not really!</p><blockquote>There was a high probability that the person who hacked the wallet had set up a bot that will immediately take out all the assets transferred to the wallet, so if we transfer any Ether to the wallet high probability is that it would be taken out immediately.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1N0eyC0ltdgor2WXFU42tw.jpeg" /></figure><h3>What’s the solution then?</h3><p>It’s simple we need to transfer some Ether to the wallet and transfer the ownership of the contract before the bot set up by the hacker can perform any action, it has to be fast. means it has to be done in a single block</p><p>Can we do it manually? <strong>Noooo</strong>, that’s when the Flashbots come to rescue</p><h3>Let’s understand some terms first</h3><h4>Maximal Extractable Value (MEV)</h4><p>Maximal Extractable Value (MEV) represents excess value captured by miners (or validators) from users in a cryptocurrency network. This excess value often comes from reordering user&#39;s transactions to maximize fees or inserting new transactions that allow a miner to front-run users’ transactions.</p><p>More: <a href="https://ethereum.org/en/developers/docs/mev/">Maximal extractable value (MEV) | ethereum.org</a></p><h4>Flashbots</h4><p>Flash boats refer to automated programs that use high-speed communication and data processing technologies to execute trades on decentralized exchanges (DEXs) or other types of blockchain-based trading platforms.</p><p>Like traditional flash boats, these programs use algorithms to analyze market data and identify trading opportunities in real time. They can make trades based on a wide range of factors, such as changes in the prices of various cryptocurrencies or tokens, news events, and changes in market liquidity.</p><h3>Scenario</h3><p>For this article, I’ve tried to replicate a similar scenario</p><p>We have a wallet that has been hacked, the hacker has taken out all the Eth from that wallet, but that wallet still has some ERC20 tokens left inside it, we want to take these tokens out and transfer them to another wallet.</p><h3>Let’s see the code</h3><p>You can clone the starter code from this <a href="https://github.com/Deep1144/flashbot-rescue-assets">Repo</a>.<br>First of all, set the environment variables</p><pre>TOKENS=Address of ERC20 token which we need to takeout of that wallet  <br>RESCUER=Private key of wallet in which we want to transfer those tokens<br>HACKED_WALLET=Private key of wallet that has been hacked</pre><p>Let’s define some constants first</p><pre>const provider = new providers.JsonRpcProvider(&#39;&lt;https://rpc.ankr.com/eth_goerli&gt;&#39;)<br>const authSigner = Wallet.createRandom()<br>const flashbotProvider = await FlashbotsBundleProvider.create(<br>        provider,<br>        authSigner,<br>        FLASHBOTS_URL<br>    )<br>const rescuer = new Wallet(RESCUER).connect(provider)<br>const hackedWallet = new Wallet(HACKED_WALLET).connect(provider)</pre><p>We have created all the signers we need, and we are using Ankr as the RPC provider.</p><p>We will be using a method from flashbotProvider called sendBundle .</p><p>This method takes an array of Transactions that we want to perform in a single block, and as a second argument, it takes the number of blocks in which we want to include the transactions.</p><p>cool, so let’s get the current block number first</p><pre>provider.on(&#39;block&#39;, async (blockNo) =&gt; {<br>	const targetBlock = blockNo + 1;<br>})</pre><p>Out target block is the next block that is to be produced.</p><p>And now let’s use the sendBundle method</p><pre>const resp = await flashbotProvider.sendBundle([<br>            {<br>                signer: rescuer,<br>                transaction: {<br>                    chainId: 5,<br>                    type: 2,<br>                    to: hackedWallet.address,<br>                    value: utils.parseEther(&#39;0.01&#39;),<br>                    maxFeePerGas: utils.parseUnits(&#39;20&#39;, &#39;gwei&#39;),<br>                    maxPriorityFeePerGas: utils.parseUnits(&#39;13&#39;, &#39;gwei&#39;)<br>                }<br>            },<br>            {<br>                signer: hackedWallet,<br>                transaction: {<br>                    chainId: 5,<br>                    type: 2,<br>                    to: TOKENS,<br>                    gasLimit: &#39;70000&#39;,<br>                    data: iface.encodeFunctionData(&quot;transfer&quot;, [<br>                        rescuer.address,<br>                        utils.parseEther(&#39;200&#39;)<br>                    ]),<br>                    maxFeePerGas: utils.parseUnits(&#39;20&#39;, &#39;gwei&#39;),<br>                    maxPriorityFeePerGas: utils.parseUnits(&#39;13&#39;, &#39;gwei&#39;)<br>                }<br>            }<br>        ], targetBlock)</pre><p>Basically, we will be performing two transactions</p><ol><li>We need to transfer some Ether to the wallet that has been hacked to provide it with the gas fees that will be used to transfer the ERC20 tokens to the rescuer wallet</li><li>We now call the transfer function from the ERC20 contract using the signer of hacked wallet and transfer all the tokens to the rescuer wallet</li></ol><p>These transactions can be anything <br>Like transfer, an NFT, Transfer Ownership of a contract, call any contract method.</p><p>And that’s it,</p><blockquote><strong>Want to connect? DM me on twitter @</strong><a href="https://twitter.com/pateldeep_eth"><strong>pateldeep_eth</strong></a><strong> or </strong><a href="https://www.linkedin.com/in/patel-deep-dev/"><strong>Linkedin</strong></a></blockquote><p>Want to explore more examples? <br><a href="https://github.com/flashbots/searcher-sponsored-tx">https://github.com/flashbots/searcher-sponsored-tx</a></p><h3>Also, Read</h3><ul><li><a href="https://medium.com/better-programming/in-the-world-of-javascript-finding-the-length-of-string-is-such-an-easy-thing-just-do-str-length-4b4b33dbed09">How to Find Length of String in Solidity — From the Smart Contract of “ens”</a></li><li><a href="https://medium.com/better-programming/permanent-file-storage-for-web3-apps-with-arweave-bundlr-next-js-rainbowkit-and-wagmi-18aa1506fa6e">Permanent File Storage for Web3 Apps With Arweave, Bundlr, Next.js, RainbowKit, and Wagmi</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f32ae3f25edd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authenticate Users in Your DApp with Sign in with Ethereum: A Step-by-Step Guide]]></title>
            <link>https://pateldeep-eth.medium.com/authenticate-users-in-your-dapp-with-sign-in-with-ethereum-a-step-by-step-guide-63011d29dd1c?source=rss-36b5aa8ffc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/63011d29dd1c</guid>
            <category><![CDATA[dapps]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Deep Patel]]></dc:creator>
            <pubDate>Wed, 21 Dec 2022 14:31:45 GMT</pubDate>
            <atom:updated>2022-12-21T14:31:45.581Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>How to Connect Your DApp with a Backend Using Sign in with Ethereum</blockquote><p>In an ideal scenario, A Dapp should not have any <strong>centralized </strong>backend server, everything should be on-chain.</p><blockquote><strong>Then why Backend?</strong></blockquote><ol><li>With a fully on-chain approach, we need to (at least right now) compromise on user experience</li><li>Not everything needs to be on a chain, it just doesn’t make sense. Wouldn’t will it be great if we can make our apps sufficiently decentralized?<br>There is a great <a href="https://www.varunsrinivasan.com/2022/01/11/sufficient-decentralization-for-social-networks">Article</a> By <a href="https://twitter.com/varunsrin">Varun Srinivasan</a> on Sufficient Decentralization which everyone should give read</li><li>Better scalability: A backend can help a Dapp scale more easily by handling tasks that might otherwise slow down the blockchain or consume a large amount of gas.</li><li>Off-chain computation: Some tasks, such as image or video processing, can be resource-intensive and may not be practical to perform on the blockchain. A backend can handle these tasks and communicate with the Dapp as needed.</li></ol><blockquote>For this or any reason you might need to have the backend connected to your Dapp, but how? let’s get started with it</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*3UcEW1KXM3y0MMJlk6D9Lg.jpeg" /></figure><h4>So, what are we building Deep? 👀</h4><p>A Dapp which connects to your backend maintains a session and connects with the Database.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.loom.com%2Fembed%2F1c339b09dc5f4920ab6477fcad4a1735&amp;display_name=Loom&amp;url=https%3A%2F%2Fwww.loom.com%2Fshare%2F1c339b09dc5f4920ab6477fcad4a1735&amp;image=https%3A%2F%2Fcdn.loom.com%2Fsessions%2Fthumbnails%2F1c339b09dc5f4920ab6477fcad4a1735-00001.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=loom" width="1280" height="960" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b0a21d4a7247ceecc554e573718da39/href">https://medium.com/media/0b0a21d4a7247ceecc554e573718da39/href</a></iframe><h3><strong>What is SIWE (Sign-In with Ethereum)?</strong></h3><p>Sign-In with Ethereum describes how Ethereum accounts to authenticate with off-chain services by signing a standard message format parameterized by scope, session details, and security mechanisms (e.g., a nonce). This specification aims to provide a self-custodied alternative to centralized identity providers, improve interoperability across off-chain services for Ethereum-based authentication, and provide wallet vendors with a consistent machine-readable message format to achieve enhanced user experiences and consent management.</p><p>More details can be found here <a href="https://docs.login.xyz/general-information/siwe-overview/eip-4361">https://docs.login.xyz/general-information/siwe-overview/eip-4361</a></p><p><strong>Here are some steps we will be following</strong></p><ol><li>Connect wallet</li><li>Sign SIWE message with the nonce generated by the backend</li><li>Verify the submitted SIWE message and signature via the POST request</li><li>Add validated SIWE fields to the session (via JWT, cookie, etc.)</li><li>Store user details(eg: name) in MongoDB</li><li>Update user information</li><li>Maintaining sessions b/w page refreshes</li></ol><p><strong>Tools We are going to use:</strong></p><ol><li><a href="https://nextui.org/">NextUI</a> — Component library, of course, I hate CSS and I’m not going to write any of it</li><li><a href="https://wagmi.sh/">Wagmi</a> — React Hooks for Ethereum</li><li><a href="https://github.com/vvo/iron-session">Iron Session</a></li></ol><p>Clone the code from the <a href="https://github.com/Deep1144/siwe-with-backend">GitHub repo</a>, to follow through</p><h3>Step1: Let’s create some API routes first</h3><p>under <strong>pages/api</strong> create a file nonce.ts with the following content</p><p>pages/api/nonce.ts</p><pre>import { withIronSessionApiRoute } from &#39;iron-session/next&#39;<br>import { sessionOptions } from &#39;lib/session&#39;<br>import { NextApiRequest, NextApiResponse } from &#39;next&#39;<br>import { generateNonce } from &#39;siwe&#39;<br><br>const handler = async (req: NextApiRequest, res: NextApiResponse) =&gt; {<br>  const { method } = req<br>  switch (method) {<br>    case &#39;GET&#39;:<br>      req.session.nonce = generateNonce()<br>      await req.session.save()<br>      res.setHeader(&#39;Content-Type&#39;, &#39;text/plain&#39;)<br>      res.send(req.session.nonce)<br>      break<br>    default:<br>      res.setHeader(&#39;Allow&#39;, [&#39;GET&#39;])<br>      res.status(405).end(`Method ${method} Not Allowed`)<br>  }<br>}<br><br>export default withIronSessionApiRoute(handler, sessionOptions)</pre><p>Next, add an API route to verify a SIWE message and make the user session.</p><p>pages/api/verify.ts</p><pre>import { handleLoginOrSignup } from &#39;core/services/user.service&#39;<br>import { withIronSessionApiRoute } from &#39;iron-session/next&#39;<br>import dbConnect from &#39;lib/dbConnect&#39;<br>import { sessionOptions } from &#39;lib/session&#39;<br>import { NextApiRequest, NextApiResponse } from &#39;next&#39;<br>import { SiweMessage } from &#39;siwe&#39;<br><br>const handler = async (req: NextApiRequest, res: NextApiResponse) =&gt; {<br>    const { method } = req<br>    switch (method) {<br>        case &#39;POST&#39;:<br>            try {<br>                await dbConnect();<br>                const { message, signature } = req.body<br>                const siweMessage = new SiweMessage(message)<br>                const fields = await siweMessage.validate(signature)<br><br>                if (fields.nonce !== req.session.nonce) {<br>                    return res.status(422).json({ message: &#39;Invalid nonce.&#39; })<br>                }<br><br>                req.session.siwe = fields;<br>		// maintaining users details in MongoDB from below line<br>	        // we will get backto this later ignore for now<br>                const user = await handleLoginOrSignup(fields.address);<br>                req.session.user = user;<br>                await req.session.save()<br>                res.json({ ok: true })<br>            } catch (_error) {<br>                console.log(&#39;error -&gt; verify&#39;, _error)<br>                res.json({ ok: false, error: _error })<br>            }<br>            break<br>        default:<br>            res.setHeader(&#39;Allow&#39;, [&#39;POST&#39;])<br>            res.status(405).end(`Method ${method} Not Allowed`)<br>    }<br>}<br><br>export default withIronSessionApiRoute(handler, sessionOptions)</pre><pre>const { message, signature } = req.body<br>const siweMessage = new SiweMessage(message)<br>const fields = await siweMessage.validate(signature)</pre><p>We will be passing a message and signature done by the user&#39;s wallet from the Frontend, on the API side we are verifying it and the nonce, nonce will prevent the replay attacks.</p><p>our iron session config file is going to look something like</p><pre>// this file is a wrapper with defaults to be used in both API routes and `getServerSideProps` functions<br>import type { IronSessionOptions } from &quot;iron-session&quot;;<br>import { IUser } from &quot;models/User&quot;;<br><br>export const sessionOptions: IronSessionOptions = {<br>  password: &#39;passowrd_cookie&#39;,<br>  cookieName: &quot;iron-session/examples/next.js&quot;,<br>  cookieOptions: {<br>    secure: process.env.NODE_ENV === &quot;production&quot;,<br>  },<br>};<br><br>// This is where we specify the typings of req.session.*<br>declare module &quot;iron-session&quot; {<br>  interface IronSessionData {<br>    siwe: any;<br>    nonce: any;<br>    user: IUser | undefined; // users details from DB<br>  }<br>}</pre><p>Now, let’s create an API for checking user’s sessions and returning users details if a user is already logged in pages/api/me.ts Note: findUserByAddress is a helper method that is getting user&#39;s details from MongoDB, you can check out the code from GitHub, to explore this helper method</p><pre>import { findUserByAddress } from &#39;core/services/user.service&#39;<br>import { ReasonPhrases, StatusCodes } from &#39;http-status-codes&#39;<br>import { withIronSessionApiRoute } from &#39;iron-session/next&#39;<br>import { sessionOptions } from &#39;lib/session&#39;<br>import { NextApiRequest, NextApiResponse } from &#39;next&#39;<br><br>const handler = async (req: NextApiRequest, res: NextApiResponse) =&gt; {<br>  const { method } = req<br>  switch (method) {<br>    case &#39;GET&#39;:<br>      const address = req.session.siwe?.address<br>      if (address) {<br>        const user = await findUserByAddress(address)<br>        res.json({ address: req.session.siwe?.address, user })<br>        return<br>      }<br>      res.status(StatusCodes.UNAUTHORIZED).json({<br>        message: ReasonPhrases.UNAUTHORIZED,<br>      })<br>      break<br>    default:<br>      res.setHeader(&#39;Allow&#39;, [&#39;GET&#39;])<br>      res.status(405).end(`Method ${method} Not Allowed`)<br>  }<br>}<br><br>export default withIronSessionApiRoute(handler, sessionOptions)</pre><p>And lastly logout route, where we are destroying the session</p><pre>import { withIronSessionApiRoute } from &#39;iron-session/next&#39;<br>import { sessionOptions } from &#39;lib/session&#39;<br>import { NextApiRequest, NextApiResponse } from &#39;next&#39;<br><br>const handler = async (req: NextApiRequest, res: NextApiResponse) =&gt; {<br>  const { method } = req<br>  switch (method) {<br>    case &#39;POST&#39;:<br>      await req.session.destroy()<br>      res.send({ ok: true })<br>      break<br>    default:<br>      res.setHeader(&#39;Allow&#39;, [&#39;POST&#39;])<br>      res.status(405).end(`Method ${method} Not Allowed`)<br>  }<br>}<br><br>export default withIronSessionApiRoute(handler, sessionOptions)</pre><p>Now, let’s create a state file for maintaining all user data and related methods we are going to use context API for this</p><pre>import { IUser } from &#39;models/User&#39;<br>import React, { createContext, useContext, useState } from &#39;react&#39;<br>import { SiweMessage } from &#39;siwe&#39;<br>import { Connector, useAccount, useConnect } from &#39;wagmi&#39;<br>import axios from &#39;axios&#39;<br>import { useRouter } from &#39;next/router&#39;<br>import { toast } from &#39;react-toastify&#39;<br><br>export interface IUserState {<br>  user: IUser | undefined<br>  loadingUser: boolean<br>  setUser: React.Dispatch&lt;React.SetStateAction&lt;undefined&gt;&gt;<br>  handleSignOut: () =&gt; void<br>  handleSignIn: (connector: Connector) =&gt; Promise&lt;void&gt;<br>}<br><br>const UserContext = createContext&lt;IUserState&gt;({<br>  user: undefined,<br>  setUser: () =&gt; {},<br>  loadingUser: false,<br>  handleSignOut: () =&gt; {},<br>  handleSignIn: async () =&gt; {},<br>})<br><br>export function UserState({ children }: { children: JSX.Element }) {<br>  const router = useRouter()<br>  const [user, setUser] = useState(undefined)<br>  const [, connect] = useConnect()<br>  const [loadingUser, setLoadingUser] = useState(false)<br>  const [, disconnect] = useAccount({<br>    fetchEns: true,<br>  })<br><br>  const handleSignOut = async () =&gt; {<br>    disconnect()<br>    await axios.post(&#39;/api/logout&#39;)<br>    setUser(undefined)<br>    router.replace(&#39;/&#39;)<br>  }<br><br>  const handleSignIn = async (connector: Connector) =&gt; {<br>    try {<br>      const res = await connect(connector) // connect from useConnect<br>      if (!res.data) throw res.error ?? new Error(&#39;Something went wrong&#39;)<br><br>      setLoadingUser(true)<br>      const nonceRes = await axios(&#39;/api/nonce&#39;)<br>      const message = new SiweMessage({<br>        domain: window.location.host,<br>        address: res.data.account,<br>        statement: &#39;Sign in with Ethereum to the app.&#39;,<br>        uri: window.location.origin,<br>        version: &#39;1&#39;,<br>        chainId: res.data.chain?.id,<br>        nonce: nonceRes.data,<br>      })<br><br>      const signer = await connector.getSigner()<br>      const signature = await signer.signMessage(message.prepareMessage())<br>      // console.log(&#39;message&#39;, message, { signature })<br>      await axios.post(&#39;/api/verify&#39;, {<br>        message,<br>        signature,<br>      })<br>      const me = await axios(&#39;/api/me&#39;)<br>      setUser(me.data.user)<br>      // It worked! User is signed in with Ethereum<br>    } catch (error) {<br>      // Do something with the error<br>      toast.error(&#39;Something went wrong!&#39;)<br>      handleSignOut()<br>      console.log(&#39;error&#39;, error)<br>    } finally {<br>      setLoadingUser(false)<br>    }<br>  }<br><br>  return (<br>    &lt;UserContext.Provider<br>      value={{ user, setUser, handleSignOut, handleSignIn, loadingUser }}<br>    &gt;<br>      {children}<br>    &lt;/UserContext.Provider&gt;<br>  )<br>}<br><br>export function useUserContext() {<br>  return useContext(UserContext)<br>}</pre><h3>Breaking down handleSignIn method</h3><pre>const res = await connect(connector) // connect from useConnect<br>if (!res.data) throw res.error ?? new Error(&#39;Something went wrong&#39;)</pre><p>we are connected to the wallet here</p><p>Once the user is connected we generate a random nonce using the API we created earlier</p><pre>const nonceRes = await axios(&#39;/api/nonce&#39;)<br>      const message = new SiweMessage({<br>        domain: window.location.host,<br>        address: res.data.account, // users waller address<br>        statement: &#39;Sign in with Ethereum to the app.&#39;,<br>        uri: window.location.origin,<br>        version: &#39;1&#39;,<br>        chainId: res.data.chain?.id,<br>        nonce: nonceRes.data,<br>      })<br><br>const signer = await connector.getSigner()<br>const signature = await signer.signMessage(message.prepareMessage())</pre><p>then we ask the user to sign a message, using SiweMessage constructor exposed by SIWE and creates a signature</p><pre>await axios.post(&#39;/api/verify&#39;, {<br>        message,<br>        signature,<br>      })<br>const me = await axios(&#39;/api/me&#39;)<br>setUser(me.data.user)</pre><p>verifying users, and getting logged in user’s data using me API we created earlier, then set the user&#39;s data to state</p><p>Now let’s make the API for updating user details in the Database,</p><pre>import withAuth from &#39;core/middleware/withAuth&#39;<br>import { findUserById, updateUser } from &#39;core/services/user.service&#39;<br>import { ReasonPhrases, StatusCodes } from &#39;http-status-codes&#39;<br>import { withIronSessionApiRoute } from &#39;iron-session/next&#39;<br>import { sessionOptions } from &#39;lib/session&#39;<br>import { isValidObjectId } from &#39;mongoose&#39;<br>import { NextApiRequest, NextApiResponse } from &#39;next&#39;<br><br>const handler = async (req: NextApiRequest, res: NextApiResponse) =&gt; {<br>    const { method, query } = req<br>    const queryId = query.id;<br><br>    if (!queryId || !isValidObjectId(queryId)) {<br>        res.status(StatusCodes.BAD_REQUEST).json({<br>            message: &quot;Valid id is required&quot;<br>        })<br>        return;<br>    }<br>    switch (method) {<br>        case &#39;PUT&#39;:<br>            return await handlePatchUser();<br>        default:<br>            res.setHeader(&#39;Allow&#39;, [&#39;PUT&#39;])<br>            res.status(405).end(`Method ${method} Not Allowed`)<br>    };<br><br>    async function handlePatchUser() {<br>        if (req.session.user?._id !== queryId) {<br>            res.status(StatusCodes.FORBIDDEN).json({<br>                message: ReasonPhrases.FORBIDDEN<br>            });<br>            return;<br>        }<br>        const user = await updateUser(queryId, req.body);<br>        if (!user) {<br>            res.status(StatusCodes.BAD_REQUEST).json({<br>                message: &quot;User not found with requested id&quot;<br>            })<br>        }<br>        res.json({<br>            user<br>        })<br>    }<br>}<br><br>export default withIronSessionApiRoute(withAuth(handler), sessionOptions)</pre><p>Notice we are using withAuth here it is a <strong>middleware</strong> we have created, so only authorized users can access our API routes <strong>Link to code</strong></p><p>Now let’s create a profile in pages/profile.ts</p><pre>import type { NextPage } from &#39;next&#39;<br>import Head from &#39;next/head&#39;<br>import { BaseLayout } from &#39;components/ui/Layout/BaseLayout&#39;<br>import { ComponentWithLayout } from &#39;../_app&#39;<br>import { useFormik } from &#39;formik&#39;<br>import axios from &#39;axios&#39;<br>import { useUserContext } from &#39;core/state/user.state&#39;<br>import { useState } from &#39;react&#39;<br>import { Button, Loading } from &#39;@nextui-org/react&#39;<br>import { toast } from &#39;react-toastify&#39;<br><br>const Profile: NextPage = () =&gt; {<br>  const { user } = useUserContext()<br>  const [loading, setLoading] = useState(false)<br>  const formik = useFormik({<br>    enableReinitialize: true,<br>    initialValues: {<br>      ...user,<br>    },<br>    onSubmit: async (values) =&gt; {<br>      try {<br>        setLoading(true)<br>        await axios.put(`/api/users/${user?._id}`, values)<br>        toast.success(&#39;Data saved successfully&#39;)<br>      } catch (error: any) {<br>        toast.error(error.message)<br>      } finally {<br>        setLoading(false)<br>      }<br>    },<br>  })<br><br>  return (<br>    &lt;div className=&quot;flex flex-col items-center justify-center py-2&quot;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Profile&lt;/title&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot; /&gt;<br>      &lt;/Head&gt;<br>      &lt;section className=&quot;bg-blueGray-100 rounded-b-10xl&quot;&gt;<br>        &lt;div className=&quot;container mx-auto px-4&quot;&gt;<br>          &lt;div className=&quot;-mx-4 flex flex-wrap&quot;&gt;<br>            &lt;div className=&quot;w-full px-4&quot;&gt;<br>              &lt;div className=&quot;mx-auto max-w-xl rounded-xl bg-white py-14 px-8 md:px-20 md:pt-16 md:pb-20&quot;&gt;<br>                &lt;h3 className=&quot;font-heading mb-12 text-4xl font-medium&quot;&gt;<br>                  Profile Details<br>                &lt;/h3&gt;<br>                &lt;input<br>                  className=&quot;placeholder-darkBlueGray-400 mb-5 w-full rounded-xl border px-12 py-5 text-xl focus:bottom-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50&quot;<br>                  type=&quot;text&quot;<br>                  placeholder=&quot;Your Name&quot;<br>                  name=&quot;name&quot;<br>                  onChange={formik.handleChange}<br>                  value={formik.values.name}<br>                /&gt;<br><br>                &lt;div className=&quot;text-right&quot;&gt;<br>                  &lt;Button<br>                    clickable={!loading}<br>                    color=&quot;primary&quot;<br>                    className=&quot;inline-block w-full  text-center text-xl font-medium tracking-tighter md:w-auto&quot;<br>                    onClick={formik.submitForm}<br>                    size=&quot;lg&quot;<br>                    icon={<br>                      loading &amp;&amp; (<br>                        &lt;Loading type=&quot;spinner&quot; color=&quot;white&quot; size=&quot;md&quot; /&gt;<br>                      )<br>                    }<br>                  &gt;<br>                    Save<br>                  &lt;/Button&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/section&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default Profile<br>;(Profile as ComponentWithLayout).Layout = BaseLayout</pre><p>And that’s a wrap,</p><p><strong>Follow me on Medium</strong> for more such content on web3, and Full stack development in general.</p><blockquote>Connect with me on Twitter: <a href="http://twitter.com/pateldeep_eth">@pateldeep_eth</a>, <a href="https://www.linkedin.com/in/patel-deep-dev/">Linkedin</a></blockquote><h4>More Web3 related content you might be interested in,</h4><ul><li><a href="https://betterprogramming.pub/permanent-file-storage-for-web3-apps-with-arweave-bundlr-next-js-rainbowkit-and-wagmi-18aa1506fa6e">Permanent File Storage for Web3 Apps With Arweave, Bundlr, Next.js, RainbowKit, and Wagmi</a></li><li><a href="https://betterprogramming.pub/in-the-world-of-javascript-finding-the-length-of-string-is-such-an-easy-thing-just-do-str-length-4b4b33dbed09">How to Find Length of String in Solidity — From the Smart Contract of “ens”</a></li></ul><h3>pateldeep.eth/lens | EthIndia on Twitter: &quot;I just published How to develop and deploy smart contracts with #Foundry &amp; #Openzeppelin https://t.co/jzfoM3mM7l / Twitter&quot;</h3><p>I just published How to develop and deploy smart contracts with #Foundry &amp; #Openzeppelin https://t.co/jzfoM3mM7l</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63011d29dd1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to develop and deploy smart contracts with Foundry & Openzeppelin]]></title>
            <link>https://medium.com/coinmonks/how-to-develop-and-deploy-smart-contracts-with-foundry-openzeppelin-6bba51ddb438?source=rss-36b5aa8ffc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bba51ddb438</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[foundry]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Deep Patel]]></dc:creator>
            <pubDate>Fri, 25 Nov 2022 05:20:22 GMT</pubDate>
            <atom:updated>2022-11-25T05:20:22.677Z</atom:updated>
            <content:encoded><![CDATA[<p>Foundry is a blazing fast, portable and modular toolkit for Ethereum application development written in Rust.</p><p>Foundry is made up of three components:</p><p><a href="https://github.com/foundry-rs/foundry/tree/master/forge">Forge</a>: Ethereum testing framework (like Truffle, Hardhat, and DappTools).</p><p><a href="https://github.com/foundry-rs/foundry/tree/master/cast">Cast</a>: CLI for interacting with EVM smart contracts, sending transactions, and getting chain data.</p><p><a href="https://github.com/foundry-rs/foundry/tree/master/anvil">Anvil</a>: local Ethereum node, similar to Ganache or Hardhat Network.</p><h3><strong>Why should we use it?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SpttNRShCalW2K5p.jpg" /></figure><ul><li>It’s speedy, no more wasted time while running tests.</li><li>It allows you to write tests in solidity which minimizes context switching.</li><li>Many testing features like fuzzing, console.log, and cheat codes give you more power and flexibility.</li></ul><h3>Topics we are going to cover in this Article</h3><ol><li>Project setup</li><li>How to install dependencies in Foundry (EX. OpenZeppelin)</li><li>Integrating Foundry with VSCode</li><li>Writing the contract and test cases using Foundry</li><li>Understanding Traces in Foundry</li><li>Generating Gas report using Foundry</li><li>Deploying the contract using Foundry</li></ol><h3>Installation</h3><p>Installation of Foundry is well explained in the foundry book, check out the instructions here</p><p><a href="https://book.getfoundry.sh/getting-started/installation">https://book.getfoundry.sh/getting-started/installation</a></p><h3>Setting up the project</h3><p>once, the foundry is installed we can create a new project using</p><pre>forge init foundry-demo // forge-demo is name of the project</pre><p>once the project is created, use commands to check if everything is working correctly</p><pre>cd foundry-demo &amp;&amp; forge build</pre><h3>Installing dependencies</h3><p>Forge manages dependencies using <a href="https://git-scm.com/book/en/v2/Git-Tools-Submodules">git submodules</a> by default, which means that it works with any GitHub repository that contains smart contracts.</p><p>To use <strong>OpenZeppelin</strong> we need to install it as a dependency in our project, to-do so use the command</p><pre>forge install OpenZeppelin/openzeppelin-contracts<br>// forge install is command which is used for installing  dependencies <br>// &lt;https://github.com/OpenZeppelin/openzeppelin-contracts&gt;<br>// use {{username}}/{{repo_name}} from the github url</pre><h3>Integrate Foundry with VSCode</h3><p>After installing <strong>OpenZeppelin</strong> as a dependency try importing something from it in the contract (your contract is there under the /src directory), If you are using VSCode an error will popup</p><figure><img alt="Foundry import error" src="https://cdn-images-1.medium.com/max/1024/0*4k7zsZrv7WH8KBut" /></figure><p>To fix this error, Run this command</p><pre>forge remappings &gt; remappings.txt</pre><p>What this command does is it creates a remappings.txt file inside the root directory of the project</p><p>At this moment the content in the file might look like this,</p><pre>ds-test/=lib/forge-std/lib/ds-test/src/<br>forge-std/=lib/forge-std/src/<br>openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/</pre><p>For more details visit here <a href="https://book.getfoundry.sh/config/vscode">https://book.getfoundry.sh/config/vscode</a></p><h3>Writing the contract</h3><p>Rename the file src/Counter.sol → src/FDemo.sol, the code for our ERC721 smart contract is as below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/970ec9565654616e39ae0b2812406931/href">https://medium.com/media/970ec9565654616e39ae0b2812406931/href</a></iframe><h3>Testing the contract using Foundry</h3><p>Let&#39;s start by renaming the test file to match the name of our contract Counter.t.sol → FDemo.t.sol</p><p>Forge uses the following keywords in tests:</p><ul><li>setUp: An optional function invoked before each test case is run</li></ul><pre>function setUp() public {<br>    testNumber = 42;<br>}</pre><ul><li>test: Functions prefixed with test are run as a test case</li></ul><pre>function testNumberIs42() public {     <br>  assertEq(testNumber, 42); <br>}</pre><ul><li>testFail: The inverse of the test prefix — if the function does not revert, the test fails</li></ul><pre>function testNumberIs42() public {     <br>  assertEq(testNumber, 42); <br>}</pre><p>So, Right now we only have one method mint, so we will be writing a test case for this method</p><p>and this is going to be a pretty simple one</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7497c2376114ad3254dfe7d2c0e327a4/href">https://medium.com/media/7497c2376114ad3254dfe7d2c0e327a4/href</a></iframe><p>Now, to run this test we can use the command forge test</p><p>If we want to explore more details/ events/ flow about the test cases, we can use Traces To enable Traces while running test cases use -vvv or -vvvv</p><p>The attached screenshot shows the result of test cases with and without traces</p><figure><img alt="Foundry logs" src="https://cdn-images-1.medium.com/max/1024/0*kgX9gigS1r5uRaWZ" /></figure><p>More details on the Traces: <a href="https://book.getfoundry.sh/forge/traces">https://book.getfoundry.sh/forge/traces</a></p><h3>Generating Gas report using Foundry</h3><p>to generate gas report use <strong>— gas-report</strong> with the test command</p><pre>forge test --gas-report</pre><figure><img alt="Foundry gas report" src="https://cdn-images-1.medium.com/max/1024/0*lFq2lcRfBnk8BUGa" /></figure><p>More details on the Gas Report here: <a href="https://book.getfoundry.sh/forge/gas-reports">https://book.getfoundry.sh/forge/gas-reports</a></p><h3>Deploying and verifying contracts with Foundry</h3><p>Forge can deploy smart contracts to a given network with the [forge create](&lt;https://book.getfoundry.sh/reference/forge/forge-create.html&gt;) command.</p><p>Forge can deploy smart contracts to a given network with the [forge create](&lt;https://book.getfoundry.sh/reference/forge/forge-create.html&gt;) command.</p><p>Some options we can use with forge create while deploying the contract</p><ul><li>—rpc-url : Rpc URL of the network on which we want to deploy our contract (in our case we will be using the RPC URL of polygon mumbai testnet)</li><li>-constructor-args : Pass arguments to the constructor</li><li>-private-key : Private key of deployers wallet</li></ul><p>We can optionally pass --verify &amp;&amp; --etherscan-api-key if we want to verify our contract</p><pre>$ forge create --rpc-url &lt;your_rpc_url&gt; \\<br>    --constructor-args &quot;ForgeUSD&quot; &quot;FUSD&quot; 18 1000000000000000000000 \\<br>    --private-key &lt;your_private_key&gt; src/MyToken.sol:MyToken \\<br>    --etherscan-api-key &lt;your_etherscan_api_key&gt; \\<br>    --verify</pre><p>Let&#39;s deploy, now</p><pre>forge create --rpc-url &lt;https://rpc.ankr.com/polygon_mumbai&gt; <br>--private-key &lt;your_private_key&gt;  src/FDemo.sol:FDemo <br>--etherscan-api-key &lt;your_etherscan_api_key&gt; <br>--verify</pre><figure><img alt="Forge create | Foundry deploy" src="https://cdn-images-1.medium.com/max/1024/0*bennTFz91RaZJgk5" /></figure><p>Complete code: <a href="https://github.com/Deep1144/foundry-demo-contract">GitHub</a></p><blockquote>💡 Follow me on Twitter for more awesome stuff like this <a href="https://twitter.com/transitive_bs">@</a><a href="https://twitter.com/pateldeep_eth">pateldeep_eth</a> <br><a href="https://www.linkedin.com/in/patel-deep-dev/">Linkedin</a></blockquote><blockquote>New to trading? Try <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">crypto trading bots</a> or <a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">copy trading</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bba51ddb438" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/how-to-develop-and-deploy-smart-contracts-with-foundry-openzeppelin-6bba51ddb438">How to develop and deploy smart contracts with Foundry &amp; Openzeppelin</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Permanent File Storage for Web3 Apps With Arweave, Bundlr, Next.js, RainbowKit, and Wagmi]]></title>
            <link>https://medium.com/better-programming/permanent-file-storage-for-web3-apps-with-arweave-bundlr-next-js-rainbowkit-and-wagmi-18aa1506fa6e?source=rss-36b5aa8ffc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/18aa1506fa6e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Deep Patel]]></dc:creator>
            <pubDate>Mon, 27 Jun 2022 15:42:24 GMT</pubDate>
            <atom:updated>2022-06-27T15:42:24.446Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to create an excellent way to store your data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4_aEaUYIFIOfjgTt" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, I will be showing you how to create a Dapp that allows us to store data on the Arweave network, using bundlr on testnet.</p><p>Before going forward, let’s see what are we going to build today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4dj3gwBQJjGOex__rN82Q.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.loom.com%2Fembed%2F808aff5aa5d84ead93c106cfb96ff05f&amp;display_name=Loom&amp;url=https%3A%2F%2Fwww.loom.com%2Fshare%2F808aff5aa5d84ead93c106cfb96ff05f&amp;image=https%3A%2F%2Fcdn.loom.com%2Fsessions%2Fthumbnails%2F808aff5aa5d84ead93c106cfb96ff05f-00001.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=loom" width="1280" height="960" frameborder="0" scrolling="no"><a href="https://medium.com/media/31a02cfde204b962e1fc6f6c9bb982cd/href">https://medium.com/media/31a02cfde204b962e1fc6f6c9bb982cd/href</a></iframe><p>Here is the deployed link if you want to try it out:</p><p><a href="https://bundlr-arweave.netlify.app/">https://bundlr-arweave.netlify.app/</a></p><h3>Tech Stack and Libraries I’ve Used:</h3><ul><li>Nextjs</li><li>Chakra UI</li><li>RainbowKit</li><li>Wagmi</li><li>Bundlr Client</li></ul><h3>Well, Well, Let’s Go Through What Is Arweave and Bundlr First (From the Doc)</h3><p>If you enjoy videos like me, here is a video for you:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDQbwiiXMtMo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDQbwiiXMtMo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDQbwiiXMtMo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/514b5f6cf24c0e95a6c0fb86a55b85c6/href">https://medium.com/media/514b5f6cf24c0e95a6c0fb86a55b85c6/href</a></iframe><h3><a href="https://www.arweave.org/">Arweave</a></h3><p>Arweave makes information permanence sustainable.</p><p>Arweave is a new type of storage that backs data with sustainable and perpetual endowments, allowing users and developers to truly store data forever — for the very first time.</p><h3><a href="https://docs.bundlr.network/docs/about/introduction">Bundlr</a></h3><p>Bundlr makes web3 data storage on Arweave accessible by making it as fast, easy, and reliable as traditional data storage. Arweave is the only truly decentralized, permanent data storage solution.</p><p>Bundlr increases the number of transactions conducted on Arweave by 4,000% without sacrificing security or usability and is around ~3,000x faster at uploading data.</p><p>Bundlr currently accounts for over 90% of data uploaded to Arweave. It enables infinite scalability and enables instant and guaranteed transaction finality. It is a multichain solution and is compatible with leading blockchains including Ethereum, Solana, Avalanche, Polygon, and many more.</p><h3>Steps We Have to Follow to Upload to Arweave Using Bundlr</h3><ol><li>Connect wallet</li><li>Initialize the Bundlr client</li><li>Add funds ($BNDLR tokens)</li><li>Upload the files</li></ol><blockquote><em>Note: we will be bulding this app on polygon mumbai testnet</em></blockquote><blockquote><em>Bundlr has a devnet which allows you to use devnet/testnet cryptocurrency networks to pay for storage. The devnet node behaves exactly as a mainnet node — other than data is never moved to Arweave and will be cleared from Bundlr after a week.</em></blockquote><h3>Let’s Get Building</h3><p>Keep the completed code open on the side for a better understanding <a href="https://github.com/Deep1144/bundlr-arweave-testnet-uploader">Github</a></p><h3>1. Setting Up the Project</h3><p>Setup a Nextjs project with tailwind CSS and Chakra UIYou can use <a href="https://github.com/dhaiwat10/create-web3-frontend">create-web3-frontend</a> package to get done with setup quickly or just clone this <a href="https://github.com/Deep1144/bundlr-arweave-testnet-uploader">project repo</a></p><p>Also, install these two dependencies:</p><pre>yarn add @bundlr-network/client bignumber.js</pre><h3>2. Connect Wallet</h3><p>As we are using Rainbow kit, this step is very easy in index.tsx:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/322ecc1f91e4400fabea177e444cea3d/href">https://medium.com/media/322ecc1f91e4400fabea177e444cea3d/href</a></iframe><p>And with these 5–6 lines of code, we are done with connecting the wallet.</p><p>We have also added a condition to check if a user is on the Mumbai test, as we will be using polygon Mumbai testnet for this article.</p><p>In _app.jsx while configuring Rainbow kit we have configures it for using polygon Mumbai testnet</p><pre>const { chains, provider } = configureChains(<br>  [chain.polygonMumbai],<br>  [<br>    jsonRpcProvider({ rpc: () =&gt; ({ http: process.env.NEXT_PUBLIC_ALCHEMY_RPC_URL }) }),<br>    publicProvider(),<br>  ]<br>);</pre><p>So, Rainbow kit will also take care of changing the network for us, this is how this warning will look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*4RZkREkSVli0yGXe.png" /></figure><h3>3. Initializing the Bundlr</h3><p>Let’s create a context for bundlr so we can maintain all bundlr-related logic from there.</p><p>Create bundlr.context.tsx</p><p>Inside this file, let&#39;s create the context now. You can see the completed version of the file <a href="https://github.com/Deep1144/bundlr-arweave-testnet-uploader/blob/main/state/bundlr.context.tsx">here</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d2125c10a43121c794f82b1094650ae/href">https://medium.com/media/0d2125c10a43121c794f82b1094650ae/href</a></iframe><p>For initializing the Bundlr, we will be using initialiseBundlr the method from the code above. The code is also pretty straightforward.</p><pre>const bundlr = new WebBundlr(<br>            &quot;https://devnet.bundlr.network&quot;,<br>            &quot;matic&quot;,<br>            provider,<br>            {<br>                providerUrl:<br>                    process.env.NEXT_PUBLIC_ALCHEMY_RPC_URL,<br>            }<br>        );<br>        await bundlr.ready();<br>        setBundlrInstance(bundlr);</pre><p>We are creating an instance of the Bundlr client and storing it in a state variable</p><p>Read more about <a href="https://docs.bundlr.network/docs/client/js">bundlr client</a>.</p><p>For using Bundlr with testnet, <a href="https://docs.bundlr.network/docs/devnet">read here</a>.</p><blockquote>In order to use the devnet, you need to use https://devnet.bundlr.network as the node and set the provider url to a correct testnet/devnet RPC endpoint for the given chain.</blockquote><p>Our RPC URL will look something like this, as we will be using polygon testnet.</p><pre>NEXT_PUBLIC_ALCHEMY_RPC_URL=https://polygon-mumbai.g.alchemy.com/v2/{{alchemy_project_id}}</pre><p>Read, about all the supported currencies/ networks by bundlr <a href="https://docs.bundlr.network/docs/currencies">here</a>.</p><h3>4. Add Funds ($bndlr Tokens)</h3><p>We already have data about our balance in the bundlr context, and we also have a method fundWallet which we will be using to add the funds.</p><p>Adding funds is also pretty straightforward. Just use the fund method on the bundlrInstance and pass the amount you want to fund the wallet with.</p><pre>let response = await bundlrInstance.fund(amountParsed)</pre><p>In index.tsx, make these changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5d4cfbdbc650776d00a97d38caf9fd3/href">https://medium.com/media/f5d4cfbdbc650776d00a97d38caf9fd3/href</a></iframe><p>Now, let’s create the &lt;FundWallet /&gt; component.</p><p>Create components/FundWallet.tsx</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9acf06af01cdf6dfbc98accb5a5b969/href">https://medium.com/media/d9acf06af01cdf6dfbc98accb5a5b969/href</a></iframe><h3>5. Upload Images</h3><p>Now, as we’ve already added the funds, we can upload the images (or any other files) to the Arweave network.</p><p>In index.tsx , add the following code at the end of the file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97be745e25b821bf30dac712659ee9f8/href">https://medium.com/media/97be745e25b821bf30dac712659ee9f8/href</a></iframe><p>Now, let’s create the &lt;UploadImage /&gt; component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea66fa92951d025b677cafcbb56bf3ad/href">https://medium.com/media/ea66fa92951d025b677cafcbb56bf3ad/href</a></iframe><p>And, with this in place, we can now upload the files to the Arweave network.</p><h3>Further Improvement</h3><ol><li>Right now, we are only uploading images. We can add support for other formats as well (video, audio, anything).</li><li>Store URLs of uploaded images with wallet address in Supabase, and show the list of files previously uploaded by users when they connect their wallet.</li></ol><p>Completed code: <a href="https://github.com/Deep1144/bundlr-arweave-testnet-uploader">GitHub</a></p><pre><strong>Want to Connect?</strong></pre><pre>Connect with me on <a href="https://twitter.com/pateldeep_eth">Twitter</a> @pateldeep_eth.</pre><pre><a href="https://www.linkedin.com/in/patel-deep-dev/">Linkedin</a></pre><pre><em>Originally published at </em><a href="http://pateldeep.xyz/"><em>https://pateldeep.xyz/</em></a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18aa1506fa6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/permanent-file-storage-for-web3-apps-with-arweave-bundlr-next-js-rainbowkit-and-wagmi-18aa1506fa6e">Permanent File Storage for Web3 Apps With Arweave, Bundlr, Next.js, RainbowKit, and Wagmi</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Find Length of String in Solidity — From the Smart Contract of “ens”]]></title>
            <link>https://medium.com/better-programming/in-the-world-of-javascript-finding-the-length-of-string-is-such-an-easy-thing-just-do-str-length-4b4b33dbed09?source=rss-36b5aa8ffc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b4b33dbed09</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Deep Patel]]></dc:creator>
            <pubDate>Sat, 21 May 2022 17:01:42 GMT</pubDate>
            <atom:updated>2022-05-23T05:34:12.682Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Why bytes(str).length is not enough for getting the length of the string in Solidity — and let’s understand the strlen method from contracts of ens</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqbwcvVW3ntBjYopG73AfA.png" /><figcaption>Find length of string in solidity</figcaption></figure><p>In the world of Javascript finding the length of string is such an easy thing<br>just do str.length and that’s all.</p><p>But strings are not so friendly to work within Solidity.</p><p>In solidity, the string is a group of characters stored inside an array and stores the data in bytes.</p><p><strong>There is no length method in string type.</strong></p><p>I was going through Buildspace’s <a href="https://buildspace.so/p/build-polygon-ens">build-polygon-ens</a> project and found the link to <a href="https://gist.github.com/AlmostEfficient/669ac250214f30347097a1aeedcdfa12">StringUtils.sol</a></p><p>I knew how to find the length of the string in Solidity we can convert the string into bytes and find the length of it. So it should be as easy as doing bytes(str).length; but the method in this util file was a bit different:</p><pre>// SPDX-License-Identifier: MIT<br>// Source:<br>// https://github.com/ensdomains/ens-contracts/blob/master/contracts/ethregistrar/StringUtils.sol<br>pragma solidity &gt;=0.8.4;</pre><pre>library StringUtils {<br>    /**<br>     * @dev Returns the length of a given string<br>     *<br>     * @param s The string to measure the length of<br>     * @return The length of the input string<br>     */<br>    function strlen(string memory s) internal pure returns (uint256) {<br>        uint256 len;<br>        uint256 i = 0;<br>        uint256 bytelength = bytes(s).length;</pre><pre>        for (len = 0; i &lt; bytelength; len++) {<br>            bytes1 b = bytes(s)[i];<br>            if (b &lt; 0x80) {<br>                i += 1;<br>            } else if (b &lt; 0xE0) {<br>                i += 2;<br>            } else if (b &lt; 0xF0) {<br>                i += 3;<br>            } else if (b &lt; 0xF8) {<br>                i += 4;<br>            } else if (b &lt; 0xFC) {<br>                i += 5;<br>            } else {<br>                i += 6;<br>            }<br>        }<br>        return len;<br>    }<br>}</pre><p>It had this weird loop in code that I couldn’t understand.</p><p>So, the developer in me googled it, but all the articles I came across did this to find the length of the stringbytes(str).length; I found some similar code on Stackoverflow but no one actually explained what is happening inside.</p><pre>for(len = 0; i &lt; bytelength; len++) {<br>            bytes1 b = bytes(s)[i];<br>            if(b &lt; 0x80) {<br>                i += 1;<br>            } else if (b &lt; 0xE0) {<br>                i += 2;<br>            } else if (b &lt; 0xF0) {<br>                i += 3;<br>            } else if (b &lt; 0xF8) {<br>                i += 4;<br>            } else if (b &lt; 0xFC) {<br>                i += 5;<br>            } else {<br>                i += 6;<br>            }<br>  }</pre><p>After 3 hours of self-exploration I was able to figure it out myself (a little slow but I did it).</p><p>So I thought let’s write it down so it would be helpful for all the folks like me (not so experienced with bits, bytes 0️⃣1️⃣).</p><h3>So now, let’s try to Unblock/ Decode this</h3><h4>How bytes(str).length works</h4><p>When we convert string to bytes this is what Solidity does:</p><pre>// if we do bytes(&quot;xyz&quot;), solidity converts it as <br>xyz -&gt; 78 79 7a // 78=x, 79=y, 7a=z<br>ABC -&gt; 41 42 43 // 41=A, 42=B, 43=C</pre><p>Note: Use this <a href="https://onlinestringtools.com/convert-string-to-bytes">website</a> for converting strings to bytes.</p><p>If you see each character generates 1 byte. That’s why when we do bytes(””).length we get the length of the string,</p><p>But there are some characters for which generated bytes are more than one. For example:</p><pre>€ -&gt; e2 82 ac</pre><p>For the symbol of the Euro, generated bytes are 3.</p><p>So if we try to find the length of string which includes the symbol of Euro in it, the length returned by bytes(str).length, will not return the correct string length for this character as <strong>€</strong> there are 3 bytes generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*Zgnay75vlmYejTc1.png" /></figure><p>That’s when that for loop we&#39;ve seen above comes to the rescue.</p><p>Let’s iterate over this e2 82 ac bytes array and check what’s happening inside that loop:</p><pre>for(len = 0; i &lt; bytelength; len++) {<br>            bytes1 b = bytes(s)[i];<br>                        // b = e2 for first iteration<br>            if(b &lt; 0x80) {<br>                i += 1;<br>            } else if (b &lt; 0xE0) {<br>                i += 2;<br>            } else if (b &lt; 0xF0) {<br>                i += 3;<br>            } else if (b &lt; 0xF8) {<br>                i += 4;<br>            } else if (b &lt; 0xFC) {<br>                i += 5;<br>            } else {<br>                i += 6;<br>            }<br>  }</pre><p>For the first iteration b=e2 there is a condition on the following line:</p><pre>if(b &lt; 0x80) {<br>     i += 1;<br>}</pre><p>Let&#39;s decode this. This condition will basically compare decimal values of these hexadecimal characters:</p><pre>0x80 -&gt; 128<br>// our b is e2 at the moment, decimal value for e2 = 226<br>0xe2 -&gt; 226</pre><p>For regular characters, decimal conversion of their hex character will be &lt; 128 , like for a, it is 97</p><p>So, if we check all conditions like this:</p><pre>for(len = 0; i &lt; bytelength; len++) {<br>            bytes1 b = bytes(s)[i];<br>            if(b &lt; 0x80) { //0x80 = 128 =&gt; 226 &lt; 128 ❌<br>                i += 1;<br>            } else if (b &lt; 0xE0) { //0xE0 = 224 =&gt; 226 &lt; 224 ❌<br>                i += 2;<br>            } else if (b &lt; 0xF0) { //0xF0 = 240 =&gt; 226 &lt; 240 ✅<br>                i += 3;<br>            } <br>                        ...<br>  }</pre><p>So, now our i is 3,</p><p>so the condition in for loop will be 3&lt;3, which is false and the loop will break, and the value of</p><p>len will be 1 at the moment</p><blockquote><em>And that’s it, it is the correct value for the length of string “</em><strong><em>€</em></strong><em>”</em></blockquote><p>If you want to try some more strings like “<strong>€</strong>”, here is a small list of characters that occupies more than 1 byte:</p><pre>€ -&gt; e2 82 ac <br>Ã -&gt; c3 83<br>¢ -&gt; c2 a2</pre><p>Create, a random string anything like abc¢Ã, for example, and try it out.</p><p>Ta-Da! And now it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*GK1kMUuVdusLrWhp.png" /></figure><pre><strong>Want to Connect?</strong></pre><pre>Connect with me on <a href="https://twitter.com/pateldeep_eth">Twitter</a>: <a href="https://twitter.com/pateldeep_eth">@pateldeep_eth</a> Linkedin: <a href="https://www.linkedin.com/in/patel-deep-dev/">Linkedin</a></pre><pre>Originally published at <a href="http://pateldeep.xyz/">https://pateldeep.xyz/</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b4b33dbed09" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/in-the-world-of-javascript-finding-the-length-of-string-is-such-an-easy-thing-just-do-str-length-4b4b33dbed09">How to Find Length of String in Solidity — From the Smart Contract of “ens”</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Add Sentry to your Angular project with Graphql]]></title>
            <link>https://pateldeep-eth.medium.com/how-to-add-sentry-to-your-angular-project-with-graphql-aca015064c0c?source=rss-36b5aa8ffc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/aca015064c0c</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[sentry]]></category>
            <dc:creator><![CDATA[Deep Patel]]></dc:creator>
            <pubDate>Sun, 06 Feb 2022 06:36:49 GMT</pubDate>
            <atom:updated>2022-02-06T06:39:13.265Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Sentry.io is an external monitoring and logging service which can help you identify and triage errors in your code.</em></blockquote><p>These logs provide information such as a trace stack, breadcrumbs, and (assuming this is a web application) browser data. This can help you triage issues and resolve bugs faster, with less investigative overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHcuDvcuodC28Eu9Cp31NA.png" /><figcaption>How to Add Sentry to your Angular project with Graphql</figcaption></figure><h3>How to Create a Sentry Project</h3><p>You can follow this walkthrough doc for creating Sentry project. <a href="https://docs.sentry.io/product/sentry-basics/integrate-frontend/create-new-project/#:~:text=Log%20in%20to%20your%20Sentry,to%20create%20your%20first%20project.">Create new Sentry project</a></p><h3>How to Add Sentry to your Angular App</h3><p>Follow this amazing guide to get you up and running with Sentry’s SDK in Angular App. <a href="https://docs.sentry.io/platforms/javascript/guides/angular/">Add Sentry to Angular App</a></p><h3>How to log Graphql errors using Sentry</h3><p>Best way to handle Graphql errors is using <a href="https://www.apollographql.com/docs/react/api/link/apollo-link-error/">Error Links</a>. Error Link allow you to log both GraphQL errors (errors returned as part of the response) as well as network errors (failed requests, invalid queries, etc.).</p><p>Use the onError link to perform custom logic when a GraphQL or network error occurs. You pass this link a function that’s executed if an operation returns one or more errors:</p><p>Inside onError link we can capture Graphql errors with Sentry<br><strong>Example use would be like this:</strong></p><pre>import { onError } from &quot;@apollo/client/link/error&quot;;<br>import * as Sentry from &quot;@sentry/angular&quot;;</pre><pre>const errorHandlerLink = onError((err, ...param) =&gt; {<br>  const { graphQLErrors, networkError } = err;<br>  if (graphQLErrors)<br>    graphQLErrors.map(({ message, locations, path }) =&gt; {<br>      Sentry.captureMessage(message)<br>    }<br>  )<br>  if (networkError) {<br>    Sentry.captureException(networkError)<br>  }<br>});</pre><pre>// Using errorHandlerLink while creating apollo instance<br>apollo.create({<br>      link: errorHandlerLink.concat(httpLink.create({ uri })),<br>});</pre><p>*<em>A complete example Graphql module file *</em></p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { APOLLO_OPTIONS } from &#39;apollo-angular&#39;;<br>import { InMemoryCache } from &#39;@apollo/client/core&#39;;<br>import { HttpLink } from &#39;apollo-angular/http&#39;;<br>import { environment } from &#39;src/environments/environment&#39;;<br>import { onError } from &quot;@apollo/client/link/error&quot;;<br>import * as Sentry from &quot;@sentry/angular&quot;;</pre><pre>const uri = environment.apiEndpoint; // &lt;-- add the URL of the GraphQL server here</pre><pre>export function createApollo(httpLink: HttpLink) {</pre><pre>  const errorHandlerLink = onError((err, ...param) =&gt; {<br>    const { graphQLErrors, networkError } = err;<br>    if (graphQLErrors)<br>      graphQLErrors.map(({ message, locations, path }) =&gt; {<br>        Sentry.captureMessage(message)<br>      }<br>      )<br>    if (networkError) {<br>      Sentry.captureException(networkError)<br>    }<br>  });</pre><pre>  return {<br>    link: errorHandlerLink.concat(httpLink.create({ uri })),<br>    cache: new InMemoryCache({ addTypename: false }),<br>  };<br>}</pre><pre>@NgModule({<br>  providers: [<br>    {<br>      provide: APOLLO_OPTIONS,<br>      useFactory: createApollo,<br>      deps: [HttpLink],<br>    },<br>  ],<br>})<br>export class GraphQLModule { }</pre><p>You have now successfully integrated Sentry with your Angular project. You are now ready to start receiving error information, triaging issues, and improving your project’s stability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aca015064c0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the !! (not not) operator in JavaScript?]]></title>
            <link>https://pateldeep-eth.medium.com/what-is-the-not-not-operator-in-javascript-4cda56bc2566?source=rss-36b5aa8ffc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cda56bc2566</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[operators]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[node]]></category>
            <dc:creator><![CDATA[Deep Patel]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 03:18:45 GMT</pubDate>
            <atom:updated>2021-02-07T03:18:45.511Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is the !! (not not) operator in JavaScript?</h3><p>Converts Object to boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, true.</p><pre>!oObject  // inverted boolean<br>!!oObject // non inverted boolean so true boolean</pre><h3>Representation</h3><p>So !! is not an operator, it’s just the ! operator twice.</p><h3>Example :</h3><pre>&lt;CustomModal<br>  disabled={isDisable}<br>  title=&quot;Delete&quot;<br>  children=&quot;Are you sure you want to delete ?&quot;<br>  onCancel={() =&gt; setDataToDelete(null)}<br>  onConfirm={() =&gt; {}}<br>  show={!!dataToDelete} //show only accepts boolean<br>/&gt;;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cda56bc2566" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>