Back to all

how-to-ensure-smart-contract-security
Crypto

How to Ensure Smart Contract Security

<p><span style="font-weight: 400;">Smart contracts enable people to do extraordinary things! For example, in 2015, two women set out on a journey to create a startup that would allow for a more efficient </span><a href="https://www.kidner-project.com/"><span style="font-weight: 400;">kidney transplant matching</span></a><span style="font-weight: 400;">.&nbsp;</span></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">In the legal world, smart contract technology can significantly lower the costs of signing a legal agreement since no lawyer or other intermediary is needed. Smart contracts also allow crypto gamers to create, store and transfer NFTs. However, for all of this to function properly, ensuring smart contract security is the key.</span></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">In this article, we'll first briefly explain </span><a href="https://wizardia.io/blog/introduction-to-smart-contracts"><span style="font-weight: 400;">what smart contracts are</span></a><span style="font-weight: 400;"> and go through their vulnerabilities. But, most importantly, we'll cover smart contract security and how to ensure it.</span></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">Terms and concepts related to blockchain security are pretty technical, but we did our best to keep it simple so you can feel confident about what to do next in your crypto journey.</span></p> <p>&nbsp;</p> <h2 id="what-are-smart-contracts">What are smart contracts?</h2> <p><span style="font-weight: 400;">Smart contracts are pieces of code on a </span><a href="https://wizardia.io/blog/what-is-blockchain"><span style="font-weight: 400;">blockchain</span></a><span style="font-weight: 400;"> where a network of computers runs smart contracts once predetermined conditions are met. The logic is pretty straightforward: if/when something happens, something else follows.&nbsp;</span></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">Smart contracts are beneficial since they automate the execution of agreements and workflows, helping to save time and minimize costs since no intermediary is needed. All participants can be sure of the wanted outcome.&nbsp;</span></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">Think of smart contracts as vending machines!</span></p> <p>&nbsp;</p> <p><span style="font-weight: 400;"><picture><source srcset="https://wizardia.io/images/blog/thumb/1-smart-contracts-as-vending-machines-4832.webp 576w, https://wizardia.io/images/blog/inner/1-smart-contracts-as-vending-machines-4832.webp " type="image/webp"></source><source srcset="https://wizardia.io/images/blog/thumb/1-smart-contracts-as-vending-machines-4832.jpg 576w, https://wizardia.io/images/blog/inner/1-smart-contracts-as-vending-machines-4832.jpg " type="image/jpg"></source><img srcset="https://wizardia.io/images/blog/thumb/1-smart-contracts-as-vending-machines-4832.jpg 576w, https://wizardia.io/images/blog/inner/1-smart-contracts-as-vending-machines-4832.jpg " alt="A picture with two vending machines." loading="lazy" width="1471" height="981"></picture></span></p> <p class="text-center" style="text-align: center;"><span style="font-weight: 400;">Image source: <a href="https://wizardia.io/v1/admin/articles/86/unsplash.com" target="_blank" rel="noopener">unsplash.com</a></span></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">For example, your lobby's vending machine has a rule that if you insert a dollar, you can get a candy bar of your choice. When you insert your dollar, the vending machine verifies that it's the correct amount and gives you your snack. This is how smart contracts work, too, except they're much smarter and more secure.</span></p> <p>&nbsp;</p> <p><picture><source srcset="https://wizardia.io/images/blog/thumb/2-how-smart-contracts-work-8463.webp 576w, https://wizardia.io/images/blog/inner/2-how-smart-contracts-work-8463.webp " type="image/webp"></source><source srcset="https://wizardia.io/images/blog/thumb/2-how-smart-contracts-work-8463.jpg 576w, https://wizardia.io/images/blog/inner/2-how-smart-contracts-work-8463.jpg " type="image/jpg"></source><img srcset="https://wizardia.io/images/blog/thumb/2-how-smart-contracts-work-8463.jpg 576w, https://wizardia.io/images/blog/inner/2-how-smart-contracts-work-8463.jpg " alt="An image detailing how smart contracts work in a course of action: Pre-defined contract (terms and conditions are agreed by all the parties involved) -&gt; Events (execution of the contract is triggered by an event) -&gt; Execution (the smart contract is executed automatically) -&gt; Settlement (all the settlements are executed quickly and efficiently)." loading="lazy" width="2560" height="1140"></picture></p> <p class="text-center" style="text-align: center;"><span style="font-weight: 400;">Image source: </span><a href="https://wizardia.io/v1/admin/articles/86/dcxlearn.com"><span style="font-weight: 400;">dcxlearn.com</span></a></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">So, at the core, smart contracts are pieces of code that:</span></p> <ol> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Store rules</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Verify rules</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Self-execute rules</span></li> </ol> <p>&nbsp;</p> <p><strong>Deploying smart contracts</strong></p> <p><span style="font-weight: 400;">Smart contracts are widely used in the crypto gaming sector, and the business world is also beginning to embrace them. Their ability to execute automatically without intermediaries like governments, corporations and even lawyers is fascinating. There are numerous applications of smart contracts in the financial sector, IoT, supply chain, etc.</span></p> <p>&nbsp;</p> <h2 id="types-of-smart-contracts">Types of smart contracts&nbsp;</h2> <p><span style="font-weight: 400;">The need for smart contract security tools can also depend on the type of smart contracts, so let's quickly go over the four most popular types of smart contracts. They are categorized according to how programmers use them to create applications.</span></p> <p>&nbsp;</p> <ol> <li><strong>Distributed Applications (DApps).</strong><span style="font-weight: 400;"> DApps are digital applications that operate autonomously on a blockchain in combination with other smart contracts. They are the most common application-based codes that work with smart contracts.</span><span style="font-weight: 400;"><br><br></span></li> <li><strong>Decentralized Autonomous Organizations (DAOs). </strong><span style="font-weight: 400;">A </span><a href="https://wizardia.io/blog/what-is-dao"><span style="font-weight: 400;">DAO</span></a><span style="font-weight: 400;"> is a decentralized organization controlled by a group of people who agree with specific rules for a shared goal. Smart contracts are the backbone of these organizations-they define the rules established inside DAOs, which can't be affected by external entities.</span><span style="font-weight: 400;"><br><br></span></li> <li><strong>Contracts of Applied Logics (ALCs)</strong><span style="font-weight: 400;">.</span><strong> </strong><span style="font-weight: 400;">ALCs contain an application-based code that allows for communication across a smart contract with the front-end user interface. For example, ALCs help create and validate communication between IoT devices.</span></li> <li><strong>Smart Legal Contracts</strong><span style="font-weight: 400;"> &ndash; involves strict legal resources and are legally binding(also known as legally enforceable smart contracts). All the contractual agreements set are executed by a computer program automatically.</span></li> </ol> <p>&nbsp;</p> <h2 id="what-are-smart-contract-vulnerabilities">What are smart contract vulnerabilities?</h2> <p><span style="font-weight: 400;">Here are some of the most common smart contract security vulnerabilities:</span></p> <p>&nbsp;</p> <p><strong>1. DoS attacks</strong></p> <p><span style="font-weight: 400;">The Denial of Service (hence referred to as DoS) restricts authorized users from using smart contracts for a certain amount of time or permanently. Such attacks are done by overloading ports with requests or denying authentication.</span></p> <p>&nbsp;</p> <p><strong>2. Unencrypted files</strong></p> <p><span style="font-weight: 400;">Storing unencrypted information on the blockchain is one of the main threats to smart contract security-you can put your entire network in danger.</span></p> <p>&nbsp;</p> <p><strong>3. Not possible to upgrade</strong></p> <p><span style="font-weight: 400;">By definition, smart contracts are immutable-once you've put something on a blockchain, you can't modify it. However, certain risks come with that, too. For instance, bugs may prevent your smart contracts from running smoothly.&nbsp;</span></p> <p>&nbsp;</p> <p><strong>4. Function default</strong></p> <p><span style="font-weight: 400;">Functions are visible by default, therefore, meaning everyone can execute them.</span></p> <p>&nbsp;</p> <p><strong>5. Reentrancy Attack</strong></p> <p><span style="font-weight: 400;">Hackers can call functions repeatedly, withdraw balances from smart contracts and transfer to unauthorized contracts until no funds are left.</span></p> <p>&nbsp;</p> <p><strong>6. Oracle manipulation</strong></p> <p><span style="font-weight: 400;">If the oracle is corrupted, it can send false information on-chain. For example, with flash loans, a hacker could dramatically increase the “price” of a token and use this manipulated price to receive more funds than they should.</span></p> <p>&nbsp;</p> <h2 id="how-to-ensure-ethereum-smart-contract-security">How to ensure Ethereum smart contract security</h2> <p><span style="font-weight: 400;">Ethereum smart contracts are the most common. Let's quickly look at how you can keep them safe according to the guidelines of </span><a href="https://ethereum.org/en/developers/docs/smart-contracts/security/"><span style="font-weight: 400;">ethereum.org</span></a><span style="font-weight: 400;">.</span></p> <p>&nbsp;</p> <p><picture><source srcset="https://wizardia.io/images/blog/thumb/3-ethereum-smart-contracts-2222.webp 576w, https://wizardia.io/images/blog/inner/3-ethereum-smart-contracts-2222.webp " type="image/webp"></source><source srcset="https://wizardia.io/images/blog/thumb/3-ethereum-smart-contracts-2222.jpg 576w, https://wizardia.io/images/blog/inner/3-ethereum-smart-contracts-2222.jpg " type="image/jpg"></source><img srcset="https://wizardia.io/images/blog/thumb/3-ethereum-smart-contracts-2222.jpg 576w, https://wizardia.io/images/blog/inner/3-ethereum-smart-contracts-2222.jpg " alt="An image that shows the logo of the Ethereum blockchain in a dark background." loading="lazy" width="1497" height="968"></picture></p> <p class="text-center" style="text-align: center;"><span style="font-weight: 400;">Image source: <a href="https://wizardia.io/v1/admin/articles/86/unsplash.com" target="_blank" rel="noopener">unsplash.com</a></span></p> <p>&nbsp;</p> <p><strong>1. Develop your smart contracts according to the best practices</strong></p> <p><span style="font-weight: 400;">Do your best to write high-quality code.</span></p> <p>&nbsp;</p> <ul> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Make sure all of your code is stored in a version control system.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Use pull requests to make all code modifications.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Hire at least one independent reviewer to check your pull requests.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Use a development environment when compiling, testing, and deploying smart contracts.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Before merging each pull request, run your code using Mythril, Slither, or other basic code analysis tools.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Describe your smart contract architecture in a simple language and document it properly so that others can review your code easily.</span><span style="font-weight: 400;"><br><br></span></li> </ul> <p><strong>2. KISS (keep it simple, stupid)</strong></p> <p><span style="font-weight: 400;">The KISS principle is widely known among traditional software developers and is just as important when writing smart contracts.&nbsp;</span></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">One way to avoid pointless sophistication in your code is to reuse existing libraries like </span><a href="https://docs.openzeppelin.com/contracts/4.x/"><span style="font-weight: 400;">OpenZeppelin Contracts</span></a><span style="font-weight: 400;">. They've been tested numerous times, and you're much less likely to find bugs in them than trying to write code from scratch.</span></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">It's also advised to create small functions and split business logic across multiple smart contracts-it helps to keep them modular.</span></p> <p>&nbsp;</p> <p><strong>3. Implement secure access controls</strong></p> <p><span style="font-weight: 400;">Functions marked external or public can be called by any network participant. This is necessary if you want them to be able to interact with your smart contracts. However, this may also quickly become problematic if any person can run sensitive operations, such as minting new NFTs.</span></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">You must design proper access controls if you want to ensure that no unauthorized use of smart contracts occurs. Two patterns-the </span><strong>ownable pattern</strong><span style="font-weight: 400;"> and </span><strong>role-based control </strong><span style="font-weight: 400;">can help you do that.</span></p> <p><span style="font-weight: 400;">&nbsp;</span></p> <p><strong>4. Guard smart contract operations</strong></p> <p><span style="font-weight: 400;">Once your smart contract is deployed on the Ethereum blockchain, anyone can run public functions. You should implement internal safeguards beforehand to ensure correct contract behavior. Use these three statements: require(), assert(), revert().</span></p> <p>&nbsp;</p> <p><strong>5. Test your smart contracts extensively</strong></p> <p>&nbsp;</p> <p><strong><picture><source srcset="https://wizardia.io/images/blog/thumb/4-testing-smart-contracts-9117.webp 576w, https://wizardia.io/images/blog/inner/4-testing-smart-contracts-9117.webp " type="image/webp"></source><source srcset="https://wizardia.io/images/blog/thumb/4-testing-smart-contracts-9117.jpg 576w, https://wizardia.io/images/blog/inner/4-testing-smart-contracts-9117.jpg " type="image/jpg"></source><img srcset="https://wizardia.io/images/blog/thumb/4-testing-smart-contracts-9117.jpg 576w, https://wizardia.io/images/blog/inner/4-testing-smart-contracts-9117.jpg " alt='An image that shows a smartphone in a dark background, with text "Eat Sleep Code Repeat" displayed on the screen.' loading="lazy" width="1470" height="980"></picture></strong></p> <p class="text-center" style="text-align: center;"><strong><span style="font-weight: 400;">Image source: <a href="https://wizardia.io/v1/admin/articles/86/unsplash.com" target="_blank" rel="noopener">unsplash.com</a></span></strong></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">Since smart contracts are immutable, they require much more testing during their development. Looking for any unpredictable results will significantly increase your chances of implementing a secure smart contract code and ensure long-term user protection.</span></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">One of the best methods is to combine property-based testing with unit testing. Use</span><a href="https://ethereum.org/en/developers/docs/smart-contracts/testing/#static-dynamic-analysis"><span style="font-weight: 400;"> static and dynamic analysis</span></a><span style="font-weight: 400;"> to do that.</span></p> <p>&nbsp;</p> <p><strong>7. Have your code reviewed independently</strong></p> <p><span style="font-weight: 400;">Testing by yourself is not enough, and it's recommended to ask other developers to check your smart contract for possible vulnerabilities. You can organize a review of your code in two ways: commission a security audit (more on that later on) or set up a bug bounty.</span></p> <p>&nbsp;</p> <p><strong>7. Be ready for malicious exploits</strong></p> <p><span style="font-weight: 400;">Have a fallback plan ready in case someone attacks your smart contract. Such a plan should consist of three parts:</span><span style="font-weight: 400;"><br><br></span></p> <ul> <li aria-level="1"><strong>Smart contract upgrades. </strong><span style="font-weight: 400;">While, by definition, smart contracts can't be altered once deployed, you can still edit them a tiny bit with the help of upgrade patterns. You can read about it in detail </span><a href="https://ethereum.org/en/developers/docs/smart-contracts/upgrading/"><span style="font-weight: 400;">here</span></a><span style="font-weight: 400;">.</span></li> <li style="font-weight: 400;" aria-level="1"><strong>Emergency stops</strong><span style="font-weight: 400;">. While upgrade mechanisms may help, they take time to implement, and hackers can still cause you damage in the meantime. So, in case your smart contract becomes too vulnerable after its deployment, you must have an emergency stop ready for untrusted contracts. It will block calls to vulnerable functions in your contract.&nbsp;</span></li> <li aria-level="1"><strong>Event monitoring. </strong><span style="font-weight: 400;">Logging and monitoring events will give you insights into possible hacker actions. For example, you could write a code that emits an event each time someone runs a critical operation, e.g., withdraws funds. Event monitoring will increase your chances of securing authorized users by performing an upgrade or pausing essential functions.</span><span style="font-weight: 400;"><br></span></li> </ul> <p>&nbsp;</p> <p><strong>8. Create secure governance systems</strong></p> <p><span style="font-weight: 400;">If you want to decentralize your application and give control of key smart contracts to your community members, you need to be aware of the possible risks that come with such a governance model. For example, a hacker could take out a flash loan and carry out a malicious proposal with all the new voting power they've just acquired (it depends on the number of tokens held).</span></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">Use a timelock to prevent such attacks from happening. It delays administrative actions by preventing smart contracts from running specific function calls until a certain time has passed.</span></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">Another option is to assign a “voting weight” to each token. You can do it based on 1) the voting power of an address at a historical period or 2) the time the token has been locked up for.</span></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">Both ways help secure your decentralized governance systems by minimizing the potential to gather enough votes to influence on-chain votes quickly.</span></p> <p>&nbsp;</p> <p><strong>9. Protect yourself against potential vulnerabilities</strong></p> <p><span style="font-weight: 400;">Earlier in the article, we've listed five common smart contract vulnerabilities: DoS attacks, unencrypted files, difficulties upgrading smart contracts, function default, reentrancy attacks, and oracle manipulation. Below are some tips on how to defend against them.</span></p> <p>&nbsp;</p> <ul> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Make sure you first encrypt everything confidential before saving it on the blockchain.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Include failsafe into your contracts.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Check that all nodes have sufficient processing power and storage.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Create smart contracts that can be upgraded with proxies and emergency stops.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Create well-defined functions.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Prevent reentrancy attacks by following the </span><a href="https://docs.soliditylang.org/en/develop/security-considerations.html#use-the-checks-effects-interactions-pattern"><span style="font-weight: 400;">checks-effects-interactions pattern</span></a><span style="font-weight: 400;">.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Avoid oracle manipulation by using a decentralized oracle network that checks information from various sources, helping to steer clear of single points of failure.</span></li> </ul> <p>&nbsp;</p> <h2 id="smart-contract-security-audits">Smart contract security audits</h2> <p class="text-center" style="text-align: center;">&nbsp;</p> <p class="text-center" style="text-align: left;"><picture><source srcset="https://wizardia.io/images/blog/thumb/5-smart-contract-security-audits-7327.webp 576w, https://wizardia.io/images/blog/inner/5-smart-contract-security-audits-7327.webp " type="image/webp"></source><source srcset="https://wizardia.io/images/blog/thumb/5-smart-contract-security-audits-7327.jpg 576w, https://wizardia.io/images/blog/inner/5-smart-contract-security-audits-7327.jpg " type="image/jpg"></source><img srcset="https://wizardia.io/images/blog/thumb/5-smart-contract-security-audits-7327.jpg 576w, https://wizardia.io/images/blog/inner/5-smart-contract-security-audits-7327.jpg " alt="An illustration that shows how a smart contract security audit works with green animated icons representing the processes." loading="lazy" width="1600" height="900"></picture></p> <p class="text-center" style="text-align: center;"><span style="font-weight: 400;">Image source: </span><a href="https://icommunity.io/en/5-key-vulnerabilities-of-smart-contracts/"><span style="font-weight: 400;">icommunity.io</span></a></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">Minor mistakes in smart contract code can cost you millions. Thus, smart contract developers must carry out security audits before deploying contracts. Plus, frequent security audits help to gather valuable analytical insights like specifics regarding vulnerabilities.&nbsp;</span></p> <p>&nbsp;</p> <p><span style="font-weight: 400;">Here are the three standard steps of a security audit process:</span><span style="font-weight: 400;"><br><br></span></p> <ol> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Auditors gather details on code specifications to understand the objectives and scope of the smart contract in question.</span><span style="font-weight: 400;"><br><br></span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">You either get a manual or automated audit. Manual audits are usually more efficient since auditors don't need to depend on software.</span><span style="font-weight: 400;"><br><br></span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Auditors draft the security audit report. It's usually done after the initial stage of the audit has been completed. In this report, you should find your code issues and recommendations for resolving them. Once the issues are fixed, the auditors should provide you with the final report highlighting which remedial measures were implemented.</span></li> </ol> <p>&nbsp;</p> <h2 id="smart-contract-security-tools">Smart contract security tools</h2> <p><span style="font-weight: 400;">Here are a few useful tools for ensuring a smooth smart contract development:</span></p> <p>&nbsp;</p> <ul> <li style="font-weight: 400;" aria-level="1"><a href="https://ethereum.org/en/developers/docs/smart-contracts/testing/#testing-tools-and-libraries"><span style="font-weight: 400;">Testing tools and libraries</span></a><span style="font-weight: 400;"> &ndash; for analyzing smart contracts and checking code accuracy.</span></li> <li style="font-weight: 400;" aria-level="1"><a href="https://docs.openzeppelin.com/defender/sentinel"><span style="font-weight: 400;">OpenZeppelin Defender Sentinels</span></a><span style="font-weight: 400;"> &ndash; for automatically monitoring smart contracts and responding to events.</span></li> <li style="font-weight: 400;" aria-level="1"><a href="https://docs.openzeppelin.com/defender/admin"><span style="font-weight: 400;">OpenZeppelin Defender Admin</span></a><span style="font-weight: 400;"> &ndash; for secure administration of smart contracts.</span></li> <li style="font-weight: 400;" aria-level="1"><a href="https://consensys.net/diligence/"><span style="font-weight: 400;">ConsenSys Diligence</span></a><span style="font-weight: 400;"> &ndash; smart contract auditing services (note that this is just one of the plenty possible providers of security audits).</span></li> <li style="font-weight: 400;" aria-level="1"><a href="https://immunefi.com/"><span style="font-weight: 400;">Immunefi</span></a><span style="font-weight: 400;"> &ndash; a bug bounty platform that can help you to review your code and find vulnerabilities.&nbsp;</span></li> </ul> <p>&nbsp;</p> <h2 id="faqs">FAQs</h2> <p><strong>What are smart contract security best practices?</strong></p> <ol> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Write high-quality code to ensure a smooth development process.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Keep your code simple, so other developers can easily audit it.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Implement secure access controls.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Design internal safeguards to ensure correct contract behavior.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Test your smart contracts extensively.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Commission security audits or set up a bug bounty.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Design smart contract upgrades, emergency stops, and monitor events.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Use a timelock to create secure governance systems.</span></li> </ol> <p>&nbsp;</p> <p><strong>What is a smart contract security audit?</strong></p> <p><span style="font-weight: 400;">A smart contract security audit thoroughly examines your smart contract code. Its goal is to find potential vulnerabilities and inefficient coding and provide smart contract owners with recommendations on removing bugs.</span></p> <p>&nbsp;</p> <p><strong>What is a smart contract security checklist?</strong></p> <p><span style="font-weight: 400;">To ensure your smart contract security, follow this checklist recommended by Ethereum creators:</span></p> <ol> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Review your smart contracts for common vulnerabilities with Slither or Crytic.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Analyze special features of your smart contract, such as your upgradeability code or integration with 3rd party tokens.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Document the most important security properties and evaluate them with automated test generators.</span></li> <li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Manually check issues that can't always be found with automated tools: front-running transactions, risky interactions, or lack of privacy.</span></li> </ol>

10 min read
Dec 5, 2022
Julija Paškevičienė
Read this article

Smart contracts enable people to do extraordinary things! For example, in 2015, two women set out on a journey to create a startup that would allow for a more efficient kidney transplant matching

 

In the legal world, smart contract technology can significantly lower the costs of signing a legal agreement since no lawyer or other intermediary is needed. Smart contracts also allow crypto gamers to create, store and transfer NFTs. However, for all of this to function properly, ensuring smart contract security is the key.

 

In this article, we’ll first briefly explain what smart contracts are and go through their vulnerabilities. But, most importantly, we’ll cover smart contract security and how to ensure it.

 

Terms and concepts related to blockchain security are pretty technical, but we did our best to keep it simple so you can feel confident about what to do next in your crypto journey.

 

What are smart contracts?

Smart contracts are pieces of code on a blockchain where a network of computers runs smart contracts once predetermined conditions are met. The logic is pretty straightforward: if/when something happens, something else follows. 

 

Smart contracts are beneficial since they automate the execution of agreements and workflows, helping to save time and minimize costs since no intermediary is needed. All participants can be sure of the wanted outcome. 

 

Think of smart contracts as vending machines!

 

A picture with two vending machines.

Image source: unsplash.com

 

For example, your lobby’s vending machine has a rule that if you insert a dollar, you can get a candy bar of your choice. When you insert your dollar, the vending machine verifies that it’s the correct amount and gives you your snack. This is how smart contracts work, too, except they’re much smarter and more secure.

 

An image detailing how smart contracts work in a course of action: Pre-defined contract (terms and conditions are agreed by all the parties involved) -> Events (execution of the contract is triggered by an event) -> Execution (the smart contract is executed automatically) -> Settlement (all the settlements are executed quickly and efficiently).

Image source: dcxlearn.com

 

So, at the core, smart contracts are pieces of code that:

  1. Store rules
  2. Verify rules
  3. Self-execute rules

 

Deploying smart contracts

Smart contracts are widely used in the crypto gaming sector, and the business world is also beginning to embrace them. Their ability to execute automatically without intermediaries like governments, corporations and even lawyers is fascinating. There are numerous applications of smart contracts in the financial sector, IoT, supply chain, etc.

 

Types of smart contracts 

The need for smart contract security tools can also depend on the type of smart contracts, so let’s quickly go over the four most popular types of smart contracts. They are categorized according to how programmers use them to create applications.

 

  1. Distributed Applications (DApps). DApps are digital applications that operate autonomously on a blockchain in combination with other smart contracts. They are the most common application-based codes that work with smart contracts.

  2. Decentralized Autonomous Organizations (DAOs). A DAO is a decentralized organization controlled by a group of people who agree with specific rules for a shared goal. Smart contracts are the backbone of these organizations—they define the rules established inside DAOs, which can’t be affected by external entities.

  3. Contracts of Applied Logics (ALCs). ALCs contain an application-based code that allows for communication across a smart contract with the front-end user interface. For example, ALCs help create and validate communication between IoT devices.
  4. Smart Legal Contracts – involves strict legal resources and are legally binding(also known as legally enforceable smart contracts). All the contractual agreements set are executed by a computer program automatically.

 

What are smart contract vulnerabilities?

Here are some of the most common smart contract security vulnerabilities:

 

1. DoS attacks

The Denial of Service (hence referred to as DoS) restricts authorized users from using smart contracts for a certain amount of time or permanently. Such attacks are done by overloading ports with requests or denying authentication.

 

2. Unencrypted files

Storing unencrypted information on the blockchain is one of the main threats to smart contract security—you can put your entire network in danger.

 

3. Not possible to upgrade

By definition, smart contracts are immutable—once you’ve put something on a blockchain, you can’t modify it. However, certain risks come with that, too. For instance, bugs may prevent your smart contracts from running smoothly. 

 

4. Function default

Functions are visible by default, therefore, meaning everyone can execute them.

 

5. Reentrancy Attack

Hackers can call functions repeatedly, withdraw balances from smart contracts and transfer to unauthorized contracts until no funds are left.

 

6. Oracle manipulation

If the oracle is corrupted, it can send false information on-chain. For example, with flash loans, a hacker could dramatically increase the “price” of a token and use this manipulated price to receive more funds than they should.

 

How to ensure Ethereum smart contract security

Ethereum smart contracts are the most common. Let’s quickly look at how you can keep them safe according to the guidelines of ethereum.org.

 

An image that shows the logo of the Ethereum blockchain in a dark background.

Image source: unsplash.com

 

1. Develop your smart contracts according to the best practices

Do your best to write high-quality code.

 

  • Make sure all of your code is stored in a version control system.
  • Use pull requests to make all code modifications.
  • Hire at least one independent reviewer to check your pull requests.
  • Use a development environment when compiling, testing, and deploying smart contracts.
  • Before merging each pull request, run your code using Mythril, Slither, or other basic code analysis tools.
  • Describe your smart contract architecture in a simple language and document it properly so that others can review your code easily.

2. KISS (keep it simple, stupid)

The KISS principle is widely known among traditional software developers and is just as important when writing smart contracts. 

 

One way to avoid pointless sophistication in your code is to reuse existing libraries like OpenZeppelin Contracts. They’ve been tested numerous times, and you’re much less likely to find bugs in them than trying to write code from scratch.

 

It’s also advised to create small functions and split business logic across multiple smart contracts—it helps to keep them modular.

 

3. Implement secure access controls

Functions marked external or public can be called by any network participant. This is necessary if you want them to be able to interact with your smart contracts. However, this may also quickly become problematic if any person can run sensitive operations, such as minting new NFTs.

 

You must design proper access controls if you want to ensure that no unauthorized use of smart contracts occurs. Two patterns—the ownable pattern and role-based control can help you do that.

 

4. Guard smart contract operations

Once your smart contract is deployed on the Ethereum blockchain, anyone can run public functions. You should implement internal safeguards beforehand to ensure correct contract behavior. Use these three statements: require(), assert(), revert().

 

5. Test your smart contracts extensively

 

An image that shows a smartphone in a dark background, with text "Eat Sleep Code Repeat" displayed on the screen.

Image source: unsplash.com

 

Since smart contracts are immutable, they require much more testing during their development. Looking for any unpredictable results will significantly increase your chances of implementing a secure smart contract code and ensure long-term user protection.

 

One of the best methods is to combine property-based testing with unit testing. Use static and dynamic analysis to do that.

 

7. Have your code reviewed independently

Testing by yourself is not enough, and it’s recommended to ask other developers to check your smart contract for possible vulnerabilities. You can organize a review of your code in two ways: commission a security audit (more on that later on) or set up a bug bounty.

 

7. Be ready for malicious exploits

Have a fallback plan ready in case someone attacks your smart contract. Such a plan should consist of three parts:

  • Smart contract upgrades. While, by definition, smart contracts can’t be altered once deployed, you can still edit them a tiny bit with the help of upgrade patterns. You can read about it in detail here.
  • Emergency stops. While upgrade mechanisms may help, they take time to implement, and hackers can still cause you damage in the meantime. So, in case your smart contract becomes too vulnerable after its deployment, you must have an emergency stop ready for untrusted contracts. It will block calls to vulnerable functions in your contract. 
  • Event monitoring. Logging and monitoring events will give you insights into possible hacker actions. For example, you could write a code that emits an event each time someone runs a critical operation, e.g., withdraws funds. Event monitoring will increase your chances of securing authorized users by performing an upgrade or pausing essential functions.

 

8. Create secure governance systems

If you want to decentralize your application and give control of key smart contracts to your community members, you need to be aware of the possible risks that come with such a governance model. For example, a hacker could take out a flash loan and carry out a malicious proposal with all the new voting power they’ve just acquired (it depends on the number of tokens held).

 

Use a timelock to prevent such attacks from happening. It delays administrative actions by preventing smart contracts from running specific function calls until a certain time has passed.

 

Another option is to assign a “voting weight” to each token. You can do it based on 1) the voting power of an address at a historical period or 2) the time the token has been locked up for.

 

Both ways help secure your decentralized governance systems by minimizing the potential to gather enough votes to influence on-chain votes quickly.

 

9. Protect yourself against potential vulnerabilities

Earlier in the article, we’ve listed five common smart contract vulnerabilities: DoS attacks, unencrypted files, difficulties upgrading smart contracts, function default, reentrancy attacks, and oracle manipulation. Below are some tips on how to defend against them.

 

  • Make sure you first encrypt everything confidential before saving it on the blockchain.
  • Include failsafe into your contracts.
  • Check that all nodes have sufficient processing power and storage.
  • Create smart contracts that can be upgraded with proxies and emergency stops.
  • Create well-defined functions.
  • Prevent reentrancy attacks by following the checks-effects-interactions pattern.
  • Avoid oracle manipulation by using a decentralized oracle network that checks information from various sources, helping to steer clear of single points of failure.

 

Smart contract security audits

 

An illustration that shows how a smart contract security audit works with green animated icons representing the processes.

Image source: icommunity.io

 

Minor mistakes in smart contract code can cost you millions. Thus, smart contract developers must carry out security audits before deploying contracts. Plus, frequent security audits help to gather valuable analytical insights like specifics regarding vulnerabilities. 

 

Here are the three standard steps of a security audit process:

  1. Auditors gather details on code specifications to understand the objectives and scope of the smart contract in question.

  2. You either get a manual or automated audit. Manual audits are usually more efficient since auditors don’t need to depend on software.

  3. Auditors draft the security audit report. It’s usually done after the initial stage of the audit has been completed. In this report, you should find your code issues and recommendations for resolving them. Once the issues are fixed, the auditors should provide you with the final report highlighting which remedial measures were implemented.

 

Smart contract security tools

Here are a few useful tools for ensuring a smooth smart contract development:

 

 

FAQs

What are smart contract security best practices?

  1. Write high-quality code to ensure a smooth development process.
  2. Keep your code simple, so other developers can easily audit it.
  3. Implement secure access controls.
  4. Design internal safeguards to ensure correct contract behavior.
  5. Test your smart contracts extensively.
  6. Commission security audits or set up a bug bounty.
  7. Design smart contract upgrades, emergency stops, and monitor events.
  8. Use a timelock to create secure governance systems.

 

What is a smart contract security audit?

A smart contract security audit thoroughly examines your smart contract code. Its goal is to find potential vulnerabilities and inefficient coding and provide smart contract owners with recommendations on removing bugs.

 

What is a smart contract security checklist?

To ensure your smart contract security, follow this checklist recommended by Ethereum creators:

  1. Review your smart contracts for common vulnerabilities with Slither or Crytic.
  2. Analyze special features of your smart contract, such as your upgradeability code or integration with 3rd party tokens.
  3. Document the most important security properties and evaluate them with automated test generators.
  4. Manually check issues that can’t always be found with automated tools: front-running transactions, risky interactions, or lack of privacy.
Julija Paškevičienė

Julija Paškevičienė

Julija is a freelance content marketer. Specialized in content writing, social media, and finding the best dog memes, she helps businesses get their message across and create content that sells.

JOIN OUR COMMUNITY

Discord
58,706
Twitter
119,546
Telegram
29,743
TikTok
154,300
Email
195,195

Avoid scam, check official Wizardia links

MY CART

Your cart is currently empty