Ethereum smart contracts are extremely flexible, capable of both holding large quantities of tokens (often in excess of $1B) and running immutable logic based on previously deployed smart contract code. While this has created a vibrant and creative ecosystem of trustless, interconnected smart contracts, it is also the perfect ecosystem to attract attackers looking to profit by exploiting vulnerabilities in smart contracts and unexpected behavior in Ethereum. Smart contract code usuallyhg0088线上 cannot be changed to patch security flaws, assets that have been stolen from smart contracts are irrecoverable, and stolen assets are extremely difficult to track. The total of amount of value stolen or lost due to smart contract issues is easily in the $1B. Some of the larger due to smart contract coding errors include:


This will cover smart contract security so make sure you're familiar with smart contracts before tackling security.

How to write more secure Smart Contract code

hg0088线上before launching any code to mainnet, it is important to take sufficient precaution to protect anything of value your smart contract is entrusted with. in this article, we will discuss a few specific attacks, provide resources to learn about more attack types, and leave you with some basic tooling and best practices to ensure your contracts function correctly and securely.

Audits are not a silver bullet

Years prior, the tooling for writing, compiling, testing, and deploying smart contracts was very immature, leading many projects to write Solidity code in haphazard ways, throw it over a wall to an auditor who would investigate the code to ensure it functions securely and as expected. In 2020, the development processes and tooling that support writing Solidity is significantly better; leveraging these best practices not only ensures your project is easier to manage, it is a vital part of your project's security. An audit at the end of writing your smart contract is no longer sufficient as the only security consideration your project makes. Security starts before you write your first line of smart contract code, security starts with proper design and development processes.

Smart Contract Development Process

at a minimum:

there is much more to be said for development process, but these items are a good place to start. for more items and detailed explanations, see the . is an unofficial public service publishing reviews of various large, public ethereum dapps. part of the defisafety rating system includes how well the project adheres to this process quality checklist. by following these processes:

Attacks and vulnerabilities

now that you are writing solidity code using an efficient development process, let's look at some common solidity vulnerabilities to see what can go wrong.


re-entrancy is one of the largest and most significant security issue to consider when developing smart contracts. while the evm cannot run multiple contracts at the same time, a contract calling a different contract pauses the calling contract's execution and memory state until the call returns, at which point execution proceeds normally. this pausing and re-starting can create a vulnerability known as "re-entrancy".

hg0088线上here is a simple version of a contract that is vulnerable to re-entrancy:

2contract Victim {
3 mapping (address => uint256) public balances;
5 function deposit() external payable {
6 balances[msg.sender] += msg.value;
7 }
9 function withdraw() external {
10 uint256 amount = balances[msg.sender];
11 (bool success, ) = msg.sender.call.value(amount)("");
12 require(success);
13 balances[msg.sender] = 0;
14 }
📋 Copy

to allow a user to withdraw eth they have previously stored on the contract, this function

  1. Reads how much balance a user has
  2. Sends them that balance amount in ETH
  3. Resets their balance to 0, so they cannot withdraw their balance again.

If called from a regular account (such as your own Metamask account), this functions as expected: msg.sender.call.value() simply sends your account ETH. However, smart contracts can make calls as well. If a custom, malicous contract is the one calling withdraw(), msg.sender.call.value() will not only send amount of ETH, it will also implicitly call the contract to begin executing code. Imagine this malicious contract:

1contract Attacker {
2 function beginAttack() external payable {
3 Victim(VICTIM_ADDRESS).deposit.value(1 ether)();
4 Victim(VICTIM_ADDRESS).withdraw();
5 }
7 function() external payable {
8 if (gasleft() > 40000) {
9 Victim(VICTIM_ADDRESS).withdraw();
10 }
11 }
📋 Copy

calling attacker.beginattack() will start a cycle that looks something like:

10.) Attacker's EOA calls Attacker.beginAttack() with 1 ETH
20.) Attacker.beginAttack() depits 1 ETH into Victim
4 1.) Attacker -> Victim.withdraw()
5 1.) Victim reads balanceOf[msg.sender]
6 1.) Victim sends ETH to Attacker (which executes default function)
7 2.) Attacker -> Victim.withdraw()
8 2.) Victim reads balanceOf[msg.sender]
9 2.) Victim sends ETH to Attacker (which executes default function)
10 3.) Attacker -> Victim.withdraw()
11 3.) Victim reads balanceOf[msg.sender]
12 3.) Victim sends ETH to Attacker (which executes default function)
13 4.) Attacker no longer has enough gas, returns without calling again
14 3.) balances[msg.sender] = 0;
15 2.) balances[msg.sender] = 0; (it was already 0)
16 1.) balances[msg.sender] = 0; (it was already 0)

hg0088线上calling attacker.beginattack with 1 eth will re-entrancy attack victim, withdrawing more eth than it provided (taken from other users' balances, causing the victim contract to become under-collateralized)

How to deal with re-entrancy (the wrong way)

one might consider defeating re-entrancy by simply preventing any smart contracts from interacting with your code. you search stackoverflow, you find this snippet of code with tons of upvotes:

1function isContract(address addr) internal returns (bool) {
2 uint size;
3 assembly { size := extcodesize(addr) }
4 return size > 0;
📋 Copy

hg0088线上seems to make sense: contracts have code, if the caller has any code, don't allow it to deposit. let's add it:

2contract ContractCheckVictim {
3 mapping (address => uint256) public balances;
5 function isContract(address addr) internal returns (bool) {
6 uint size;
7 assembly { size := extcodesize(addr) }
8 return size > 0;
9 }
11 function deposit() external payable {
12 require(!isContract(msg.sender); // <- NEW LINE
13 balances[msg.sender] += msg.value;
14 }
16 function withdraw() external {
17 uint256 amount = balances[msg.sender];
18 (bool success, ) = msg.sender.call.value(amount)("");
19 require(success);
20 balances[msg.sender] = 0;
21 }
📋 Copy

hg0088线上now in order to deposit eth, you must not have smart contract code at your address. however, this is easily defeated with the following attacker contract:

1contract ContractCheckAttacker {
2 constructor() public payable {
3 ContractCheckVictim(VICTIM_ADDRESS).deposit(1 ether); // <- New line
4 }
6 function beginAttack() external payable {
7 ContractCheckVictim(VICTIM_ADDRESS).withdraw();
8 }
10 function() external payable {
11 if (gasleft() > 40000) {
12 Victim(VICTIM_ADDRESS).withdraw();
13 }
14 }
📋 Copy

whereas the first attack was an attack on contract logic, this is an attack on ethereum contract deployment behavior. during construction, a contract has not yet returned its code to be deployed at its address, but retains full evm control during this process.

hg0088线上it is technically possible to prevent smart contracts from calling your code, using this line:

1require(tx.origin == msg.sender)
📋 Copy

hg0088线上however, this is still not a good solution. one of the most exciting aspects of ethereum is its composability, smart contracts integrate with and building on each other. by using the line above, you are limiting the usefulness of your project.

How to deal with re-entrancy (the right way)

By simply switching the order of the storage update and external call, we prevent the re-entrancy condition that enabled the attack. Calling back into withdraw, while possible, will not benefit the attacker, since the balanceshg0088线上 storage will already be set to 0.

1contract NoLongerAVictim {
2 function withdraw() external {
3 uint256 amount = balances[msg.sender];
4 balances[msg.sender] = 0;
5 (bool success, ) = msg.sender.call.value(amount)("");
6 require(success);
7 }
📋 Copy

the code above follows the "checks-effects-interactions" design pattern, which helps protect against re-entrancy. you can

How to deal with re-entrancy (the nuclear option)

Any time you are sending ETH to an untrusted address or interacting with an unknown contract (such as calling transfer() of a user-provided token address), you open yourself up to the possibility of re-entrancy. By designing contracts that neither send ETH nor call untrusted contracts, you prevent the possibility of re-entrancy!

More attack types

hg0088线上the attack types above cover smart-contract coding issues (re-entrancy) and ethereum oddities (running code inside contract constructors, before code is available at the contract address). there are many, many more attack types to be aware of, such as:

further reading:

Security tools

while there is no substitute for understanding ethereum security basics and engaging a professional auditing firm to review your code, there are many tools available to help highlight potential issues in your code.

Smart Contract Security

Slither - Solidity static analysis framework written in Python 3.

MythX - Security analysis API for Ethereum smart contracts.

Mythril - Security analysis tool for EVM bytecode.

SmartContract.Codes - Search engine for verified solidity source codes.

Manticore - A command line interface that uses a symbolic execution tool on smart contracts and binaries.

Securify - Security scanner for Ethereum smart contracts.

ERC20 Verifier - A verification tool used to check if a contract complies with the ERC20 standard.

Formal Verification

Information on Formal Verification

Using tools

two of the most popular tools for smart contract security analysis are:

Both are useful tools that analyze your code and report issues. Each has a [commercial] hosted version, but are also available for free to run locally. The following is a quick example of how to run Slither, which is made available in a convenient Docker image trailofbits/eth-security-toolbox. You will need to .

$ mkdir test-slither
$ curl http://gist.githubusercontent.com/epheph/460e6ff4f02c4ac582794a41e1f103bf/raw/9e761af793d4414c39370f063a46a3f71686b579/gistfile1.txt > bad-contract.sol
$ docker run -v `pwd`:/share -it --rm trailofbits/eth-security-toolbox
docker$ cd /share
docker$ solc-select 0.5.11
docker$ slither bad-contract.sol

will generate this output:

ethsec@1435b241ca60:/share$ slither bad-contract.sol
Reentrancy in Victim.withdraw() (bad-contract.sol#11-16):
External calls:
- (success) = msg.sender.call.value(amount)() (bad-contract.sol#13)
State variables written after the call(s):
- balances[msg.sender] = 0 (bad-contract.sol#15)
Reference: http://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnerabilities
Low level call in Victim.withdraw() (bad-contract.sol#11-16):
- (success) = msg.sender.call.value(amount)() (bad-contract.sol#13)
Reference: http://github.com/crytic/slither/wiki/Detector-Documentation#low-level-calls
INFO:Slither:bad-contract.sol analyzed (1 contracts with 46 detectors), 2 result(s) found
INFO:Slither:Use http://crytic.io/ to get access to additional detectors and Github integration

hg0088线上slither has identified the potential for re-entrancy here, identifying the key lines where the issue might occur and giving us a link for more details about the issue:


allowing you to quickly learn about potential problems with your code. like all automated testing tools, slither is not perfect, and it errs on the side of reporting too much. it can warn about a potential re-entrancy, even when no exploitable vulnerability exists. often, reviewing the difference in slither output between code changes is extremely illuminating, helping discover vulnerabilities that were introduced much earlier than waiting until your project is code-complete.

Further reading

Smart Contract Security Best Practices Guide

Smart Contract Security Verification Standard (SCSVS)

Know of a community resource that helped you? Edit this page and add it!

Back to top ↑
  • On this page
  • Prerequisites
  • How to write more secure Smart Contract code
  • Audits are not a silver bullet
  • Smart Contract Development Process
  • Attacks and vulnerabilities
  • More attack types
  • Security tools
  • Further reading
  • Related tutorials