<?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 Vladislav Yaroshuk on Medium]]></title>
        <description><![CDATA[Stories by Vladislav Yaroshuk on Medium]]></description>
        <link>https://medium.com/@gr_gred?source=rss-55814727e1d0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7bitOc1WF57FYIWqNYJROQ.jpeg</url>
            <title>Stories by Vladislav Yaroshuk on Medium</title>
            <link>https://medium.com/@gr_gred?source=rss-55814727e1d0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 08:13:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gr_gred/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[How to Lose $600k After Pausing a Protocol? The Penpie Exploit Explained (September 2024).]]></title>
            <link>https://medium.com/@gr_gred/how-to-lose-600k-after-pausing-a-protocol-the-penpie-exploit-explained-september-2024-78a49250bc1c?source=rss-55814727e1d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/78a49250bc1c</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Vladislav Yaroshuk]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 07:57:53 GMT</pubDate>
            <atom:updated>2024-09-23T07:57:53.164Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OzDMgWwhz17MuSKuvn827Q.jpeg" /></figure><p>On September 3, 2024, the Penpie platform was exploited due to a reentrancy vulnerability, resulting in the theft of 11,113.6 ETH.</p><h3>TLDR:</h3><ul><li><strong>~$27.3 million</strong> was stolen.</li><li>The root cause was a reentrancy vulnerability in the claimRewards() function, allowing the attacker to execute deposits, which the system considered as rewards.</li><li>The contract was paused 20 minutes after the start of the exploit but only on one chain, leading to further exploitation on other chains.</li><li>Pendle Finance (a separate project) paused its contract, safeguarding ~$70 million that could have been drained further from Penpie.</li><li>The stolen funds were not returned, with some sent to Tornado Cash.</li></ul><h3>Transactions and Addresses:</h3><ul><li>Malicious Pendle market creation: <a href="https://etherscan.io/tx/0xfda0dde38fa4c5b0e13c506782527a039d3a87f93f9208c104ee569a642172d2">TX1</a></li><li>Attack transactions: <a href="https://etherscan.io/tx/0x56e09abb35ff12271fdb38ff8a23e4d4a7396844426a94c4d3af2e8b7a0a2813">TX2</a>, <a href="https://etherscan.io/tx/0x42b2ec27c732100dd9037c76da415e10329ea41598de453bb0c0c9ea7ce0d8e5">TX3</a>, <a href="https://etherscan.io/tx/0x663b55a1ee992603f7636ef23ff5cf19d3b261ab81494d06e218c86482df5342">TX4</a></li><li>Penpie contract pause transaction: <a href="https://etherscan.io/tx/0x85b241607ec9ca812ad764a92df01397a940e104c323d509be5e78ee70ec541f">TX5</a></li><li>Final draining on Arbitrum after the pause on Ethereum ($621k gUSDC): <a href="https://arbiscan.io/tx/0x67c5400da117b906f8c0fc5f5149e4ea10ed6358cd9ea2ec0ed8f559d757b7df">TX6</a></li><li>Negotiation message sent to the attacker: <a href="https://etherscan.io/tx/0xb62d5d6cedc06e214230803612b46691005450d0cf13087b726d88a08bd3a064">TX7</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2swlYhpkVOWGKgSb" /><figcaption>Token transfers on one of the attack transactions</figcaption></figure><h3>What Happened?</h3><p>Penpie functions as a yield-boosting layer built on top of Pendle Finance, allowing users to deposit Pendle Finance Market Tokens and earn boosted PENDLE rewards.</p><p>Two primary factors contributed to the exploit:</p><ol><li>The PendleGauge contract had a vulnerable claimRewards function that allowed re-entry, which could modify the contract’s state before the batchHarvest function finished.</li><li>Penpie automatically accepted all Pendle markets as valid pools, and since the creation of Pendle Markets, PT, and YT tokens was permissionless, the attacker exploited the system with a malicious market.</li></ol><p>By exploiting this flaw, the attacker created a fake Pendle market using a malicious SY (erc-20 token) contract and during the `batchHarvest` call the attacker made deposits to the system which were also marked as rewards.</p><h3>Attack Breakdown</h3><p>The hacker’s actions followed a specific process:</p><p><strong>Preparation:</strong></p><p>1. <a href="https://etherscan.io/tx/0x2287aa2d87b256b3d6dc79b84463911fd1c6b38b29957235d293b562e62872c4">Created</a> a ERC-20 token with the malicious claimRewards function. This token in the Penpie system is called SY.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GKlwKcJDZgo38URe" /><figcaption>PoC from DefiHackLabs</figcaption></figure><p>2. <a href="https://app.blocksec.com/explorer/tx/eth/0xfda0dde38fa4c5b0e13c506782527a039d3a87f93f9208c104ee569a642172d2?line=59&amp;debugLine=59">Called </a>createYieldContract to register this token and create 2 wrapped tokens called PT and YT, this tokens have PendlePrincipalToken format.</p><p>3. Created and then registered a fake Pendle Market using PT token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T7UFcjndnyv7jbRg" /><figcaption>Market code and execution of preparation before the attack</figcaption></figure><p>4. Minted liquidity YT and PT tokens by calling the mintPY function of the YT contract, with the amount depending on the exchange rate returned by the malicious SY contract and deposited to the fake Pendle market.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6BhizyqhnO0qf0Ss" /><figcaption>Mint of tokens</figcaption></figure><p>5. These fake PT were then deposited into Penpie and minted LPT tokens, which then deposited to the pool to get PRT tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G-LOdc91fzrNzgAf" /><figcaption>Transfers of fake tokens</figcaption></figure><p><strong>The attack:</strong></p><p>6. Used a flash loan to borrow large amounts of wstETH, sUSDe, egETH, and rswETH from Balancer, which were then transferred into the malicious SY contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-x7LsRTd8wFaDBYa" /><figcaption>Inititial flashloan on one of the attack transactions</figcaption></figure><p>7. Invoked the PendleStaking.batchHarvestMarketRewards function on the malicious Pendle Market. During this call the contract calculates how much tokens an account will receive as rewards based on balance before and after.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JHJEkmV0vit6mhzL" /><figcaption>Call to malicious Market</figcaption></figure><p>8. In the redeemRewards function of the market the updateAndDistributeRewards function is called. As you can see, the redeemRewards function even has a nonReentrant modifier, so it’s incorrect to say that this function is the root cause of the problem, as most of other media has stated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*46pPdPHEbX_Rsl_t" /><figcaption>redeemRewards function on the Market contract</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yk4bm9HEc-gyMV1b" /><figcaption>redeemRewards function calls _updateAndDistributeRewardsForTwo</figcaption></figure><p>This function then calls _updateAndDistributeRewardsForTwo function, and _updateRewardIndex function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7wNvS6kwhcsKF9b2" /><figcaption>_updateAndDistributeRewardsForTwo function calls _updateRewardIndex</figcaption></figure><p>And finally the _updateRewardIndex function calls _redeemExternalReward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SSFct5SqpePJ3-Dg" /><figcaption>_updateRewardIndex function calls _redeemExternalReward</figcaption></figure><p>Where there is a direct external call to the malicious SY contract, that is the place where magic happens!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W_w7_TDtOHYlSWmN" /><figcaption>_redeemExternalReward function calls claimRewards, where attacker reenters</figcaption></figure><p>9. In the claimRewards function it’s possible to re-enter batchHarvest function execution flow and start depositing flashloned funds into the pools, to inflate the reward calculation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g3ox6USqHlsHqOAm" /><figcaption>Attack flow after claimRewards call</figcaption></figure><p>And with the each addLiquiditySingleTokenKeepYt and depositMarket call all flashloned tokens are deposited to the markets and corresponding LPT tokens are minted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*poVeMNwwjzk9AA-r" /><figcaption>Inflated balance of the Markets</figcaption></figure><p>You can see how the balance has changed after depositing funds to the pools:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wcaoZPW6gNIO4jn7" /><figcaption>Inflated balance of the Markets</figcaption></figure><p>9. These newly deposited market tokens in the Penpie pool are now double-accounted and considered to be rewards, since the batchHarvestMarketRewards function takes a difference of the balance before and after redeemRewards call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fGH8q1lNfFu5MRLy" /><figcaption>Contract double accounts deposit funds as rewards</figcaption></figure><p>10. Since the attacker was the only depositor in this fake Pendle Market, he was able to claim all rewards using multiclaim function of the MasterPenpie contract to withdraw these LPT tokens from the Rewarder contract.</p><p>11. Finally, the attacker used the withdrawMarket function of the PendleMarketDepositHelper contract to burn the deposited PRT tokens, redeem the market tokens, and remove the liquidity along with the rewards obtained in the previous step, draining the pool.</p><p>12. Finally returned the flash loan and keep the profits.</p><h3>Incident Response</h3><p>The first attack on Penpie started at <strong>6:23 PM UTC</strong> on Ethereum. By <strong>6:45 PM UTC</strong>, Pendle successfully paused its platform on Ethereum, considered a fast response time by today’s web3 standards. However, Penpie did not know the attack was occurring until Pendle informed them at <strong>7:00 PM UTC</strong>.</p><p>The attacker stole an additional <strong>$621k gUSDC</strong> on Arbitrum at <strong>7:14 PM UTC</strong>, since the protocol had only been paused on Ethereum. By <strong>7:19 PM UTC</strong>, Pendle fully paused its Arbitrum platform, but it wasn’t until <strong>7:38 PM UTC</strong> that Penpie paused its protocol across all chains.</p><p>This is very sad to see that both teams even despite noticing attack early and pausing protocol due to lack of planning for counteracting measures has lost additional 600 k $ of users funds just because they haven’t thought of pausing other chains.</p><h3>Penpie Audit History</h3><p>Even though all of the code has been audited by multiple audit firms, and the project has never suffered any exploits before that. So how could this happen?</p><p>When Penpie launched in June 2023, its contracts underwent two audits, one by Zokyo and another by WatchPug. While Zokyo didn’t flag any issues with the PendleStakingBaseUpg:batchHarvest function, WatchPug noted a concern about reward distribution. Specifically, the redeemRewards function allowed rewards to be claimed on behalf of any user, which was fixed by adding manual reward distribution. Neither audit mentioned reentrancy protection, likely because, at that time, only the Penpie team’s multisig could register new Pendle Markets, minimizing reentrancy risks from malicious contracts. And this makes sense, since as an auditor you don’t really want to ask to add more protections to functions, consuming more user gas, since there is no possible way of exploitation, because the market is a trusted actor of the system. For this case a finding which asks for more reentrancy protection will be a feature request, which is not the greatest practice, but still would be a good info finding or a note.</p><p>In May 2024, Penpie introduced permissionless pool registration, allowing anyone to register Pendle Markets, provided they were already listed on Pendle Finance. This means that the vulnerability were hiding for almost 3 months. This change was audited by AstraSec, a separate firm, but since the PendleStakingBaseUpg contract hadn’t been significantly altered since the earlier audits, it wasn’t included in AstraSec’s scope. So if the contract is out-of-scope, this means that AstraSec also can’t be blamed for missing this issue. So I would say that rekt.news is wrong by putting Watch Pug and Zokyo on the leaderboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*L4SkaVpfNfC-DWr1" /><figcaption>Rekt news leaderboard</figcaption></figure><p>The full audit reports can be found here:</p><ul><li><a href="https://github.com/magpiexyz/audit/blob/main/Penpie/WatchPug_V1.pdf">Penpie V1 Zokyo Audit Report</a></li><li><a href="https://github.com/magpiexyz/audit/blob/main/Penpie/Zokyo_V1.pdf">Penpie V1 WatchPug Audit Report</a></li><li><a href="https://github.com/astrasecai/audit-reports/blob/main/AstraSec-AuditReport-Magpie-Penpie.pdf">AstraSec Incremental Audit Report</a></li></ul><p>And such cases has already occurring in web3 sec space, when there was found a<a href="https://blog.lido.fi/vulnerability-response-update/"> frontrunning vulnerability of deposits in Lido protocol</a>, which has been submitted to the Immunefi, which has been missed by all auditors, since the official beacon chain deposit contract has never been added to the scope. So, in cases like that Penpie either should spent more money and had a full scope of files, or had a bug bounty program, which could have had a chance to minimize amounts of lost funds from tens of millions to just millions.</p><p>In the war of white hats and black hats, the black hats always have an advantage, they all the scope, all the state, as well as all the time in this world to try to find a vulnerability, as well as with the time the web3 sec space is developing, there appearing new ways of exploitation, however audits are made only once at a time with the fixed scope and limited time.</p><h3>What Can We Learn from This Exploit?</h3><ul><li><strong>Protocols should have a counter-exploit plan</strong>: Even with pausing mechanisms in place, the inability to act fast across multiple chains led to further losses.</li><li><strong>Be cautious when calling external contracts</strong>, especially if they can be permissionlessly created and controlled by anyone.</li><li><strong>Limited audit scopes can leave hidden vulnerabilities</strong>: It’s crucial to consider all potential risks, even if certain contract changes seem minor.</li><li><strong>Bug bounty programs can catch overlooked issues</strong>: Proactively inviting white-hat hackers to find vulnerabilities can prevent massive losses and save tens of millions of dollars.</li><li><strong>Audits should mention informational issues</strong>: It’s okay to note in your audit report informational issues and notes, because sometimes developers of the protocols can make wrong assumptions about their system, thinking it’s safe in all the cases, even when one of the actors of the system is malicious.</li></ul><p><strong>Thanks for reading! Follow my </strong><a href="https://t.me/kotyaSec"><strong>Telegram channel</strong></a><strong> for more insights into web3 security!</strong></p><h3>Link References:</h3><ul><li><a href="https://x.com/peckshield/status/1831072098669953388">Peckshield</a></li><li><a href="https://x.com/AnciliaInc/status/1831080555292856476">AnciliaInc</a></li><li><a href="https://x.com/hackenclub/status/1831383106554573099">HackenClub</a></li><li><a href="https://x.com/Penpiexyz_io/status/1831462760787452240">Penpie Post-Mortem</a></li><li><a href="https://slowmist.medium.com/slowmist-incident-analysis-penpie-hack-e6157975898f">SlowMist Incident Analysis</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78a49250bc1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Li.Fi Exploits Explained: The Same Mistake Twice]]></title>
            <link>https://medium.com/@gr_gred/li-fi-exploits-explained-the-same-mistake-twice-b46b1b9b4610?source=rss-55814727e1d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b46b1b9b4610</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Vladislav Yaroshuk]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 11:00:52 GMT</pubDate>
            <atom:updated>2024-08-12T11:00:52.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cbhmJSO7BpAH9xIz" /><figcaption>Image generated by DALLE.</figcaption></figure><p>On July 16, 2024, five days after adding a new smart contract facet, the LI.FI contract experienced an exploit.</p><p><strong>TLDR:</strong></p><ul><li>The total amount stolen is estimated to be around $11.6 million.</li><li>A vulnerability in the newly deployed facet allowed the attackers to steal funds from users who had set infinite token approval for the LI.FI contract.</li><li>The attack occurred on Ethereum and Arbitrum, impacting 153 wallets.</li><li>Assets drained included USDC, USDT, and DAI.</li><li>A very similar exploit occurred with Li.Fi in March 2022.</li></ul><p><strong>Transactions and addresses related to the July 2024 exploit:</strong></p><ul><li><a href="https://github.com/lifinance/contracts/pull/700">New feature that was still in development</a>.</li><li><a href="https://etherscan.io/tx/0xd82fe84e63b1aa52e1ce540582ee0895ba4a71ec5e7a632a3faa1aff3e763873">Attack transaction</a>.</li><li><a href="https://etherscan.io/address/0xf28A352377663cA134bd27B582b1a9A4dad7e534">Facet on Ethereum</a>.</li><li><a href="https://arbiscan.io/address/0xf28A352377663cA134bd27B582b1a9A4dad7e534">Facet on Arbitrum</a>.</li><li><a href="https://etherscan.io/tx/0x73608c1b348e5673c24912d44817672265c8d4c5e5583dd4f8288f938483de4c">Deployment of the Dummy implementation</a>.</li><li><a href="https://etherscan.io/address/0x4a3760ac5a8364ee1ab26b08ebdf80804747bebe#code">Dummy implementation</a>.</li><li><a href="https://etherscan.io/address/0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae#code">Diamond proxy</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dytYhH8e1kipkvEu" /><figcaption>Token transfers in one of the attack transactions of July 2024 exploit.</figcaption></figure><p><strong>What Happened?</strong></p><p>On July 16, 2024, the LI.FI protocol experienced a security breach for the second time in the project’s history. The root problem in both cases was the arbitrary call to arbitrary contracts in the same library. How is it possible to make the same mistake twice? To understand that, we will dive deep into what Li.Fi is, how it operates, and investigate both exploits, along with what Li.Fi protocol has done to mitigate them. I have been working together with the Li.Fi team when I was a smart-contract developer at the Cross-chain aggregator, so I have a good understanding of the protocol’s architecture.</p><p><strong>What is Li.Fi?</strong></p><p>Imagine you are a true decentralization enthusiast and need to transfer a token from one chain to another without using a CEX, going through KYC, depositing, swapping, and withdrawing… It sounds too complicated; you need something decentralized that allows you to do everything in one click. Your main option is to use a cross-chain bridge. You have a $15 worth of meme token with a multi-billion capitalization and expect everything to be easy. You visit the first bridge, the second, the third… and in all cases, you see an error message: “Your token is not supported” or “There is no liquidity in the pool for the provided token.” Why does this happen? Bridges usually have a limited quantity of tokens that users can transfer between chains because they want as much liquidity as possible for bridging to allow large amounts of funds to be passed from one chain to another. If your token is missing in the bridge liquidity pools, you can’t bridge funds. Usually, those tokens in the bridge pool are stablecoins, so no chance to bridge your meme token, fren.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*GGs6nLWAGHL51J-c" /></figure><p>Since you are a decentralization enthusiast, this isn’t a problem for you. You will use DEX to swap your token into another token supported by the bridge. You start opening different DEXs on this chain. However, some of them don’t have a pool with this token; others have a very small amount of tokens in reserves, so you execute a swap and lose 40% of your token’s value. Some DEXs work so poorly that you can’t even open the swapping interface. Finally, you decide to execute a swap with a 40% loss, receiving 9 stablecoin tokens in return. Then you return to the bridge only to see the new error message: “Minimum Bridging amount is $10.” The world of crypto is fascinating, with so many ways to receive an error message!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/0*FXOKd0KGf5kdLEjk" /><figcaption>Example of the not supported token.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/0*ykvSBvK8UVoXEKhE" /><figcaption>Example of the big price impact.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g0HRN6l2op-PXmjg" /><figcaption>Example of the minimum amount error.</figcaption></figure><p>To solve these problems, DEX aggregators were invented to provide the best routes under one interface. Cross-chain bridges started to use DEX aggregators to allow users to bridge any token to any token (aggregating different DEX aggregators under one interface). The first cross-chain aggregators aggregated the cross-chain bridges to offer a wider choice. Li.Fi wasn’t the first cross-chain aggregator, but it aggregated all other cross-chain aggregators, becoming <strong>the ultimate Aggregator of Aggregators of Aggregators of Aggregators.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/0*-aW9-LeWsGKIz2Jm" /></figure><p><strong>Li.Fi’s Architecture</strong></p><p>Li.Fi protocol utilizes the diamond proxy pattern. This means there is one general proxy contract with which all users interact, and multiple implementations, called facets, are delegate-called by the proxy. Since smart contracts are limited in bytecode size, it would be impossible to fit all these integrations into one contract. For some protocols, Li.Fi has just a call with arbitrary data, but for most protocols, it implements its own facet and calls the provider with the interface. At the time of writing, there are 46 different facet implementations for various protocols. Li.Fi integrates not only the aggregators but also the protocols integrated by the aggregators, meaning Li.Fi has integrated several protocols twice to get better rates and faster response times for calculating orders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7nZG2lcfaRwetZVQ" /><figcaption>Illustration, which shows that Li.Fi integrates each project natively.</figcaption></figure><p>Could you imagine that there are 46 different facets calling providers by the interface? Additionally, a big list of protocols is integrated by calling them directly with encoded data, and all of that is multiplied across 20 networks. What a giant beast! Just look at the deployments <a href="https://github.com/lifinance/contracts/tree/main/deployments">folder</a>; there are hundreds, if not thousands, of Li.Fi contracts deployed across numerous networks. Imagine how hard it is to keep up with all of that, set everything up, configure, and operate. However, Li.Fi does a great job. The final product is great, with the best exchange rates, a simple interface, and no fees. This is why I personally love Li.Fi.</p><p><strong>Security Problems in Li.Fi Architecture</strong></p><p>The main security problem in this architecture is that Li.Fi integrates not only the bridge’s logic but also enhances all security problems related to the protocols, such as the <a href="https://x.com/lifiprotocol/status/1661777403478257676?s=20">Multichain incident</a>. Li.Fi is a third party; if something goes wrong with the provider, the Li.Fi protocol becomes part of the issue. Because of this, Li.Fi needs to monitor what is happening in the web3 space and ensure their routing is correct and sound. For now, I haven’t heard about major incidents related to third-party problems. But that’s more about the Li.Fi SDK, which searches for the best routes and builds data. What about smart contracts?</p><p>On the smart-contract level, it’s important that the contract logic works the same on all networks with different EVMs. There should be validations of the contracts regarding where the call goes, what selector it executes, user slippage protection, approval to the provider contract, and correct event logging. Unfortunately, there have already been two exploits of the Li.Fi contracts.</p><p><strong>March 2022 Exploit</strong></p><p>On March 20, 2022, the Li.Fi protocol operating on the Ethereum blockchain was exploited due to the implementation of the pre-bridge swap feature. This feature allowed users to pass an array of multiple swaps using any address with arbitrary calldata, providing maximum flexibility in selecting decentralized exchanges (DEXs) and methods to call. However, this flexibility also introduced a severe risk: it enabled anyone to call other contracts, not just DEXs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YFqWSP4eeKtnWBYo" /><figcaption>Vulnerable code for the 2022 exploit.</figcaption></figure><p>The attacker started the hack by making a legitimate swap, exchanging a small amount of 50 USDT to USDC. Following this, they made multiple direct calls to various token contracts. By calling the transferFrom method, the attacker transferred funds from users&#39; wallets that had previously granted infinite approval to the Li.Fi contract for specific tokens. This allowed the attacker to bypass typical restrictions and transfer these funds directly to their address.</p><p>The Hacker:</p><ol><li>Called the swapAndStartBridgeTokensViaCBridge function, starting the legitimate swap of 50 USDT to USDC.</li><li>Called token addresses directly, executing transferFrom from users who had given excessive allowance to the contract, transferring funds to their address.</li><li>Successfully completed the bridge of 50 USDC.</li></ol><p>This breach resulted in a financial loss of $600,000 for the Li.Fi protocol. In response, Li.Fi returned these funds from their own pocket to the users.</p><p>To prevent future incidents, Li.Fi implemented mitigation strategies and underwent several audits:</p><ul><li>Introduced a contract whitelist to ensure only approved contracts could be interacted with, limiting unauthorized contract calls.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CmH4zCbBrgghXXkt" /><figcaption>Contract address whitelist.</figcaption></figure><ul><li>Implemented a selector whitelist, restricting the functions that could be called to a vetted list.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dzP2nMbhhoUAGkzj" /><figcaption>Function selector whitelist.</figcaption></figure><ul><li>Disabled infinite approvals by default on the UI, requiring users to explicitly approve the exact amount for each transaction, preventing excessive allowances that could be exploited.</li></ul><p>These fixes were significant. 46 facets across 20 networks required the correct configuration with the selector and contract whitelist. That’s thousands of addresses that needed reviewing and configuring on the facets, an enormous job that some projects like Li.Fi have <a href="https://x.com/peckshield/status/1606937055761952770">failed at and been hacked for.</a></p><p><a href="https://blog.li.fi/20th-march-the-exploit-e9e1c5c03eb9">Official post-mortem</a>.</p><p><strong>July 2024 Exploit</strong></p><p>On July 11th, a <a href="https://etherscan.io/tx/0x058ffc047f2c621991c65facf62073848433e6a50b4673db59179cb018e91dc2">new contract facet</a>, <a href="https://etherscan.io/address/0xf28A352377663cA134bd27B582b1a9A4dad7e534#code">GasZipFacet</a>, was added to the Li.Fi protocol, adding functionality to swap ERC20 tokens to native and deposit them to the <a href="https://www.gas.zip/">gas.zip</a> protocol. The Li.Fi team had done this many times before, but this time it went wrong.</p><p>Based on the <a href="https://github.com/lifinance/contracts/pull/700/commits">GitHub pull request</a>, development started on May 2nd, giving more than two months for development before deployment, a reasonable amount of time. The mistake was not due to limited development time. The information about the audit is not available, but I believe this code wasn’t reviewed by external security engineers, especially since Li.Fi has never posted anything related to the facet’s audit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RPWXrOj00TFRUGwl" /></figure><p>On July 16, 2024, at 12:04:47 PM UTC, five days after adding GasZipFacet, this facet was exploited, leading to a loss of around $11.6 million. The attack occurred on Ethereum and Arbitrum, impacting 153 wallets. Assets drained included USDC, USDT, and DAI. The vulnerability was limited to infinite approvals and did not affect finite approvals.</p><p>From the official <a href="https://li.fi/knowledge-hub/incident-report-16th-july/">post-mortem</a>, we see that the root cause was within the LibSwap library, allowing arbitrary calls to arbitrary contracts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HI92skSq9hwOGg-x" /><figcaption>The picture with the code in the post-mortem has a very poor quality.</figcaption></figure><p>So, the root problem of the exploit was usage of the LibSwap library directly in both exploits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W3jooHJuowMJNFdr" /><figcaption>Comparison of the vulnerable code in 2022 and 2024 exploits.</figcaption></figure><p>The attack flow in 2024 was the same as in 2022. Li.Fi now had a whitelist of contracts and selector whitelist, but these validations were in the <a href="https://github.com/lifinance/contracts/blob/1faf3c830929d5c6a58426be805b0e4cbf119b7d/src/Helpers/SwapperV2.sol#L283-L285">Helpers folder</a> in the SwapperV2 contract and missing in the LibSwap library. The developers imported the wrong contract during development, and the missing audit of the new facet led to the hack.</p><p>Calling the swap function of the LibSwap library without validation is dangerous in many ways. For example, this function grants infinite approval from the Li.Fi contract to any address, allowing the theft of tokens from the Li.Fi token balance to the attacker’s contract. However, Li.Fi doesn’t store any tokens on it’s address, as well as it doesn’t much a lot since right after that there is an arbitrary call to any address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jKzueT568S_J74vA" /><figcaption>Vulnerable swap implementation in <a href="https://etherscan.io/address/0xf28A352377663cA134bd27B582b1a9A4dad7e534#code">GasZipFacet</a>.</figcaption></figure><p>Although, this approve call is important in the attack flow. Li.Fi contract will deposit only the amount of tokens, which it has received after the swap call:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uRxZr9Pgofxo59gD" /><figcaption>Calculation of the amount of tokens to send in <a href="https://etherscan.io/address/0xf28A352377663cA134bd27B582b1a9A4dad7e534#code">GasZipFacet</a>.</figcaption></figure><p>And in the GasZip provider contract there is a validation, that the deposit amount can’t be zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YdjvQCVbC3DnLBSu" /><figcaption>Deposit implementation in the GasZip provider.</figcaption></figure><p>So, since there is only one arbitrary call, if you will call the token contract directly, you will be able to transfer tokens from the victim to your address, however the native balance on the Li.Fi contract will not increase and it will remain 0, leading to the revert. Because of that the hacker used that approve call to call his own address and add native tokens to the Li.Fi contract.</p><p><strong>The Hacker:</strong></p><ol><li>Called the depositToGasZipERC20 function, passing arbitrary transferFrom data and assetId as the attacker’s contract.</li><li>During the approve call to the hacker’s contract, a new contract was deployed and self-destructed, increasing the Li.Fi contract’s balance by 1 wei.</li><li>Executed the call from the facet to the token addresses, calling transferFrom from users who had given excessive allowance to the contract, transferring tokens to their address.</li><li>Finished the transaction with the successful deposit of 1 wei.</li></ol><p><strong>Incident Response</strong></p><p>On July 16, 2024, at 07:08:59 AM UTC, almost 5 hours after the exploit, the team activated the incident response plan, successfully disabling the vulnerable facet across all chains. They replaced the vulnerable facet with the <a href="https://etherscan.io/address/0x4a3760ac5a8364ee1ab26b08ebdf80804747bebe#code">dummy implementation</a>, removing the threat:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qP6oi05ZWQmO-9wm" /><figcaption>Deployed dummy implementation.</figcaption></figure><p>This is a good example of how to easily pause an attack, limiting funds at risk.</p><p><strong>Lessons Learned from the Second Exploit</strong></p><p>In the post-mortem, Li.Fi stated: “The incident was caused by an individual human error in overseeing the deployment process. To prevent such incidents going forward, we have started to completely reassess our deployment review process.”</p><p>I agree that individual human error was present in this exploit by importing and utilizing the incorrect library and forgetting the proper configuration of whitelists and selectors. However, it’s more about the development process than the deployment process. A technical task for the developer should be created, then the developer implements it, adds proper test coverage, the code undergoes an audit, and then the contract is deployed with the right configuration.</p><p>From the latest exploit, we see there was not enough test coverage checking for possible incidents, no audit report, and no proper configuration. We should learn that:</p><ul><li>Contracts must be audited. It’s also would be a great practice to have a full time security engineer in the team.</li><li>The repo must have good test coverage to ensure secure code delivery.</li><li>Any written code which goes to production should be cross-checked and reviewed.</li><li>Add documentation to the code, specifying how to use libraries securely, there was no documentation in the hacked library.</li><li>Teams must prepare an incident response to be ready for any circumstances.</li><li>A contract should have a blacklist of function selectors/addresses.</li><li>All contracts of big protocols are always monitored by bad actors. For example, a <a href="https://t.me/tdly_audit_alerts">Telegram channel</a> posts new updates of proxy contracts. If there is vulnerable code in a big project, it will most likely be exploited. It can take 40 minutes, as happened with the <a href="https://medium.com/@gr_gred/the-ronin-hack-explained-august-2024-5415495acc08">Ronin bridge hack</a>, or 5 days.</li><li>Don’t make infinite approvals. Revoke your existing approvals using <a href="https://revoke.cash/">revoke.cash</a>.</li></ul><p>Thanks for reading! Follow my <a href="https://t.me/kotyaSec">Telegram channel</a> for more insights into web3 security!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b46b1b9b4610" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ronin Hack Explained (August 2024)]]></title>
            <link>https://medium.com/@gr_gred/the-ronin-hack-explained-august-2024-5415495acc08?source=rss-55814727e1d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5415495acc08</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Vladislav Yaroshuk]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 17:11:12 GMT</pubDate>
            <atom:updated>2024-08-06T17:11:12.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*w1GuzWoO2NQnm3-r.jpg" /><figcaption>Image is created by DALLE.</figcaption></figure><h3>The Ronin Hack Explained (August 2024)</h3><p>On August 6, 2024, the Ronin bridge experienced a smart contract exploit several hours after an implementation update.</p><p><strong>TLDR:</strong></p><ul><li>~$12 million was stolen.</li><li>Users don’t need to take any action; no approval revokes are necessary.</li><li>The root cause was a failure to properly `initialize` the operator weight configuration required for cross-chain transaction confirmation during the contract upgrade. The `minimumVoteWeight` parameter was set to zero, allowing any signature to pass cross-chain verification.</li><li>The contract was paused approximately 40 minutes after the incident, and no future exploitation is expected.</li><li>The attack transaction was front-run by MEV bots, which appeared to be white-hats. The project stated: “We are currently negotiating with the actors, who appear to be acting as white-hats and have responded in good faith. Regardless of the result of the negotiations, all user funds are safe and any shortfalls will be re-deposited into the bridge when it opens up.”</li><li><a href="https://x.com/Ronin_Network/status/1820846361945792751">The Ethereum tokens were returned in full</a>, and USDC tokens will be returned. The bounty for the white-hats is $500,000.</li></ul><p><strong>Transactions and addresses:</strong></p><p>Frontrunned <a href="https://etherscan.io/tx/0x2619570088683e6cc3a38d93c3d98899e5783864e15525d5f5810c11189ba6cb">attack transaction</a>.</p><p>Update <a href="https://upgradehub.xyz/diffs/etherscan/0x64192819ac13ef72bf6b5ae239ac672b43a9af08?selected=4">Diff</a>.</p><p><a href="https://etherscan.io/tx/0x855dd3b1194e3b889f4667b6a0996220e350e034d35d3eab29b4f23bc205767e">Pause transaction</a> from the Ronin team.</p><p><a href="https://etherscan.io/tx/0x855dd3b1194e3b889f4667b6a0996220e350e034d35d3eab29b4f23bc205767e">Transaction with the update</a> of implantation.</p><p><a href="https://etherscan.io/address/0xfc274ec92bbb1a1472884558d1b5caac6f8220ee#code">Implementation</a> to which the proxy has been updated.</p><p><a href="https://etherscan.io/tx/0xf8f097982bc0f9a8f4279d4132dc91cfe17ab2d4fc70e7f740bc3ed752165601">Funds were moved back to the </a>Ronin team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2pzD1wrSqkrK63wr" /><figcaption>Screenshot from the etherscan of the attack transaction.</figcaption></figure><h3>What Happened?</h3><p>On August 6, 2024, the Ronin protocol was exploited for $12 million. This is the second hack of the protocol, and currently, the Ronin bridge remains at the top of the Rekt leaderboard, even without considering this exploit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*93CxIySyIWCT_wEA" /><figcaption>Rekt leaderboard.</figcaption></figure><p>The previous post mortem can be <a href="https://rekt.news/ronin-rekt/">found here</a>.</p><p><strong>STEP 1. The Update.</strong></p><p>The Ronin bridge uses the Transparent Upgradable Proxy pattern, needed for updating protocol implementation and changing the logic if needed. This contract implements a proxy that is upgradeable by an admin. The Ronin protocol uses a multisig for updating purposes, and the update can only be initiated by the governance of the protocol (though I couldn’t find a proposal on the <a href="https://app.roninchain.com/governance?t=bridge">governance page</a>).</p><p>On August 6, 2024, at 08:48:47 AM UTC, the Ronin team updated their implementation. From this transaction, we see that the Ronin team updated their proxy twice, moving the version of the proxy from 2 to 4. Looking into the new implementation, it becomes clear that two separate initialize functions were added:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yrtqq1CtG5dLvi9_" /><figcaption>State changes in the update transaction.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LA0pxgMzUdd1FTOX" /><figcaption>New implementation.</figcaption></figure><p>However, in the update transaction flow, only the `initializeV4` function was called, bypassing the `initializeV3` function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*42eFeWWDbpI6qfxj" /><figcaption>Invocation flow in the update transaction.</figcaption></figure><p>Due to incorrect proxy initialization in the update transaction, the `_totalOperatorWeight` variable was left uninitialized and equaled zero. Previous versions of the Ronin Bridge fetched totalWeight from the MainchainBridgeManager contract, so this was why `_totalOperatorWeight` should have been reinitialized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*H1re1_2cEeoFL9j2" /></figure><p>This led to the contract’s exploitation. The hacker discovered that the team forgot to initialize one of the functions, causing the contract to be set up incorrectly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*b9-C0L5rlJT1bdfc" /></figure><p><strong>STEP 2. The Exploit.</strong></p><p>At 9:37:23 AM UTC, only 48 minutes after the update, the attack transaction was executed. Based on <a href="https://x.com/BeosinAlert/status/1820795419905110469">existing analyses</a>, in the `_submitWithdrawal` function, there is a check that the signer of the withdrawal must have enough weight to withdraw funds from the contract. This function is expected to be executed by the Ronin team’s executor, where the transaction must be signed by a set of validators, each with a special weight, and in total, the weight must exceed the `minimumWeight` threshold. Apparently, the `minimumWeight` is zero, so this check always passes for anyone, meaning anyone can withdraw any amount of funds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Py6PiCjQF6AdOrJv" /><figcaption>`_submitWithdrawal` in the new implementation.</figcaption></figure><p>This is precisely what happened in the attack transaction. The MEV bot found this exploit transaction in the pool, changed the address receiving funds from the attacker’s credentials to its own, and front-ran the transaction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wjY5MACjV0WkCogI" /><figcaption>`_submitWithdrawal` in the new implementation.</figcaption></figure><p>The hacker succeeded in stealing 4,000 Ethereum tokens from the Ronin bridge contract, while 28,270.65 ETH tokens, worth about $72 million, were left on the contract even after the attack. The hacker was unable to steal these funds due to a daily withdrawal limit, which saved the additional $72 million tokens from being stolen — an excellent example of best security practices in the code.</p><p><strong>STEP 3. The Pause.</strong></p><p>At 10:15:23 AM UTC, around 38 minutes after the exploit, the contract was paused, and an investigation began. SEAL 911 assisted the Ronin team with the return of funds process. Eventually, the Ethereum tokens were returned, and a bounty of $500,000 was announced.</p><p><strong>What Can We Learn from This Exploit?</strong></p><ol><li>Always implement tests for upgrading your contracts.</li><li>Collaborate with auditors to verify the correct deployment.</li><li>Be careful with the `Initializable` contract from OpenZeppelin:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R4GA07rLaxDBpziY" /><figcaption>Initializable contract.</figcaption></figure><p>The Ronin team used the version of the Initializable contract last updated in `v4.7.0`, but for the `reinitializer` function, it still works the same. The contract checks that the next version to which it will be updated is higher than the current, but there are no checks that versions in the reinitializer calls must go one after another. If the Ronin team had known about this flaw, the problem could have been avoided. Even if they tried to initialize the v4 version directly, forgetting about the v3 initializer, the call would have reverted.</p><p>Thanks for reading! <a href="https://t.me/kotyaSec">Follow my Telegram channel</a> for more insights into web3 security!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5415495acc08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Bugs and Features of Solidity Compiler Versions: A Guide for Smart Contract…]]></title>
            <link>https://blog.oxor.io/exploring-the-bugs-and-features-of-solidity-compiler-versions-a-guide-for-smart-contract-fe04e852ea64?source=rss-55814727e1d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe04e852ea64</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Vladislav Yaroshuk]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 10:17:07 GMT</pubDate>
            <atom:updated>2023-05-09T13:32:21.083Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Exploring the Bugs and Features of Solidity Compiler Versions: A Guide for Smart Contract Developers</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6kZjIpXNM-JrXemqZZsa0w.png" /></figure><p>Solidity is an open-source programming language widely used to create smart contracts on blockchain platforms such as Ethereum. This article will examine some of the bugs and features introduced in three different major Solidity compiler versions in order to see how they impact contract security.</p><p>Solidity is a rapidly evolving programming language that has seen many changes and updates since its inception. As with any programming language, it is not unusual to encounter bugs or have features that are introduced or changed with new compiler versions. However, the stakes are much higher with smart contracts since any coding errors or security vulnerabilities can result in the loss of valuable digital assets. Therefore, it is essential that developers that use Solidity pay close attention to the updates and changes in each new compiler version to ensure their smart contracts remain stable and secure.</p><p>This article takes a closer look at three recent Solidity compiler versions: 0.4.24, 0.6.12, and 0.8.9. We explore some of the bugs that have been identified and fixed in each of these versions, along with the features that have been added.</p><p>To illustrate these concepts in a real-world context, we examine smart contracts of Lido finance that have been affected by bugs introduced in these three Solidity compiler versions. By analyzing these case studies, we hope to provide valuable insights into how Solidity developers can avoid potential issues and ensure the stability and security of their smart contracts.</p><p>The best way to understand which bugs are present in a particular Solidity compiler version is to read the release notes and the changelog provided by the Solidity team. These documents typically contain a list of all the bugs that have been identified and fixed, as well as all the new features or changes that have been implemented.</p><p>In addition to reading the release notes, you can also search through the Solidity issues on GitHub to see if any additional bugs have been reported but not yet addressed. Additionally, software testing and auditing tools like Slither or Echidna can help to identify potential bugs in your code when working with a specific Solidity compiler version.</p><p>It is also essential to keep up-to-date with the latest news and developments in the Solidity community, as other developers or security researchers may report new bugs. Finally, it is always a good practice to thoroughly test and audit your smart contract code before deploying it to a production environment, as it can help to identify any potential bugs before they become a problem.</p><p><strong>Features</strong></p><p>There are a lot of different language “features” that are not clear to developers, and sometimes these problems can lead to different bugs and exploits. Unfortunately, there is no proper documentation for all problems, and you can learn about them only in practice. For example, such issues as integer overflow may be related to Solidity’s specific feature on compiler versions before the 0.8.0 release, however as this is a well-known fact, it won’t be covered in this article. Instead, it focuses on different, less popular, but still very interesting features.</p><p><strong>1. </strong><strong>Try/catch feature.</strong></p><p>Consider the following code, which calls the _to address, the recipient of the NFT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jqzpG9yH6dFH31dy" /></figure><p>This code looks safe, and developers may think that transaction can’t revert in try/catch block (spoiler: try/catch doesn’t catch a lot of cases).</p><ul><li>Try/catch returns a proper retval of an external address.</li><li>Try/catch properly catches revert in the external onERC721Received method.</li></ul><p>But…</p><ul><li>Try/catch <strong>crashes</strong> if a non-existent address is called (e.g. address(0)) (In this example, it’s protected with _to.isContract).</li><li>Try/catch <strong>crashes</strong> if the target contract doesn’t have that method.</li><li>Try/catch <strong>crashes</strong> if the target contract returns a wrong number of arguments.</li></ul><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4bdd735d7181a91b9460df1dfffcd68/href">https://medium.com/media/c4bdd735d7181a91b9460df1dfffcd68/href</a></iframe><p><strong>2. Interface inheritance breaks the layout.</strong></p><p>Let’s look at the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6001d886697353cdb93bf7acf0c1c576/href">https://medium.com/media/6001d886697353cdb93bf7acf0c1c576/href</a></iframe><p>The expected layout in this snippet is as follows:</p><ul><li>V1: p11, p12</li><li>V2: p11, p12, p21, p22</li></ul><p>But compiling the code above gives the following storage layouts:</p><ul><li>V1: p11, p12</li><li>V2: p21, p11, p12, p22</li></ul><p>When ITest is removed from P22, the layout is generated as expected.<br>This effect depends on the position of interfaces on the inheritance list, especially for contracts with complex compositions.</p><p><strong>3. </strong><strong>Immutables may not be initialized.</strong></p><p>When trying to compile a contract in which the constructor does not initialize an immutable state variable, the compiler outputs:</p><p>TypeError: Construction control flow ends without initializing all immutable state variables.</p><p>By embedding the initialization of such a variable in a for loop so that the control flow never reaches the initialization instruction, it is possible to compile a contract that does not initialize an immutable.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abda41e7034e6c525b722c6312df52c5/href">https://medium.com/media/abda41e7034e6c525b722c6312df52c5/href</a></iframe><p><strong>4. </strong><strong>Staticcall feature.</strong></p><p>The staticcall returns false when the call goes to the contract with a non-existent interface or when the function reverts. When calls go to the EOA address — a staticcall will always return true.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/070fc985634900e0557929ce271e2cf5/href">https://medium.com/media/070fc985634900e0557929ce271e2cf5/href</a></iframe><p>This behavior is expected for a call because you can call an EOA address and send value to it. But with the staticcall, the call to an EOA address doesn’t make any difference. So if you have staticcalls in your contract — be sure that you are calling the contract since the success variable will always be true.</p><p><strong>5. </strong><strong>Permit feature.</strong></p><p>Interface call won’t revert to a non-existent function if the call goes to the contract with an old compiler version (e.g. 0.4.X).</p><p>For example, WETH contract does not have a permit()<em> </em>function.<strong> </strong>But it does have a <a href="https://www.geeksforgeeks.org/solidity-fall-back-function/#:~:text=The%20solidity%20fallback%20function%20is,plain%20Ether%20without%20any%20data.">fallback function</a> that is called when a function is called but not found. WETH’s fallback function is deposit(), it does nothing material in this case, only allows its calling function’s execution to continue as it does not fail.</p><p>Multichain <a href="https://medium.com/zengo/without-permit-multichains-exploit-explained-8417e8c1639b">was hacked</a> because of this compiler feature. At the same time Interface call will revert if it goes to an EOA address or to the contract with a higher compiler version.</p><p><strong>6. Copy instead of re-write in </strong><strong>Structs.</strong></p><p>Let’s dive into the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cacd4c802918b3729f974c8bcd8e69b0/href">https://medium.com/media/cacd4c802918b3729f974c8bcd8e69b0/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94bd8ba18ed7d56e0857fb3b37c4c4a3/href">https://medium.com/media/94bd8ba18ed7d56e0857fb3b37c4c4a3/href</a></iframe><p>The problem is that the following snippet:</p><p>Struct memory y = x;</p><p>doesn’t really create a new struct in the memory, all it does is create a pointer to the struct. If y is changed, it means that x is changed too.</p><p>This feature also is present in Multichain staking contracts, here is <a href="https://medium.com/@gr_gred/how-i-found-2-bugs-after-2-audits-on-smart-contracts-with-20-mil-3a23209b463d">an article about that.</a></p><p><strong>7. </strong><strong>View and </strong><strong>pure can modify state in 0.4.X.</strong></p><p>Adding the view modifier makes it clear that the function only reads from the state and allows the compiler to help us maintain that behavior through the lifetime of the codebase. But before the 0.5.0 release, the compiler won’t throw you errors if you modify the state in view or pure functions:</p><p>Disbursement.sol:102:9: Warning: Function declared as view, but this expression (potentially) modifies the state and thus requires non-payable (the default) or payable.<br>withdrawnTokens = 0;<br>^ — — — — — — -^</p><p>With the 0.5.0 compiler version and higher, the compilation will fail with an error instead of just logging a warning.</p><h3><strong>BUGS</strong></h3><p>After we have discovered different features of Solidity, let’s continue discovering well-known Solidity compiler bugs and their presence in Lido finance contracts.</p><p>First of all, a short guide for developers and security researchers on how to understand which known bugs are present in the Solidity compiler by version:<br>1) Visit an <a href="https://github.com/ethereum/solidity/blob/develop/docs/bugs_by_version.json">official github repository of Solidity</a> and find your compiler version in the list and copy the name of the error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/0*w4YaF3SSbfPytdSh" /></figure><p>2) After that, open <a href="https://github.com/ethereum/solidity/blob/develop/docs/bugs.json">a list with the description of Solidity compiler bugs</a>, find a bug in the list, and check the info about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/0*hfDcc3SdNOwLM_5F" /></figure><p>3) When searching for a bug in a Solidity compiler version, it is important to look at the conditions in which the bug occurs. E.g. yulOptimizer: true or ABIEncoderV2: true.</p><ol><li><strong>Copying </strong><strong>bytes arrays from memory or calldata to storage may result in dirty storage values.</strong></li></ol><blockquote>Introduced: 0.0.1.<br>Fixed: 0.8.15.<br>Severity: low.<br>Link: <a href="https://blog.soliditylang.org/2022/06/15/dirty-bytes-array-to-storage-bug/">https://blog.soliditylang.org/2022/06/15/dirty-bytes-array-to-storage-bug/</a></blockquote><p>Copying bytes arrays from memory or calldata to storage is done in chunks of 32 bytes even if the length is not a multiple of 32. Thereby, extra bytes past the end of the array may be copied from calldata or memory to storage. These dirty bytes may then become observable after a .push() without arguments to the bytes array in storage, i.e. such a push will not result in a zero value at the end of the array as expected. This bug only affects the legacy code generation pipeline, the new code generation pipeline via IR is not affected.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f94ce34beaf70dabf29a559bba1fa7e2/href">https://medium.com/media/f94ce34beaf70dabf29a559bba1fa7e2/href</a></iframe><p>After a quick search, I found empty push in the Lido contracts during the initialization of the contract. But the push was done to the array in storage, not the bytes, so everything is good over there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/0*Zew-8saqJneZhiGd" /></figure><p><strong>2. If used on </strong><strong>memory byte arrays, a result of the function </strong><strong>abi.decode can depend on the contents of </strong><strong>memory outside of the actual byte array that is decoded.</strong></p><blockquote>Introduced: 0.4.16.<br>Fixed: 0.8.4.<br>Conditions: ABIEncoderV2: <strong>true.<br></strong>Severity: very low.<br>Link: <a href="https://blog.soliditylang.org/2021/04/21/decoding-from-memory-bug/">https://blog.soliditylang.org/2021/04/21/decoding-from-memory-bug/</a></blockquote><p>The ABI specification uses pointers to data areas for everything that is dynamically-sized. When decoding data from memory (instead of calldata), the ABI decoder did not properly validate some of these pointers. More specifically, it was possible to use large values for the pointers inside arrays so that computing the offset resulted in an undetected overflow. This could lead to decoding of these pointers targeting areas in memory outside of the actual area. This way, it was possible for abi.decode to return different values for the same encoded byte array.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ef2e88eb2cea4c92c3df3a5bdfcd308/href">https://medium.com/media/9ef2e88eb2cea4c92c3df3a5bdfcd308/href</a></iframe><p>In the Lido finance ABIEncoderV2 is not used on the earliest versions of the contracts, so this bug is missing in the contracts.</p><p><strong>3. </strong><strong>Keccak caching.</strong></p><blockquote>Fixed: 0.8.3.<br>Conditions: optimizer: <strong>true.<br></strong>Severity: medium.<br>Link: <a href="https://blog.soliditylang.org/2021/03/23/keccak-optimizer-bug/">https://blog.soliditylang.org/2021/03/23/keccak-optimizer-bug/</a></blockquote><p>The bytecode optimizer incorrectly re-used previously evaluated Keccak-256 hashes. You are unlikely to be affected if you do not compute Keccak-256 hashes in inline assembly.</p><p>Solidity’s bytecode optimizer has a step that can compute Keccak-256 hashes if the contents of the memory are known during compilation time. This step also has a mechanism to determine that two Keccak-256 hashes are equal even if the values in memory are not known during compile time. This mechanism had a bug where Keccak-256 of the same memory content but of different sizes were considered equal. More specifically, keccak256(mpos1, length1) and keccak256(mpos2, length2) in some cases were considered equal if length1 and length2, when rounded up to the nearest multiple of 32 was the same, and when the memory contents at mpos1 and mpos2 can be deduced to be equal. You may be affected if you compute multiple Keccak-256 hashes of the same content but with different lengths inside the inline assembly. The problem is avoided if your code uses keccak256 with a length that is not a compile-time constant or if it is always a multiple of 32.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47d64ab7b67a571a485c74261dd8e234/href">https://medium.com/media/47d64ab7b67a571a485c74261dd8e234/href</a></iframe><p>This bug is quite easily found without tests, with the help of the search I found a library with an old compiler version that used keccak256 in inline-assembly with a custom len variable. So, here is the first Solidity compiler bug in Lido finance contracts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*Knb3LU2RDISjlD_4" /></figure><p>The worst thing about such compiler bugs is that the code looks good, and under normal circumstances, it’s very hard to find such a bug in the code, without proper testing or knowledge of the compiler bugs.</p><p><strong>4. Empty byte array copy.</strong></p><blockquote>Fixed: 0.7.4.<br>Severity: medium.<br>Link: <a href="https://blog.soliditylang.org/2020/10/19/empty-byte-array-copy-bug/">https://blog.soliditylang.org/2020/10/19/empty-byte-array-copy-bug/</a></blockquote><p>Copying an empty byte array (or string) from memory or calldata to storage can result in data corruption if the target array’s length is increased subsequently without storing new data.</p><p>The routine that copies byte arrays from memory or calldata to storage stores unrelated data from after the source array in the storage slot if the source array is empty. If the storage array’s length is subsequently increased either by using .push() or by assigning to its .length attribute (only before 0.6.0), the newly created byte array elements will not be zero-initialized but will contain the unrelated data. You are not affected if you do not assign to .length and do not use .push() on byte arrays, or only use .push(&lt;arg&gt;) or manually initialize the new elements.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e76ea67ba2afde477ee3912e9f2f79bd/href">https://medium.com/media/e76ea67ba2afde477ee3912e9f2f79bd/href</a></iframe><p>There are a lot of places where this bug can be present in the code, and it’s much harder to find this bug in the code than all previous bugs. So, the code should be tested properly before saying that the bug is present in the code. This and many other bugs that are hard to identify won’t be covered in this article.</p><p><strong>5. Dynamic array cleanup.</strong></p><blockquote>Fixed: 0.7.3.<br>Severity: medium.<br>Link: <a href="https://blog.soliditylang.org/2020/10/07/solidity-dynamic-array-cleanup-bug/">https://blog.soliditylang.org/2020/10/07/solidity-dynamic-array-cleanup-bug/</a></blockquote><p>When assigning a dynamically-sized array with types of size <strong>at most 16 bytes</strong> in storage causing the assigned array to <strong>shrink</strong>, some parts of deleted slots were not zeroed out.</p><p>Consider a dynamically-sized array in storage whose base-type is small enough so that multiple values can be packed into a single slot, such as uint128[]. Let us define its length to be l. When this array gets assigned from another array with a smaller length, say m, the slots between elements m and l have to be cleaned by zeroing them out. However, this cleaning was not performed properly. Specifically, after cleaning the slot corresponding to m, only the first packed value was cleaned up. If this array gets resized to a length larger than m, the indices corresponding to the unclean parts of the slot will contain the original value instead of 0. The resizing here is performed by assigning to the array length by a push() or via inline assembly. You are not affected if you are only using .push(&lt;arg&gt;) or if you assign a value (even zero) to the new elements after increasing the length of the array.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14e837705202cc2dc239f4a5a3be4dcf/href">https://medium.com/media/14e837705202cc2dc239f4a5a3be4dcf/href</a></iframe><p>This bug wasn’t found by the manual search, but it still can be present in the code.</p><p><strong>6. Implicit </strong><strong>constructor call value check.</strong></p><blockquote>Introduced: 0.4.5.<br>Fixed: 0.6.8.<br>Severity: very low.</blockquote><p>The contract creation code that does not define a constructor but has a base that defines a constructor did not revert for calls with a non-zero value.</p><p>Starting from Solidity 0.4.5, the contract creation code without an explicit payable constructor is supposed to contain a callvalue check that results in contract creation reverting if a non-zero value is passed. However, this check was missing if no explicit constructor was defined in a contract at all, but the contract had a base that does define a constructor. In these cases, it is possible to send value in a contract creation transaction or using inline assembly without revert, even though the creation code is supposed to be non-payable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/0*XlFNByjF0em4S1Ey" /></figure><p>This problem is present in code since a lot of Lido contracts are upgradable, and they are missing an implicit constructor for initialization. But since the contracts already operate with native coins, the severity of the problem is very low.</p><p><strong>7. Tuple Assignment Multi Stack Slot Components.</strong></p><blockquote>Introduced: 0.1.6.<br>Fixed: 0.6.6.<br>Severity: very low.</blockquote><p>Tuple assignments with components that occupy several stack slots, i.e. nested tuples, pointers to external functions or references to dynamically sized calldata arrays, can result in invalid values.</p><p>Tuple assignments did not correctly account for tuple components that occupy multiple stack slots in case the number of stack slots differs between the left-hand side and right-hand side. This can either happen in the presence of nested tuples or if the right-hand side contains external function pointers or references to dynamic calldata arrays while the left-hand side contains an omission.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3eadcc6f95db599e7935c4e7a005e0e/href">https://medium.com/media/c3eadcc6f95db599e7935c4e7a005e0e/href</a></iframe><p>This example actually looks more severe than it is described. I found a part of the code that can be affected since the contentURI variable is dynamically sized, but since it is memory, the code is not affected by this bug.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/0*4dEe1kghFUp6kgcP" /></figure><p><strong>8. Memory array creation overflow.</strong></p><blockquote>Introduced: 0.2.0.<br>Fixed: 0.6.5.<br>Severity: low.<br>Link: <a href="https://blog.soliditylang.org/2020/04/06/memory-creation-overflow-bug/">https://blog.soliditylang.org/2020/04/06/memory-creation-overflow-bug/</a></blockquote><p>The creation of very large memory arrays can result in overlapping memory regions and thus memory corruption.</p><p>No runtime overflow checks were performed for the length of memory arrays during creation. In cases when the memory size of an array is in bytes, i.e. the array length times 32, is larger than 2²⁵⁶-1, the memory allocation will overflow, potentially resulting in overlapping memory areas. The length of the array is still stored correctly, so copying or iterating over such an array will result in out-of-gas.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be88d813bcf58ff9130e07d340befc80/href">https://medium.com/media/be88d813bcf58ff9130e07d340befc80/href</a></iframe><p>I was able to find an array, with the custom length depending on the activeNodeOperatorCount variable, which is uint256. So, theoretically, there could be a scenario when a number of active operators will grow to a value more than 2⁶⁴-1 and corrupt memory, which is a critical security point to the Lido, but at the same time, the likelihood of this scenario is very low.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xgJyUu-vlPnFJ-wz" /></figure><p><strong>9. </strong><strong>Private can be overridden.</strong></p><blockquote>Introduced: 0.3.0<br>Fixed: 0.5.17<br>Severity: low</blockquote><p>Private methods can be overridden by inheriting contracts.</p><p>While private methods of base contracts are not visible and cannot be called directly from the derived contract, it is still possible to declare a function of the same name and type and thus change the behavior of the base contract’s function.</p><p>I haven’t found any overrides of the private variables in the code.</p><p><strong>10. Signed array </strong><strong>storage copy.</strong></p><blockquote>Introduced: 0.4.7<br>Fixed: 0.5.10<br>Severity: low/medium<br>Link <a href="https://blog.soliditylang.org/2019/06/25/solidity-storage-array-bugs/">https://blog.soliditylang.org/2019/06/25/solidity-storage-array-bugs/</a></blockquote><p>Assigning an array of signed integers to a storage array of different type can lead to data corruption in that array.</p><p>In two’s complement, negative integers have their higher order bits set. In order to fit into a shared storage slot, these have to be set to zero. When a conversion is done at the same time, the bits set to zero were incorrectly determined from the source and not the target type. This means that such copy operations can lead to incorrect values being stored.</p><p>If you have deployed contracts that use signed integer arrays in storage and either directly assign</p><ul><li>A literal array with at least one negative value in it (x = [-1, -2, -3];)</li><li>Or an existing array of a <strong>different</strong> signed integer type</li></ul><p>to it, this will lead to data corruption in the storage array.</p><p>Contracts that only assign individual array elements (i.e. with x[2] = -1;) are not affected.</p><p>There are no integer storage arrays in the code, so Lido definitely doesn’t have this bug. But, to be fair, I couldn’t reproduce the bug in Remix.</p><p><strong>11. ABI Encoder V2 storage array with multi slot element.</strong></p><blockquote>Introduced: 0.4.16.<br>Fixed: 0.5.10.<br>Severity: low.<br>Conditions: ABIEncoderV2: <strong>true.<br></strong>Link: <a href="https://blog.soliditylang.org/2019/06/25/solidity-storage-array-bugs/">https://blog.soliditylang.org/2019/06/25/solidity-storage-array-bugs/</a></blockquote><p>Storage arrays containing structs or other statically-sized arrays are not read properly when directly encoded in external function calls or in abi.encode.</p><p>When storage arrays in which elements occupy more than a single storage slot are directly encoded in external function calls or using abi.encode, their elements are read in an overlapping manner, i.e. the element pointer is not properly advanced between reads. This is not a problem when the storage data is first copied to a memory variable or if the storage array only contains value types or dynamically-sized arrays.</p><p>During the encoding process, the experimental ABI encoder does not properly advance to the next element in an array in case the elements occupy more than a single slot in storage. This only concerns elements that are structs or statically-sized arrays. Arrays of dynamically-sized arrays or elementary datatypes are not affected.</p><p>The specific effect you will see is that data is “shifted” in the encoded array: If you have an array of type uint[2][] and it contains the data [[1, 2], [3, 4], [5, 6]], then it will be encoded as [[1, 2], [2, 3], [3, 4]] because the encoder only advances by a single slot between elements instead of two.</p><p>In Lido finance, ABIEncoderV2 is not used on the earliest versions of the contracts, so this bug is missing in the contracts.</p><p><strong>12. Dynamic constructor arguments </strong><strong>Clipped ABI V2.</strong></p><blockquote>Introduced: 0.4.16.<br>Fixed: 0.5.9.<br>Conditions: ABIEncoderV2: <strong>true.<br></strong>Severity: very low.</blockquote><p>A contract’s constructor that takes structs or arrays that contain dynamically-sized arrays revert or decodes to invalid data.</p><p>During the construction of a contract, constructor parameters are copied from the code section to memory for decoding. The amount of bytes to copy was calculated incorrectly if all parameters are statically-sized but contain dynamically-sized arrays as struct members or inner arrays. Such types are only available if ABIEncoderV2 is activated.</p><p>In Lido finance, ABIEncoderV2 is not used in the earliest versions of the contracts, so this bug is missing in the contracts.</p><p><strong>13. Uninitialized function pointer in </strong><strong>constructor.</strong></p><blockquote>Introduced: 0.4.5.<br>Fixed: 0.4.26.<br>Severity: very low.</blockquote><p>Calling uninitialized internal function pointers created in the constructor does not always revert and can cause unexpected behavior.</p><p>Uninitialized internal function pointers point to a special piece of code that causes a revert when called. Jump target positions are different during construction and after deployment, but the code for setting this special jump target only considered the situation after deployment.</p><p>I skipped this bug since the severity of it is very low. It won’t be covered in this article.</p><p><strong>14. Incorrect </strong><strong>event signature in libraries.</strong></p><blockquote>Introduced: 0.3.0.<br>Fixed: 0.4.26.<br>Severity: very low.</blockquote><p>Contract types used in events in libraries cause an incorrect event signature hash.</p><p>Instead of using the type address in the hashed signature, the actual contract name was used, leading to a wrong hash in the logs.</p><p>I haven’t found the usage of contract types in events in the code.</p><p><strong>15. </strong><strong>ABIEncoder V2 packed </strong><strong>storage.</strong></p><p>Introduced: 0.4.19.<br>Fixed: 0.4.26.<br>Severity: low.<br>Conditions: ABIEncoderV2: <strong>true.<br></strong>Link: <a href="https://blog.soliditylang.org/2019/03/26/solidity-optimizer-and-abiencoderv2-bug/">https://blog.soliditylang.org/2019/03/26/solidity-optimizer-and-abiencoderv2-bug/</a></p><p>Elements of structs and arrays that are shorter than 32 bytes are not properly decoded from storage when encoded directly (i.e. not via a memory type) using ABIEncoderV2. This can cause corruption in the values themselves but can also overwrite other parts of the encoded data.</p><p>In Lido finance, ABIEncoderV2 is not used in the earliest versions of the contracts, so this bug is not present there.</p><p><strong>16. Exponent cleanup.</strong></p><blockquote>Fixed: 0.4.25.<br>Severity: medium/high.<br>Link: <a href="https://blog.soliditylang.org/2018/09/13/solidity-bugfix-release/">https://blog.soliditylang.org/2018/09/13/solidity-bugfix-release/</a></blockquote><p>Using the ** operator with an exponent of type shorter than 256 bits can result in unexpected values.</p><p>Higher order bits in the exponent are not properly cleaned before the EXP opcode is applied if the type of the exponent expression is smaller than 256 bits and not smaller than the type of the base. In that case, the result might be larger than expected if the exponent is assumed to lie within the value range of the type. Literal numbers as exponents are unaffected, nor are exponents or bases of type uint256.</p><p>I haven’t found usage of exponents in old compiler versions in the code.</p><p><strong>17. Event </strong><strong>struct wrong data.</strong></p><blockquote>Introduced: 0.4.17.<br>Fixed: 0.4.25.<br>Severity: very low.<br>Link: <a href="https://blog.soliditylang.org/2018/09/13/solidity-bugfix-release/">https://blog.soliditylang.org/2018/09/13/solidity-bugfix-release/</a></blockquote><p>Using structs in events logged wrong data. If a struct is used in an event, the address of the struct is logged instead of the actual data.</p><p>Structs were not meant to be supported as event parameters without the new ABI encoder. The compiler did accept them nevertheless but encoded their memory address instead of their actual value. Even with the new ABI encoder, structs cannot be indexed event parameters.</p><p>I haven’t found usage of structs in events.</p><p><strong>18. ABI reencoding head overflow with static array cleanup.</strong></p><p>Introduced: 0.5.8.<br>Fixed: 0.8.16.<br>Conditions ABIEncoderV2: <strong>true.<br></strong>Severity: medium.<br>Link: <a href="https://blog.soliditylang.org/2022/08/08/calldata-tuple-reencoding-head-overflow-bug/">https://blog.soliditylang.org/2022/08/08/calldata-tuple-reencoding-head-overflow-bug/</a></p><p>ABI-encoding of a tuple with a statically-sized calldata array in the last component would corrupt 32 leading bytes of its first dynamically encoded component.</p><p>When a statically-sized calldata array is ABI-encoded, the compiler always pads the data area to a multiple of 32-bytes and ensures that the padding bytes are zeroed. In some cases, this cleanup used to be performed by always writing exactly 32 bytes, regardless of how many needed to be zeroed. This was done with the assumption that the data that would eventually occupy the area past the end of the array had not yet been written because the encoder processes tuple components in the order they were given. While this assumption is mostly true, there is an important corner case: dynamically encoded tuple components are stored separately from the statically-sized ones in an area called the *tail* of the encoding, and the tail immediately follows the *head*, which is where the statically-sized components are placed. The aforementioned cleanup, if performed for the last component of the head, would cross into the tail and overwrite up to 32 bytes of the first component stored there with zeros. The only array type for which the cleanup could actually result in an overwrite was arrays with uint256 or bytes32 as the base element type, and in this case, the size of the corrupted area was always exactly 32 bytes. The problem affected tuples at any nesting level. This also included structs, which are encoded as tuples in the ABI. Note also that lists of parameters and return values of functions, events, and errors are encoded as tuples.</p><p>Plausible attacks against affected contracts can only occur in situations where the contract accepts a static calldata array as a part of its input and forwards it to another external call without modifying the content.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50c8bc7b5682557ba03958ae403793f1/href">https://medium.com/media/50c8bc7b5682557ba03958ae403793f1/href</a></iframe><p>In the Lido finance ABIEncoderV2 is not used on the earliest versions of the contracts, so this bug is not present in the older contracts. But it can be present in the 0.8.9 version. This bug is very hard to find without tests, it won’t be covered in this article.</p><p><strong>19. Data location change in </strong><strong>internal override.</strong></p><blockquote>Introduced: 0.6.9.<br>Fixed: 0.8.14.<br>Severity: very low.<br>Link: <a href="https://blog.soliditylang.org/2022/05/17/data-location-inheritance-bug/">https://blog.soliditylang.org/2022/05/17/data-location-inheritance-bug/</a></blockquote><p>It was possible to change the data location of the parameters or return variables from calldata to memory and vice-versa while overriding internal and public functions. This caused invalid code to be generated when calling such a function internally through virtual function calls.</p><p>When calling external functions, it is irrelevant if the data location of the parameters is calldata or memory, the encoding of the data does not change. Because of that, changing the data location when overriding external functions are allowed. The compiler incorrectly also allowed a change in the data location for overriding public and internal functions. Since public functions can be called internally as well as externally, this causes invalid code to be generated when such an incorrectly overridden function is called internally through the base contract. The caller provides a memory pointer, but the called function interprets it as a calldata pointer or vice-versa.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa030818eba0c8ae2e33c90fad7a8bec/href">https://medium.com/media/aa030818eba0c8ae2e33c90fad7a8bec/href</a></iframe><p>I skipped this bug since the severity of it is very low.</p><p><strong>20. Nested </strong><strong>calldata array ABI reencoding size validation</strong></p><blockquote>Introduced: 0.5.8.<br>Fixed: 0.8.14.<br>Severity: very low.<br>Link: <a href="https://blog.soliditylang.org/2022/05/17/calldata-reencode-size-check-bug/">https://blog.soliditylang.org/2022/05/17/calldata-reencode-size-check-bug/</a></blockquote><p>ABI-reencoding of nested dynamic calldata arrays did not always perform proper size checks against the size of calldata and could read beyond calldatasize().</p><p>Calldata validation for nested dynamic types is deferred until the first access to the nested values. Such access may, for example, be a copy to memory or an index or member access to the outer type. While in most cases calldata validation correctly checks that the data area of the nested array is completely contained in the passed calldata (i.e. in the range [0, calldatasize()]), this check may not be performed when such nested types are ABI encoded again directly from calldata. For instance, this can happen if a value in calldata with a nested dynamic array is passed to an external call, used in abi.encode , or emitted as the event. In such cases, if the data area of the nested array extends beyond calldatasize(), ABI encoding did not revert but continued reading values from beyond calldatasize() (i.e. zero values).</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a74a355aea393a85c76395ab8751e34/href">https://medium.com/media/7a74a355aea393a85c76395ab8751e34/href</a></iframe><p>There are a lot of places where this bug can be present in Lido finance contracts, tests are necessary in order to find out if the bug is present in the code.</p><p><strong>21. Signed </strong><strong>immutables.</strong></p><blockquote>Introduced: 0.6.5.<br>Fixed: 0.8.9.<br>Severity: very low.<br>Link: <a href="https://blog.soliditylang.org/2021/09/29/signed-immutables-bug/">https://blog.soliditylang.org/2021/09/29/signed-immutables-bug/</a></blockquote><p>Immutable variables of signed integer type shorter than 256 bits can lead to values with invalid higher-order bits if the inline assembly is used.</p><p>When immutable variables of signed integer type shorter than 256 bits are read, their higher-order bits were unconditionally set to zero. The correct operation would be to sign-extend the value, i.e. set the higher-order bits to one if the sign bit is one. This sign-extension is performed by Solidity just prior to when it matters, i.e. when a value is stored in memory, when it is compared, or when a division is performed. Because of that, to our knowledge, the only way to access the value in its unclean state is by reading it through the inline assembly.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64259aeffe8f6edc0ec6a7945130eb6c/href">https://medium.com/media/64259aeffe8f6edc0ec6a7945130eb6c/href</a></iframe><p>Lido finance doesn’t use signed immutables in storage.</p><p>Ultimately, the key to identifying and addressing bugs in Solidity is to perform thorough testing and analysis and to stay vigilant for potential vulnerabilities or issues. By staying informed and up-to-date on the latest developments in Solidity programming and by utilizing best practices and security measures, developers can minimize the risk of bugs and vulnerabilities in their code.</p><p>It is also important to keep in mind that Solidity is a complex and rapidly evolving programming language and that bugs can sometimes be difficult to track down. In these cases, it may be helpful to seek out the advice or assistance of other experienced Solidity developers and audit your code before the release.</p><p><strong>Thank you for your attention!</strong></p><p>The article was prepared by OXORIO auditor Vladislav Yaroshuk as part of the work on the <a href="https://blog.lido.fi/introducing-lido-v2/">LIDO project</a>.</p><p>To ensure you don’t miss anything, subscribe to <a href="https://medium.com/@oxorio">@oxorio</a> and <a href="https://medium.com/@gr_gred">@gr_gred</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe04e852ea64" width="1" height="1" alt=""><hr><p><a href="https://blog.oxor.io/exploring-the-bugs-and-features-of-solidity-compiler-versions-a-guide-for-smart-contract-fe04e852ea64">Exploring the Bugs and Features of Solidity Compiler Versions: A Guide for Smart Contract…</a> was originally published in <a href="https://blog.oxor.io/">Oxorio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I found 2 bugs after 2 audits on smart contracts with 20 mil. $]]></title>
            <link>https://medium.com/@gr_gred/how-i-found-2-bugs-after-2-audits-on-smart-contracts-with-20-mil-3a23209b463d?source=rss-55814727e1d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a23209b463d</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Vladislav Yaroshuk]]></dc:creator>
            <pubDate>Mon, 17 Oct 2022 07:59:33 GMT</pubDate>
            <atom:updated>2022-10-17T07:59:33.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ICvFej5kiwYRUZPy" /></figure><p>Today people trust audits and think if the contract was audited it is completely safe and doesn’t have any bugs. Unfortunately, it’s not. Today I will tell you how I found 2 bugs on Multichain Staking contracts and received a reward for them as a whitehat hacker.</p><p>Multichain forked vote escrow contract from Solidly exchange. So this bugs are present on both exchanges. They were previously audited by: <a href="https://github.com/anyswap/Anyswap-Audit/blob/master/BlockSec/blocksec_audit_multichain_v1.0-signed.pdf">Blocksec</a>, <a href="https://github.com/grGred/solidly/blob/master/audits/e456a816-3802-4384-894c-825a4177245a.pdf">Peckshield</a>.</p><ol><li><strong>Incorrect calculations of history points.</strong></li></ol><p>The bug is connected with calculation of voting power of the veMulti NFTs at* specific time and breaks amount of pending reward and in some cases even leads to loss of all unclaimed reward for a specific NFT, that&#39;s why I identify it as a critical bug.</p><p>Since Multichain has multiple stakings on different chains and market is bearish it’s very likely to happen that people will not interact with one of the contracts for more than a week.</p><p><strong>Bug description</strong>:</p><p>If contract has 0 checkpoints per week, checkpoint internal function will write multiple checkpoints to point_history with the same block number and different timestamp, and extrapolation of time will be broken. The problem line <a href="https://github.com/grGred/Anyswap-staking/blob/main/contracts/ve.sol#L826">is L826.</a></p><p><strong>Proof of concept:</strong></p><p>In checkpoint function there is a for loop, before the for loop we save the latest checkpoint.</p><pre>// initial_last_point is used for extrapolation to calculate block number<br>// (approximately, for *At methods) and save them<br>// as we cannot figure that out exactly from inside the contract<br>Point memory initial_last_point = last_point;</pre><p>The problem is that this doesn’t really create new variable with last point, it creates a pointer to latest point. If initial_last_point is changed it means that last_point is changed too.</p><p>Proof:</p><p>Contract:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b56b89399206010e3fe54be4328b67a3/href">https://medium.com/media/b56b89399206010e3fe54be4328b67a3/href</a></iframe><p>Test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7baceaf08f1be34fc935be3f1aeca924/href">https://medium.com/media/7baceaf08f1be34fc935be3f1aeca924/href</a></iframe><p>So if there would be no points in a week, the for loop will incorrectly write checkpoint in points_history with one blocknumber -&gt; multiple timestamps.</p><p><strong>How it will effect on reward distribution:</strong></p><p>People with expired locks can’t claim their rewards if there are any. They will disappear. If a person with expired lock will claim his rewards and withdraw his funds, all other users with active NFTs will lose significant amount of pending rewards (up to 50%). So the reward distribution will work incorrectly and their voting power will be wrong.</p><p><strong>Mitigation steps:</strong></p><p>Redeploy the contract with:</p><pre>// Copy all the data of last point<br>Point memory initial_last_point = Point({<br>    bias: last_point.bias,<br>    slope: last_point.slope,<br>    ts: last_point.ts, blk:<br>    last_point.blk<br>});</pre><p>The fixed contract with console logs <a href="https://github.com/grGred/Anyswap-staking/blob/main/contracts/veFixed.sol#L828-L833">can be found there.</a></p><p>The other solution is to create backend which will call checkpoint function every day, so there would be no chance to fall into for loop and break rewards. Multichain used this variant and now they have backend that calls checkpoint function.</p><p>If you run the test <a href="https://github.com/grGred/Anyswap-staking">in my github repo</a> “Rewards after withdraw disappears for expired locks” you can see that it writes multiple checkpoint with the same blocknumber and different timestamp:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*IUuXUsrekaLSzd1Kzp447g.jpeg" /></figure><p>2.<strong> Supply of tokens doesn’t decrease with the merge function.</strong></p><p>User can merge two NFTs in one, The problem is in this function.<br>_burn burns the nft, but doesn’t decrease supply amount, so it possible to increase Supply for a merging amount forever. Supply amount isn’t used for reward distribution, so I identify this bug as medium.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a741b27e6e6501011a7ab708a6feca7/href">https://medium.com/media/4a741b27e6e6501011a7ab708a6feca7/href</a></iframe><p><strong>Proof of concept:</strong></p><p>Here is the test which logs the supply amount before and after the merge.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9f0f2145c03ee41b3f2adf1b1c5250b/href">https://medium.com/media/a9f0f2145c03ee41b3f2adf1b1c5250b/href</a></iframe><p>As you can see supply amount increased and it doesn’t equal amount of tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*490-ZVLeYWAaFerLV9oBmg.png" /></figure><p>In conclusion I want to say, that no matter how much security audits you will have you must cover your code with unit tests properly. Especially if this contract locks big amount of tokens.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a23209b463d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deflationary-Commission Tokens Detection]]></title>
            <link>https://medium.com/better-programming/deflationary-commission-tokens-detection-d71a5f451556?source=rss-55814727e1d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d71a5f451556</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Vladislav Yaroshuk]]></dc:creator>
            <pubDate>Sat, 15 Oct 2022 22:01:27 GMT</pubDate>
            <atom:updated>2022-10-18T15:46:03.051Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tips to help you detect nonstandard tokens</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*uviubwba6ZNnfEZ6" /><figcaption>image from <a href="https://unsplash.com/photos/71KzaWjdt84">Unsplash</a></figcaption></figure><p>Defi is gaining popularity daily, and today there are many different token standards, like ERC20, ERC721, ERC1155, etc. However, deflationary tokens (or tokens with commission) and all other tokens where the recipient receives a different amount of tokens than the amount sent don’t have their official implementation.</p><p>This creates lots of trouble for different web3 developers because it’s not easy to define if the token is non-standard without using backend simulations of the transaction and so on. That’s why many devs say this is a scam token (e.g., <a href="https://github.com/safemoonprotocol/Safemoon.sol/pull/33">safemoon pull request</a> suggesting deleting all the code from GitHub). In this article, we will talk about ways developers can easily detect these kinds of tokens.</p><p>First, let’s define a common line for deflationary/commission tokens. The main difference is almost always located in <em>_transfer </em>function because both transfer and transferFrom use it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d22aae887f3e86f303e4526a18995fae/href">https://medium.com/media/d22aae887f3e86f303e4526a18995fae/href</a></iframe><p>Deflationary tokens are tokens fashioned to reduce supply over time. So, it would be a good idea to check the total supply of tokens back in time and now. If the amount has decreased — most likely, this is a deflationary token. But this method is still not ideal. An admin can burn tokens from the hacker (blacklisted address) or just burn some tokens to decrease the total supply and increase token emission. So this method is good, but it’s inaccurate since tokens with commission don’t decrease the total supply.</p><p>Commission tokens (as I define them) send some tokens from the transaction to a specific address. It can be the address of the owner or just the zero address. From my developer’s point of view, this kind of token is the same as the previous one. In this scenario, the total supply doesn’t decrease, and it’s much harder to understand if the token is not ERC20-standard, and almost impossible to understand the percentage of fees without opening a source code.</p><h3>So, How To Detect These Tokens?</h3><p>Starting from <a href="https://github.com/ethereum/solidity/releases/tag/v0.8.4">Solidity v0.8.4</a>, there is a convenient and gas-efficient way to explain to users why an operation failed through custom errors. Earlier, you could already use strings to give more information about failures (e.g., revert (“Insufficient funds”), but it is difficult to use dynamic information in them. So, with <a href="https://blog.soliditylang.org/2021/04/21/custom-errors/">custom errors</a>, we can easily log the amount sent and received and compare them. From the front side, the only thing a developer has to do is to make a static call to the contract and decode error data.</p><p>First, we need to define the error selector. For example, if we have the following error:</p><pre>error AmntReceived_AmntExpected_Transfer(uint256 amountReceived, uint256 amountExpected);</pre><p>We can easily find this selector by using Solidity. But don’t forget to remove spaces and names of your variables:</p><pre>bytes4 public constant FUNC_SELECTOR = bytes4(keccak256(‘AmntReceived_AmntExpected_Transfer(uint256,uint256)’));</pre><p>It is 0x5afe9b48.</p><p>Or you can decode this selector using <a href="https://docs.ethers.io/v5/api/utils/hashing/">ethers.utils.keccak256 function</a> in TypeScript/JavaScript.</p><p>The easiest way would be to add this error as a function in abi.</p><pre>const abi = [</pre><pre>“function error AmntReceived_AmntExpected_Transfer(uint256 amountReceived, uint256 amountExpected);”</pre><pre>];</pre><p>And after that, decode data using ethers. Here’s how to do that:</p><pre>const interface = new ethers.utils.Interface(abi);</pre><pre>const decoded = interface.decodeFunctionData(</pre><pre>interface.functions[“AmntReceived_AmntExpected_Transfer(uint256,uint256)”], error_data);</pre><p>So, when we have an understanding of how to cope with custom errors, we need to create a smart contract that will emit the right logs and give us information about the following:</p><ul><li>Fees in a simple transfer function. Some tokens have different fees for different amounts.</li><li>Fees in buy function in DEXs, since many safemoon forks have different fee percentages for routers.</li><li>Fees in sell function in DEXs.</li></ul><p>The main problem we are facing is developing a simulator smart contract — failed external calls. We want to be reverted only with our already known custom errors.</p><ol><li>Simple token transfer to contract. Since we are using transferFrom function -&gt; contract must be approved before. This function is not usable because of the allowance problem and the problem that msg.sender must have tokens on their address. But this is still okay for tests while you are developing static call logic. Or if you are hardcore and want to create a big database of deflationary tokens. Just buy a small amount of each token, make an approval of each token, and use it.</li></ol><p>The error log after the static call would be:</p><pre>error AmntReceived_AmntExpected_Transfer(uint256 amountReceived, uint256 amountExpected);</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e389164640a48aa6cfa943f89f13856e/href">https://medium.com/media/e389164640a48aa6cfa943f89f13856e/href</a></iframe><p>2. Swap tokens for the token with fee and then transfer it back to msg.sender. You can swap any token for a token you want to check on DEX by making the recipient address in swap data — simulator contract address. After that, the contract will transfer tokens back to msg.sender and log commissions.</p><p>Since you won’t really be swapping tokens and your static call will revert, it’s recommended to set the slippage of 100% and the deadline on max uint. I suggest you build the swap data for this static call from address zero, and tokenIn should be native coin. Since zero address is a classic burn address, it always has enough coin balance for this call on almost any EVM blockchain, and native coin doesn’t need allowance for transfers. You can receive swap data via a 1-inch API request, for example.</p><p>The error log after the static call would be:</p><pre>error AmntReceived_AmntExpected_TransferSwap(uint256 amountReceived, uint256 amountExpected);</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f88e9b661e0f0ec7bfc054da951c24bb/href">https://medium.com/media/f88e9b661e0f0ec7bfc054da951c24bb/href</a></iframe><p>These two methods are more than enough to detect non-standard tokens with fees. You can easily receive a percentage of the fees with this code:</p><pre>feePercent = amountReceived/amountExpected.</pre><p>But since safemoon uses custom fees for buys and sells, the log from the functions pointed out above won’t be enough. I won’t describe how to do that in detail because it becomes more complex, and this information is not useful for most projects. But if you are interested, you can find the source code <a href="https://github.com/grGred/Commission-Simulator/blob/master/contracts/Simulator.sol">on my GitHub</a>.</p><p>Please be careful when using error data since its origin is not tracked. The error data, by default, bubbles up through the chain of external calls, which means that a contract may forward an error that is not defined in any of the contracts it calls directly.</p><p>Furthermore, any contract can fake any error by returning data that matches an error signature, even if the error is not defined anywhere.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d71a5f451556" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/deflationary-commission-tokens-detection-d71a5f451556">Deflationary-Commission Tokens Detection</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[Solidity Gas Optimizations Tricks]]></title>
            <link>https://medium.com/better-programming/solidity-gas-optimizations-and-tricks-2bcee0f9f1f2?source=rss-55814727e1d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bcee0f9f1f2</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Vladislav Yaroshuk]]></dc:creator>
            <pubDate>Sun, 02 Oct 2022 09:40:26 GMT</pubDate>
            <atom:updated>2022-12-13T09:23:31.375Z</atom:updated>
            <content:encoded><![CDATA[<h4>An in-depth guide to optimise fees on your Ethereum blockchain</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*2-cfQyzB4Ti1egWS.png" /><figcaption>image by author</figcaption></figure><p>This article is about advanced gas optimizations for Solidity. Here you can find all the best practices of gas-optimized code! I update this article quite often <a href="https://gist.github.com/grGred/9bab8b9bad0cd42fc23d4e31e7347144">on my gist</a>. Don’t be shy to star it.</p><p>Solidity Gas is a fee that is required to conduct a transaction on the Ethereum blockchain. The purpose of gas is to limit the number of transactions the system will perform. This limits computations from running forever and spamming the network.</p><h3>Upgrade Pragma to the Latest Solidity Compiler Version</h3><p>Using newer compiler versions and the optimizer gives gas optimizations and additional safety checks for free!</p><p>The advantages of versions 0.8.* over &lt;0.8.0 are:</p><ul><li>Safemath by default from 0.8.0 (can be more gas efficient than some library-based safemath).</li><li><a href="https://blog.soliditylang.org/2021/03/02/saving-gas-with-simple-inliner/">Low-level inliner</a> from 0.8.2, leads to cheaper runtime gas. Especially relevant when the contract has small functions. For example, OpenZeppelin libraries typically have a lot of small helper functions and if they are not inlined, they cost an additional 20 to 40 gas because of two extra jump instructions and additional stack operations needed for function calls.</li><li><a href="https://blog.soliditylang.org/2021/03/23/solidity-0.8.3-release-announcement/#optimizer-improvements">Optimizer improvements in packed structs</a>: Before 0.8.3, storing packed structs, in some cases, they used an additional storage read operation. After <a href="https://eips.ethereum.org/EIPS/eip-2929">EIP-2929</a>, if the slot was already cold, this means unnecessary stack operations and extra deploy time costs. However, if the slot was already warm, this means an additional cost of 100 gas alongside the same unnecessary stack operations and extra deploy time costs.</li><li><a href="https://blog.soliditylang.org/2021/04/21/custom-errors">Custom errors</a> from 0.8.4, leads to cheaper deploy- and run-time costs. Note: the run time cost is only relevant when the revert condition is met. In short, replace revert strings with custom errors.</li><li>Solidity 0.8.10 has a useful change that <a href="https://blog.soliditylang.org/2021/11/09/solidity-0.8.10-release-announcement/">reduced gas costs of external calls</a> which expect a return value. Code Generator skips existence check for the external contract if return data is expected. In this case, the ABI decoder will revert if the contract does not exist. 0.8.10 also enables the new EVM code generator for pure Yul mode.</li><li><a href="https://blog.soliditylang.org/2022/06/15/solidity-0.8.15-release-announcement/">Improved Inlining Heuristics in Yul Optimizer</a>. The compiler used to be very conservative before Solidity version 0.8.15 in deciding whether to inline a function or not. This was necessary due to the fact that inlining may easily increase stack pressure and lead to the dreaded Stack too deep error. In 0.8.15 the conditions necessary for inlining are relaxed. Benchmarks show that the change significantly decreases the bytecode size (which impacts the deployment cost) while the effect on the runtime gas usage is smaller.</li><li><a href="https://blog.soliditylang.org/2022/09/08/solidity-0.8.17-release-announcement/">Overflow checks multiplications more efficiently</a> in Solidity v0.8.17. Yul Optimizer: Prevent the incorrect removal of storage writes before calls to Yul functions that conditionally terminate the external EVM call; Simplify the starting offset of zero-length operations to zero. Code Generator: More efficient overflow checks for multiplication.</li></ul><h3>For Loops Improvement</h3><h4>Caching the length in for loops</h4><p>Reading array length at each iteration of the loop takes 6 gas (three for mload and three to place memory_offset ) in the stack. Caching the array length in the stack saves around 3 gas per iteration. I suggest storing the array’s length in a variable before the for-loop.</p><p>Example of an array arr and the following loop:</p><pre>for (uint i = 0; i &lt; length; i++) {<br>    // do something that doesn&#39;t change the value of i<br>}</pre><p>In the above case, the solidity compiler will always read the length of the array during each iteration.</p><ol><li>If it is a storage array, this is an extra sload operation (100 additional extra gas (<a href="https://eips.ethereum.org/EIPS/eip-2929">EIP-2929</a>) for each iteration except for the first),</li><li>If it is a memory array, this is an extra mload operation (3 additional gas for each iteration except for the first),</li><li>If it is a calldata array, this is an extra calldataload operation (3 additional gas for each iteration except for the first) These extra costs can be avoided by caching the array length (in the stack):</li></ol><pre>uint length = arr.length;<br>for (uint i = 0; i &lt; length; i++) {<br>    // do something that doesn&#39;t change arr.length<br>}</pre><p>In the above example, the sload or mload or calldataload operation is only called once and subsequently replaced by a cheap dupN instruction. Even though mload, calldataload and dupN have the same gas cost, mload and calldataload needs an additional dupN to put the offset in the stack, i.e., an extra 3 gas.</p><p>This optimization is especially important if it is a storage array or if it is lengthy for loop.</p><h4>The increment in the for loop’s post condition can be made unchecked</h4><p>In Solidity 0.8+, there’s a default overflow check on unsigned integers. It’s possible to uncheck this in for-loops and save some gas at each iteration, but at the cost of some code readability, as this uncheck <a href="https://github.com/ethereum/solidity/issues/10695">cannot be made inline</a>.</p><p>Here’s an example for loop:</p><pre>for (uint i = 0; i &lt; length; i++) {<br>    // do something that doesn&#39;t change the value of i<br>}</pre><p>In this example, the for loop’s post condition, i.e., i++ involves checked arithmetic, which is not required. This is because the value of i is always strictly less than length &lt;= 2**256 - 1. Therefore, the theoretical maximum value of i to enter the for loop body is 2**256 - 2. This means that the i++ in the for loop can never overflow. Regardless, the overflow checks are performed by the compiler.</p><p>Unfortunately, the Solidity optimizer is not smart enough to detect this and remove the checks. You should manually do this with this code:</p><pre>for (uint i = 0; i &lt; length; i = unchecked_inc(i)) {<br>    // do something that doesn&#39;t change the value of i<br>}</pre><pre>function unchecked_inc(uint i) returns (uint) {<br>    unchecked {<br>        return i + 1;<br>    }<br>}</pre><p>Or use the following:</p><pre>for (uint i = 0; i &lt; length;) {<br>    // do something that doesn&#39;t change the value of i<br>    unchecked { i++; }<br>}</pre><p>Note that it’s important that the call to unchecked_inc is inlined. This is only possible for solidity versions starting from 0.8.2.</p><p>Gas savings: roughly speaking this can save 30–40 gas per loop iteration. For lengthy loops, this can be significant! (This is only relevant if you are using the default solidity-checked arithmetic.)</p><h4>++i costs less gas compared to i++ or i += 1</h4><p>++i costs less gas compared to i++ or i += 1 for an unsigned integer, as pre-increment is cheaper (about 5 gas per iteration). This statement is true even with the optimizer enabled.</p><p>Example: i++ increments i and returns the initial value of i, which looks like the following:</p><pre>uint i = 1; <br>i++; // == 1 but i == 2</pre><p>But ++i returns the actual incremented value.</p><pre>uint i = 1; <br>++i; // == 2 and i == 2 too, so no need for a temporary variable</pre><p>In the first case, the compiler has to create a temporary variable (when used) for returning 1 instead of 2.</p><h4>No need to explicitly initialize variables with default values</h4><p>If a variable is not set/initialized, it is assumed to have the default value (0 for uint, false for bool, address(0) for address, etc.). Explicitly initializing it with its default value is an anti-pattern and wastes gas. As an example: for (uint256 i = 0; i &lt; numIterations; ++i) { should be replaced with: for (uint256 i; i &lt; numIterations; ++i) {</p><h4>Don’t remove the initialization of i variable in for loops</h4><p>I see a lot of projects where developers mistakenly believe that the removal of i variable outside of the for loop will save gas. In the following snippets, you can see that this is wrong:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fbe7f311b05097bf6dd1cbe80c87747/href">https://medium.com/media/2fbe7f311b05097bf6dd1cbe80c87747/href</a></iframe><h4>To sum up, the best gas-optimized loop will be:</h4><pre>uint length = arr.length;<br>for (uint i; i &lt; length;) {<br>    unchecked { ++i; }<br>}</pre><h3>Use calldata Instead of Memory for Function Parameters</h3><p>In some cases, having function arguments in calldata instead of memory is more optimal. When arguments are read-only on external functions, the data location should be calldata.</p><p>Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d384b15383565de2051012a359baabb/href">https://medium.com/media/8d384b15383565de2051012a359baabb/href</a></iframe><p>In the above example, the dynamic array arr has the storage location memory. When the function gets called externally, the array values are kept in calldata and copied to memory during ABI decoding (using the opcode calldataload and mstore). And during the for loop, arr[i] accesses the value in memory using a mload. However, for the above example, this is inefficient. Consider the following snippet instead:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06514f5d94dc6d6481f87e46b8502cc7/href">https://medium.com/media/06514f5d94dc6d6481f87e46b8502cc7/href</a></iframe><p>In the above snippet, instead of going via memory, the value is directly read from calldata using calldataload. That is, there are no intermediate memory operations that carry this value.</p><p>Gas savings: In the former example, the ABI decoding begins with copying value from calldata to memory in a for loop. Each iteration would cost at least 60 gas. In the latter example, this can be completely avoided. This will also reduce the number of instructions and therefore reduces the deploy time cost of the contract.</p><p>In short, use calldata instead of memory if the function argument is only read.</p><p>Note that in older Solidity versions, changing some function arguments from memory to calldata may cause the “unimplemented feature error.” This can be avoided by using a newer (0.8.*) Solidity compiler.</p><h3>Change State Variables to Immutable Where Possible</h3><p><a href="https://blog.soliditylang.org/2020/04/06/solidity-0.6.5-release-announcement/">Solidity 0.6.5</a> introduced immutable as a major feature. It allows setting contract-level variables at construction time which gets stored in code rather than storage.</p><p>Here’s an example:</p><pre>contract C {<br>    /// The owner is set during contruction time, and never changed afterwards.<br>    address public owner = msg.sender;<br>}</pre><p>In the above example, each call to the function owner() reads from storage, using a sload. After <a href="https://eips.ethereum.org/EIPS/eip-2929">EIP-2929</a>, this costs 2100 gas cold or 100 gas warm. However, the following snippet is more gas efficient:</p><pre>contract C {<br>    /// The owner is set during contruction time, and never changed afterwards.<br>    address public immutable owner = msg.sender;<br>}</pre><p>In the above example, each storage read of the owner state variable is replaced by the instruction push32 value, where the value is set during contract construction time. Unlike the last example, this costs only 3 gas.</p><h3>Change Constant to Immutable for keccak Variables</h3><p>The use of constant keccak variables results in extra hashing (and so gas). This results in the keccak operation being performed whenever the variable is used, increasing gas costs relative to just storing the output hash. Changing to immutable will only perform hashing on contract deployment which will save gas. You should use immutables until the referenced issues are implemented, then you only pay the gas costs for the computation at deploy time.</p><p>Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38d02aa030a455c4ad258587749c6bab/href">https://medium.com/media/38d02aa030a455c4ad258587749c6bab/href</a></iframe><p>As you can see on the compiler version 0.8.15 and with optimizator on 200 runs immutables are cheaper and save you about 20 gas. For other variables, constants are equal to immutables.</p><p>See: (<a href="https://github.com/ethereum/solidity/issues/9232#issuecomment-646131646">ethereum/solidity#9232 (comment)</a>, <a href="https://github.com/seen-haus/seen-contracts/issues/29">Inefficient Hash Constants</a>).</p><h3>Consider Having Short Revert Strings</h3><p>Let’s consider the following require statement:</p><pre>// condition is boolean<br>// str is a string<br>require(condition, str)</pre><p>The string str is split into 32-byte sized chunks and then stored in memory using mstore, then the memory offsets are provided to revert(offset, length). For chunks shorter than 32 bytes, and for low --optimize-runs value (usually even the default value of 200), instead of push32 val, where val is the 32-byte hexadecimal representation of the string with 0 padding on the least significant bits, the solidity compiler replaces it by shl(value, short-value)). Where short value does not have any 0 padding.</p><p>This saves the total bytes in the deploy code and therefore saves deploy time cost, at the expense of extra 6 gas during runtime. This means that shorter revert strings save deploy time costs of the contract. Note that this kind of saving is not relevant for high values of — optimize-runs as push32 value will not be replaced by a shl(..., ...) equivalent by the Solidity compiler.</p><p>Going back, each 32-byte chunk of the string requires an extra mstore. That is, additional cost for mstore, memory expansion costs, as well as stack operations. Note that, this runtime cost is only relevant when the revert condition is met.</p><p>Overall, shorter revert strings can save deploy time as well as runtime costs.</p><p>Note that if your contracts already allow using at least Solidity 0.8.4, then consider using <a href="https://blog.soliditylang.org/2021/04/21/custom-errors">Custom errors</a>. This is more gas efficient while allowing the developer to describe the errors in detail using <a href="https://docs.soliditylang.org/en/latest/natspec-format.html">NatSpec</a>. A disadvantage to this approach is that some tooling may not have proper support for this.</p><h3>Use Clones for Cheap Contract Deployments</h3><p>Here’s an example:</p><pre>function _executeTransfer(address _owner, uint256 _idx) internal {<br>         (bytes32 salt, ) = precompute(_owner, _idx);<br>         new FlashEscrow{salt: salt}( //gas: deployment can cost less through clones<br>             nftAddress,<br>             _encodeFlashEscrowPayload(_idx)<br>         );<br>     }</pre><p>There’s a way to save a significant amount of gas on deployment using Clones: <a href="https://www.youtube.com/watch?v=3Mw-pMmJ7TA">OpenZeppelin video</a> This is a solution that was adopted, as an example, by Porter Finance. They realized that deploying using clones was 10x cheaper. I suggest applying a similar pattern in factory contracts.</p><p>See: <a href="https://github.com/porter-finance/v1-core/issues/15#issuecomment-1035639516">porter-finance/v1-core#15 (comment)</a> <a href="https://github.com/porter-finance/v1-core/pull/34">porter-finance/v1-core#34</a></p><h3>Use Modifiers Instead of Functions To Save Gas</h3><p>Example of two contracts with modifiers and internal view function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbace2d730a0e56b56c73d7ef874a106/href">https://medium.com/media/dbace2d730a0e56b56c73d7ef874a106/href</a></iframe><p>Differences:</p><pre>Deploy Modifier.sol<br>108727<br>Deploy Inlined.sol<br>110473<br>Modifier.foo<br>21532<br>Inlined.foo<br>21556</pre><p>This with 0.8.9 compiler and optimization enabled. As you can see it&#39;s cheaper to deploy with a modifier, and it will save you about 30 gas. But sometimes modifiers increase code size of the contract.</p><h3>Use Internal View Functions in Modifiers To Save Bytecode</h3><p>It is recommended to move the modifiers require statements into an internal virtual function. This reduces the size of compiled contracts that use the modifiers. Putting the require in an internal function decreases contract size when a modifier is used multiple times. There is no difference in deployment gas cost with private and internal functions.</p><p>With Solidity 0.8.14 and optimisations on (200):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/197c95554231bfd468068dca8fb47e84/href">https://medium.com/media/197c95554231bfd468068dca8fb47e84/href</a></iframe><p>See: <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3347/">Optimize Ownable and Pausable modifiers’ size impact #3347</a> <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3223">Reduce contract size and deployment gas for </a><a href="https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3223">onlyOwner modifier</a>.</p><h3>&gt;= is cheaper than &gt;</h3><p>Non-strict inequalities (&gt;=) are cheaper than strict ones (&gt;). This is due to some supplementary checks (ISZERO, 3 gas)).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc26a3c4fba193ddd6c96cf270895840/href">https://medium.com/media/cc26a3c4fba193ddd6c96cf270895840/href</a></iframe><p>Gas savings: non-strict inequalities will save you 15–20 gas.</p><h3>&gt; 0 is cheaper than != 0 sometimes</h3><p>!= 0 costs less gas compared to &gt; 0 for unsigned integers in require statements with the optimizer enabled. But &gt; 0 is cheaper than !=, with the optimizer enabled and outside a require statement. <a href="https://twitter.com/gzeon/status/1485428085885640706">https://twitter.com/gzeon/status/1485428085885640706</a></p><p>Example with optimizer disabled:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0be8d000b42f7420d62bb233b1fb7b7d/href">https://medium.com/media/0be8d000b42f7420d62bb233b1fb7b7d/href</a></iframe><p>Example with optimizer enabled:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/283880bf0123b3dbaa9a6fc55fffc2ea/href">https://medium.com/media/283880bf0123b3dbaa9a6fc55fffc2ea/href</a></iframe><p>Gas savings: it will save you about 10 gas.</p><pre>To sum up on 0.8.15:<br>    Without optimizer:<br>        In require:<br>            `&gt; 0` equals to `!= 0`<br>        Outside require:<br>            `&gt; 0` more expensive than `!= 0` <br>    With optimizer:<br>        In require:<br>            `&gt; 0` more expensive than `!= 0`<br>        Outside require:<br>            `&gt; 0` cheaper than `!= 0`</pre><p>See: <a href="https://twitter.com/gzeon/status/1485428085885640706">https://twitter.com/gzeon/status/1485428085885640706</a></p><h3>Use Shift Right/Left instead of Division/Multiplication if possible</h3><p>A division/multiplication by any number x being a power of 2 can be calculated by shifting log2(x) to the right/left. While the DIV opcode uses 5 gas, the SHR opcode only uses 3 gas. Furthermore, Solidity&#39;s division operation also includes a division-by-0 prevention which is bypassed using shifting.</p><h3>Use Double Require Instead of Operator &amp;&amp;</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0153f93c637678b7f381c28978e40e3/href">https://medium.com/media/d0153f93c637678b7f381c28978e40e3/href</a></iframe><p>Gas savings: Usage of double require will save you around 10 gas with the optimizer enabled.</p><h3>Use Custom Errors Instead of Revert Strings To Save Gas</h3><p>I already mentioned it earlier, and I strongly recommend using this. Custom errors from Solidity 0.8.4 are cheaper than revert strings (cheaper deployment cost and runtime cost when the revert condition is met) Source: <a href="https://blog.soliditylang.org/2021/04/21/custom-errors/">https://blog.soliditylang.org/2021/04/21/custom-errors/</a>: Starting from <a href="https://github.com/ethereum/solidity/releases/tag/v0.8.4">Solidity </a><a href="https://github.com/ethereum/solidity/releases/tag/v0.8.4">v0.8.4</a>, there is a convenient and gas-efficient way to explain to users why an operation failed through the use of custom errors.</p><p>Until now, you could already use strings to give more information about failures (e.g., revert(&quot;Insufficient funds.&quot;);), but they are rather expensive, especially when it comes to deploy cost, and it is difficult to use dynamic information in them. Custom errors are defined using the error statement, which can be used inside and outside of contracts (including interfaces and libraries).</p><h3>There Is No Difference in Gas Cost Between Public/External/Internal/Private for Variables and Functions</h3><p>It’s still better to define function visibility strictly because of security reasons, but it won’t affect gas usage. But it would affect deployment gas costs for such functions. There is no difference in internal and private functions in deployment gas cost.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8dd59019ebceec3de1ff4e98f7700ce/href">https://medium.com/media/c8dd59019ebceec3de1ff4e98f7700ce/href</a></iframe><p>Public variables cost the same amount as the internal and private ones:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee8f8cd80427497a75417e64bdf53193/href">https://medium.com/media/ee8f8cd80427497a75417e64bdf53193/href</a></iframe><p>By the way, variable visibility affects the deployed gas. public variables cost more than private or internal, but there is no difference in deployment gas cost between private and internal.</p><h3>Caching Storage Variables in Memory To Save Gas</h3><p>Anytime you are reading from storage more than once, it is cheaper in gas cost to cache the variable in memory: a SLOAD cost 100gas, while MLOAD and MSTORE cost 3 gas.</p><p>Gas savings: at least 97 gas.</p><h3>Be Careful With Copying the Whole Struct to Memory</h3><p>Sometimes, it’s better to use storage instead of copying struct in memory. Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f83068d8085d234dc55f29186a8ea35/href">https://medium.com/media/9f83068d8085d234dc55f29186a8ea35/href</a></iframe><p>Here, a copy in memory is costing 3 SLOADs and 3 MSTORES. The, 2 variables are only read once through MLOAD (position.owner and position.unlockAt) and one is read twice (position.lockAmount). It&#39;s better to replace the memory keyword with storage and only copying position.lockAmount in memory.</p><h3>Help the Optimizer by Saving a Storage Variable’s Reference</h3><p>To help the optimizer, declare a storage type variable and use it instead of repeatedly fetching the reference in a map or an array. The effect can be quite significant.</p><pre>function borrow(<br>   Position storage position = positions[_nftIndex];</pre><h3>Using Addresses With Lots of Leading Zeroes</h3><p>Well if you have two addresses — 0x000000a4323… and 0x0000000000f38210. Because of the leading zeroes, you can pack them both into the same storage slot, then just prepend the necessary amount of zeroes when using them. This saves you storage when doing things such as checking the owner of a contract.</p><h3>Writing to an Existing Storage Slot Is Cheaper Than Using a New One</h3><p>EIP — 2200 changed a lot with gas, and now if you hold 1 Wei of a token it’s cheaper to use the token than if you hold 0. There is a lot to unpack here so just google EIP 2200 and learn if you want, but in general, if you need to use a storage slot, don’t empty it if you plan to refill it later.</p><h3>Pack Structs in Solidity</h3><p><a href="https://dev.to/javier123454321/solidity-gas-optimizations-pt-3-packing-structs-23f4">Struct packing article here</a>.</p><p>A basic optimization but important to know, structs should be organized so that they sequentially add up to multiples of 256 bits in size. So, use the following:</p><pre>Struct {<br>    uint112 <br>    uint112 <br>    uint256 <br>}</pre><p>Instead of:</p><pre>Struct {<br>    uint112 <br>    uint256 <br>    uint112<br>}</pre><p>The same thing with the order of variables in the contract. Follow the optimized order to save gas for deployments. So, use the following:</p><pre>contract Test {<br>    uint256 // 2 storage slots<br>    address // address is 20 bytes and bool is 1 byte are packed in one slot<br>    bool<br>}</pre><p>Instead of:</p><pre>contract Test {<br>    address // 3 storage slots<br>    uint256 <br>    bool<br>}</pre><h3>Use Gasleft() To Measure Used Gas Instead of Checking Transaction Gas Cost, in Order To Find Gas Optimization</h3><p>While auditing code for gas optimization improvements, it’s very convenient to have <a href="https://www.npmjs.com/package/hardhat-gas-reporter">hardhat gas reporter</a>. It will show the gas usage per unit test. But if you don’t have time to initialize a new project and write tests for your function, or you want to check a myth about gas optimization, you shouldn’t look at the gas cost of the transaction. Don’t forget that in Solidity, <a href="https://medium.com/joyso/solidity-how-does-function-name-affect-gas-consumption-in-smart-contract-47d270d8ac92">function names and their order in the contract</a> take different amounts of gas.</p><p>Here’s an example:</p><pre>contract Test {<br>    function a() public { // 125 gas<br>    }<br>    <br>    function b() public { // 147 gas<br>    }<br>}</pre><p>That’s why you should wrap the body of the transaction as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ce5d0c4922188bd43232511980d014c/href">https://medium.com/media/5ce5d0c4922188bd43232511980d014c/href</a></iframe><p>And don’t forget to test both functions with the same conditions. Remember the tip “Writing to an existing Storage Slot is cheaper than using a new one.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bcee0f9f1f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/solidity-gas-optimizations-and-tricks-2bcee0f9f1f2">Solidity Gas Optimizations Tricks</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>
    </channel>
</rss>