Token integration analyzer

From cyotee/indexedex · View interactive version

Token integration analyzer is an AI agent skill from the GitHub repository cyotee/indexedex. Review token implementations and integrations for ERC conformance, weird-token behavior, privileges, and integration risks.

How to use this skill

Skill file

Token Integration Analyzer

IndexedEx integration

Read the target repository's CLAUDE.md and docs/agent/SKILL_CATALOG.md; current product law and canonical crane-* / indexedex-* guidance override generic examples here. Tests are production-first, never SUT mocks; use Crane TestBases, CREATE3/FactoryService for facets and the IndexedEx manager registry for vault/DETF DFPkgs, never direct new. For testing within the current authorized task: forge build --use solar before tests, default hermetic or FOUNDRY_PROFILE=fork; no via_ir or package profiles.

Analysis produces findings and recommendations, not silent production fixes. Commands, installation, scans, network/RPC, tests, deployments, Git writes and broadcasts require scope in the current request; examples grant none. Reading or installing this skill executes none. Current task authorization may already cover routine local analysis and validation; do not demand a second approval for those actions. Assessment-only requests do not authorize production fixes. Use Native's actual read, grep, glob, LSP and apply_patch tools as available; allowed-tools metadata is not enforcement. No Claude aliases or plugin agent registration is assumed. Report missing tools and unverified results rather than claiming success. Reports go only to the user-scoped output path. Historical examples and sample scores are illustrative, not IndexedEx findings or proof of tool correctness. Retained upstream interface metadata is inert in references/upstream-openai.yaml. Upstream pointers to audit-context-building or issue-writer are optional, not installed commands; use scoped code reading and the included report templates when they are absent.

IndexedEx token policy

Fee-on-transfer and rebasing underlyings are forbidden; detecting them is an incompatibility finding, not a request to support them. Pause/blocklist behavior is accepted but liveness and failure paths still need analysis. Non-18 decimals are allowed; normalize only where pricing adapters require it, and keep DETF/sDETF native 9 decimals. rebasingClaimToken is a protocol product, not a permitted rebasing underlying. Do not add a PkgArgs allowlist. Generic mitigation examples below are not changes to these rules.

Purpose

Systematically analyzes the codebase for token-related security concerns using Trail of Bits' token integration checklist:

  1. Token Implementations: Analyze if your token follows ERC20/ERC721 standards or has non-standard behavior
  2. Token Integrations: Analyze how your protocol handles arbitrary tokens, including weird/non-standard tokens
  3. On-chain Analysis: Query deployed contracts for scarcity, distribution, and configuration
  4. Security Assessment: Identify risks from 20+ known weird token patterns

Framework: Building Secure Contracts - Token Integration Checklist + Weird ERC20 Database


How This Works

Phase 1: Context Discovery

Determines analysis context:

Phase 2: Slither Analysis (if Solidity)

For Solidity projects, I'll help run:

Phase 3: Code Analysis

Analyzes:

Phase 4: On-chain Analysis (if deployed)

Only when the current request explicitly includes read-only network/contract queries, and an address plus endpoint are supplied, assess:

Phase 5: Risk Assessment

Provides:


Assessment Categories

I check 10 comprehensive categories covering all aspects of token security. For detailed criteria, patterns, and checklists, see ASSESSMENT_CATEGORIES.md.

Quick Reference:

  1. General Considerations - Security reviews, team transparency, security contacts
  2. Contract Composition - Complexity analysis, SafeMath usage, function count, entry points
  3. Owner Privileges - Upgradeability, minting, pausability, blacklisting, team accountability
  4. ERC20 Conformity - Return values, metadata, decimals, race conditions, Slither checks
  5. ERC20 Extension Risks - External calls/hooks, transfer fees, rebasing/yield-bearing tokens
  6. Token Scarcity Analysis - Supply distribution, holder concentration, exchange distribution, flash loan/mint risks
  7. Weird ERC20 Patterns (24 patterns including):
  1. Token Integration Safety - Safe transfer patterns, balance verification, allowlists, wrappers, defensive patterns
  2. ERC721 Conformity - Transfer to 0x0, safeTransferFrom, metadata, ownerOf, approval clearing, token ID immutability
  3. ERC721 Common Risks - onERC721Received reentrancy, safe minting, burning approval clearing

Example Output

When analysis is complete, you'll receive a comprehensive report structured as follows:

=== TOKEN INTEGRATION ANALYSIS REPORT ===

Project: MultiToken DEX
Token Analyzed: Custom Reward Token + Integration Safety
Platform: Solidity 0.8.20
Analysis Date: March 15, 2024

---

## EXECUTIVE SUMMARY

Token Type: ERC20 Implementation + Protocol Integrating External Tokens
Overall Risk Level: MEDIUM
Critical Issues: 2
High Issues: 3
Medium Issues: 4

**Top Concerns:**
⚠ Fee-on-transfer tokens not handled correctly
⚠ No validation for missing return values (USDT compatibility)
⚠ Owner can mint unlimited tokens without cap

**Recommendation:** Address critical/high issues before mainnet launch.

---

## 1. GENERAL CONSIDERATIONS

✓ Contract audited by CertiK (June 2023)
✓ Team contactable via security@project.com
✗ No security mailing list for critical announcements

**Risk:** Users won't be notified of critical issues
**Action:** Set up security@project.com mailing list

---

## 2. CONTRACT COMPOSITION

### Complexity Analysis

**Slither human-summary Results:**
- 456 lines of code
- Cyclomatic complexity: Average 6, Max 14 (transferWithFee())
- 12 functions, 8 state variables
- Inheritance depth: 3 (moderate)

✓ Contract complexity is reasonable
⚠ transferWithFee() complexity high (14) - consider splitting

### SafeMath Usage

✓ Using Solidity 0.8.20 (built-in overflow protection)
✓ No unchecked blocks found
✓ All arithmetic operations protected

### Non-Token Functions

**Functions Beyond ERC20:**
- setFeeCollector() - Admin function ✓
- setTransferFee() - Admin function ✓
- withdrawFees() - Admin function ✓
- pause()/unpause() - Emergency functions ✓

⚠ 4 non-token functions (acceptable but adds complexity)

### Address Entry Points

✓ Single contract address
✓ No proxy with multiple entry points
✓ No token migration creating address confusion

**Status:** PASS

---

## 3. OWNER PRIVILEGES

### Upgradeability

⚠ Contract uses TransparentUpgradeableProxy
**Risk:** Owner can change contract logic at any time

**Current Implementation:**
- ProxyAdmin: 0x1234... (2/3 multisig) ✓
- Timelock: None ✗

**Recommendation:** Add 48-hour timelock to all upgrades

### Minting Capabilities

❌ CRITICAL: Unlimited minting
File: contracts/RewardToken.sol:89

function mint(address to, uint256 amount) external onlyOwner {

_mint(to, amount); // No cap!

}


**Risk:** Owner can inflate supply arbitrarily
**Fix:** Add maximum supply cap or rate-limited minting

### Pausability

✓ Pausable pattern implemented (OpenZeppelin)
✓ Only owner can pause
⚠ Paused state affects all transfers (including existing holders)

**Risk:** Owner can trap all user funds
**Mitigation:** Use multi-sig for pause function (already implemented ✓)

### Blacklisting

✗ No blacklist functionality
**Assessment:** Good - no centralized censorship risk

### Team Transparency

✓ Team members public (team.md)
✓ Company registered in Switzerland
✓ Accountable and contactable

**Status:** ACCEPTABLE

---

## 4. ERC20 CONFORMITY

### Slither-check-erc Results

Command: slither-check-erc . RewardToken --erc erc20

✓ transfer returns bool
✓ transferFrom returns bool
✓ name, decimals, symbol present
✓ decimals returns uint8 (value: 18)
✓ Race condition mitigated (increaseAllowance/decreaseAllowance)

**Status:** FULLY COMPLIANT

### slither-prop Test Results

Command: slither-prop . --contract RewardToken

**Generated 12 properties, all passed:**
✓ Transfer doesn't change total supply
✓ Allowance correctly updates
✓ Balance updates match transfer amounts
✓ No balance manipulation possible
[... 8 more properties ...]

**Echidna fuzzing:** 50,000 runs, no violations ✓

**Status:** EXCELLENT

---

## 5. WEIRD TOKEN PATTERN ANALYSIS

### Integration Safety Check

**Your Protocol Integrates 5 External Tokens:**
1. USDT (0xdac17f9...)
2. USDC (0xa0b86991...)
3. DAI (0x6b175474...)
4. WETH (0xc02aaa39...)
5. UNI (0x1f9840a8...)

### Critical Issues Found

❌ **Pattern 7.2: Missing Return Values**
**Found in:** USDT integration
File: contracts/Vault.sol:156

IERC20(usdt).transferFrom(msg.sender, address(this), amount);

// No return value check! USDT doesn't return bool


**Risk:** Silent failures on USDT transfers
**Exploit:** User appears to deposit, but no tokens moved
**Fix:** Use OpenZeppelin SafeERC20 wrapper

---

❌ **Pattern 7.3: Fee on Transfer**
**Risk for:** Any token with transfer fees
File: contracts/Vault.sol:170

uint256 balanceBefore = IERC20(token).balanceOf(address(this));

token.transferFrom(msg.sender, address(this), amount);

shares = amount * exchangeRate; // WRONG! Should use actual received amount


**Risk:** Accounting mismatch if token takes fees
**Exploit:** User credited more shares than tokens deposited
**IndexedEx recommendation:** Flag the fee-on-transfer underlying as forbidden; do not add support. For other protocols whose policy explicitly supports transfer fees, the generic mitigation is to account from `balanceAfter - balanceBefore`.

---

### Known Non-Standard Token Handling

✓ **USDC:** Properly handled (SafeERC20, 6 decimals accounted for)
⚠ **DAI:** permit() function not used (opportunity for gas savings)
✗ **USDT:** Missing return value not handled (CRITICAL)
✓ **WETH:** Standard wrapper, properly handled
⚠ **UNI:** Large approval handling not checked (reverts >= 2^96)

---

[... Additional sections for remaining analysis categories ...]

For complete report template and deliverables format, see REPORT_TEMPLATES.md.


Rationalizations (Do Not Skip)

| Rationalization | Why It's Wrong | Required Action |

|-----------------|----------------|-----------------|

| "Token looks standard, ERC20 checks pass" | 20+ weird token patterns exist beyond ERC20 compliance | Check ALL weird token patterns from database (missing return, revert on zero, hooks, etc.) |

| "Slither shows no issues, integration is safe" | Slither detects some patterns, misses integration logic | Complete manual analysis of all 5 token integration criteria |

| "No fee-on-transfer detected, skip that check" | Fee-on-transfer can be owner-controlled or conditional | Test all transfer scenarios, check for conditional fee logic |

| "Balance checks exist, handling is safe" | Balance checks alone don't protect against all weird tokens | Verify safe transfer wrappers, revert handling, approval patterns |

| "Token is deployed by reputable team, assume standard" | Reputation doesn't guarantee standard behavior | Analyze actual code and on-chain behavior, don't trust assumptions |

| "Integration uses OpenZeppelin, must be safe" | OpenZeppelin libraries don't protect against weird external tokens | Verify defensive patterns around all external token calls |

| "Can't run Slither, skipping automated analysis" | Slither provides critical ERC conformance checks | Manually verify all slither-check-erc criteria or document why blocked |

| "This pattern seems fine" | Intuition misses subtle token integration bugs | Systematically check all 20+ weird token patterns with code evidence |


Deliverables

When analysis is complete, I'll provide:

  1. Compliance Checklist - Checkboxes for all assessment categories
  2. Weird Token Pattern Analysis - Presence/absence of all 24 patterns with risk levels and evidence
  3. On-chain Analysis Report (if applicable) - Holder distribution, exchange listings, configuration
  4. Integration Safety Assessment (if applicable) - Safe transfer usage, defensive patterns, weird token handling
  5. Prioritized Recommendations - CRITICAL/HIGH/MEDIUM/LOW issues with specific fixes

Complete deliverable templates available in REPORT_TEMPLATES.md.


Ready to Begin

What I'll need:

Let's analyze your token implementation or integration for security risks!

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.