DEV Community

丁久
丁久

Posted on • Originally published at dingjiu1989-hue.github.io

Blockchain and Smart Contract Security

This article was originally published on AI Study Room. For the full version with working code examples and related articles, visit the original post.

Blockchain and Smart Contract Security

Blockchain and Smart Contract Security

Blockchain and Smart Contract Security

Blockchain and Smart Contract Security

Blockchain and Smart Contract Security

Blockchain and Smart Contract Security

Blockchain and Smart Contract Security

Blockchain and Smart Contract Security

Blockchain and Smart Contract Security

Blockchain and smart contract security presents unique challenges. Once deployed, smart contracts are immutable. A vulnerability in a contract can result in millions of dollars in losses with no recourse. This article covers common smart contract vulnerabilities, auditing tools and techniques, formal verification, and wallet security.

Common Smart Contract Vulnerabilities

Reentrancy

Reentrancy is the most infamous smart contract vulnerability. It occurs when a contract calls an external contract before updating its own state, allowing the external contract to recursively call back into the original contract before the first invocation completes.

// VULNERABLE: Reentrancy

contract VulnerableWithdraw {

mapping(address => uint) public balances;

function withdraw(uint amount) public {

require(balances[msg.sender] >= amount);

// STATE NOT UPDATED BEFORE EXTERNAL CALL

(bool success, ) = msg.sender.call{value: amount}("");

require(success, "Transfer failed");

balances[msg.sender] -= amount; // TOO LATE

}

}

An attacker contract can exploit this by calling withdraw repeatedly from its receive function, draining all funds before the balance is updated.

Prevention:

  • Use the checks-effects-interactions pattern: update state before making external calls.

  • Use OpenZeppelin's ReentrancyGuard modifier.

// SAFE: Checks-Effects-Interactions

contract SafeWithdraw {

using ReentrancyGuard for *;

mapping(address => uint) public balances;

function withdraw(uint amount) public nonReentrant {

require(balances[msg.sender] >= amount);

balances[msg.sender] -= amount; // Update state first

(bool success, ) = msg.sender.call{value: amount}("");

require(success, "Transfer failed");

}

}

Oracle Manipulation

Smart contracts rely on oracles to bring off-chain data (price feeds, randomness) on-chain. If an oracle is manipulated, contracts depending on that data behave incorrectly.

Flash loan attacks: An attacker borrows a large amount of tokens, trades them to manipulate the pool price, then exploits a contract that reads the manipulated price. The attacker repays the flash loan in the same transaction.


Read the full article on AI Study Room for complete code examples, comparison tables, and related resources.

Found this useful? Check out more developer guides and tool comparisons on AI Study Room.

Top comments (0)