Irrespective of whether you are working on launching any smart contract applications or designing DeFi protocols, there are numerous security considerations that one needs to take into account before launching them on a blockchain mainnet. This is imperative to avoid web3 security risks.
When examining their code, most people pay attention to Solidity web3 vulnerabilities. Still, other factors are frequently to be considered to ensure a dApp’s security is robust enough to be mainnet-ready.
Oracle attacks, brute force assaults, and other threats could potentially cost you and your users billions of dollars as well as months of pain and sorrow if you are unaware of the most common types of DeFi security flaws.
Before releasing your code, it is crucial to do your due diligence, regardless of whether you are forking an already functional codebase or creating everything from scratch. This is what web3 security audit companies do.
Let us understand these issues, risks, and solutions in detail.
Three Critical Risks that DeFi Developers Should be Aware Of.
Table of Contents
Before discussing the DeFi risks, it is essential to understand DeFi security. So, what is DeFi security?
Customers and investors gain a lot from DeFi, including removing intermediaries and centralized control, increasing the accessibility of financial markets for ordinary investors, and creating new investment options.
The two main software dangers associated with DeFi protocols are “bugs,” or code mistakes that might cause the protocol to malfunction, and “vulnerabilities,” which would allow thieves, or “hackers,” to infiltrate the network and steal money. The techniques or ways to save DeFi from these threats are known as maintaining DeFi security.
Now, let us proceed with the risks we discussed in the above graphic and learn the solutions to eliminate them.
Unexpected Liquidity or Token Migrations
The Issue:
When a project moves its tokens from one liquidity provider like DEX, CEX, or a new DeFi application to another, it is known as liquidity migration. A situation where a project upgrades to a newer version of the existing token is known as token migration.
The Risk:
When token migration occurs, the upgraded token requires a new price feed so that the asset’s current price is accurately reported. When liquidity migration occurs, it leads to low liquidity in the original market. As a result, it will become more susceptible to market manipulation, affecting the other protocols.
The Solution:
Before performing liquidity or token migration, there should be coordination between the users, stakeholders, oracle node operators, and liquidity providers. This will ensure that all the prices are accurately reported throughout the migration process.
Exploitable Sources of Randomness
The Issue:
Using only the inputs related to block production generates a random number for an application. This includes inputs like blockhash, block.timestamp, block.difficulty etc.
The Risk:?
Blockchains are predictable. This is why “re-rolling”?deleting transactions, rearranging transactions inside blocks, or withholding blocks with unfavorable block hashes?can give users and miners undue influence to alter dApp results.
The Solution:?
With Chainlink, protocols can access a source of randomness that cannot be tampered with and is supported by an on-chain cryptographic proof that verifies the output’s integrity. This stops miners, oracles, developers, or users from affecting the random number produced.
Using a Time-Weighted Average Price(TWAP) Oracle for Data
The Issue:
Using a decentralized exchange’s time-weighted average pricing to calculate an asset’s exchange rate.
The Risk:
Because TWAP oracles employ data from a single exchange, their stated price might not correspond to the spot price for the entire market, mainly when there is a lot of volatility. Additionally, at times of low liquidity, their values may be manipulated, leading to erroneous liquidations, unfair deals, or the issuing of enormous loans.
The Solution:
To assist that the reported price reflects activity across the whole market, use a decentralized oracle system that takes a volume-weighted average from data aggregators that track all pertinent exchanges, such as Chainlink Data Feeds. By doing this, you may defend your project against pricing alterations or manipulations.
In light of this, let’s look at 10 DeFi security best practices that can shield your application from attacks, minimize uncomfortable user interactions, and safeguard and enhance your reputation as a highly secure developer.
Recommended: Defi Security Audit Company
Ten Best DeFi Security Practices
You must know and implement these ten best DeFi security practices to establish a safe and secure financial environment.
- Stay away from Reenetrancy Attacks.
One typical type of DeFi security attack is the reentrancy attack?the form of the infamous DAO compromise. This occurs when a contract calls another contract outside of its own before changing its state.
Additional Read: What is a DAO?
Let?s look at an example:?
In this function, we have called another account with msg.sender.call. The point to take note of here is that this can even be some other smart contract!
The external contract could be programmed to contact the withdraw function once more prior to (b?l?ess,) =msg. Sender. call{value:shares[msg.sender]}(??); returns. In doing so, the user would be able to withdraw all the funds from a contract before the state is updated.
The best practice is to update the state before calling any contracts outside of a project. Another practice is to impose a mutex upon critical functions, e.g., the non-reentrant modifier in ReentrancyGuard.
- Use a Decentralized Oracle Network
A decentralized oracle network is employed to find the true value of an exchange rate that reflects wide market coverage as opposed to using a centralized oracle (in this case, a single on-chain exchange) to calculate exchange rates. A DEX is a decentralized exchange that serves as a single point of access to pricing data.
To achieve a decentralized and accurate depiction of the global exchange rates of the underlying assets, you should instead collect prices from all liquid centralized and decentralized exchanges, weight the prices by volume, and remove outliers/wash trading to ensure full market coverage.
- Use Chainlik VRF as a Verifiable Randomness Oracle
Developers require a method for producing verified randomness that is verifiable to miners and user rerolling in order to prevent exploits. It is necessary to use randomness that is obtained off-chain via an oracle. However, a lot of oracles that allow you to source randomness lack the capacity to truly demonstrate that the number you receive was generated randomly.
Developers must have the ability to source randomness off-chain and a means of conclusively and cryptographically demonstrating that the randomness has not been altered.
This is exactly what the Chainlink Verifiable Random Function (VRF) accomplishes. It generates an off-chain random number with a cryptographic guarantee of integrity using oracle nodes. The VRF Coordinator then checks the cryptographic evidence on-chain to confirm the VRF’s integrity as deterministic and tamper-proof.
- Avoid common glitches
This idea serves as a type of catch-all for Solidity, but in order to create a secure contract, you must keep in mind each of these DeFi security concepts. You need to understand how Solidity functions in order to write really solid Solidity. If not, you could be exposed to many vulnerabilities like:
- Overflows/underflows
- Loops gas limit
- Avoid using tx.origin
- Proxy storage collision
- Token transfer calculation accuracy
- Proper data removal
- Go for an external audit before deploying to mainnet
Consider an audit of your code to be a peer review that focuses on security. Auditors will examine your whole codebase line by line and test your smart contracts for vulnerabilities using formal verification methods. It’s simple to expose oneself to potential vulnerabilities by deploying code without doing an audit or by altering code and redeploying after conducting an audit.
There are several ways you may assist your auditors and yourself in making sure your audit is as thorough as possible:
- Maintain communication with them and keep lines of communication available in case they have questions.
- Document everything so they can more easily follow what is occurring.
- Make your code easy for your team and theirs by adding comments.
- Testing and static analysis tool
You must implement tests for your application. Tools for static analysis will also aid with your earlier bug discovery. They are made to automatically review your contract and scan for any potential weaknesses.
Based on the learnings from its considerable expertise in auditing, verifying, and monitoring smart contracts, some new, next-generation static analysis, syntactic analysis, exploit analysis, and formal verification tools are being constructed.
- Think of Security as a whole lifecycle process
Prior to commercial deployment, you should without a doubt make every effort to design a secure and trustworthy smart contract. However, given the rapid evolution of blockchain and DeFi protocols as well as the ongoing development of new attacks, you cannot afford to stop there.
Instead, to access and take advantage of the rapidly expanding pool of dynamic security intelligence, you should get and adhere to the most recent monitoring and alert intelligence and, if at all possible, strive to implement future-proofing in the smart contract itself.
- Be prepared with a Disaster Recovery Plan
Based on your protocol, it is always suggested to be ready with a recovery plan in case you get hacked. Some of the most famous methodologies include:
- Taking insurance: Insurance protocols are one of the most decentralized methods of disaster recovery and are becoming more and more common. They increase financial security while having no negative effects on decentralization.
- Having an upgrade plan: The same problems exist with an upgrade plan. Moving to a smart contract without bugs can be excellent, but you must upgrade your contract carefully to preserve decentralization.
- Having an emergency ?pause? feature: Including an emergency “pause” feature is a tactic with benefits and drawbacks. In the event that a cybersecurity attack is discovered, a feature like this would shut down all communication with your smart contract. Be sure your users know who has access to this functionality if you implement it. If there is only one user, your protocol is not decentralized, and a skilled user may examine your code to determine this.
- Protect against frontrunning
In blockchains, every transaction is accessible in the mempool, giving everyone the chance to witness it and maybe complete their own transaction before yours, profiting from your transaction
The main characteristics of Fair Sequencing Services, a secure off-chain service powered by Chainlink Decentralized Oracle Networks (DONs), are described in the Chainlink 2.0 whitepaper. This service will be used to order transactions in accordance with a temporal notion of fairness specified by the dApp (such as first seen in the mempool). FSS is made to significantly lessen the impact of frontrunning and MEV as well as to lower fees for users throughout the blockchain ecosystem. In addition to this blog post’s introduction, the Chainlink 2.0 whitepaper’s section five goes into greater detail on FSS.
Reducing the importance of ordering your transactions whenever possible will disincentivize transaction reordering and MEV within your protocol, which is one of the best ways to combat the issue of frontrunning outside of FSS.
- Function Visibility and Restrictions
The Solidity language has four different types of function visibility:
Internal: One can view the function in the current and in derived contracts;
Private: It can only be visible in the current contract;
External: One can only view the function to external calls;
Public: Both internal and external calls can see the function.
The term “function visibility” refers to one of the aforementioned four visibilities for the particular function, which is used to restrict access for a specified user group. Regarding restriction, it alludes to a special code fragment created with access restriction in mind.
The Bottom Line:
We’ve already seen too many exploits and assaults that have cost consumers tens of millions of dollars, therefore there are several crucial DeFi security considerations when it comes to safeguarding your smart contracts. You may prevent these weaknesses when developing your smart contracts by mastering these best 10 DeFi security practices.