Vyper's @nonreentrant: Language-Level Reentrancy Guards That Replace Manual Mutex Patterns
Vyper's @nonreentrant decorator enforces key-based reentrancy locks using transient storage on Cancun+ chains (~100 gas), with regular storage fallback elsewhere.
04 Jul 2026, 13:38 UTC

The Problem: Reentrancy Still Bites
You've audited the withdrawal function, added the checks-effects-interactions pattern, and still a reentrancy exploit slips through. The culprit? A callback from an ERC-20 transfer or a malicious contract that calls back into your code before state updates finish. In Solidity, the standard fix is OpenZeppelin's ReentrancyGuard — a boolean mutex stored in a storage slot. It works, but it costs ~5,000 gas per SSTORE and leaves dirty storage unless you manually clear it.
Vyper takes a different approach: @nonreentrant is a compiler-enforced decorator that acquires a lock on function entry and releases it on exit (including reverts). Since Vyper 0.3.10, it uses transient storage (EIP-1153) on Cancun+ networks, dropping the overhead to ~100 gas and auto-clearing after the transaction. This post walks through how it works, where it fits, and the trade-offs you'll face when adopting it.
How @nonreentrant Works
The decorator syntax is @nonreentrant('key') where the key is a compile-time string literal. Every function sharing the same key forms a mutual-exclusion group — only one can execute at a time within a single transaction. Distinct keys allow controlled concurrency.
# vyper 0.4.x
@external
@nonreentrant('withdrawal')
def withdraw(amount: uint256) -> bool:
assert self.balances[msg.sender] >= amount
self.balances[msg.sender] -= amount
# external call — primary reentrancy vector
ERC20(token).transfer(msg.sender, amount)
return True
@external
@nonreentrant('withdrawal') # same key = mutual exclusion
def batch_withdraw(amounts: uint256[5]) -> bool:
# ... same lock, cannot run concurrently with withdraw()
pass
@external
@nonreentrant('governance') # independent domain, runs concurrently
def propose(param: bytes32) -> bool:
# ... separate lock
pass
On Cancun-enabled chains (Ethereum mainnet, Sepolia, Holesky, Arbitrum, Optimism, Base), the compiler emits tload/tstore against a transient slot derived from the key. On pre-Cancun networks or L2s without support, it falls back to regular sload/sstore — same semantics, higher gas (~5k vs ~100) and the slot stays dirty until the transaction ends.
Key-Based vs Contract-Wide: Why It Matters
Solidity's ReentrancyGuard typically uses a single _status boolean per contract. That means any guarded function blocks all others — even unrelated ones like governance voting and token withdrawals. Vyper's key system lets you isolate lock domains:
- Same key: functions serialize. Use for operations touching the same state (balances, allowances, vault shares).
- Different keys: functions run concurrently. Use for independent domains (withdrawals vs governance vs oracle updates).
This granularity avoids over-locking. A governance proposal won't block a user's withdrawal just because both are guarded.
Worked Example: Guarding a Vault Withdrawal
Consider a simple vault where users deposit and withdraw a single ERC-20. The withdrawal is the critical path.
# vault.vy
from vyper.interfaces import ERC20
token: immutable(ERC20)
balances: HashMap[address, uint256]
def __init__(_token: address):
self.token = ERC20(_token)
@external
@nonreentrant('vault')
def deposit(amount: uint256) -> bool:
assert amount > 0
self.token.transferFrom(msg.sender, self, amount)
self.balances[msg.sender] += amount
return True
@external
@nonreentrant('vault')
def withdraw(amount: uint256) -> bool:
assert self.balances[msg.sender] >= amount
self.balances[msg.sender] -= amount
# state updated BEFORE external call — checks-effects-interactions
self.token.transfer(msg.sender, amount)
return True
@view
external
def balance_of(user: address) -> uint256:
return self.balances[user]
Both deposit and withdraw share the 'vault' key. A malicious token that calls back into withdraw during transfer will hit the lock and revert with reentrant call. The balance_of view function needs no guard — it doesn't modify state.
Gas check: Deploy to Sepolia (Cancun-enabled). Call withdraw twice — first succeeds, second reverts. Measure gas: the lock adds ~100 gas vs an unguarded function making the same external call. On pre-Cancun, expect ~5,000 gas for the SSTORE.
Trade-offs and Limitations
Cross-Contract Reentrancy Isn't Solved Automatically
If Contract A (Vyper) calls Contract B (Solidity) which calls back into Contract A, each contract needs its own @nonreentrant. The key namespace is per-contract — Contract A's 'vault' key doesn't block Contract B's _status. In mixed-language systems, you need coordinated discipline or a shared library pattern.
Internal Calls From Unguarded Entry Points Bypass the Lock
Vyper 0.4.0+ enforces that a @nonreentrant function cannot be called internally from a non-guarded external function without explicit key passing. Earlier versions allowed this silently. Example of what 0.4.0 rejects:
@external
def unguarded():
self._internal() # compile error if _internal is @nonreentrant
@internal
@nonreentrant('key')
def _internal():
pass
Fix: either guard the external entry point with the same key, or make the internal function non-guarded and reason about safety manually.
Transient Storage Fallback Costs
On networks without Cancun (some L2s, older testnets), the fallback to regular storage increases gas and leaves slots dirty. If you deploy to such a network, budget ~5k gas per guarded call and consider manual cleanup if the slot is reused.
Key Count Affects Contract Size
Each distinct key allocates a storage slot. Hundreds of keys can push deployment gas near limits on complex contracts. Most projects need 3–10 keys (withdrawal, deposit, governance, oracle, emergency).
Actionable Checklist
- Audit your external entry points: Every state-changing
@externalfunction should have@nonreentrantunless you have a documented reason not to. - Group by state domain: Use the same key for functions that touch overlapping storage (balances, allowances, vault shares). Use different keys for independent domains.
- Verify Cancun support: Check your target chain's fork schedule. If pre-Cancun, test gas costs and plan for dirty storage slots.
- Test reentrancy explicitly: Write a Foundry/Hardhat test where a malicious contract calls back into your guarded function. Assert the second call reverts with
reentrant call. - Coordinate with Solidity contracts: If your Vyper contract calls Solidity contracts that call back, ensure both sides have guards. Don't assume one protects the other.
Closing Thought
Vyper's @nonreentrant moves reentrancy protection from a library pattern you might forget to a language feature you can't easily bypass. The key-based model gives you finer control than a single boolean guard, and transient storage makes it cheap on modern chains. The main discipline required: guard every external state-changing function, pick keys that match your state domains, and test the fallback path if you deploy to pre-Cancun networks. That's a small price for eliminating an entire class of vulnerabilities at compile time.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.