> For the complete documentation index, see [llms.txt](https://calnix.gitbook.io/eth-dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://calnix.gitbook.io/eth-dev/solidity-patterns/checks-effects-interactions-pattern.md).

# checks-effects-interactions pattern

## Objective: Negate Reentrancy attacks

![](/files/k33EF1bW8igposkCc4si)

### Negative Example

```solidity
function withdrawToken(uint256 amount) public {
    require(userBalance[msg.sender] >= amount, "requested amount exceeds user balance");
    require(iToken.transferFrom(address(this), msg.sender, amount), "failed on withdrawal");
    userBalance[msg.sender] -= amount;
```

* `iToken.transferFrom` could be maliciously coded to call `withdrawToken` again,&#x20;
* and the contract would transfer iToken out in a loop without modifying the user balance.&#x20;
* The attacker would only have to be careful of stopping the loop before running out of gas, and it would drain your contract of iToken.

### Positive Example

```solidity
    function withdraw(uint amount) external {      
        balances[msg.sender] -= amount;
        
        bool success = wmdToken.transfer(msg.sender, amount);
        require(success, "Withdrawal failed!");
        emit Withdrawal(msg.sender, amount);
    }
```

### Further Readings

* <https://www.securing.pl/en/reentrancy-attack-in-smart-contracts-is-it-still-a-problem/>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://calnix.gitbook.io/eth-dev/solidity-patterns/checks-effects-interactions-pattern.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
