Cointime

Download App
iOS & Android

A Developer’s Guide to Securing Ethereum Smart Contracts

Ethereum uses "smart contracts," or programmable software programs built on blockchain technology, to power decentralized applications (dApps), non-fungible tokens (NFTs), and decentralized autonomous organizations (DAOs). The rich functionality provided by Ethereum smart contracts has allowed web3 developers to create complex blockchain-based applications.

However, the experimental nature of smart contracts increases vulnerabilities, bugs, and errors, and with the cryptocurrency market cap in the trillions of dollars, black hat hackers are looking for weaknesses in smart contracts that they can exploit.

In this article, we'll cover smart contract security best practices, fail-safe protections, and smart contract analysis tools for hardening smart contract security.

An Introduction to Ethereum Smart Contracts 

Ethereum smart contracts are written in Solidity, a language that's similar to C++ and Javascript. Ethereum smart contracts run on the Ethereum blockchain, and their execution is managed by the Ethereum Virtual Machine (EVM) — a virtual supercomputer that executes Ethereum smart contracts, and is distributed across several nodes around the world. 

The architecture of an Ethereum smart contract may differ from others. Smart contracts can be simple with limited functionality or complex with multi-layered functionality. 

4 Benefits of Smart Contracts

Regardless of their intended design, smart contracts offer the same set of benefits:

1. Immutability 

A smart contract cannot be easily modified (except when it is pre-programmed to do so), making them resistant to unapproved alterations. Once the contract is verified and live on the blockchain, it takes a lot of effort to alter or upgrade smart contract code. 

2. Trust

By design, smart contracts automatically execute a set of instructions when predefined conditions are met. This happens without external control, so the users involved can trust the code to work in absence of human intermediation. Two people can transact without trusting each other, safe in the knowledge that the smart contract will act as a fair arbiter. 

3. Cost-effectiveness 

The combination of smart contracts with legal instruments, (smart legal contracts) can simplify transactions between individuals and remove the need for middlemen. With no intermediaries to compensate, parties can spend less on executing and enforcing agreements. 

4. Speed 

Every smart contract operates on conditional programming (i.e. if this, then that). These programmed actions occur immediately when the rules of the contract's logic are met. As a result, transactions can happen faster than they do with legacy systems. 

6 Proven Ways to Secure Ethereum Smart Contracts

Smart contracts running on blockchain are set to transform governance, finance, IoT, and many more industries for users all over the world. However, with all the security challenges developers must consider, smart contract security vulnerabilities must be taken seriously.

Here are some fundamental smart contract security best practices web3 developers must employ when building dapps on Ethereum and EVM-compatible blockchains.

1. Perform Smart Contract Audits Religiously 

In 2022, deploying smart contracts without a security audit should be a crime. Even so, many developers are still launching unaudited smart contracts. The State of DeFi Security report from Certik shows that the majority of exploited smart contracts received no security audits. 

Understandably, hiring a smart contract auditor won't come cheap. But the right security checks can save you more down the road. In DeFi, millions have been lost in hacks that exploited the weaknesses in poorly written code. 

A good blockchain security auditor follows a proven audit process to find flaws in the smart contract code and spot errors that go unnoticed during development. Moreover, they can give useful advice on fixing and optimizing smart contracts before deployment. 

2. Test Your Code 

Test, test, and re-test your code to find bugs and other vulnerabilities.

Rigorous testing is perhaps the easiest and most effective way to ensure smart contracts perform as intended once they are deployed to mainnet. 

Deploy the smart contract on a test network and observe it for any abnormalities. That way, you can know if the protocol is functioning as it should. 

Recommended testnets for testing Ethereum smart contracts include:

  • Rinkeby
  • Kovan
  • Ropsten
  • Truffle

Need testnet ETH? Use Alchemy's free Rinkeby ETH faucet to start testing your contracts.

Run Unit Tests to Isolate Single Code Snippets

Unit tests are also a good idea for improving contract security. A unit test looks at a single part of your code, so you can tell what went wrong if a failure occurs. 

It is advisable to run unit tests for each new feature before integrating it into the smart contract. Remember that smart contracts are immutable by nature, making it impossible to patch the code should a vulnerability appear later. 

3. Review Code with Peers

If you're working in a team, ensure every member conducts an independent code audit and provides detailed feedback. Solo developers may want to find a trusted colleague to peer review their smart contract code throughout the development process to increase security. 

4. Reduce Software Complexity 

The ultimate rule of software security is to keep code simple. The more complexity there is in the code, the more variables which increase the chances of something failing.

As the Dutch computer scientist Edsger W. Dijkstra said: "Simplicity is a prerequisite for reliability." 

This doesn't mean you should avoid building feature-rich smart contracts, however, you should start with a simple architecture at the beginning and slowly expand functionality over time using clean code and familiar patterns.. 

5. Implement Fail-Safe Protection

A rule of thumb when writing Ethereum smart contracts is to "prepare for failure." No matter how many times you test, you cannot possibly cover every possible bug that can affect the smart contract. As such, designing a fail-safe mechanism for your Ethereum smart contract is necessary. 

A fail-safe mode can be useful for limiting damage from malicious attacks. They are designed to trigger once abnormal smart contract activity is detected. 

4 Examples of Smart Contract Fail-Safe Protections

Examples of fail-safe protection for EVM-compatible smart contracts include:

1. Circuit Breakers 

A "circuit breaker" can be used to prevent the execution of functions when bugs and vulnerabilities are discovered. With circuit breakers, you have two options for activating them:

  • Give trusted admins permission to trigger the circuit breaker
  • Program the circuit-breaking mechanism to run once preset conditions are met.

Because smart contracts are automated, circuit breakers restrict operations when errors occur.

2. Speed Bumps

A speed bump is a fail-safe mechanism to slow down malicious behaviors, although it won't prevent the attack, speed bumps give admins enough time to take immediate corrective actions.

A prime example of a speed bump comes from the infamous DAO hack of 2016. The program ensured that no one could withdraw funds from the DAO until after 27 days, which kept the funds in the smart contract until developers were able to retrieve them. 

3. Rate Limits 

A rate limit can control the frequency of call functions within a specific timeframe, providing a stop-gap measure against exploits that call functions repeatedly to drain locked funds (e.g. re-entrancy attacks), issue a large amount of ETH tokens, or perform multiple withdrawals.

Additionally, a rate limit at the contract level can be used to restrict the number of tokens issued within a time interval.

Given the number of exploits where bad actors issued an extraordinary amount of tokens within a short period of time, rate limits are a good preventive measure to harden smart contract security. 

4. Balance Limits 

Balance limits reduce smart contract risk by limiting the total amount of ETH that can be locked in a single smart contract.

A balance limit will monitor the balance of funds held in the smart contract. Once the threshold is reached, the mechanism triggers an automatic rejection of subsequent payments. 

If you're launching a new smart contract, balance limits may be a good preventative security measure to use until you're confident of the contract's security. 

6. Design Secure Access Control Mechanisms

Access control mechanisms determine who can govern and alter certain elements of the contract, and it is a crucial path of your Ethereum smart contract's architecture.

If the wrong person gets ownership or admin privileges, they can reprogram the contract to execute malicious transactions.

To prevent the wrong person from getting admin permissions, ensure that sensitive functions require multiple levels of authorization before they can be accessed. 

4 Smart Contract Security Tools Web3 Developers Should Know

Smart contract security is serious. Here are some analysis tools that can help you secure your smart contract against exploits, bugs, and vulnerabilities:

1. Octopus

Octopus is a highly functional analysis tool for analyzing smart contract bytecode to deeply understand internal behaviors. It is compatible with smart contracts built on popular blockchains, such as NEO, Bitcoin, and of course, Ethereum. 

2. Oyente 

Oyente is an automated smart contract audit tool used for identifying common smart contract security vulnerabilities. It comprises a Validator, Explorer, CoreAnalysis tool, and CGF builder. Each component performs a critical function; for example, the Explorer runs the smart contracts and CoreAnalysis detects any issues in the resulting output. 

3. Mythril 

Mythril is a smart contract security tool built by ConSensys that is useful for testing Ethereum Virtual Machine (EVM) bytecode. It uses a combination of taint analysis, SMT solving, and symbolic execution to discover vulnerabilities in smart contract code. 

4. Securify 

Securify is a smart contract vulnerability scanner backed by the Ethereum Foundation. This popular Ethereum smart contract scanner can detect up to 37 smart contract vulnerabilities and implements context-specific static analysis for more accurate security reports. 

Secure your next project with smart contract security best practices

When implemented correctly, smart contract technology can be adapted to support a variety of use cases. However, a smart contract is code, written by humans, and is sometimes imperfect. 

As a smart contract developer, you must follow best practices for security when writing code including running a detailed security analysis, leverage multiple security analysis tools and resources, get peer reviews, simplify code structures, and implement fail-safe mechanisms.

Comments

All Comments

Recommended for you

  • Hyperliquid Assistance Fund Repurchases and Destroys Over 47.5 Million HYPE Worth $4.366 Billion

    According to monitoring, the Hyperliquid assistance fund has repurchased and destroyed over 47.5058 million HYPE, with a total purchase cost of approximately $1.321 billion, currently valued at around $4.366 billion.

  • Fidelity Executive: Bitcoin Power Law Model Indicates New Bull Market Cycle, Target Price of $300,000 by 2029

    On September 26, Jurrien Timmer, Global Macro Director at Fidelity Investments, stated on social media that the mathematical calculations of Bitcoin's 'power law' continue to indicate that a new cyclical bull market is forming after holding the $60,000 level, with a target price of $300,000 by 2029. Timmer also included a chart illustrating Bitcoin's power law valuation as evidence. It should be noted that the power law model is a long-term trend fitting tool, and its extrapolated prices are not deterministic predictions; actual trends are still influenced by liquidity, regulation, and changes in market structure.

  • Foreign Ministry Spokesperson Answers Questions on Artificial Intelligence

    On September 26, a reporter asked: We noticed that during the introduction of the results of this visit, the U.S. side used 'superintelligence' instead of 'artificial intelligence.' What is China's comment on this? The spokesperson responded: During the meeting between the Chinese and U.S. heads of state, in-depth discussions were held on the issue of artificial intelligence. Regarding the terminology of artificial intelligence, China values the U.S. position and respects their phrasing. The technology of artificial intelligence is continuously evolving, and all parties can strengthen communication, engage in in-depth discussions, and seek consensus based on the latest developments.

  • Iranian President: We No Longer Trust Negotiations with the U.S.

    On September 26, Al Jazeera reported that Iranian President Ebrahim Raisi stated that Iran "no longer trusts negotiations with Washington" because the U.S. has repeatedly launched attacks and imposed sanctions after each round of talks. Qatar and Pakistan are currently mediating between Iran and the U.S., relaying Tehran's messages to Washington. Raisi also mentioned that negotiations should be based on the memorandum of understanding previously signed by the two countries, adding that the Americans must clarify their position regarding this memorandum. Furthermore, he attributed the closure of the Strait of Hormuz to the U.S., stating, "It is the U.S. that has blocked our path." When Iran's path is obstructed, closing the Strait of Hormuz is a natural response. The crisis in the Strait of Hormuz can be resolved through negotiations rather than the use of force. If negotiations lead to a resolution of disputes, the waterway "will remain open for trade."

  • Bitget CEO Reveals $80,000 Loss from Impersonation Scam Linked to Lazarus Group

    On September 26, Crypto Briefing reported that Bitget CEO Gracy Chen disclosed a loss of approximately $80,000 from her personal wallet due to a social engineering attack disguised as a journalist interview. The attack involved hackers stealing the X account of a well-known crypto media outlet and impersonating a journalist to contact her under the guise of scheduling an interview. Chen stated that her personal losses are not covered by Bitget's user protection fund, which only covers users and not the CEO's personal wallet. Previously, Bitget's cold and hot wallets were hacked, resulting in an estimated loss of about $387.5 million (revised from an initial estimate of $351.6 million). The attackers did not utilize private keys but instead forged transaction data to redirect funds; the user protection fund has a scale of over $464 million. Chen attributed both incidents to the North Korean Lazarus Group, noting that the modus operandi and operational characteristics are consistent with the group's past actions, and mentioned that her personal wallet had previously been targeted, with tactics related to those used against other exchanges.

  • Bitget Confirms Being Deceived into 'Self-Approving' $388 Million Transfer, Losses Revised

    On September 26, Unchained reported that Bitget stated attackers transferred approximately $387.5 million from its exchange on Thursday, revising the initially estimated loss of $351.6 million after accounting for transfers on the Zcash and TRON chains. The attackers did not require private keys: CEO Gracy Chen mentioned that the attackers compromised key backend systems of its wallet infrastructure, forged transaction data, and triggered the authorization process, which was signed by Bitget's own system. The related vulnerability has been identified and fixed, and the withdrawal status, which has been suspended since Thursday, will be announced before midnight Eastern Time. Mandiant and SlowMist are assisting with the investigation. Chen noted that based on IP behavior patterns and on-chain signatures, this attack is consistent with methods used by North Korean-linked hacker organizations and resembles the previous $1.5 billion theft case from Bybit. Nansen tracking shows that 40,000 ETH were evenly distributed to four new addresses; as of Friday, 6:34 PM Eastern Time, eight attacker addresses held a total of approximately 68,300 ETH (about $18.4 million), with no further transactions initiated. Bitget stated that some of the funds have been frozen and is offering a 5% bounty on the recovered amounts to those who facilitate the freezing; the $464 million protection fund fully covers the losses.

  • Vitalik: Significant Progress in Mobile Offline Local Knowledge Applications, but Problem-Solving Ability Still Weaker than Notebook-Level Models

    On September 26, Ethereum co-founder Vitalik Buterin posted on X that he is testing a mobile offline local knowledge application recently developed by the community (with a related bounty link attached). He noted that these applications are significantly better than the product he attempted to build himself two months ago, but they still perform slower and less effectively than models that can run on a notebook when handling complex problems. Vitalik pointed out that the weakest aspect of these applications is professional travel-related queries, citing the test case 'Tell me the best vegetarian restaurant in my current city,' but none of the tested applications performed well. He expressed hope for continued improvements in such products and wishes to reach a level where users can comfortably query any facts of interest without needing an internet connection.

  • This Week, U.S. Bitcoin Spot ETFs See Net Inflows of Approximately $2.386 Billion, Led by IBIT

    On September 26, according to data from Farside Investors, U.S. Bitcoin spot ETFs experienced a total net inflow of $2.3858 billion this week. In terms of individual products, BlackRock's IBIT led with a net inflow of $1.1576 billion, followed by Fidelity's FBTC with $701.6 million, ARK 21Shares' ARKB with $294.7 million, Morgan Stanley's MSBT with $203.3 million, and Bitwise's BITB with $13.9 million. BTCW recorded a net outflow of $3.2 million, while BTCO and BRRR remained flat at zero.

  • Ethena: USDe-Related Token Incentives to Reach Zero, Down Approximately 85% Since 2024

    On September 26, Ethena announced that since the first airdrop in 2024, token incentives related to the growth of USDe have decreased by approximately 85% from 2024 to this year. The official statement indicated that by the end of this month, token incentives and additional issuance related to USDe will reach zero, and there will be no further incentive arrangements thereafter. Ethena also expressed gratitude to all users who have participated and supported the development of the product to date.

  • Analyst: Bitcoin Enters Bull Market Phase as MVRV Ratio Surpasses 1.0 Baseline

    On September 26, crypto analyst Axel Adler Jr. stated that Bitcoin has transitioned from an early bull market to a bull market phase. The adjusted MVRV 30-day/365-day moving average ratio he tracks broke above the 1.0 baseline on September 20 (with the short-term average surpassing the annual average), at which point BTC was priced at $80,691. Previously, this ratio had crossed above the 365-day moving average on August 20, marking the entry into the early bull market when BTC was priced at $71,255; this phase lasted for 31 days, during which Bitcoin rose by 13%. The current ratio stands at 1.018, with BTC priced at $84,156. As long as it remains above 1.0, the structure will maintain a bullish outlook. This marks the sixth such transition since 2012, and in four of the previous five instances, the bull market ended with prices above the entry price, with the only exception being August 2015, when the bull market lasted only 16 days.