{"id":"749adb7d-d4b0-4ffc-bb84-52796c7b5174","entityType":"agent","slug":"clawhub-skills-1kalin-afrexai-web3-engineering","name":"afrexai-web3-engineering","canonicalUrl":"https://www.xpersona.co/agent/clawhub-skills-1kalin-afrexai-web3-engineering","canonicalPath":"/agent/clawhub-skills-1kalin-afrexai-web3-engineering","generatedAt":"2026-10-09T16:33:23.331Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"description":"Web3 & Blockchain Engineering Web3 & Blockchain Engineering Complete methodology for evaluating, designing, building, securing, and operating blockchain-based systems. Covers smart contract development, DeFi protocol design, token economics, security auditing, and production operations. Zero dependencies. Framework-agnostic. Works with any blockchain, any language, any AI agent. --- Phase 1: Should You Use Blockchain? The Database Test Before wri","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. Last updated 4/15/2026.","installCommand":"clawhub skill install skills:1kalin:afrexai-web3-engineering","sourceUrl":"https://github.com/openclaw/skills/tree/main/skills/1kalin/afrexai-web3-engineering","homepage":null,"primaryLinks":[{"label":"View on ClawHub","url":"https://github.com/openclaw/skills/tree/main/skills/1kalin/afrexai-web3-engineering","kind":"source"}],"safetyScore":84,"overallRank":62,"popularityScore":50,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Web3 & Blockchain Engineering Web3 & Blockchain Engineering Complete methodology for evaluating, designing, building, securing, and operating blockchain-based s"},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[{"label":"avoid","status":"self-declared"},{"label":"selling","status":"self-declared"},{"label":"rug","status":"self-declared"},{"label":"always","status":"self-declared"},{"label":"only","status":"self-declared"},{"label":"restore","status":"self-declared"},{"label":"help","status":"self-declared"}],"verifiedCount":0,"selfDeclaredCount":8,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"},{"key":"avoid","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"},{"key":"selling","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"},{"key":"rug","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"},{"key":"always","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"},{"key":"only","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"},{"key":"restore","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"},{"key":"help","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile capability:avoid|supported|profile capability:selling|supported|profile capability:rug|supported|profile capability:always|supported|profile capability:only|supported|profile capability:restore|supported|profile capability:help|supported|profile"}},"adoption":{"evidence":{"source":"no-adoption-signals","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"No source adoption metrics were available."},"stars":null,"forks":null,"downloads":null,"packageName":null,"latestVersion":null,"tractionLabel":null},"release":{"evidence":{"source":"agent-index","verified":false,"confidence":"medium","updatedAt":"2026-02-25T05:53:02.337Z","emptyReason":null},"lastUpdatedAt":"2026-04-15T00:45:39.800Z","lastCrawledAt":"2026-02-25T05:53:02.337Z","lastIndexedAt":null,"nextCrawlAt":"2026-02-26T05:53:02.337Z","lastVerifiedAt":null,"highlights":[]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install skills:1kalin:afrexai-web3-engineering","setupComplexity":"low","setupSteps":["Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-web3-engineering/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-web3-engineering/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-web3-engineering/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-web3-engineering/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-web3-engineering/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-web3-engineering/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-09T16:33:23.330Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-web3-engineering/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-web3-engineering/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-web3-engineering/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-web3-engineering/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"readme":"# Web3 & Blockchain Engineering\n\nComplete methodology for evaluating, designing, building, securing, and operating blockchain-based systems. Covers smart contract development, DeFi protocol design, token economics, security auditing, and production operations.\n\n> Zero dependencies. Framework-agnostic. Works with any blockchain, any language, any AI agent.\n\n---\n\n## Phase 1: Should You Use Blockchain?\n\n### The Database Test\n\nBefore writing a single line of Solidity, answer honestly:\n\n```yaml\nblockchain_evaluation:\n  problem: \"[describe the core problem]\"\n  \n  requirements:\n    multiple_untrusting_parties: true/false    # >1 org needs shared truth\n    no_trusted_authority: true/false            # no single party everyone trusts\n    immutability_critical: true/false           # history must be tamper-proof\n    censorship_resistance_needed: true/false    # no entity should block access\n    value_transfer_required: true/false         # moving assets between parties\n    transparency_required: true/false           # all parties need verifiable state\n  \n  disqualifiers:\n    single_org_controls_data: true/false        # → use a database\n    data_deletion_required: true/false          # → GDPR conflict, careful\n    high_throughput_low_latency: true/false     # → >10K TPS? consider L2 or database\n    users_cant_manage_wallets: true/false       # → account abstraction or custodial\n    trusted_authority_exists: true/false        # → database with audit log\n  \n  score: \"[count true requirements - count true disqualifiers]\"\n  verdict: \"blockchain / hybrid / database\"\n```\n\n**Decision rules:**\n- Score ≤ 0 → Use PostgreSQL with audit logs\n- Score 1-2 → Hybrid (anchoring/notarization on-chain, logic off-chain)\n- Score 3+ → Blockchain is justified\n\n### Platform Selection Matrix\n\n| Platform | TPS | Finality | Gas Cost | Best For |\n|----------|-----|----------|----------|----------|\n| Ethereum L1 | ~30 | ~12 min | $1-50+ | Settlement, high-value DeFi |\n| Arbitrum | ~4,000 | ~1 sec (soft) | $0.01-0.10 | DeFi, general dApps |\n| Optimism | ~2,000 | ~2 sec (soft) | $0.01-0.15 | Public goods, governance |\n| Base | ~2,000 | ~2 sec (soft) | $0.001-0.05 | Consumer apps, social |\n| Polygon PoS | ~7,000 | ~2 sec | $0.001-0.01 | Gaming, mass-market |\n| Solana | ~65,000 | ~400ms | $0.00025 | High-frequency, DePIN |\n| Avalanche C | ~4,500 | ~1 sec | $0.01-0.10 | Enterprise, subnets |\n| BNB Chain | ~2,000 | ~3 sec | $0.01-0.05 | Retail, low-cost |\n| Bitcoin L1 | ~7 | ~60 min | $0.50-5+ | Store of value, settlement |\n| Bitcoin L2 (Lightning) | ~1M+ | instant | <$0.01 | Micropayments, P2P |\n\n**Selection decision tree:**\n1. Store of value / settlement only? → Bitcoin\n2. Micropayments / instant P2P? → Lightning Network\n3. Need EVM compatibility? → Yes: continue. No: consider Solana, Cosmos\n4. High-value DeFi / maximum security? → Ethereum L1\n5. General dApp with low gas? → Arbitrum or Base\n6. Mass-market consumer? → Base or Polygon\n7. Enterprise with custom rules? → Avalanche subnets or Hyperledger\n\n---\n\n## Phase 2: Smart Contract Architecture\n\n### Design Principles\n\n1. **Minimize on-chain state** — Storage is expensive. Put data on-chain only if it needs consensus\n2. **Fail loudly** — Use `require()` / `revert()` with descriptive messages, never silent failures\n3. **Immutability by default** — Upgradeability adds attack surface. Only use if genuinely needed\n4. **Separation of concerns** — One contract per responsibility\n5. **Gas-conscious design** — Every operation costs money. Optimize hot paths\n\n### Contract Architecture Patterns\n\n```yaml\narchitecture_brief:\n  project: \"[name]\"\n  type: \"DeFi / NFT / DAO / Token / Marketplace / Infrastructure\"\n  \n  contracts:\n    core:\n      - name: \"[MainContract]\"\n        responsibility: \"[single clear purpose]\"\n        state_variables: [\"list key storage\"]\n        external_calls: [\"contracts it calls\"]\n    \n    periphery:\n      - name: \"[Router/Helper]\"\n        responsibility: \"[user-facing convenience]\"\n    \n    libraries:\n      - name: \"[MathLib/SafeLib]\"\n        responsibility: \"[shared pure functions]\"\n  \n  upgrade_strategy: \"immutable / transparent-proxy / UUPS / diamond / beacon\"\n  access_control: \"Ownable / AccessControl / Timelock+Multisig / DAO\"\n```\n\n### Upgrade Pattern Decision\n\n| Pattern | Complexity | Gas Overhead | Storage Layout Risk | Best For |\n|---------|-----------|-------------|-------------------|----------|\n| Immutable | None | None | None | Simple contracts, tokens |\n| Transparent Proxy | Medium | +gas per call | High | Standard upgradeable |\n| UUPS | Medium | Lower than transparent | High | Gas-efficient upgradeable |\n| Diamond (EIP-2535) | High | Medium | High | Large modular systems |\n| Beacon | Medium | Medium | High | Many identical instances |\n\n**Rule:** If you can avoid upgradeability, do it. If you must upgrade, use UUPS with timelock + multisig governance.\n\n### Solidity Development Standards\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\n// — IMPORTS: Use named imports, pin versions —\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\n\n/// @title VaultV1\n/// @notice Single-asset vault with deposit/withdraw\n/// @dev Uses SafeERC20 for all token transfers\ncontract VaultV1 is ReentrancyGuard {\n    using SafeERC20 for IERC20;\n\n    // — STATE: Group by slot for packing —\n    IERC20 public immutable asset;       // slot 0\n    uint128 public totalDeposits;        // slot 1 (packed)\n    uint128 public totalShares;          // slot 1 (packed)\n    \n    mapping(address => uint256) public shares;\n\n    // — EVENTS: Index searchable fields —\n    event Deposited(address indexed user, uint256 amount, uint256 shares);\n    event Withdrawn(address indexed user, uint256 amount, uint256 shares);\n\n    // — ERRORS: Custom errors save gas vs strings —\n    error ZeroAmount();\n    error InsufficientShares(uint256 requested, uint256 available);\n\n    constructor(IERC20 _asset) {\n        asset = _asset;\n    }\n\n    /// @notice Deposit assets, receive proportional shares\n    /// @param amount Asset amount to deposit\n    /// @return mintedShares Shares minted to caller\n    function deposit(uint256 amount) external nonReentrant returns (uint256 mintedShares) {\n        if (amount == 0) revert ZeroAmount();\n        \n        // Calculate shares BEFORE transfer (prevent manipulation)\n        mintedShares = totalDeposits == 0\n            ? amount\n            : (amount * totalShares) / totalDeposits;\n        \n        // Effects before interactions (CEI pattern)\n        totalDeposits += uint128(amount);\n        totalShares += uint128(mintedShares);\n        shares[msg.sender] += mintedShares;\n        \n        // Interaction last\n        asset.safeTransferFrom(msg.sender, address(this), amount);\n        \n        emit Deposited(msg.sender, amount, mintedShares);\n    }\n}\n```\n\n### Coding Standards Checklist\n\n- [ ] NatSpec on every public/external function\n- [ ] Custom errors instead of require strings (saves ~50 gas each)\n- [ ] Events for every state change\n- [ ] CEI pattern (Checks-Effects-Interactions) on every external call\n- [ ] `nonReentrant` on functions with external calls\n- [ ] `immutable` / `constant` where possible\n- [ ] SafeERC20 for all token transfers\n- [ ] No `tx.origin` for auth (phishing vector)\n- [ ] Explicit visibility on all functions and state variables\n- [ ] Storage variable packing (group smaller types together)\n\n---\n\n## Phase 3: Token Economics (Tokenomics)\n\n### Token Type Decision\n\n| Type | Standard | Use Case | Regulatory Risk |\n|------|----------|----------|----------------|\n| Utility token | ERC-20 | Access, governance, gas | Medium |\n| Governance token | ERC-20 + voting | Protocol control | Medium |\n| Security token | ERC-1400/3643 | Equity, revenue share | HIGH — requires compliance |\n| NFT (unique) | ERC-721 | Collectibles, identity, access | Low-Medium |\n| Semi-fungible | ERC-1155 | Gaming items, editions | Low |\n| Soulbound (SBT) | ERC-5192 | Credentials, reputation | Low |\n| Stablecoin | ERC-20 + peg | Payments, DeFi collateral | HIGH — regulatory scrutiny |\n\n### Token Design Framework\n\n```yaml\ntokenomics:\n  token_name: \"[Name]\"\n  symbol: \"[SYM]\"\n  standard: \"ERC-20 / ERC-721 / ERC-1155\"\n  total_supply: \"[fixed / capped / inflationary]\"\n  \n  distribution:\n    team: \"[%] — [vesting schedule]\"\n    investors: \"[%] — [vesting schedule]\"\n    community: \"[%] — [distribution mechanism]\"\n    treasury: \"[%] — [governance-controlled]\"\n    ecosystem: \"[%] — [grants, incentives]\"\n    liquidity: \"[%] — [DEX pairs, market making]\"\n  \n  vesting:\n    team_cliff: \"12 months minimum\"\n    team_linear: \"24-48 months after cliff\"\n    investor_cliff: \"6-12 months\"\n    investor_linear: \"12-36 months\"\n  \n  value_accrual:\n    mechanism: \"[fee sharing / buyback-burn / staking yield / utility demand]\"\n    fee_structure: \"[% of protocol revenue → token holders]\"\n    burn_mechanism: \"[deflationary pressure source]\"\n  \n  governance:\n    voting_power: \"1 token = 1 vote / quadratic / conviction\"\n    quorum: \"[% of supply needed]\"\n    timelock: \"[delay between vote and execution]\"\n    \n  inflation_schedule:\n    year_1: \"[%]\"\n    year_2: \"[%]\"\n    long_term: \"[target %/year]\"\n    \n  sustainability_test:\n    without_new_buyers: \"Does the token have utility even if price = 0?\"\n    revenue_source: \"Where does yield come from? (real yield vs emissions)\"\n    death_spiral_risk: \"Can selling pressure create feedback loop?\"\n```\n\n### Tokenomics Red Flags\n\n| Red Flag | Why It's Bad | Fix |\n|----------|-------------|-----|\n| >20% team allocation | Centralization, dump risk | Cap at 15-20%, long vesting |\n| No cliff period | Immediate sell pressure | 12-month cliff minimum |\n| Inflationary without utility | Token printing → zero | Emissions tied to real revenue |\n| \"Yield\" from new deposits | Ponzi economics | Real yield from fees only |\n| Governance without timelock | Admin can rug | Timelock + multisig mandatory |\n| 100% unlocked at launch | Massive sell pressure | Staged unlock over 2-4 years |\n\n---\n\n## Phase 4: DeFi Protocol Design\n\n### Core DeFi Primitives\n\n| Primitive | What It Does | Key Risk | Examples |\n|-----------|-------------|----------|----------|\n| AMM (DEX) | Trustless token swaps | Impermanent loss | Uniswap, Curve |\n| Lending | Overcollateralized loans | Liquidation cascades | Aave, Compound |\n| Stablecoin | Price-stable token | Depeg risk | MakerDAO, Ethena |\n| Yield aggregator | Optimize yield farming | Smart contract risk stacking | Yearn |\n| Perpetuals | Leveraged derivatives | Liquidation, oracle manipulation | GMX, dYdX |\n| Liquid staking | Stake + maintain liquidity | Slashing, depeg | Lido, Rocket Pool |\n| Bridges | Cross-chain transfers | Bridge exploits (billions lost) | LayerZero, Wormhole |\n| Restaking | Re-use staked assets | Cascading slashing | EigenLayer |\n\n### AMM Design (Uniswap V2/V3 Pattern)\n\n```\nConstant Product: x * y = k\nPrice Impact: Δy = y - k/(x + Δx)\nSlippage: (expected_price - actual_price) / expected_price\n\nV3 Concentrated Liquidity:\n- LPs choose price range [Pa, Pb]\n- Capital efficiency: up to 4000x vs V2\n- Trade-off: must actively manage positions\n```\n\n### DeFi Security Invariants\n\nEvery DeFi protocol MUST maintain these:\n\n1. **Solvency** — Total assets ≥ total liabilities (always)\n2. **No free tokens** — No path creates tokens from nothing\n3. **Monotonic shares** — Depositing increases shares, withdrawing decreases\n4. **Oracle freshness** — Price data is within acceptable staleness window\n5. **Liquidation viability** — Undercollateralized positions can always be liquidated\n6. **Access control** — Admin functions behind timelock + multisig\n7. **Withdrawal guarantee** — Users can always withdraw their assets (no lock-up without consent)\n\n---\n\n## Phase 5: Security Auditing\n\n### Vulnerability Taxonomy\n\n| Category | Severity | Common Patterns |\n|----------|----------|-----------------|\n| Reentrancy | Critical | External call before state update |\n| Oracle manipulation | Critical | Flash loan → price manipulation → profit |\n| Access control | Critical | Missing auth on privileged functions |\n| Integer overflow | High | Pre-0.8 math without SafeMath |\n| Front-running | High | Sandwich attacks, MEV extraction |\n| Flash loan attacks | High | Atomic arbitrage exploiting price feeds |\n| Logic errors | High | Wrong formula, edge cases, rounding |\n| Denial of service | Medium | Gas limit exploitation, stuck states |\n| Centralization | Medium | Single admin key, no timelock |\n| Griefing | Medium | Making others' transactions fail/expensive |\n\n### Security Audit Checklist (100+ Points)\n\n#### Critical (Must Pass)\n\n- [ ] **Reentrancy protection** — All external calls follow CEI pattern OR use `nonReentrant`\n- [ ] **Access control** — Every privileged function has appropriate modifier\n- [ ] **Oracle security** — Price feeds have freshness checks, manipulation resistance\n- [ ] **Integer safety** — Solidity ≥0.8 (built-in overflow checks) or SafeMath\n- [ ] **Flash loan resistance** — Protocol functions work correctly within single transaction\n- [ ] **Approval hygiene** — No unlimited approvals to untrusted contracts\n- [ ] **Initialization** — Proxy contracts can only be initialized once\n- [ ] **Self-destruct protection** — No `selfdestruct` in implementation contracts\n- [ ] **Signature replay** — Nonces prevent signature reuse across chains/contracts\n\n#### High Priority\n\n- [ ] **Front-running protection** — Commit-reveal or deadline parameters on sensitive operations\n- [ ] **Slippage protection** — Min output amounts on swaps/withdrawals\n- [ ] **Rounding direction** — Always round in protocol's favor (against user)\n- [ ] **Gas griefing** — External calls can't force excessive gas consumption\n- [ ] **Token compatibility** — Handles fee-on-transfer, rebasing, and missing-return tokens\n- [ ] **Withdrawal path** — Users can always exit, even if admin functions fail\n- [ ] **Timelock on admin** — Governance changes have delay period\n- [ ] **Key management** — Multisig for all admin functions, no single points of failure\n- [ ] **Upgrade safety** — Storage layout preserved across upgrades (no slot collision)\n\n#### Medium Priority\n\n- [ ] **Event emission** — All state changes emit events for off-chain tracking\n- [ ] **Input validation** — Zero address checks, bounds checking on parameters\n- [ ] **Dust attacks** — Small deposits can't grief the accounting\n- [ ] **Block timestamp** — No reliance on exact block.timestamp (manipulable ±15s)\n- [ ] **Gas optimization** — No unbounded loops, batch operations have limits\n- [ ] **Error messages** — Custom errors with meaningful context\n- [ ] **Test coverage** — >95% line coverage, 100% on critical paths\n\n### Common Attack Vectors with Mitigations\n\n```\n1. Reentrancy\n   Attack: Call back into contract before state is updated\n   Fix: CEI pattern + ReentrancyGuard\n   \n2. Oracle Manipulation (Flash Loan)\n   Attack: Borrow → manipulate price → exploit → repay (atomic)\n   Fix: TWAP oracles, Chainlink price feeds, manipulation-resistant design\n   \n3. Sandwich Attack (MEV)\n   Attack: Front-run user's swap → inflate price → back-run to profit\n   Fix: Deadline parameter, max slippage, private mempools (Flashbots)\n   \n4. Governance Attack\n   Attack: Flash-borrow governance tokens → vote → execute\n   Fix: Snapshot at proposal creation, timelock, vote escrow (ve-model)\n   \n5. Price Oracle Stale Data\n   Attack: Use outdated price to exploit arbitrage\n   Fix: Chainlink heartbeat check, staleness threshold, circuit breakers\n```\n\n### Audit Process\n\n```yaml\naudit_checklist:\n  pre_audit:\n    - [ ] Code freeze — no changes during audit\n    - [ ] Documentation complete (spec, architecture, flow diagrams)\n    - [ ] Test suite passing with >95% coverage\n    - [ ] Known issues documented\n    - [ ] Deployment scripts tested on testnet\n    \n  audit_scope:\n    contracts: [\"list all in-scope contracts\"]\n    lines_of_code: \"[total Solidity LoC]\"\n    complexity: \"low / medium / high / critical\"\n    prior_audits: \"[list previous audit firms]\"\n    \n  recommended_firms:\n    tier_1: [\"Trail of Bits\", \"OpenZeppelin\", \"Consensys Diligence\"]\n    tier_2: [\"Spearbit\", \"Code4rena\", \"Sherlock\"]\n    bug_bounty: [\"Immunefi (post-deployment)\"]\n    \n  budget_guide:\n    simple_token: \"$5K-15K\"\n    defi_protocol: \"$50K-200K\"\n    complex_system: \"$200K-500K+\"\n    \n  post_audit:\n    - [ ] All critical/high findings fixed\n    - [ ] Fix review by auditor\n    - [ ] Audit report published (transparency)\n    - [ ] Bug bounty program launched\n```\n\n---\n\n## Phase 6: Testing Strategy\n\n### Test Pyramid for Smart Contracts\n\n```\n                    /\\\n                   /  \\        Mainnet Fork Tests\n                  /    \\       (real state, real tokens)\n                 /------\\\n                /        \\     Integration Tests\n               /          \\    (multi-contract interactions)\n              /------------\\\n             /              \\   Unit Tests\n            /                \\  (single function, isolated)\n           /------------------\\\n          /                    \\ Static Analysis\n         /                      \\ (Slither, Mythril, Aderyn)\n        /________________________\\\n```\n\n### Testing Checklist\n\n```yaml\ntesting_requirements:\n  static_analysis:\n    tools: [\"Slither\", \"Mythril\", \"Aderyn\"]\n    run: \"On every commit (CI)\"\n    \n  unit_tests:\n    coverage_target: \">95% line, 100% critical paths\"\n    framework: \"Foundry (preferred) or Hardhat\"\n    must_test:\n      - All require/revert conditions\n      - Boundary values (0, 1, max_uint256)\n      - Access control on every privileged function\n      - Math precision and rounding\n      \n  integration_tests:\n    must_test:\n      - Full user flows (deposit → earn → withdraw)\n      - Multi-contract interactions\n      - Upgrade paths (storage layout preservation)\n      - Governance proposal → execution flow\n      \n  fork_tests:\n    must_test:\n      - Real mainnet state interactions\n      - Oracle price feed behavior\n      - Token compatibility (USDT, USDC, DAI, etc.)\n      - Gas costs with real-world state size\n      \n  fuzz_tests:\n    tool: \"Foundry fuzz / Echidna / Medusa\"\n    invariants:\n      - \"Total supply == sum of all balances\"\n      - \"Total assets >= total liabilities\"\n      - \"Share price monotonically increases (yield vaults)\"\n      - \"No function creates tokens from nothing\"\n      \n  formal_verification:\n    when: \"Critical DeFi with >$10M TVL\"\n    tools: [\"Certora\", \"Halmos\", \"KEVM\"]\n```\n\n### Foundry Test Pattern\n\n```solidity\n// test/VaultV1.t.sol\ncontract VaultV1Test is Test {\n    VaultV1 vault;\n    MockERC20 token;\n    address alice = makeAddr(\"alice\");\n    \n    function setUp() public {\n        token = new MockERC20(\"Test\", \"TST\", 18);\n        vault = new VaultV1(IERC20(address(token)));\n        token.mint(alice, 1000e18);\n        vm.prank(alice);\n        token.approve(address(vault), type(uint256).max);\n    }\n    \n    function test_deposit_mintsShares() public {\n        vm.prank(alice);\n        uint256 shares = vault.deposit(100e18);\n        \n        assertEq(shares, 100e18, \"First deposit: 1:1 shares\");\n        assertEq(vault.shares(alice), 100e18);\n        assertEq(vault.totalDeposits(), 100e18);\n    }\n    \n    function test_deposit_revertsOnZero() public {\n        vm.prank(alice);\n        vm.expectRevert(VaultV1.ZeroAmount.selector);\n        vault.deposit(0);\n    }\n    \n    // Fuzz test: any deposit amount preserves invariants\n    function testFuzz_deposit_invariants(uint128 amount) public {\n        vm.assume(amount > 0 && amount <= token.balanceOf(alice));\n        \n        uint256 prevTotal = vault.totalDeposits();\n        vm.prank(alice);\n        vault.deposit(amount);\n        \n        assertEq(vault.totalDeposits(), prevTotal + amount);\n        assertTrue(vault.totalShares() > 0);\n    }\n}\n```\n\n---\n\n## Phase 7: Deployment & Operations\n\n### Deployment Checklist\n\n```yaml\npre_deployment:\n  - [ ] All tests passing (unit, integration, fork, fuzz)\n  - [ ] Static analysis clean (no high/critical findings)\n  - [ ] Audit complete, all findings addressed\n  - [ ] Deployment scripts tested on testnet (exact same flow)\n  - [ ] Multisig wallets created and configured\n  - [ ] Timelock contracts deployed and tested\n  - [ ] Constructor arguments verified\n  - [ ] Gas estimates confirmed within budget\n  \ndeployment:\n  - [ ] Deploy to mainnet from hardened machine\n  - [ ] Verify source on block explorer (Etherscan)\n  - [ ] Transfer ownership to multisig/timelock\n  - [ ] Renounce deployer privileges\n  - [ ] Test all functions with small amounts\n  - [ ] Set initial parameters (fees, limits, oracles)\n  \npost_deployment:\n  - [ ] Bug bounty program live (Immunefi)\n  - [ ] Monitoring dashboards deployed\n  - [ ] Alert rules configured\n  - [ ] Documentation published\n  - [ ] Community announcement\n```\n\n### Monitoring Dashboard\n\n```yaml\nsmart_contract_monitoring:\n  on_chain:\n    - metric: \"TVL (Total Value Locked)\"\n      alert: \"Drop >10% in 1 hour\"\n      severity: \"P0\"\n    - metric: \"Unique active users (daily)\"\n      alert: \"Drop >50% vs 7-day avg\"\n      severity: \"P1\"\n    - metric: \"Gas costs per transaction\"\n      alert: \"Spike >3x average\"\n      severity: \"P2\"\n    - metric: \"Admin function calls\"\n      alert: \"ANY unexpected admin call\"\n      severity: \"P0\"\n    - metric: \"Large withdrawals\"\n      alert: \">5% of TVL in single tx\"\n      severity: \"P1\"\n      \n  oracle:\n    - metric: \"Price feed freshness\"\n      alert: \"Stale >30 minutes\"\n      severity: \"P0\"\n    - metric: \"Price deviation vs CEX\"\n      alert: \">2% deviation\"\n      severity: \"P1\"\n      \n  infrastructure:\n    - metric: \"RPC node health\"\n      alert: \"Latency >500ms or errors\"\n      severity: \"P1\"\n    - metric: \"Indexer sync status\"\n      alert: \">100 blocks behind\"\n      severity: \"P1\"\n```\n\n### Incident Response\n\n| Severity | Response Time | Actions |\n|----------|-------------|---------|\n| P0 — Active exploit | < 5 min | Pause contracts, war room, post-mortem |\n| P1 — Vulnerability found | < 1 hour | Assess impact, prepare fix, notify team |\n| P2 — Degraded service | < 4 hours | Investigate, fix, monitor |\n| P3 — Minor issue | < 24 hours | Schedule fix in next deployment |\n\n**P0 Emergency Protocol:**\n1. Activate circuit breaker / pause contracts\n2. Assess: What was exploited? What's the exposure?\n3. Communicate: Alert team + trusted security researchers\n4. Contain: Block exploit path if possible\n5. Recover: Plan rescue transaction if funds recoverable\n6. Post-mortem: Full timeline, root cause, fix, prevention\n\n---\n\n## Phase 8: Wallet & Key Management\n\n### Key Hierarchy\n\n```\nSeed Phrase (BIP-39)\n  └── Master Key\n      ├── m/44'/60'/0'/0/0  → Ethereum Account 0\n      ├── m/44'/60'/0'/0/1  → Ethereum Account 1\n      ├── m/44'/0'/0'/0/0   → Bitcoin Account 0\n      └── m/84'/0'/0'/0/0   → Bitcoin SegWit Account 0\n```\n\n### Wallet Security Tiers\n\n| Tier | Type | Use Case | Security Level |\n|------|------|----------|---------------|\n| Hot wallet | Browser extension (MetaMask) | Daily interactions, small amounts | Low |\n| Warm wallet | Mobile wallet (Rainbow, Trust) | Medium amounts, on-the-go | Medium |\n| Cold wallet | Hardware (Ledger, Trezor) | Large holdings, long-term | High |\n| Air-gapped | Keystone, dedicated offline | Maximum security, institutional | Very High |\n| Multisig | Safe (Gnosis) | Treasury, protocol admin | Highest |\n\n### Multisig Best Practices\n\n```yaml\nmultisig_config:\n  protocol_treasury:\n    signers: 5\n    threshold: 3  # 3-of-5\n    signer_diversity:\n      - Different devices/locations\n      - Different key types (hardware + mobile)\n      - No single point of failure\n    timelock: \"48 hours for >$100K\"\n    \n  operational:\n    signers: 3\n    threshold: 2  # 2-of-3\n    use_case: \"Day-to-day parameter changes\"\n    timelock: \"24 hours\"\n```\n\n### Self-Custody Security Rules\n\n1. **Seed phrase storage** — Metal plate (Cryptosteel/Billfodl), never digital\n2. **Geographic distribution** — Copies in ≥2 physical locations\n3. **Test recovery** — Verify you can restore from seed BEFORE storing value\n4. **Phishing defense** — Bookmark official URLs, never click links, verify contract addresses\n5. **Hardware wallet firmware** — Update only from official sources\n6. **Transaction simulation** — Use Tenderly/Fire before signing large transactions\n7. **Approval hygiene** — Revoke unused token approvals regularly (revoke.cash)\n\n---\n\n## Phase 9: Layer 2 & Scaling\n\n### L2 Architecture Types\n\n| Type | How It Works | Data Availability | Examples |\n|------|-------------|-------------------|----------|\n| Optimistic Rollup | Assume valid, challenge period | On-chain calldata | Arbitrum, Optimism, Base |\n| ZK Rollup | Prove validity with ZK proof | On-chain calldata | zkSync, StarkNet, Scroll |\n| Validium | ZK proof + off-chain data | Off-chain (DAC) | Immutable X |\n| Plasma | Exit game mechanism | Off-chain | (largely deprecated) |\n| State Channel | Off-chain with on-chain settlement | Off-chain | Lightning Network |\n| Sidechain | Independent chain with bridge | Own consensus | Polygon PoS |\n\n### Cross-Chain Bridge Security\n\nBridges are the #1 attack vector in crypto (>$2.5B lost).\n\n**Bridge security checklist:**\n- [ ] Multisig or decentralized validator set (not single key)\n- [ ] Rate limiting on bridge transfers\n- [ ] Monitoring for unusual withdrawal patterns\n- [ ] Emergency pause functionality\n- [ ] Regular security audits\n- [ ] Insurance fund for bridge exploits\n\n**Safer bridging approaches:**\n1. Native bridges (Arbitrum/Optimism canonical) → Slow but trustless\n2. LayerZero/Axelar → Decentralized messaging\n3. Circle CCTP → Native USDC bridging (no wrapped tokens)\n4. Avoid: New/unaudited bridges, single-key admin bridges\n\n---\n\n## Phase 10: Regulatory & Compliance\n\n### Regulatory Landscape (2025)\n\n| Jurisdiction | Framework | Token Classification | Key Requirement |\n|-------------|-----------|---------------------|----------------|\n| US (SEC) | Howey Test | Security vs Utility | Registration or exemption |\n| US (CFTC) | CEA | Commodity (BTC, ETH) | Derivatives regulation |\n| EU (MiCA) | Markets in Crypto-Assets | Utility/E-Money/ART | Licensing, reserves |\n| UK (FCA) | Financial Promotions | Crypto-asset | Marketing restrictions |\n| Singapore (MAS) | Payment Services Act | Digital Payment Token | Licensing |\n| Japan (FSA) | FIEA/PSA | Crypto-asset | Registration |\n\n### Compliance Checklist\n\n```yaml\ncompliance:\n  token_classification:\n    - [ ] Legal opinion on token classification (security vs utility)\n    - [ ] Howey test analysis documented\n    - [ ] Jurisdictional analysis complete\n    \n  aml_kyc:\n    - [ ] KYC/AML provider integrated (if applicable)\n    - [ ] Sanctions screening (OFAC, EU, UN)\n    - [ ] Transaction monitoring for suspicious activity\n    - [ ] SAR (Suspicious Activity Report) filing process\n    \n  mca_eu:\n    - [ ] Whitepaper published (if issuing tokens)\n    - [ ] Notification to competent authority\n    - [ ] Reserve requirements (for stablecoins)\n    \n  tax:\n    - [ ] Tax treatment documented per jurisdiction\n    - [ ] Reporting infrastructure (1099/DAC8)\n    - [ ] Cost basis tracking for users\n```\n\n### Decentralization as Compliance Strategy\n\nThe more decentralized a protocol, the stronger the argument it's not a security:\n\n| Factor | Centralized (Risky) | Decentralized (Safer) |\n|--------|-------------------|---------------------|\n| Development | Single company | Multiple contributor orgs |\n| Governance | Admin key | Token-weighted DAO |\n| Treasury | Company-controlled | Community-governed |\n| Revenue | Flows to team | Flows to token holders |\n| Upgrades | Admin deploys | Governance proposal + timelock |\n| Front-end | Single website | Multiple alternative UIs |\n\n---\n\n## Phase 11: Bitcoin & Lightning Network\n\n### Bitcoin Development\n\n| Layer | Purpose | Key Technologies |\n|-------|---------|-----------------|\n| L1 (Base) | Settlement, store of value | Script, Taproot, SegWit |\n| Lightning | Instant micropayments | Payment channels, HTLCs |\n| Ordinals/BRC-20 | NFTs, tokens on Bitcoin | Inscription, witness data |\n| Stacks/Liquid | Smart contracts on Bitcoin | Clarity, Federated sidechain |\n\n### Lightning Network Integration\n\n```yaml\nlightning_integration:\n  use_cases:\n    - Micropayments (<$1)\n    - Point-of-sale payments\n    - Streaming payments (per-second)\n    - Machine-to-machine payments\n    - Tipping / donations\n    \n  implementation:\n    self_hosted:\n      options: [\"LND\", \"CLN (Core Lightning)\", \"Eclair\"]\n      requirements: \"Bitcoin full node + Lightning node\"\n      complexity: \"High\"\n      \n    hosted_api:\n      options: [\"Strike API\", \"Voltage\", \"LNbits\", \"BTCPay Server\"]\n      requirements: \"API key\"\n      complexity: \"Low-Medium\"\n      \n    standards:\n      invoices: \"BOLT11 (payment request)\"\n      keysend: \"Spontaneous payments (no invoice)\"\n      lnurl: \"User-friendly payment flows\"\n      bolt12: \"Reusable offers (emerging)\"\n```\n\n### Bitcoin Self-Custody Best Practices\n\n1. **UTXO management** — Consolidate during low-fee periods\n2. **Address reuse** — Never reuse addresses (privacy)\n3. **Coin selection** — Use coin control for privacy-sensitive transactions\n4. **Fee estimation** — Use mempool.space for current fee rates\n5. **Multi-sig** — 2-of-3 for significant holdings (Sparrow, Nunchuk)\n6. **Verify receive addresses** — On hardware wallet screen, not just software\n\n---\n\n## Phase 12: Advanced Patterns\n\n### MEV (Maximal Extractable Value)\n\n```yaml\nmev_awareness:\n  what: \"Value extracted by block producers reordering/inserting transactions\"\n  \n  types:\n    - sandwich_attack: \"Front-run + back-run user's swap\"\n    - arbitrage: \"Cross-DEX price differences\"  \n    - liquidation: \"Race to liquidate undercollateralized positions\"\n    - jit_liquidity: \"Just-in-time LP provision around large swaps\"\n    \n  protection:\n    users:\n      - \"Use private mempools (Flashbots Protect, MEV Blocker)\"\n      - \"Set tight slippage limits\"\n      - \"Use DEX aggregators with MEV protection (CoW Swap)\"\n      - \"Submit transactions through RPC endpoints with MEV protection\"\n    developers:\n      - \"Commit-reveal schemes for sensitive operations\"\n      - \"Batch auctions instead of continuous swaps\"\n      - \"Deadline parameters on all swap functions\"\n      - \"Internal oracle (TWAP) instead of spot price\"\n```\n\n### Account Abstraction (ERC-4337)\n\n```yaml\naccount_abstraction:\n  what: \"Smart contract wallets as first-class citizens\"\n  \n  benefits:\n    - Social recovery (friends can help recover account)\n    - Gas sponsorship (app pays gas for users)\n    - Batch transactions (multiple actions in one click)\n    - Session keys (limited permissions for games/dApps)\n    - Any token for gas (pay gas in USDC)\n    \n  implementation:\n    frameworks: [\"Safe{Core}\", \"ZeroDev\", \"Biconomy\", \"Alchemy AA\"]\n    bundlers: [\"Pimlico\", \"Stackup\", \"Alchemy\"]\n    paymasters: [\"Pimlico Verifying Paymaster\", \"Alchemy Gas Manager\"]\n    \n  when_to_use:\n    - Consumer-facing dApps (abstract wallet complexity)\n    - Games (session keys, gasless)\n    - B2B (multisig, spending policies)\n```\n\n### Zero-Knowledge Applications\n\n| Application | What ZK Proves | Example |\n|-------------|---------------|---------|\n| Privacy transactions | \"I have enough funds\" without revealing amount | Tornado Cash, Zcash |\n| Identity | \"I'm over 18\" without revealing age | Polygon ID, Worldcoin |\n| Scaling (zkRollup) | \"These transactions are valid\" without re-executing | zkSync, StarkNet |\n| Voting | \"I voted\" without revealing choice | MACI |\n| Compliance | \"I passed KYC\" without sharing data | zkKYC |\n\n### Gas Optimization Techniques\n\n| Technique | Gas Saved | Complexity |\n|-----------|-----------|-----------|\n| Use `calldata` instead of `memory` for read-only params | ~60 per 32 bytes | Low |\n| Pack storage variables (<256 bit types together) | ~20,000 per slot | Low |\n| Use `immutable` / `constant` | ~2,100 per SLOAD avoided | Low |\n| Custom errors vs require strings | ~50 per error | Low |\n| Unchecked math (when overflow impossible) | ~80 per operation | Medium |\n| Batch operations | Varies (amortize base cost) | Medium |\n| Assembly for hot paths | 20-50% on targeted code | High |\n| Minimal proxy (EIP-1167) for clones | ~90% deployment cost | Medium |\n\n---\n\n## Quality Rubric (0-100)\n\n| Dimension | Weight | Score Guide |\n|-----------|--------|-------------|\n| Security | 25% | 0: No audit, known vulns. 50: Basic testing. 100: Full audit, bug bounty, formal verification |\n| Architecture | 15% | 0: Monolithic, no separation. 50: Some patterns. 100: Clean separation, upgrade path, gas-optimized |\n| Testing | 15% | 0: No tests. 50: Unit tests. 100: Full pyramid (unit/integration/fork/fuzz/invariant) |\n| Tokenomics | 10% | 0: Ponzi mechanics. 50: Basic utility. 100: Sustainable value accrual, aligned incentives |\n| Documentation | 10% | 0: No docs. 50: Basic README. 100: NatSpec, architecture docs, user guides |\n| Operations | 10% | 0: No monitoring. 50: Basic alerts. 100: Full dashboard, incident playbooks, SLOs |\n| Compliance | 10% | 0: Unaddressed. 50: Basic legal opinion. 100: Multi-jurisdictional analysis, KYC/AML |\n| Decentralization | 5% | 0: Single admin key. 50: Multisig. 100: DAO governance, timelock, multiple UIs |\n\n**Grade:** 80+ Excellent | 60-79 Good | 40-59 Needs Work | <40 Critical Risk\n\n---\n\n## Common Mistakes\n\n| # | Mistake | Fix |\n|---|---------|-----|\n| 1 | Shipping without audit | Budget for audit from day 1 |\n| 2 | Single admin key | Multisig + timelock always |\n| 3 | Using spot price as oracle | TWAP or Chainlink |\n| 4 | Ignoring MEV | Private mempool + slippage protection |\n| 5 | No emergency pause | Circuit breaker on every protocol |\n| 6 | Testing only happy path | Fuzz testing + invariant tests |\n| 7 | Unlimited token approvals | Approve exact amounts needed |\n| 8 | Ignoring gas optimization | Profile gas costs, optimize hot paths |\n| 9 | No upgrade plan OR reckless upgrades | Decide upgrade strategy early |\n| 10 | Building blockchain when database works | Run the Database Test first |\n\n---\n\n## Edge Cases\n\n**Startup / Hackathon:**\n- Use Foundry + OpenZeppelin for speed\n- Deploy to Base (low gas, large ecosystem)\n- Skip formal verification (do it pre-mainnet)\n- Focus: working product > perfect security\n\n**Enterprise / Institutional:**\n- Hyperledger Besu or Avalanche Subnets for permissioned needs\n- Formal verification for critical paths\n- Multi-jurisdictional compliance from day 1\n- Hardware security modules (HSMs) for key management\n\n**High-Value DeFi (>$100M TVL):**\n- Multiple independent audits (minimum 2 firms)\n- Formal verification (Certora)\n- $1M+ bug bounty on Immunefi\n- Real-time monitoring with automatic pause triggers\n- Insurance coverage (Nexus Mutual, InsurAce)\n\n**NFT / Gaming:**\n- ERC-1155 for gas efficiency (batch operations)\n- Off-chain metadata (IPFS/Arweave for permanence)\n- Account abstraction for onboarding (gasless minting)\n- Consider L2 (Immutable X, Base, Polygon) for low gas\n\n**Cross-Chain:**\n- Start with one chain, expand after PMF\n- Use canonical bridges (slow but safe) over third-party\n- Implement chain-specific parameter tuning\n- Monitor bridge TVL and security track record\n\n---\n\n## Natural Language Commands\n\nWhen prompted, this skill responds to:\n\n1. `evaluate blockchain fit` — Run the Database Test decision framework\n2. `design smart contract` — Generate architecture brief + coding standards\n3. `design tokenomics` — Create token economics framework with distribution\n4. `audit security` — Run full security checklist against a contract\n5. `plan deployment` — Generate deployment + post-deployment checklist\n6. `assess DeFi protocol` — Evaluate DeFi design against security invariants\n7. `optimize gas` — Review code for gas optimization opportunities\n8. `review wallet security` — Generate wallet + key management recommendations\n9. `evaluate L2` — Compare Layer 2 options for specific use case\n10. `check compliance` — Run regulatory compliance checklist\n11. `design bridge strategy` — Evaluate cross-chain approach\n12. `full web3 review` — Complete assessment across all dimensions\n","readmeExcerpt":"Web3 & Blockchain Engineering Complete methodology for evaluating, designing, building, securing, and operating blockchain-based systems. Covers smart contract development, DeFi protocol design, token economics, security auditing, and production operations. Zero dependencies. Framework-agnostic. Works with any blockchain, any language, any AI agent. --- Phase 1: Should You Use Blockchain? The Database Test Before wri","codeSnippets":[],"executableExamples":[{"language":"yaml","snippet":"blockchain_evaluation:\n  problem: \"[describe the core problem]\"\n  \n  requirements:\n    multiple_untrusting_parties: true/false    # >1 org needs shared truth\n    no_trusted_authority: true/false            # no single party everyone trusts\n    immutability_critical: true/false           # history must be tamper-proof\n    censorship_resistance_needed: true/false    # no entity should block access\n    value_transfer_required: true/false         # moving assets between parties\n    transparency_required: true/false           # all parties need verifiable state\n  \n  disqualifiers:\n    single_org_controls_data: true/false        # → use a database\n    data_deletion_required: true/false          # → GDPR conflict, careful\n    high_throughput_low_latency: true/false     # → >10K TPS? consider L2 or database\n    users_cant_manage_wallets: true/false       # → account abstraction or custodial\n    trusted_authority_exists: true/false        # → database with audit log\n  \n  score: \"[count true requirements - count true disqualifiers]\"\n  verdict: \"blockchain / hybrid / database\""},{"language":"yaml","snippet":"architecture_brief:\n  project: \"[name]\"\n  type: \"DeFi / NFT / DAO / Token / Marketplace / Infrastructure\"\n  \n  contracts:\n    core:\n      - name: \"[MainContract]\"\n        responsibility: \"[single clear purpose]\"\n        state_variables: [\"list key storage\"]\n        external_calls: [\"contracts it calls\"]\n    \n    periphery:\n      - name: \"[Router/Helper]\"\n        responsibility: \"[user-facing convenience]\"\n    \n    libraries:\n      - name: \"[MathLib/SafeLib]\"\n        responsibility: \"[shared pure functions]\"\n  \n  upgrade_strategy: \"immutable / transparent-proxy / UUPS / diamond / beacon\"\n  access_control: \"Ownable / AccessControl / Timelock+Multisig / DAO\""},{"language":"solidity","snippet":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\n// — IMPORTS: Use named imports, pin versions —\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\n\n/// @title VaultV1\n/// @notice Single-asset vault with deposit/withdraw\n/// @dev Uses SafeERC20 for all token transfers\ncontract VaultV1 is ReentrancyGuard {\n    using SafeERC20 for IERC20;\n\n    // — STATE: Group by slot for packing —\n    IERC20 public immutable asset;       // slot 0\n    uint128 public totalDeposits;        // slot 1 (packed)\n    uint128 public totalShares;          // slot 1 (packed)\n    \n    mapping(address => uint256) public shares;\n\n    // — EVENTS: Index searchable fields —\n    event Deposited(address indexed user, uint256 amount, uint256 shares);\n    event Withdrawn(address indexed user, uint256 amount, uint256 shares);\n\n    // — ERRORS: Custom errors save gas vs strings —\n    error ZeroAmount();\n    error InsufficientShares(uint256 requested, uint256 available);\n\n    constructor(IERC20 _asset) {\n        asset = _asset;\n    }\n\n    /// @notice Deposit assets, receive proportional shares\n    /// @param amount Asset amount to deposit\n    /// @return mintedShares Shares minted to caller\n    function deposit(uint256 amount) external nonReentrant returns (uint256 mintedShares) {\n        if (amount == 0) revert ZeroAmount();\n        \n        // Calculate shares BEFORE transfer (prevent manipulation)\n        mintedShares = totalDeposits == 0\n            ? amount\n            : (amount * totalShares) / totalDeposits;\n        \n        // Effects before interactions (CEI pattern)\n        totalDeposits += uint128(amount);\n        totalShares += uint128(mintedShares);\n        shares[msg.sender] += mintedShares;\n        \n        // Interaction last\n        asset.safeTransferFrom(msg.sender, address(this), amount);\n     "},{"language":"yaml","snippet":"tokenomics:\n  token_name: \"[Name]\"\n  symbol: \"[SYM]\"\n  standard: \"ERC-20 / ERC-721 / ERC-1155\"\n  total_supply: \"[fixed / capped / inflationary]\"\n  \n  distribution:\n    team: \"[%] — [vesting schedule]\"\n    investors: \"[%] — [vesting schedule]\"\n    community: \"[%] — [distribution mechanism]\"\n    treasury: \"[%] — [governance-controlled]\"\n    ecosystem: \"[%] — [grants, incentives]\"\n    liquidity: \"[%] — [DEX pairs, market making]\"\n  \n  vesting:\n    team_cliff: \"12 months minimum\"\n    team_linear: \"24-48 months after cliff\"\n    investor_cliff: \"6-12 months\"\n    investor_linear: \"12-36 months\"\n  \n  value_accrual:\n    mechanism: \"[fee sharing / buyback-burn / staking yield / utility demand]\"\n    fee_structure: \"[% of protocol revenue → token holders]\"\n    burn_mechanism: \"[deflationary pressure source]\"\n  \n  governance:\n    voting_power: \"1 token = 1 vote / quadratic / conviction\"\n    quorum: \"[% of supply needed]\"\n    timelock: \"[delay between vote and execution]\"\n    \n  inflation_schedule:\n    year_1: \"[%]\"\n    year_2: \"[%]\"\n    long_term: \"[target %/year]\"\n    \n  sustainability_test:\n    without_new_buyers: \"Does the token have utility even if price = 0?\"\n    revenue_source: \"Where does yield come from? (real yield vs emissions)\"\n    death_spiral_risk: \"Can selling pressure create feedback loop?\""},{"language":"text","snippet":"Constant Product: x * y = k\nPrice Impact: Δy = y - k/(x + Δx)\nSlippage: (expected_price - actual_price) / expected_price\n\nV3 Concentrated Liquidity:\n- LPs choose price range [Pa, Pb]\n- Capital efficiency: up to 4000x vs V2\n- Trade-off: must actively manage positions"},{"language":"text","snippet":"1. Reentrancy\n   Attack: Call back into contract before state is updated\n   Fix: CEI pattern + ReentrancyGuard\n   \n2. Oracle Manipulation (Flash Loan)\n   Attack: Borrow → manipulate price → exploit → repay (atomic)\n   Fix: TWAP oracles, Chainlink price feeds, manipulation-resistant design\n   \n3. Sandwich Attack (MEV)\n   Attack: Front-run user's swap → inflate price → back-run to profit\n   Fix: Deadline parameter, max slippage, private mempools (Flashbots)\n   \n4. Governance Attack\n   Attack: Flash-borrow governance tokens → vote → execute\n   Fix: Snapshot at proposal creation, timelock, vote escrow (ve-model)\n   \n5. Price Oracle Stale Data\n   Attack: Use outdated price to exploit arbitrage\n   Fix: Chainlink heartbeat check, staleness threshold, circuit breakers"}],"parameters":{},"dependencies":[],"permissions":[],"extractedFiles":[],"languages":["typescript"],"docsSourceLabel":"CLAWHUB","editorialOverview":"Web3 & Blockchain Engineering Web3 & Blockchain Engineering Complete methodology for evaluating, designing, building, securing, and operating blockchain-based systems. Covers smart contract development, DeFi protocol design, token economics, security auditing, and production operations. Zero dependencies. Framework-agnostic. Works with any blockchain, any language, any AI agent. --- Phase 1: Should You Use Blockchain? The Database Test Before wri","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":369,"uniquenessScore":67,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-09T16:33:23.331Z","emptyReason":null},"items":[{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-10T18:48:31.762Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}