To minimize risk and prevent unauthorized use of smart contracts, it is important to understand smart contract security and how it works in daily development.The following article provides general security advice and does not reflect the complete security practices of any particular team. It is important to note that no short overview can provide an exhaustive discussion of all aspects of smart contract security.The DeFi industry has multiplied over the last few years, with market capitalization reaching $120 billion at the time of writing. As projects find innovative uses for blockchain technology, they continue to create value in the ecosystem, and intelligent contracts process large amounts of user funds.As a result, security is the most important factor in the Web3 space. Neglecting security can have disastrous consequences. DeFi hacks have resulted in a $2.32 billion loss in 2022, with $750 million exploited in October alone.Today, smart contracts are at the forefront of blockchain technology. They cater to almost every industry segment with various applications and transaction use cases.To prevent DeFi hacks, it is crucial to understand smart contract security by taking the proper precautions, avoiding certain risks, and learning about proper implementation and other aspects of securing a smart contract-based platform against exploits and hacking attempts.Six stages of securing your smart contracts.Prepare: Research what infrastructure to use, discuss how to design and correctly implement the smart contracts, and document.Develop: Developers implement research and write the system’s codeTest: Testing software to find bugs, problems, and improvement areas.Deploy: Deploying software onto mainnet for production.Monitor: Developers evaluate and modify the system to ensure it performs its intended functions.Incident Response: The acting stage involves monitoring and reacting to a bug report or an ongoing exploit.Having these different stages allows you to approach the security of your smart contracts effectively while also focusing on other parts of the building process. Let’s dive into each step, but remember that actions may overlap, and you may have to go back and forth to redo actions.PreparationThe design of smart contracts should be discussed and researched ahead of time before writing the first line of code.Documentation can be written at different levels and should be updated while implementing the smart contracts:A written description of the system describing what the smart contracts do and any assumptions in the codebase.Schema and architectural diagrams, including contract interactions and a state machine of the system. Slither printers can help generate these schemas.Through thorough code documentation, the Natspec format can be used for Solidity.Well-written documentation of the smart contracts and architecture allows you and others to have a good overview of all logic involved, making it easier to find bugs, weak points, and security concerns.DevelopmentAfter the preparation stage, the actual development of the software can begin. Development works best when basic security principles are kept in mind:Development should take place using secure coding standards. Programmers should have up-to-date knowledge of the relevant security standards and how they apply to the current project.Development should appropriately implement secure design patterns, contract libraries, and frameworks. This refers to the security architecture of the software. The development of a program can only be successful if it follows appropriate security protocols.Development should take advantage of the latest secure coding practices, such as using updated versions of, for example, Solidity that best address current security standards.One last tip is to implement and strictly enforce the Principle of Least Privilege (POLP). Essentially, POLP limits what each component of a system is able to do, minimizing the risk of being hacked. By doing this, you can dramatically improve your project’s security posture. The whole team must work together to determine each account’s permissions and then regularly review and right-size them as necessary to minimize risk.The following is an example of using AccessControl in an ERC20 token to define a ‘minter’ role, which allows accounts that have it to create new tokens:OpenZepplin AccessControlAccessControl works in scenarios where granular permissions are required, which can be implemented by defining multiple roles. We can further augment the ERC20 by also defining a ‘burner’ role:OpenZepplin AccessControlOther PLOP ExamplesProjects like Balancer have an Authorizer that reflects advanced analysis of the threat model: for instance, the “Grantors” and “Revokers” access level system to ensure that the admin will have the resources to stop a malicious or compromised Grantor from continuing an attack by extending privilege to further accounts.TestingTesting smart contracts is one of the most important measures for improving security. You should start testing early to save time and trouble down the line.Smart contract testing means analyzing and evaluating a smart contract to ensure everything works as intended. Testing your smart contract makes it easier to identify bugs and vulnerabilities and reduces the possibility of software errors that could lead to costly exploits. Test-driven development makes a failing unit test pass and then makes the code work. TDD has many benefits, such as simplifying writing code, increasing the readability of the code, and ensuring the completeness and correctness of the code.Write thorough unit tests. An extensive test suite is crucial to building high-quality software. These must be combined with static analysis, property-based testing, and formal program analysis techniques to prevent vulnerabilities. Test coverage alone is insufficient to detect all vulnerabilities.Perform static analysis and fuzzing using tools such as Slither and Echidna. Automated tools will help ensure your contract is secure.Hire a third-party developer or auditor to look over your smart contract. Human testing is very different from automated testing and comes with the benefit of finding bugs, errors, and other improvements.The process of testing is akin to attacking your code. As you hunt for vulnerabilities and edge cases, you are developing a more security-focused mindset, improving the quality of the code you write.DeploymentIn the deployment stage, you finally publish your software and allow the public to use it. But before you do, take a step back and make sure you have all the bases covered. This stage can be automated, leading to much higher confidence in the results.Teams like Balancer run fork tests, in which the code runs against the actual external contracts, on a fork of mainnet.Test that the code deployed at the addresses listed in the output is actually there and matches. And furthermore, the actionIds (used for identifying permissions in governance proposals, etc.) and continuously computed and compared against the published ones.Document internal processes for situations where a deployed smart contract does not work or introduces a new bug. Consider adding a fallback scenario that describes an action plan in the event of a failed smart contract.Deploy early in your workday so there’s enough time to test your system on production and fix potential problems.Update documentation with the correct smart contract and deployment addresses.Ongoing MonitoringMonitoring and maintenance of any software is important, but because smart contracts are immutable, they bring unique challenges compared to conventional software.Monitor your contracts. Watch the logs, and be ready to react in case of contract or wallet compromise.Launch a bug bounty program. Teams such as Balancer and Beethoven X have launched successful bug bounty programs on the leading bounty platform, Immunefi.Define contract behavior that is considered abnormal for off-chain monitoring.Consider adding more resilient solutions for detection and mitigation, especially regarding specific alternate endpoints and queries for different data and status pages and support contacts for affected services.An extra tip is to describe the important sources for vulnerability news for each language and component. Subscribe to updates for each source. Consider creating a unique private Discord/Slack channel with a bot that will post the latest vulnerability news; this will help the team keep track of updates all in one place. Also, consider assigning specific team members to keep track of the vulnerability news of a specific component of the systemIncident ResponseHaving an incident response plan is crucial. Always consider that your smart contracts can be compromised.Here are some incident response plan recommendations;Identify who (either specific people or roles) is responsible for carrying out the mitigations (deploying smart contracts, pausing contracts, upgrading the front end, etc.). Specifying these roles will strengthen the incident response plan and ease the execution of mitigating actions when necessary.Consider whether and under what circumstances your company will make affected users whole after certain issues occur. Some scenarios to consider include an individual or aggregate loss, a loss resulting from user error, a contract flaw, and a third-party contract flaw.Consider scenarios involving issues that would indirectly affect the system.Additionally, you can run periodic dry runs of specific scenarios in the incident response plan to find gaps and opportunities for improvement and to develop muscle memory. Document the intervals at which the team should perform the various scenario dry runs. For scenarios that are more likely to happen, perform dry runs more regularly. Create a template to be filled in after a dry run to describe the improvements that need to be made to the incident response.Below we will highlight a recent measure Balancer has taken toward its ecosystem contract security by partnering with security auditor Certora.Balancer x CertoraTo increase the accessibility of smart contract reviews, Balancer joined forces with top security auditor Certora by launching the Balancer Certora Security Accelerator, which helps projects building on Balancer increase their code security. The Security Accelerator provides code reviews and grants access to Certora’s formal verification Prover. You can read the full announcement here.Closing ThoughtsThe DeFi and web3 space is constantly evolving, and security measures should be an integral part of development. While this guide shares some security tips for devs, no short overview can provide a complete picture of all aspects of smart contract security. DYOR, reach out to experts in the space and remember that security measures are not “one size fits all” but a constantly evolving set of industry best practices.Website | Twitter | DiscordCommunications from Balancer are intended solely for informational purposes, and should not be construed as investment or trading advice and are not meant to be a solicitation or recommendation to buy, sell, or hold any digital assets mentioned. All figures are estimated and unaudited unless otherwise noted. Past performance is not necessarily indicative of future results. Transactions on blockchains are speculative. Carefully consider and accept all risks including risk of loss of all funds and extreme volatility of token prices and liquidity before taking action.General Smart Contract Security: A Guide for Web3 Development was originally published in Balancer Protocol on Medium, where people are continuing the conversation by highlighting and responding to this story.

Read More

Leave a Reply