Smart Contract Best Practices
An average of 20,000 Smart Contracts is created every day. Over 3 Million Smart Contracts were created in November and December 2018 alone! A report shows that 60% of all Ethereum contracts have never been interacted with, less than 10% of all created contracts are unique, and less than 1% of the contracts have the source code available. Another report shows that over 25% of all Smart Contracts created have some kind of bug 😱. Today, we’ll mention a couple of things which can help you build better Smart Contracts!
K.I.S.S. Principle (Keep It Simple, Stupid)
The KISS principle is well-known when designing a system. Keeping things simple decreases the likelihood of errors. So make your logical flow simple when designing a Smart Contract, so you will end up with a clean & tidy code.
You don’t need to reinvent the wheel! There are already well-tested libraries and frameworks (e.g. Truffle, OpenZeppelin), which help you build and modularize your logic — use them 😉. Don’t do things like creating your own random number generator.
Software Engineering Design Patterns
Patterns help us in solving some very fundamental architectural design problems. Patterns are used by millions of software throughout the word and are already a well-researched area in computer science. Understanding patterns helps you recognize problems fast and come up with better solutions for them. You can find Smart Contract / Solidity design patterns here.
There is one particular design pattern which we like: Proxy Delegate. This pattern helps you to upgrade your Contract safely.
It’s best to follow TDD (Test-Driven Design): create test-cases before writing your code, and cover positive and negative test cases. Also, try to break your own code and find logical mistakes. You can use solidity-coverage to generate test coverage.
Use Security Tools
Smart Contract security should be the utmost priority. You need to find all attack vectors. Smart Contract and ERC-20 tokens have a history of bugs. You can also check out Ethernaut puzzles to get familiar with the most famous security problems. You should also read Vitalik Buterin’s article on Smart Contract security. There are already open source security analysis tools, which you can use to analyze your Smart Contact. Here are a few of them below:
- Sūrya — Utility tool for Smart Contract systems, offering a number of visual outputs and information about the contracts’ structure. Also supports querying the function call graph.
- Solgraph — Generates a DOT graph that visualizes function control flow of a Solidity contract and highlights potential security vulnerabilities.
- EVM Lab — Rich tool package to interact with the EVM. Includes a VM, Etherchain API, and a trace-viewer.
- ethereum-graph-debugger — A graphical EVM debugger. Displays the entire program control flow graph.
Static and Dynamic Analysis
- Mythril Classic — Open-source security analyzer for Solidity code and on-chain Smart Contracts.
- Mythril Platform — SaaS platform that allows anyone to build purpose-built security tools.
- Slither — Static analysis framework with detectors for many common Solidity issues. It has taint and value tracking capabilities and is written in Python.
- Echidna — The only available fuzzer for Ethereum software. Uses property testing to generate malicious inputs that break Smart Contracts.
- Manticore — Dynamic binary analysis tool with EVM support.
- Oyente — Analyze Ethereum code to find common vulnerabilities, based on this paper.
- Securify — Fully automated online static analyzer for Smart Contracts, providing a security report based on vulnerability patterns.
- SmartCheck — Static analysis of Solidity source code for security vulnerabilities and best practices.
- Octopus — Security Analysis tool for Blockchain Smart Contracts with support of EVM and (e)WASM.
Known Attacks and Updates
There are a few major things you need to take care of when developing an ERC-20 token:
- Be aware of front-running attacks on ERC-20
- Prevent transferring tokens to the 0x0 address
- Prevent transferring tokens to the contact address
There is a better Ethereum standard such as ERC-223 and ERC-777, which you can use as an alternative for ERC-20. Also, Security EIPs are important to be aware of… either for understanding how the EVM works, or to get informed with best practices when developing a Smart Contract system.
Documentation and Procedures
Documentation is a very important practice when your code is going to handle potentially Millions of dollars. Documentation helps internal and external participants, auditors and independent reviewers to understand your contracts.
- Create specification, state machines, models which helps others to understand the system.
- Include a roll-out plan with your documentation.
- Specify the current version of the compiler.
- Specify known issues, attack vectors, limitation and potential remedies for them.
- Specify test converge and reviewers.
- Maintain a history & keep track of changes over time.
- Specify contract authors and contributors with their public contact information.
There are companies which can help you audit your Smart Contract. These services are useful as experts will audit your code for potential vulnerabilities. Highly recommended if you are building a Smart Contract on which your business will depend on.
It always helps to have more eyes on your code. Bug bounties are excellent in terms of ROI. Below are some tips for running bounty programs:
- Decide the total budget and currency for your bounty reward.
- Categories your budget in terms of different type of vulnerabilities.
- Decide a team for judging the bounty.
- Mention proper communication channel for reporting of bugs.
- Use private repos to fix the bug, involve bounty hunter in reviewing the fix.
- Do not delay in rewarding the bounty hunter.
You can check out 0x project bug bounty program.
Prepare for failure
If there is code, there is a bug 😄. When it comes to Smart Contracts, create a thorough plan for the worst case scenarios.
There are two ways to write error-free programs; only the third one works. (Alan J. Perlis)
Here are several tips which can help you to create such a plan for your token:
- Add a circuit breaker in your Smart Contract which will pause all kinds of transactions.
- Create a plan for contract upgrades, bugfixes, and improvements.
- Create a proper guideline and communication channel for disclosure policy.
- Minimize the impact of bugs and money at risk. Plan what happens in case of money loss. Recourse in case of failure (e.g. insurance, penalty fund, no recourse).
Apart from the above, always optimize your Smart Contract for Gas usage. Prevention is better than the Cure, always try to plan and prevent before things go wrong. In the case of Smart Contracts, the real money will be at stake; you need to be extra careful as the programmer. Always stay updated with the latest changes in Solidity language & compiler and known attacks in the ecosystem. With Ethereum blockchain’s nature of everything being public, and taking into account the current maturity of the ecosystem, guaranteeing that nothing will go wrong is extreme overconfidence (if not foolishness). So build, test, plan, and follow procedures to mitigate potential vulnerabilities in your Smart Contract. Happy (smart) coding!
QuikNode is building infrastructure to support the future of Web3. Since 2017, we’ve worked with hundreds of developers & companies, helping scale dApps and providing high-performance Ethereum nodes. We’re working on something interesting from the past few months and will be launching soon, so subscribe our newsletter for more updates!! 😃