0xlayerghost/solidity-agent-kit/token-antiflash

Claude Code and agent skill by 0xlayerghost/solidity-agent-kit

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

[AUTO-INVOKE] MUST be invoked when designing or reviewing ERC20 token contracts that need flash loan protection. Covers token-level defense design patterns: cost tracking, same-block cooldown, progressive sell tax, minimum balance retention, EIP-7702 aware address checks, front-run protection, and referral binding. Trigger: any ERC20 token with anti-flash-loan, anti-bot, or tokenomics security design requirements.

Install

npx vskill@latest install 0xlayerghost/solidity-agent-kit/token-antiflash

SKILL.md

The same SKILL.md was published earlier as 0xlayerghost/solidity-agent-kit/token-antiflash.

Token-Level Flash Loan Prevention Design Patterns

Language Rule

  • Always respond in the same language the user is using. If the user asks in Chinese, respond in Chinese. If in English, respond in English.
Scope: Applicable to ERC20 token contracts that need protection against flash loan attacks at the token contract level. Complements the defi-security skill (protocol-level) with token-internal defense mechanisms. All parameters mentioned below are design references — actual values should be determined based on project requirements, tokenomics, and market conditions.

Workflow Rule

When this skill is triggered, DO NOT directly implement all strategies. Follow this workflow:

  1. Assess: Identify the project's threat model — what type of token (meme, community, DeFi ecosystem), what value at stake, what attack vectors are realistic
  2. Present: Show the developer the Strategy Decision Matrix and Combination Guide. Clearly explain the trade-offs of each strategy (gas cost, UX friction, implementation complexity)
  3. Let the developer choose: Ask the developer which protection level (Basic / Standard / Advanced / Maximum) or which specific strategies they want. Do NOT assume a protection level
  4. Confirm parameters: For each chosen strategy, confirm key design parameters with the developer (e.g., tax tiers, volume limit percentages, cooldown granularity) before writing code
  5. Implement: Only after developer confirmation, implement the selected strategies with the agreed parameters

Exception: If the developer explicitly says "implement all" or "maximum protection", skip steps 2-4 and implement the Maximum combination. If the developer specifies exact strategies by number, skip to step 4 for those strategies.

Toolchain Baseline

Use solc 0.8.24 with OpenZeppelin Contracts 5.0.2. Override _update(address from, address to, uint256 amount) for ERC20 transfer customization. State whether each check requires pre-transfer balances or post-transfer balances, and call super._update exactly where that ordering requires.

solidity
// OpenZeppelin Contracts 5.0.2
function _update(address from, address to, uint256 amount) internal override {
// Perform checks that require pre-transfer state here.
super._update(from, to, amount);
// Record effects that require post-transfer state here.
}

Core Design Principle

Flash loan attacks rely on atomic execution within a single transaction: borrow → manipulate → profit → repay. Token-level defense breaks this atomicity by introducing cost, time, and identity barriers inside the token contract itself.

Strategy Decision Matrix

When designing a token with flash loan protection, evaluate which strategies to apply based on the threat model:

Threat VectorRecommended StrategiesPriority
Single-block buy→sell arbitrageSame-block cooldown + Contract address checkHigh
Zero-cost token exploitation (airdrop/exploit)Cost tracking + Progressive sell taxHigh
Large-volume manipulationPer-address volume limits + Base trade feeMedium
Multi-address Sybil bypassReferral binding + State propagation on transferMedium
Bot front-running / sandwichFront-run sell protection + Dynamic feeSituational

Strategy 1: Cost Tracking

Design Idea: Track the acquisition cost basis of tokens per address. Limit realized profit to a configurable multiplier of the cost. Tokens acquired at zero cost (airdrop, exploit, flash loan) have zero cost basis, meaning profit is capped at zero or the tokens are burned on sell.

Key Design Points:

  • Maintain per-address cost basis state, updated on every _transfer / _update
  • On transfer: cost follows the token — propagate cost from sender to receiver proportionally
  • Zero-cost tokens should be flagged and handled separately (burn or restrict sell)
  • Profit cap multiplier should be a configurable owner parameter with a reasonable upper bound
  • Consider gas cost of maintaining the extra mapping — measure impact on transfer gas

Why It Works Against Flash Loans: Flash-borrowed tokens inherently have zero cost basis. With profit capped relative to cost, there is no economic incentive to execute the attack.

Implementation:

solidity
struct CostBasis {
uint256 totalCost; // total acquisition cost in quote token units
uint256 totalAmount; // total token amount held
}
mapping(address => CostBasis) private _costBasis;
function _propagateCostBasis(address from, address to, uint256 amount) private {
CostBasis storage senderCost = _costBasis[from];
if (senderCost.totalAmount == 0) return;
// proportional cost transfer
uint256 transferredCost = (senderCost.totalCost * amount) / senderCost.totalAmount;
senderCost.totalCost -= transferredCost;
senderCost.totalAmount -= amount;
_costBasis[to].totalCost += transferredCost;
_costBasis[to].totalAmount += amount;
}
// call this when a buy is detected (from == AMM pair)
function _recordBuy(address buyer, uint256 amount, uint256 costInQuote) private {
_costBasis[buyer].totalCost += costInQuote;
_costBasis[buyer].totalAmount += amount;
}

Strategy 2: Contract Address Check (EIP-7702 Aware)

Design Idea: Block interactions from smart contracts (which flash loan contracts are) while properly handling EIP-7702 delegated EOAs.

Key Design Points:

  • EIP-7702 delegation designator has a specific code length (23 bytes: 0xef0100 + 20-byte address)
  • Allow addresses with this exact code length (they are delegated EOAs, not contracts)
  • Block addresses with other non-zero code lengths (regular smart contracts)
  • Consider also checking msg.sender == tx.origin as a secondary guard
  • Whitelist necessary contracts: LP pair, router, staking contracts

Why It Works Against Flash Loans: Flash loan execution happens inside a contract call chain. Blocking contract callers forces interaction through EOAs, breaking atomic execution.

Implementation:

solidity
// EIP-7702 delegation designator format:
// byte[0..2] = 0xef0100 (magic prefix, 3 bytes)
// byte[3..22] = target contract address (20 bytes)
// total: 23 bytes
// Plain EOA has extcodesize = 0.
// Regular contract has extcodesize > 0 (and != 23 for the magic prefix case).
bytes3 private constant EIP7702_MAGIC = 0xef0100;
/// @dev Classifies an address into three types:
/// - size == 0 → plain EOA → return false (allow)
/// - size == 23 AND prefix matches 0xef0100 → EIP-7702 delegated EOA → return false (allow)
/// - anything else → real deployed contract → return true (block)
///
/// EIP-7702 delegated EOAs are allowed because:
/// 1. They are user-controlled accounts (smart wallets), not attack contracts
/// 2. They cannot execute atomic flash loan buy→sell (Strategy 3 still blocks same-block ops)
/// 3. Blocking them would break smart wallet UX for legitimate holders
///
/// extcodecopy gas note: ~700 gas cold read. Only runs when size == 23, which is rare.
function _isRealContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
// fast path: most addresses are plain EOA or regular contract
if (size == 0) return false; // plain EOA → allow
if (size != 23) return true; // regular contract (size > 23 or 1..22) → block
// slow path: exactly 23 bytes → read prefix to distinguish 7702 from an exotic 23-byte contract
bytes3 prefix;
assembly {
// extcodecopy(addr, destMemPtr, srcOffset, length)
// write 3 bytes starting at offset 0 of the account's code into `prefix`
extcodecopy(account, prefix, 0, 3)
}
if (prefix == EIP7702_MAGIC) return false; // confirmed EIP-7702 delegated EOA → allow
return true; // exotic 23-byte contract → block
}
/// @dev Call at the top of _update to block contract interactions.
/// Whitelisted addresses (LP pair, router, staking) bypass this check entirely.
function _checkNotContract(address addr) internal view {
if (_isWhitelisted[addr]) return;
require(!_isRealContract(addr), "AntiFlash: contract caller blocked");
}

Strategy 3: Same-Block Cooldown

Design Idea: Prevent buying and selling (or receiving and selling) within the same block. This is the most direct defense against flash loans since they must complete within one transaction (one block).

Key Design Points:

  • Track the block number of last incoming transfer per address
  • On sell (transfer to LP pair): require that the tracked block number is strictly less than current block.number
  • Critical: Also handle the transfer bypass — prevent A buys → A transfers to B → B sells in the same block
  • On wallet-to-wallet transfer: propagate the block restriction using max(lastBlock[to], lastBlock[from]) to prevent state laundering
  • Do NOT use `block.timestamp` for same-block tracking — block.number is the correct metric

Why It Works Against Flash Loans: Flash loans execute and repay within a single transaction (single block). Same-block cooldown completely prevents the buy→sell cycle.

_update Integration Hub

All strategy state propagation must be wired together in a single _update override. This is the most commonly missed vulnerability — partial wiring leaves transfer bypass paths open.

solidity
function _update(address from, address to, uint256 amount) internal override {
// ── Guard: call super first so balances are updated before our checks ──
super._update(from, to, amount);
bool fromPair = _isAMMPair[from]; // buy: tokens flow from pair → user
bool toPair = _isAMMPair[to]; // sell: tokens flow from user → pair
bool isTransfer = !fromPair && !toPair && from != address(0) && to != address(0);
// ── Strategy 2: Block real contracts ──
// Only check non-whitelisted, non-pair addresses
if (from != address(0) && !fromPair) {
_checkNotContract(from);
}
// ── Strategy 3: Same-block cooldown ──
if (toPair && from != address(0)) {
// sell path: seller must not have received tokens this block
require(
block.number > _lastInteractionBlock[from],
"AntiFlash: same-block sell"
);
}
if (fromPair) {
// buy path: record the block so this address cannot sell same-block
_lastInteractionBlock[to] = block.number;
}
if (isTransfer) {
// ★ transfer path: propagate the stricter (larger) block number
// using max() ensures restriction only extends, never shortens
// prevents: buy → transfer to fresh address → sell same-block
if (_lastInteractionBlock[from] > _lastInteractionBlock[to]) {
_lastInteractionBlock[to] = _lastInteractionBlock[from];
}
}
// ── Strategy 1: Cost basis propagation ──
if (useCostTracking && isTransfer) {
_propagateCostBasis(from, to, amount);
}
if (useCostTracking && fromPair) {
// record buy cost using current price from oracle or passed-in value
// (exact cost recording depends on your price feed integration)
_recordBuy(to, amount, _getCurrentCostBasis(amount));
}
// ── Strategy 7: Progressive tax timestamp propagation ──
if (useProgressiveTax && isTransfer) {
// propagate the older (more restrictive) timestamp so receiver
// cannot launder holding time by receiving a fresh transfer
if (_firstBuyTimestamp[from] > 0) {
if (_firstBuyTimestamp[to] == 0 || _firstBuyTimestamp[from] > _firstBuyTimestamp[to]) {
_firstBuyTimestamp[to] = _firstBuyTimestamp[from];
}
}
}
if (useProgressiveTax && fromPair && _firstBuyTimestamp[to] == 0) {
_firstBuyTimestamp[to] = block.timestamp;
}

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/0xlayerghost/solidity-agent-kit/token-antiflash/badge)](https://verified-skill.com/skills/0xlayerghost/solidity-agent-kit/token-antiflash)

Something wrong with this skill or its page? Tell us.