v4-security-foundations
Security-first Uniswap v4 hook development. Use when user mentions "v4 hooks", "hook security", "PoolManager", "beforeSwap", "afterSwap", or asks about V4 hook best practices, vulnerabilities, or audit requirements.
What this skill does
# v4 Hook Security Foundations
Security-first guide for building Uniswap v4 hooks. Hook vulnerabilities can drain user funds—understand these concepts before writing any hook code.
## Threat Model
Before writing code, understand the v4 security context:
| Threat Area | Description | Mitigation |
| ----------------------- | ---------------------------------------------------------- | ---------------------------------------------- |
| **Caller Verification** | Only `PoolManager` should invoke hook functions | Verify `msg.sender == address(poolManager)` |
| **Sender Identity** | `msg.sender` always equals PoolManager, never the end user | Use `sender` parameter for user identity |
| **Router Context** | The `sender` parameter identifies the router, not the user | Implement router allowlisting |
| **State Exposure** | Hook state is readable during mid-transaction execution | Avoid storing sensitive data on-chain |
| **Reentrancy Surface** | External calls from hooks can enable reentrancy | Use reentrancy guards; minimize external calls |
## Permission Flags Risk Matrix
All 14 hook permissions with associated risk levels:
| Permission Flag | Risk Level | Description | Security Notes |
| --------------------------------- | ---------- | --------------------------- | ----------------------------- |
| `beforeInitialize` | LOW | Called before pool creation | Validate pool parameters |
| `afterInitialize` | LOW | Called after pool creation | Safe for state initialization |
| `beforeAddLiquidity` | MEDIUM | Before LP deposits | Can block legitimate LPs |
| `afterAddLiquidity` | LOW | After LP deposits | Safe for tracking/rewards |
| `beforeRemoveLiquidity` | HIGH | Before LP withdrawals | Can trap user funds |
| `afterRemoveLiquidity` | LOW | After LP withdrawals | Safe for tracking |
| `beforeSwap` | HIGH | Before swap execution | Can manipulate prices |
| `afterSwap` | MEDIUM | After swap execution | Can observe final state |
| `beforeDonate` | LOW | Before donations | Access control only |
| `afterDonate` | LOW | After donations | Safe for tracking |
| `beforeSwapReturnDelta` | CRITICAL | Returns custom swap amounts | **NoOp attack vector** |
| `afterSwapReturnDelta` | HIGH | Modifies post-swap amounts | Can extract value |
| `afterAddLiquidityReturnDelta` | HIGH | Modifies LP token amounts | Can shortchange LPs |
| `afterRemoveLiquidityReturnDelta` | HIGH | Modifies withdrawal amounts | Can steal funds |
### Risk Thresholds
- **LOW**: Unlikely to cause fund loss
- **MEDIUM**: Requires careful implementation
- **HIGH**: Can cause fund loss if misimplemented
- **CRITICAL**: Can enable complete fund theft
## CRITICAL: NoOp Rug Pull Attack
The `BEFORE_SWAP_RETURNS_DELTA` permission (bit 10) is the most dangerous hook permission. A malicious hook can:
1. Return a delta claiming it handled the entire swap
2. PoolManager accepts this and settles the trade
3. Hook keeps all input tokens without providing output
4. User loses entire swap amount
### Attack Pattern
```solidity
// MALICIOUS - DO NOT USE
function beforeSwap(
address,
PoolKey calldata,
IPoolManager.SwapParams calldata params,
bytes calldata
) external override returns (bytes4, BeforeSwapDelta, uint24) {
// Claim to handle the swap but steal tokens
int128 amountSpecified = int128(params.amountSpecified);
BeforeSwapDelta delta = toBeforeSwapDelta(amountSpecified, 0);
return (BaseHook.beforeSwap.selector, delta, 0);
}
```
### Detection
Before interacting with ANY hook that has `beforeSwapReturnDelta: true`:
1. **Audit the hook code** - Verify legitimate use case
2. **Check ownership** - Is it upgradeable? By whom?
3. **Verify track record** - Has it been audited by reputable firms?
4. **Start small** - Test with minimal amounts first
### Legitimate Uses
NoOp patterns are valid for:
- Just-in-time liquidity (JIT)
- Custom AMM curves
- Intent-based trading systems
- RFQ/PMM integrations
But each requires careful implementation and audit.
## Delta Accounting Fundamentals
v4 uses a credit/debit system through the PoolManager:
### Core Invariant
```text
For every transaction: sum(deltas) == 0
```
The PoolManager tracks what each address owes or is owed. At transaction end, all debts must be settled.
### Key Functions
| Function | Purpose | Direction |
| ---------------------------- | ----------------------------------- | ---------------------- |
| `take(currency, to, amount)` | Withdraw tokens from PoolManager | You receive tokens |
| `settle(currency)` | Pay tokens to PoolManager | You send tokens |
| `sync(currency)` | Update PoolManager balance tracking | Preparation for settle |
### Settlement Pattern
```solidity
// Correct pattern: sync before settle
poolManager.sync(currency);
currency.transfer(address(poolManager), amount);
poolManager.settle(currency);
```
### Common Mistakes
1. **Forgetting sync**: Settlement fails without sync
2. **Wrong order**: Must sync → transfer → settle
3. **Partial settlement**: Leaves transaction in invalid state
4. **Double settlement**: Causes accounting errors
## Access Control Patterns
### PoolManager Verification
Every hook callback MUST verify the caller:
```solidity
modifier onlyPoolManager() {
require(msg.sender == address(poolManager), "Not PoolManager");
_;
}
function beforeSwap(
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
bytes calldata hookData
) external override onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {
// Safe to proceed
}
```
### Why This Matters
Without this check:
- Anyone can call hook functions directly
- Attackers can manipulate hook state
- Funds can be drained through fake callbacks
## Router Verification Patterns
The `sender` parameter is the router, not the end user. For hooks that need user identity:
### Allowlisting Pattern
```solidity
mapping(address => bool) public allowedRouters;
function beforeSwap(
address sender, // This is the router
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
bytes calldata hookData
) external override onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {
require(allowedRouters[sender], "Router not allowed");
// Proceed with swap
}
```
### User Identity via hookData
```solidity
function beforeSwap(
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
bytes calldata hookData
) external override onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {
// Decode user address from hookData (router must include it)
address user = abi.decode(hookData, (address));
// CAUTION: Router must be trusted to provide accurate user
}
```
### msg.sender Trap
```solidity
// WRONG - msg.sender is always PoolManager in hooks
function beforeSwap(...) external {
require(msg.sender == someUser); // Always fails or wrong
}
// CORRECT - Use sender parameter
function beforeSwap(address sender, ...) external {
require(allowedRouters[sender], "Invalid router");
}
```
## Token Handling Hazards
Not all tokens behave like standard ERC-20s:
| Token Type | Hazard | Mitigation Related in Security
mac-ops
IncludedComprehensive macOS workstation operations — diagnose kernel panics, identify failing drives, audit launchd startup items, decode wake reasons, triage TCC permission denials, manage APFS snapshots, recover from no-boot. Use for: Mac is slow, slow bootup, won't boot, kernel panic, kernel_task hot, mds_stores CPU, photoanalysisd, cloudd, login loop, gray screen, sleep wake failure, drive failing, IO errors, APFS snapshots eating space, Time Machine local snapshots, Spotlight indexing, launchd, LaunchAgent, LaunchDaemon, login items, TCC permissions, Full Disk Access, Screen Recording denied, Gatekeeper, quarantine, com.apple.quarantine, app is damaged, helper tool, /Library/PrivilegedHelperTools, pmset, wake reasons, dark wake, sysdiagnose, panic.ips, DiagnosticReports, configuration profile, MDM profile, remote diagnostics over SSH.
a11y-audit
IncludedRun accessibility audits on web projects combining automated scanning (axe-core, Lighthouse) with WCAG 2.1 AA compliance mapping, manual check guidance, and structured reporting. Output is configurable: markdown report only, markdown plus machine-readable JSON, or markdown plus issue tracker integration. Use this skill whenever the user mentions "accessibility audit", "a11y audit", "WCAG audit", "accessibility check", "compliance scan", or asks to check a web project for accessibility issues. Also trigger when the user wants to verify WCAG conformance or map findings to a specific standard (CAN-ASC-6.2, EN 301 549, ADA/AODA).
erpclaw
IncludedAI-native ERP system with self-extending OS. Full accounting, invoicing, inventory, purchasing, tax, billing, HR, payroll, advanced accounting (ASC 606/842, intercompany, consolidation), and financial reporting. 413 actions across 14 domains, 43 expansion modules. Constitutional guardrails, adversarial audit, schema migration. Double-entry GL, immutable audit trail, US GAAP.
assess
IncludedAssesses and rates quality 0-10 across multiple dimensions (correctness, maintainability, security, performance, testability, simplicity) with pros/cons analysis. Compares against project conventions and prior decisions from memory. Produces structured evaluation reports with actionable improvement suggestions. Use when evaluating code, designs, architectures, or comparing alternative approaches.
spring-boot-security-jwt
IncludedProvides JWT authentication and authorization patterns for Spring Boot 3.5.x covering token generation with JJWT, Bearer/cookie authentication, database/OAuth2 integration, and RBAC/permission-based access control using Spring Security 6.x. Use when implementing authentication or authorization in Spring Boot applications.
code-hardcode-audit
IncludedDetect hardcoded values, magic numbers, and leaked secrets. TRIGGERS - hardcode audit, magic numbers, PLR2004, secret scanning.