<?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 Sharon  on Medium]]></title>
        <description><![CDATA[Stories by Sharon  on Medium]]></description>
        <link>https://medium.com/@sharonphiliplima?source=rss-a0ecd8b28114------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*n-v9bI9yX87XvDmx.jpg</url>
            <title>Stories by Sharon  on Medium</title>
            <link>https://medium.com/@sharonphiliplima?source=rss-a0ecd8b28114------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 13:31:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sharonphiliplima/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[Auditing strategies with Akshay Srivastav]]></title>
            <link>https://medium.com/@sharonphiliplima/auditing-strategies-with-akshay-srivastav-a5f3b4cd65f?source=rss-a0ecd8b28114------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5f3b4cd65f</guid>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Sharon ]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 12:07:10 GMT</pubDate>
            <atom:updated>2023-09-04T12:07:10.629Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RtlW1m1xIlTCa3tjux2lyQ.png" /></figure><p><em>N.B: This is a condensed transcript (and also I have used ChatGPT)</em></p><p><a href="https://youtu.be/F8Z4fIZGxps?si=2X6q-Scxxiazc9c9">https://youtu.be/F8Z4fIZGxps?si=2X6q-Scxxiazc9c9</a> PPT: <a href="https://gist.github.com/akshaysrivastav/3f84e5e43bb8002123fb0ceb9677e81f">https://gist.github.com/akshaysrivastav/3f84e5e43bb8002123fb0ceb9677e81f</a></p><p><a href="https://twitter.com/akshaysrivastv">https://twitter.com/akshaysrivastv</a></p><p><a href="https://discord.com/invite/opensense">https://discord.com/invite/opensense</a></p><p><strong>Mis4nthrOpic | OS:</strong> Good day, ladies and gentlemen. Welcome to today’s session. Allow me to introduce our esteemed guest speaker, Akshay Srivastav. Akshay, please share a bit about yourself with our audience.</p><p><strong>Akshay Srivastav:</strong> Certainly. Thank you, Mis4nthrOpic. My name is Akshay, and I work as a security researcher and a smart contract auditor. I regularly engage in public bounty programs, audit contests, and bounties on various platforms. Additionally, I also conduct private audits. Today, I will be discussing my auditing strategies and offering valuable tips for both novice and intermediate-level auditors. Let’s begin.</p><p>To start, let’s clarify <strong>what an audit entails.</strong> An audit is essentially a comprehensive review of software to ensure it functions according to its specifications. The goal is to guarantee that the final product aligns precisely with the original design and intended functionality. Typically, external auditors or audit teams are employed for this purpose. The primary aim is to identify anomalies, bugs, or extreme scenarios that may affect your codebase or product.</p><p>It’s essential to understand that <strong>auditing is not limited to code</strong>; it also encompasses the underlying software concept and its implementation. Companies often opt for code audits to have external teams scrutinize their codebases and identify potential issues.</p><p>Now, let’s delve into the <strong>mindset of an auditor.</strong> When I commence an audit, several key principles guide my approach. Firstly, I <em>always assume that the code contains numerous critical bugs</em>. This mindset fuels my determination to identify and report these bugs. Essentially, I adopt an attacker’s perspective, driving me to diligently hunt for vulnerabilities.</p><p>Secondly, I make it a point <em>to challenge the assumptions</em> made by the codebase or the development team behind it. Developers naturally formulate assumptions about their code during the development process. These assumptions can be considered invariants of the codebase. During an audit, I actively seek to <em>break these assumptions</em>. For instance, a team may assume that a particular call to an external lending protocol will always be successful. However, as an auditor, I explore scenarios where this call behaves differently than expected, thereby uncovering potential vulnerabilities.</p><p><strong>Mis4nthrOpic | OS:</strong> May I interject with a question here? How often do your findings relate to incorrect external calls?</p><p><strong>Akshay Srivastav:</strong> That’s an excellent question. Many of the findings in my audits are indeed related to incorrect external calls. Errors stemming from assumptions about external protocol behavior can lead to significant vulnerabilities.</p><p><strong>Mis4nthrOpic | OS:</strong> Thank you for the clarification. Please continue.</p><p><strong>Akshay Srivastav:</strong> Certainly. Another aspect of my approach is the <strong>constant questioning of the codebase.</strong> Throughout the audit process, I pose questions like “Why does this happen?” or “Why was this function created?” These inquiries deepen my understanding of the codebase.</p><p>Furthermore, I emphasize the importance of not succumbing to the same assumptions made by the development team. Falling into the same thought patterns as the developers can limit an auditor’s ability to think creatively and discover vulnerabilities. Therefore, it’s advisable to approach the audit with as few assumptions as possible and <strong>maintain a fresh perspective.</strong></p><p>Now, regarding complexity, auditors should not shy away from it. <strong>Complexity can be your ally</strong> as an auditor. A more complex codebase provides a larger surface area for potential vulnerabilities. Embracing complexity can lead to the discovery of unexplored code paths and extreme cases.</p><p>These principles form the foundation for auditors, whether they are beginners or seasoned professionals.</p><p><strong>For beginners:</strong></p><p>If you’re just starting in the world of audits, here’s a basic path you can follow. Begin by learning the fundamentals of Ethereum and Solidity. Understand how the blockchain operates, how transactions propagate, and the mechanics behind the scenes. Next, delve into Solidity to grasp its basic syntax and contract development. Familiarize yourself with essential tools like compilers and frameworks such as Hardhat and Truffle.</p><p>Additionally, consider exploring popular Capture The Flag (CTF) competitions like “Capture The Ether” or “<strong>Secureum</strong>.” These events offer valuable opportunities to enhance your knowledge of smart contracts and Solidity. Reading past audit reports from platforms like <strong>Code4rena</strong>, <strong>Sherlock</strong>, <strong>Trail of Bits</strong>, and <strong>OpenZeppelin</strong> can also provide insights into how vulnerabilities are discovered and exploited.</p><p>Remember that you don’t need to go through all these steps in great detail. The goal is to familiarize yourself with the concepts and common smart contract vulnerabilities. As you become more comfortable, you can participate in contests and hone your skills further.</p><p>I even shared my thoughts on this topic through a tweet a while ago. The key idea here is that there could be numerous ways to learn about auditing, but you don’t need to pursue all of them. You should focus on gaining a solid understanding of the core concepts and the underlying mechanisms at play. Once you grasp the essence of concepts like reentrancy and understand the common patterns associated with it, you can apply that knowledge when auditing real codebases. <strong>There’s no need to exhaustively read every issue related to reentrancy;</strong> that would be incredibly time-consuming.</p><p>If you’re looking for a <strong>more structured approach,</strong> you can opt for curated content or courses. These are particularly beneficial for beginners.</p><p><strong>For mid-level auditors:</strong></p><p>However, if you’ve already started auditing and consider yourself a mid-level auditor, you can take a different path.</p><p>One approach I find valuable is following top auditors in the field. Many highly skilled auditors are active on platforms like Twitter and maintain blogs where they share valuable insights. They publish articles and post-mortems about their audit experiences. Following them, engaging in conversations, and even reaching out with questions can be a great way to learn. Most of the time, these top auditors are willing to respond and offer guidance. I used to reach out to experienced developers and auditors when I was starting, and it was incredibly helpful.</p><p>Another valuable practice is reading their audit reports. By examining the bugs they discovered in various projects, you can get inside their mindset. You’ll gain a better understanding of how they approached certain code scenarios and identified vulnerabilities. This deepens your knowledge and enhances your auditing skills.</p><p>I believe in developing a <strong>structured bug-finding process.</strong> This process involves categorizing common types of bugs into several categories.</p><p>The first category includes <strong>EVM (Ethereum Virtual Machine) and Solidity-level bugs</strong>, such as overflows, rounding issues, and problems with external calls. When dealing with external calls, there are various scenarios to consider, like reentrancy, reverts, and gas consumption.</p><p>The second category comprises <strong>project-specific bugs.</strong> These are logical flaws within the codebase, like issues with interest rate calculations or liquidation processes. Deviations from project specifications are also considered bugs.</p><p><strong>Composability bugs</strong> form the third category. These bugs arise due to integrations with external protocols. They involve scenarios where your protocol interacts with other systems, and you must ensure it handles different types of tokens correctly. This category also includes cases where your code depends on specific EIPs (Ethereum Improvement Proposals) and how well your implementation aligns with them.</p><p>The final category is <strong>chain-level bugs.</strong> These bugs are specific to the blockchain you’re working on, such as Ethereum, Arbitrum, or Optimism. They involve understanding the differences in the EVM and handling scenarios like front-running.</p><p>In addition to these categories, I follow a thorough <strong>threat modeling approach.</strong> This involves testing <strong>various input values for functions</strong>, <em>exploring all possible contract states, examining multiple invocations of functions, and intentionally breaking the expected order of execution.</em> By doing so, I uncover how the protocol behaves under different conditions and scenarios.</p><p>Regarding code decompilation and bytecode analysis, I don’t frequently encounter them in my audits because I usually have access to the source code. Decompilation becomes more relevant when dealing with unverified contracts on a blockchain. In such cases, it’s essential to decompile and analyze the bytecode to understand the contract’s functionality.</p><p>Lastly, <strong>I maintain two separate repositories</strong> for the codebases I audit. One remains unchanged and serves as the original, while the second contains my notes, audit texts, and additional test cases. This separation helps keep the original codebase clean and prevents my comments or notes from interfering with the code’s readability. It also allows me to maintain a <strong>pristine version of the code</strong> for reference and future audits.</p><p><strong>Mis4nthrOpic | OS:</strong> Akshay, could you share your thoughts on the importance of result analysis in the auditing process?</p><p><strong>Akshay Srivastav:</strong> Absolutely, Mis4nthrOpic. <strong>Result analysis</strong> is a crucial aspect of the auditing process. When auditors participate in contests or review codebases, it’s essential to compare their findings with those of other auditors. Suppose, for instance, I discover only two issues in a codebase while there are a total of ten vulnerabilities present. In that case, I need to analyze why I missed the other eight issues. This analysis helps me identify the reasons behind missing those bugs, ensuring that I won’t overlook similar issues in the future.</p><p><strong>Mis4nthrOpic | OS:</strong> It seems like you’re continually reviewing contest results and findings. Is this a daily practice for you?</p><p>Akshay Srivastav: While I don’t <strong>review</strong> every <strong>contest’s results</strong> daily, I do make it a point to thoroughly examine all the issues in the contests I participate in. This is because, when I conduct a rigorous audit on a codebase and still miss some bugs, <strong>it’s crucial to analyze what went wrong.</strong> By reading and understanding the issues <strong>I initially overlooked</strong>, I aim to improve my auditing skills and ensure I can identify and report such problems in the future.</p><p><strong>Mis4nthrOpic | OS:</strong> Many auditors, especially <strong>beginners</strong>, often struggle with a <strong>lack of confidence</strong> when they start auditing. How do you suggest they overcome this challenge?</p><p><strong>Akshay Srivastav:</strong> Building confidence as an auditor is indeed a journey, and it can be challenging at the beginning. It mainly stems from the overwhelming amount of knowledge one needs to acquire in a limited timeframe. To address this, I recommend a focused approach. You don’t need to learn everything about auditing at once. Start by grasping the core concepts, such as reentrancy attacks and common vulnerability patterns.</p><p>Additionally, consider learning from established auditors and experts in the field. Follow them on platforms like Twitter, read their blog posts, and engage in conversations with them. When I was starting, I reached out to experienced developers and auditors to ask questions about audits, Solidity, Ethereum, and related topics. Surprisingly, most experts are willing to help and provide guidance.</p><p>Moreover, stay updated by reading blogs, newsletters, and post-mortems related to security in the blockchain space. Learning from others’ experiences will expand your knowledge base, making you better equipped to find and understand bugs in future projects.</p><p><strong>Mis4nthrOpic | OS:</strong> It’s essential to have a structured approach to audits. Could you share your method for auditing smart contracts?</p><p><strong>Akshay Srivastav:</strong> Certainly. I have a systematic process that I follow during audits. I’ll break it down into key steps:</p><ol><li><strong>Setting up the Repository</strong>: Begin by setting up the codebase repository and running any provided test cases. This helps you understand the code’s basic functionality.</li><li><strong>Creating Duplicate Repositories</strong>: Maintain two copies of the codebase. The first one remains untouched, while the second one is used for notes, comments, and audit-related information. This separation keeps the original codebase clean.</li><li><strong>Thoroughly Reviewing the Code</strong>: Analyze the code in-depth, looking for vulnerabilities and logical flaws. Pay attention to discrepancies between project specifications and the actual implementation.</li><li><strong>Threat Modeling</strong>: Consider various threat scenarios, including different input values, contract states, and the order of execution. Explore extreme scenarios and boundary conditions.</li><li><strong>Testing Multiple Function Invocations</strong>: Test functions with various input permutations to check how the protocol behaves under different conditions. This includes testing functions in a different order than the expected sequence.</li><li><strong>Exploring External Calls and Protocols</strong>: If the code interacts with external protocols or contracts, simulate interactions with those external entities to understand how they impact your code.</li><li><strong>Dealing with Auditing Remarks</strong>: Add audit remarks or comments to the duplicate repository if you find issues. Avoid adding comments directly to the original codebase to prevent distractions.</li><li><strong>Comparing Results</strong>: After completing the audit, compare your findings with those of other auditors or reviewers. This helps validate your observations and ensures comprehensive coverage.</li></ol><p><strong>Mis4nthrOpic | OS:</strong> Your approach sounds thorough and structured. Do you also delve into reverse engineering or analyzing bytecode during your audits?</p><p><strong>Akshay Srivastav:</strong> <strong>Reverse engineering</strong> and bytecode analysis can be valuable, but I primarily use them when I’m dealing with unverified contracts on a blockchain. In most audits, I already have access to the source code, so decompilation isn’t a frequent requirement. However, when auditing unverified contracts, decompiling bytecode can help in understanding their behavior and vulnerabilities.</p><p>In addition, I have a strategy where I divide my audit duration into three to four phases. For instance, in a 10-day audit, I would break it down as follows:</p><h3>Phase 1: Preliminary Assessment</h3><p>The initial 10% of the time, typically the first day, is dedicated to <strong>conducting quick scans</strong> of the code and reviewing the documentation. This initial scan helped me grasp the architectural structure of the codebase. It allows me to <strong>understand the protocol’s intentions</strong>, whether it’s a lending protocol, an NFT project, or an automated market maker (AMM).</p><p>I also <strong>create diagrams</strong> during this phase. These diagrams outline the external API of the codebase, highlighting the functions that change the contract’s state. By identifying these key functions, such as ‘update pool,’ ‘deposit,’ ‘withdraw,’ and ‘harvest,’ I establish a clear overview of the contract’s entry and exit points, which is crucial for both auditors and potential attackers. Additionally, I create state transition diagrams to visualize user actions, such as depositing, collecting rewards, and withdrawing.</p><p>Furthermore, I <strong>construct a flow of funds diagram</strong> to identify the contracts responsible for holding funds and the functions that allow users to interact with these funds. This step helps pinpoint critical areas within the codebase that might contain vulnerabilities.</p><p>On the first day, I also <strong>generate basic test cases</strong> for the entire flow of the codebase. These tests ensure that basic functionalities like user deposits, reward collection, and withdrawals are functioning correctly.</p><h3>Phase 2: Manual Review</h3><p>The next phase, which consumes the next 50% of my time, is focused on manual code review. During this stage, I divide my review into two parts: <strong>EVM context</strong> and <strong>Protocol context.</strong></p><p>In the <strong>EVM context</strong>, I aim to uncover low-level vulnerabilities. For example, I scrutinize statements where values are subtracted from state variables, looking for scenarios where the subtracted amount might exceed the state variable’s value, potentially causing a contract to revert. While this may not apply in simple cases, it’s vital in more complex systems with subtraction operations.</p><p>In addition to subtraction operations, I investigate issues related to integer overflows, rounding problems, and external calls. By addressing these aspects in the EVM context, I can uncover vulnerabilities that might otherwise remain hidden.</p><p>The <strong>Protocol context</strong> is the second part of my manual review. Here, I maintain a mental model of how the protocol should function. For instance, in a staking contract, I anticipate that when a user deposits, certain state variables should change, and these changes should be reversed when the user withdraws. If I encounter state variables that aren’t reset as expected, it could indicate a bug.</p><h3>Phase 3: Issue Resolution</h3><p>Finally, the last 30–40% of my time is dedicated to <strong>resolving audit remarks.</strong> This involves addressing any issues or findings that arose during the audit. I ensure that each remark either results in a resolved issue or is deemed acceptable. I also apply threat modeling, providing various input values and testing different scenarios for all functions. This helps identify vulnerabilities or weaknesses that might not be apparent during a standard code review.</p><p>I also <strong>explore edge cases</strong>, such as flash loan scenarios, to determine if the codebase handles extreme situations correctly. This phase is essential for ensuring the protocol’s robustness and security.</p><p>Regarding the <strong>tools I employ</strong>, I follow a minimalist approach. I primarily use <strong>Visual Studio Code</strong> (VS Code) with the <strong>SolVisual Auditor extension</strong> for code highlighting and bookmarks. For testing, I utilize tools like <strong>Truffle</strong> and <strong>Chisel</strong>, which allow for efficient code snippet testing and validation. Additionally, I use <strong>command generators</strong> to simplify complex mathematical operations, making them more readable and manageable.</p><p>Here are some additional tips:</p><ol><li>Focus on auditing one codebase at a time to achieve better coverage and discover more bugs.</li><li>Take <strong>regular breaks</strong> during your audit sessions to maintain a fresh perspective and avoid burnout.</li><li><em>Don’t dive too deeply into protocol documentation</em> unless necessary. Concentrate on the codebase itself to understand how functions and states behave.</li><li><strong>Choose complex codebases</strong> for auditing, as they offer more opportunities to find vulnerabilities.</li></ol><p><strong>Regarding public contests</strong>, it’s beneficial to participate even if there’s intense competition. You might discover unique vulnerabilities that set you apart from other participants. This space is continually evolving, offering numerous opportunities for auditors.</p><p><strong>Mis4nthrOpic | OS:</strong> Thank you for joining us today. We’ve had an insightful conversation, and I want to dive deeper into your strategies for auditing smart contracts. Let’s discuss how you <strong>approach</strong> auditing various smart contracts and what factors you consider when selecting a project.</p><p><strong>Akshay Srivastav:</strong> Absolutely, happy to delve into that. When it comes to auditing smart contracts, it’s crucial to be strategic in your approach. I typically consider several factors when choosing a project to audit. First and foremost, <strong>I look at the project’s reputation.</strong> Reputed projects are more likely to honor their rewards when you report issues compared to newer, less-established projects. This ensures that my efforts are rewarded appropriately.</p><p>Furthermore, I take into account the <strong>diversity of opportunities</strong> available. If multiple contests are running on different platforms simultaneously, I assess the competition. Some auditors may focus on one contest, while others concentrate on another. This diversification reduces competition and increases the chances of obtaining better rewards.</p><p>Another essential aspect is maintaining a <strong>healthy work-life balance</strong>. In this industry, there are endless opportunities, ranging from bounties to private audits and public contests. Auditors often strive to participate in all of them or dedicate excessive hours to secure more rewards. However, this can lead to burnout, adversely affecting both their health and future audit performance. Therefore, it’s crucial to strike a balance.</p><p><strong>Mis4nthrOpic | OS:</strong> That’s some valuable insight. Could you provide an example of a specific auditing strategy that you employ?</p><p><strong>Akshay Srivastav:</strong> Certainly. I like to categorize my auditing strategies into two approaches: <strong>top-down and bottom-up.</strong> The choice between these approaches depends on my preference and the time available for the project. If time is limited, I focus on auditing the main contracts to uncover potential vulnerabilities. However, if there’s ample time, I analyze each component of the codebase thoroughly. The more in-depth the analysis, the higher the chances of finding vulnerabilities.</p><p><strong>Mis4nthrOpic | OS:</strong> How do you <strong>prepare</strong> yourself before diving into a codebase? Do you start by reading the project documentation or do you immediately jump into the code?</p><p><strong>Akshay Srivastav:</strong> I believe in a <strong>balanced approach.</strong> I begin by quickly scanning the project documentation to gain a basic understanding of the codebase’s nature. This initial overview helps me form a mental map of what to expect. However, I also aim to approach the code with fresh eyes, avoiding preconceived notions. This way, I can maintain objectivity and better identify potential issues.</p><p>When dealing with codebases that include options or similar complex financial products, <strong>I adopt a progressive approach.</strong> I start by auditing the smaller contracts within the codebase, gaining a solid understanding of their functionality. Once I’m comfortable with these components, I move on to the more intricate parts. There are often recurring patterns in options protocols, so grasping one can significantly expedite the understanding of others.</p><p><strong>Mis4nthrOpic | OS:</strong> Excellent. Let’s talk about handling codebases that contain a significant amount of <strong>assembly code or complex financial products</strong> like options. How do you tackle these challenges?</p><p><strong>Akshay Srivastav:</strong> Regarding assembly code, I recommend using <strong>tools like ChatGPT,</strong> as they are exceptionally helpful in explaining the assembly code’s functionality and identifying potential issues.</p><p><strong>Mis4nthrOpic | OS:</strong> <strong>Managing your time</strong> effectively during an audit is crucial. How do you distribute your time across different aspects of an audit, such as code review and testing? Also, do you have any preferred areas of focus within a smart contract?</p><p><strong>Akshay Srivastav:</strong> Time management is indeed vital in auditing. I maintain a consistent audit process that includes both code review and testing. My focus during an audit is <strong>not determined by the project’s domain</strong> <em>but by the codebase itself.</em> However, I have observed that I tend to perform better in lending markets, so when given a choice, I prioritize auditing these types of projects. The time I allocate to an audit depends on the codebase’s complexity and size. There’s no fixed duration, as each project is unique.</p><p><strong>Mis4nthrOpic | OS:</strong> You mentioned creating <strong>two repositories</strong> — one for the original code and another for your audit notes and findings. Can you elaborate on why you follow this practice instead of using branches within a single repository?</p><p><strong>Akshay Srivastav:</strong> Certainly. This is my approach to maintaining separation between my notes and audit-related materials and the original codebase. By having two distinct repositories, I ensure that my <strong>thought process remains uncluttered</strong>, allowing me to approach the code with a fresh perspective whenever I revisit it. It prevents me from becoming overly focused on previous audit remarks and encourages an unbiased review.</p><p><strong>Mis4nthrOpic | OS:</strong> One final question before we wrap up. You’ve shared some valuable insights today. What <strong>message or advice</strong> would you like to leave for our audience, especially those aspiring to enter the world of smart contract auditing?</p><p><strong>Akshay Srivastav:</strong> I’d like to emphasize that the blockchain and smart contract auditing space is both exciting and promising. The crypto market is continuously evolving, offering new opportunities and challenges. Even if it seems daunting from the outside, I encourage everyone to give it a try. You may discover a unique perspective or finding that sets you apart from the competition. Embrace the opportunities, stay curious, and keep learning in this dynamic field.</p><p><strong>Mis4nthrOpic | OS:</strong> Thank you for your valuable insights and for taking the time to share your expertise with us. It’s been a pleasure having you here. Goodbye, and until next time!</p><p><strong>Akshay Srivastav:</strong> Thank you for having me. It’s been a pleasure. Goodbye, everyone!</p><p>Follow me on x.com -&gt; x.com/sharonplima</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5f3b4cd65f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Subject: Journal on how I arrived at the correct test]]></title>
            <link>https://medium.com/@sharonphiliplima/subject-journal-on-how-i-arrived-at-the-correct-test-34d0b166b896?source=rss-a0ecd8b28114------2</link>
            <guid isPermaLink="false">https://medium.com/p/34d0b166b896</guid>
            <category><![CDATA[foundry]]></category>
            <category><![CDATA[solidity-tutorial]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[solidity-testing]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Sharon ]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 11:56:29 GMT</pubDate>
            <atom:updated>2023-09-05T17:02:13.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*diUa4KtY5h8974Q-gWLnlw.jpeg" /></figure><p>To, Sabit, #foundry, ^Blockchain, <a href="https://twitter.com/opensensepw"><strong>Opensense</strong></a></p><p>Subject: Journal on how I arrived at the correct test</p><p>Hello Sabit,</p><p>I hope this letter finds you well. I would like to provide you with a walkthrough of how I reached the current test case for the closeTrove function. I&#39;m documenting this to solidify my own understanding, and since I have some spare time, I thought it would be beneficial to share.</p><p>The contract in discussion: <a href="https://bscscan.com/address/0x0ed40e3cf31a4e7c79db8b1dda374f6508f2ff75?utm_source=immunefi#code">https://bscscan.com/address/0x0ed40e3cf31a4e7c79db8b1dda374f6508f2ff75?utm_source=immunefi#code</a></p><p>Upon initial inspection of your test file, it seemed apparent that the main objective was to incorporate the vm.prank() function.</p><pre>//interfaces...<br>contract TroveManageraTest is Test {<br>    TroveManager public tm;<br>    address bob = vm.addr(1);<br>    address mike = vm.addr(2);</pre><pre>    function setUp() public {<br>        tm = TroveManager(0x0ed40E3Cf31a4e7c79dB8b1DDA374f6508f2ff75);<br>    }</pre><pre>    function testcloseTrove() public {<br>        tm.closeTrove(bob);<br>        vm.expectRevert();<br>    }<br>}</pre><p>Which yielded:</p><pre>gitpod /workspace/ren (main) $ forge test -vvvv --fork-url $ETH_RPC_URL<br>[⠆] Compiling...<br>No files changed, compilation skipped</pre><pre>Running 1 test for test/lend.t.sol:TroveManageraTest<br>[FAIL. Reason: **Caller is not BorrowerOperations**] testcloseTrove() (gas: 9832)<br>Traces:</pre><p>I assumed that the live contract was on the ETH mainnet after seeing ETH_RPC_URL on your forge test command. When in reality, it was deployed to the BSC chain.</p><p>So, I carried on with that, being naive, as there was no issue with the compilation.</p><p>But, the error → <strong>Caller is not BorrowerOperations</strong> still remained.</p><p>I figured after a brief code lookup that I would have to set the BorrowerOperations first to stop getting the error.</p><p>→ The setAddresses() in the same contract required many other addresses in addition to the BorrowerOperations address</p><pre>function setAddresses(<br>        address _borrowerOperationsAddress,<br>        address _activePoolAddress,<br>        address _defaultPoolAddress,<br>        address _stabilityPoolAddress,<br>        address _gasPoolAddress,<br>        address _collSurplusPoolAddress,<br>        address _priceFeedAddress,<br>        address _lusdTokenAddress,<br>        address _sortedTrovesAddress,<br>        address _lqtyTokenAddress,<br>        address _lqtyStakingAddress,<br>        address _inflationFeedAddress<br>    )<br>        external<br>        override<br>        onlyOwner<br>    {<br>//state variable initialization ...</pre><p>I was like damn, I will have to get all of them.</p><p>So, I quickly assigned something random makeAddr(”some text”) while being oblivious to the fact that they need to be contract addresses and not just some EOAs!</p><p>The error → address code size cannot be zero or something like that. I haven’t memorized the error, aye!</p><p>Code size? uhm?</p><p>I realized that the setAddresses() had another check within itself</p><p>Welcome, imported contract → import &quot;./Dependencies/CheckContract.sol&quot;;</p><pre>function setAddresses(.....)<br>        external<br>        override<br>        onlyOwner<br>{<br>        checkContract(_borrowerOperationsAddress);<br>        checkContract(_activePoolAddress);<br>        checkContract(_defaultPoolAddress);<br>        checkContract(_stabilityPoolAddress);<br>        checkContract(_gasPoolAddress);<br>        checkContract(_collSurplusPoolAddress);<br>        checkContract(_priceFeedAddress);<br>        checkContract(_lusdTokenAddress);<br>        checkContract(_sortedTrovesAddress);<br>        checkContract(_lqtyTokenAddress);<br>        checkContract(_lqtyStakingAddress);<br>        checkContract(_inflationFeedAddress);<br>}</pre><p>Oh, on looking further… I found</p><pre>function checkContract(address _account) internal view {<br>        require(_account != address(0), &quot;Account cannot be zero address&quot;);<br>        uint256 size;<br>        // solhint-disable-next-line no-inline-assembly<br>        assembly <br>           { size := extcodesize(_account) }<br>        require(size &gt; 0, &quot;Account code size cannot be zero&quot;);<br>    }</pre><p>Alright, so maybe these addresses were initialized by the owner right after the contract creation, so I went to bscscan contract →transactions</p><p>Voila, I could find all of those addresses by looking at the TX hash of the Set Addresses method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*VX1JExgFpZTlW0nJZQatrw.png" /></figure><p>It was time to bring them all into my test</p><p>Before entering them as params, I refactored the addresses to the correct checksum format</p><p>So, <em>0x7c15c91f20cee5af460e3cafd4dc0b1302ff632f becomes </em><em>0x7c15C91F20cee5aF460e3CAfd4dc0B1302fF632f Yeah, yeah, just capital letters in some places.</em></p><p>There are two ways of doing this:</p><pre>Either go to the bnbscan and get the checksummed addresses<br>    //or<br>    //use -&gt; cast to-check-sum-address 0x7c15c91f20cee5af460e3cafd4dc0b1302ff632f<br>    //I prefer the **former** as I get to see the contract names.</pre><p>Why?</p><ul><li>In the context of cryptocurrencies like Bitcoin and Ethereum, checksum addresses are used to prevent users from sending funds to incorrect addresses due to typos or mistyped characters. Without checksums, a single-character mistake could lead to the loss of funds, but with checksums, the error can be caught before the transaction is processed.</li><li>Some characters in checksummed addresses are capitalized to create a standardized format and to improve the reliability of address entry and verification.</li></ul><p>After running the forge test … I started to get errors with address code size cannot be zero But, I had all the addresses individually verified from Bscscan in place. All of them were contract addresses and none of them could have a code size of zero. None of them had self destruct function within them.</p><p>How could the error say → code size is zero</p><p>Argghh… It was frustrating by now. I had to take a break.</p><p>It usually breezes cold air on my terrace. I had to go there. I had to zone out. I needed to breathe! I came down after 15 mins. I started to write down the for loop</p><p>I needed to know which specific address could be the culprit!? because there are 11 of them.</p><p>I turned to #foundry in Opensense. Mis4nthropic and 0xRaion aided me further.</p><p>0xRaion pointed out that I was using ETH_RPC_URL instead of BNB_RPC_URL I was like yeah, everything’s working fine till now… Being so naive and oblivious at the same time.</p><p>He pointed out that BNB_RPC_URL does exist and it is for the BSCscan!</p><p>Oh damn, on further inquiry → it was found that all of the contracts except just one contract was <strong>are also present on the Ethereum mainnet!</strong></p><p>Now, after fixing those, I found that the new error was → Caller is not the Owner</p><p>Remember — the onlyOwner part? That’s why</p><pre>function setAddresses(.....)<br>        external<br>        override<br>        onlyOwner<br>{</pre><p>One thing to note here <strong><em>Sabit</em></strong>, is that whenever you are interacting with a live contract, the owner is always the deployer!</p><p>So, the deployer here is? Ans:</p><p>The From address which is named → Lendr Network: Deployer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*0u-JZ3zbKYupf69zoPWAOQ.png" /><figcaption>Lendr is -&gt; 0xC8e4292f7a852724D9cb5ACD160cF25e96911aBF</figcaption></figure><p>0xC8e4292f7a852724D9cb5ACD160cF25e96911aBF this exactly</p><p>So, vm.startPrank(this deployer address)?</p><p>Yes, but only for setAddresses, because if you look at the setAddresse() it has</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*PhOEgW1E72k5iOaSyJQpJA.png" /></figure><p>_renounceOwnership at the end of the code!</p><p>This means that the owner is now a zero address → 0x00000………..000</p><pre>vm.startPrank(0xC8e4292f7a852724D9cb5ACD160cF25e96911aBF);<br>tm.setAddresses(<br>            _borrowerOperationsAddress,<br>            _activePoolAddress,<br>            _defaultPoolAddress,<br>            _stabilityPoolAddress,<br>            _gasPoolAddress,<br>            _collSurplusPoolAddress,<br>            _priceFeedAddress,<br>            _lusdTokenAddress,<br>            _sortedTrovesAddress,<br>            _lqtyTokenAddress,<br>            _lqtyStakingAddress,<br>            _inflationFeedAddress<br>        );<br>        vm.stopPrank();</pre><p>The test looks something like the above for now.</p><p>Next, we need to add functionality for checking the working on closeTrove</p><p>I started pranking with the _borrowerOperationsAddress coz remembered the error.</p><p>The caller is not BorrowOperations.</p><p>So, I created two players… bob and sabit…</p><p>I don’t know what troves are or what the contract does → coz I didn’t read it.</p><p>All I knew was that we could expect a revert!</p><p>And to be specific… “Only one trove in the system” is the revert’s message</p><p>coz Apparently an array and a double-sided list are both getting updated with new addresses and nodes respectively. So, I found it hard to simulate them on my test :)</p><pre>vm.startPrank(_borrowerOperationsAddress);<br>        tm.addTroveOwnerToArray(bob);<br>        tm.addTroveOwnerToArray(sabit);<br>        vm.expectRevert(bytes(&quot;Only one trove in the system&quot;));<br>        tm.closeTrove(sabit);<br>        vm.stopPrank();</pre><p>AND THAT WAS IT, OUR TEST —</p><p>DIDN’T PASS!</p><p>HAHA!</p><p>That’s coz</p><pre>Test result: FAILED. 0 passed; 1 failed; 0 skipped; finished in 4.27s<br>Ran 1 test suites: 0 tests passed, 1 failed, 0 skipped (1 total tests)</pre><pre>Failing tests:<br>Encountered 1 failing test in test/TroveManageraTest.t.sol:TroveManageraTest<br>[FAIL. Reason: Ownable: caller is not the owner] testcloseTrove() (gas: 36342)</pre><p>In the setAddresses() function the deployer does this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*PhOEgW1E72k5iOaSyJQpJA.png" /><figcaption>_renounceOwnership(); in setAddresses()</figcaption></figure><p>which sets the address to → 0x00000…….000</p><p>Remember right?</p><p>so, the one we used with vm.startPrank(0xC8e4292f7a852724D9cb5ACD160cF25e96911aBF) renounces its ownership!</p><p>What could be the solution?</p><p>Any guesses?</p><h3>It’s time travel! we need a second chance</h3><p>Go back to the block before the block the original deployer renounced the ownership!</p><p>So, if 30254248 is when setAddresses() was called.</p><p>then, I had to go to 30254247</p><p>So, the forge test script should be→</p><pre>forge test --mt testcloseTrove -vvvv --fork-url $BNB_RPC_URL --fork-block-number 30254247</pre><p>And voila, our test was passed!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*ydQEnP1fKYsrjtltkei17A.png" /><figcaption>forge test — mt testcloseTrove -vvvv — fork-url $BNB_RPC_URL — fork-block-number 30254247</figcaption></figure><h3>Here is the full test for you:</h3><pre>// SPDX-License-Identifier: UNLICENSED<br>pragma solidity ^0.8.19;</pre><pre>import {Test, console} from &quot;forge-std/Test.sol&quot;;</pre><pre>interface TroveManager {<br>    function setAddresses(<br>        address _borrowerOperationsAddress,<br>        address _activePoolAddress,<br>        address _defaultPoolAddress,<br>        address _stabilityPoolAddress,<br>        address _gasPoolAddress,<br>        address _collSurplusPoolAddress,<br>        address _priceFeedAddress,<br>        address _lusdTokenAddress,<br>        address _sortedTrovesAddress,<br>        address _lqtyTokenAddress,<br>        address _lqtyStakingAddress,<br>        address _inflationFeedAddress<br>    ) external;<br>    function addTroveOwnerToArray(address _borrower) external returns (uint256 index);</pre><pre>    function closeTrove(address _borrower) external;<br>}</pre><pre>contract TroveManageraTest is Test {<br>    TroveManager public tm;</pre><pre>    address public _borrowerOperationsAddress = 0x7c15C91F20cee5aF460e3CAfd4dc0B1302fF632f;<br>    address public _activePoolAddress = 0x338A0c640067EF1C436d2731DC38F62Fc3AB8806;<br>    address public _defaultPoolAddress = 0x85dd7996ab66B4fF86BE82E414cC37b56805d4ac;<br>    address public _stabilityPoolAddress = 0xB564D3Fd456EBdC92CF4B51d426e862b11c846Be;<br>    address public _gasPoolAddress = 0x297753023cB9F741E812224529eb3A322FfBC93e;<br>    address public _collSurplusPoolAddress = 0x32BFeedbE97e573dEe96a77E8A2Cea09503d9929;<br>    address public _priceFeedAddress = 0x7be8c30dfad51f017a5f81484A9b945492dc1871;<br>    address public _lusdTokenAddress = 0x79Db48246c431C3603881C347744EB1366D63Bac;<br>    address public _sortedTrovesAddress = 0x1bAccD443e5D1559A0A90520C3b527D4DA24495b;<br>    address public _lqtyTokenAddress = 0x349bdd558bf034519a7a2559efA20347d8A36493;<br>    address public _lqtyStakingAddress = 0x4a056599A8FD5B53081C41c903562337E3700D7a;<br>    address public _inflationFeedAddress = 0x4948264C57985cDC5DA515328C4Af889d00Cba8d;</pre><pre>    address[] public list = [<br>        _borrowerOperationsAddress,<br>        _activePoolAddress,<br>        _defaultPoolAddress,<br>        _stabilityPoolAddress,<br>        _gasPoolAddress,<br>        _collSurplusPoolAddress,<br>        _priceFeedAddress,<br>        _lusdTokenAddress,<br>        _sortedTrovesAddress,<br>        _lqtyTokenAddress,<br>        _lqtyStakingAddress,<br>        _inflationFeedAddress<br>    ];</pre><pre>    // uint256 owner = 0xC8e4292f7a852724D9cb5ACD160cF25e96911aBF;</pre><pre>    address sabit = makeAddr(&quot;sabit&quot;); //lemme make you -&gt; _borrowerOperationsAddress?<br>    address bob = makeAddr(&quot;bob&quot;);</pre><pre>    function setUp() public {<br>        tm = TroveManager(0x0ed40E3Cf31a4e7c79dB8b1DDA374f6508f2ff75);<br>        console.log(msg.sender);<br>    }</pre><pre>   <br>    function testCheckContract() public view {<br>        address _account;<br>        uint256 size;</pre><pre>        for (uint256 i = 0; i &lt; list.length; i++) {<br>            _account = list[i];<br>            require(_account != address(0), &quot;Account cannot be zero address&quot;);</pre><pre>            // solhint-disable-next-line no-inline-assembly<br>            assembly {<br>                size := extcodesize(_account)<br>            }<br>            console.log(size);<br>            if (size == 0) {<br>                console.log(list[i]);<br>            }<br>            require(size &gt; 0, &quot;Account code size cannot be zero&quot;);<br>        }<br>    }</pre><pre>    function testSingleSize() public view {<br>        //0x349bdd558bf034519a7a2559efA20347d8A36493<br>        address _account = 0x349bdd558bf034519a7a2559efA20347d8A36493;<br>        uint256 size;<br>        assembly {<br>            size := extcodesize(_account)<br>        }<br>        require(size &gt; 0, &quot;Account code size cannot be zero&quot;);<br>    }</pre><pre>    function testcloseTrove() public {<br>        vm.startPrank(0xC8e4292f7a852724D9cb5ACD160cF25e96911aBF);</pre><pre>        tm.setAddresses(<br>            _borrowerOperationsAddress,<br>            _activePoolAddress,<br>            _defaultPoolAddress,<br>            _stabilityPoolAddress,<br>            _gasPoolAddress,<br>            _collSurplusPoolAddress,<br>            _priceFeedAddress,<br>            _lusdTokenAddress,<br>            _sortedTrovesAddress,<br>            _lqtyTokenAddress,<br>            _lqtyStakingAddress,<br>            _inflationFeedAddress<br>        );<br>        vm.stopPrank();</pre><pre>        vm.startPrank(_borrowerOperationsAddress);<br>        tm.addTroveOwnerToArray(bob);<br>        tm.addTroveOwnerToArray(sabit);<br>        vm.expectRevert(bytes(&quot;Only one trove in the system&quot;));<br>        tm.closeTrove(sabit);<br>        vm.stopPrank();<br>    }<br>}</pre><pre>//forge test --mt testcloseTrove -vvvv --fork-url $BNB_RPC_URL --fork-block-number 30254247</pre><p>You may ignore → testCheckContract and testSingleSize</p><h3>Key takeaways</h3><ul><li>The owner is always the deployer of the contract. So in a live contract go to the transactions and see who had deployed it.</li><li>Use the correct — fork-url. Sometimes the contracts are deployed on many chains and can fool you!</li><li>Simulate the previous code if you wanna test a particular function. That means you can’t simply arrive and expect to test closeTrove without meeting the preconditions → which are onlyOwner, checkContract(checks the size of the contract and zero address), borrowOperations… etc</li><li>Use vm.startPrank() strategically!</li><li>Use unit tests inside of the test to check if all the code is intact</li></ul><p>In our case, Sabit, I used testCheckContract and testSingleSize</p><ul><li>Use expectRevert along with the message vm.expectRevert(bytes(&quot;Only one trove in the system&quot;)); because there can be many revert statements in the code.</li><li>Use --fork-block-number flag to go back in time, coz the deployer might have just abandoned their ownership!</li></ul><p>I hope that it has added some value. I definitely learned a lot doing this.</p><p>Cheers to you, Sabit for being consistent while asking.</p><p>Cheers to Mis4anthropic and 0xarno for their help.</p><p>Cheers to OpenSense for the unbiased community.</p><p>Cheers to Sharon for spending almost the entire night on this. ^^ ))</p><p>Say my regards to the Nigerian fellow devs and researchers in the space!</p><p>Your comrade in war,</p><p>Sharon</p><p>x.com profile — @sharonplima</p><p>P.S: I am open to further improvements to this post</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34d0b166b896" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>