{
  "schemaVersion": "1.0",
  "item": {
    "slug": "afrexai-web3-engineering",
    "name": "Web3 & Blockchain Engineering",
    "source": "tencent",
    "type": "skill",
    "category": "金融交易",
    "sourceUrl": "https://clawhub.ai/1kalin/afrexai-web3-engineering",
    "canonicalUrl": "https://clawhub.ai/1kalin/afrexai-web3-engineering",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadMode": "redirect",
    "downloadUrl": "/downloads/afrexai-web3-engineering",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=afrexai-web3-engineering",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "installMethod": "Manual import",
    "extraction": "Extract archive",
    "prerequisites": [
      "OpenClaw"
    ],
    "packageFormat": "ZIP package",
    "includedAssets": [
      "README.md",
      "SKILL.md"
    ],
    "primaryDoc": "SKILL.md",
    "quickSetup": [
      "Download the package from Yavira.",
      "Extract the archive and review SKILL.md first.",
      "Import or place the package into your OpenClaw setup."
    ],
    "agentAssist": {
      "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
      "steps": [
        "Download the package from Yavira.",
        "Extract it into a folder your agent can access.",
        "Paste one of the prompts below and point your agent at the extracted folder."
      ],
      "prompts": [
        {
          "label": "New install",
          "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
        },
        {
          "label": "Upgrade existing",
          "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
        }
      ]
    },
    "sourceHealth": {
      "source": "tencent",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-04-23T16:43:11.935Z",
      "expiresAt": "2026-04-30T16:43:11.935Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=4claw-imageboard",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=4claw-imageboard",
        "contentDisposition": "attachment; filename=\"4claw-imageboard-1.0.1.zip\"",
        "redirectLocation": null,
        "bodySnippet": null
      },
      "scope": "source",
      "summary": "Source download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this source.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/afrexai-web3-engineering"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    },
    "downloadPageUrl": "https://openagent3.xyz/downloads/afrexai-web3-engineering",
    "agentPageUrl": "https://openagent3.xyz/skills/afrexai-web3-engineering/agent",
    "manifestUrl": "https://openagent3.xyz/skills/afrexai-web3-engineering/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/afrexai-web3-engineering/agent.md"
  },
  "agentAssist": {
    "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
    "steps": [
      "Download the package from Yavira.",
      "Extract it into a folder your agent can access.",
      "Paste one of the prompts below and point your agent at the extracted folder."
    ],
    "prompts": [
      {
        "label": "New install",
        "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
      },
      {
        "label": "Upgrade existing",
        "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
      }
    ]
  },
  "documentation": {
    "source": "clawhub",
    "primaryDoc": "SKILL.md",
    "sections": [
      {
        "title": "Web3 & Blockchain Engineering",
        "body": "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.\n\nZero dependencies. Framework-agnostic. Works with any blockchain, any language, any AI agent."
      },
      {
        "title": "The Database Test",
        "body": "Before writing a single line of Solidity, answer honestly:\n\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\nDecision rules:\n\nScore ≤ 0 → Use PostgreSQL with audit logs\nScore 1-2 → Hybrid (anchoring/notarization on-chain, logic off-chain)\nScore 3+ → Blockchain is justified"
      },
      {
        "title": "Platform Selection Matrix",
        "body": "PlatformTPSFinalityGas CostBest ForEthereum L1~30~12 min$1-50+Settlement, high-value DeFiArbitrum~4,000~1 sec (soft)$0.01-0.10DeFi, general dAppsOptimism~2,000~2 sec (soft)$0.01-0.15Public goods, governanceBase~2,000~2 sec (soft)$0.001-0.05Consumer apps, socialPolygon PoS~7,000~2 sec$0.001-0.01Gaming, mass-marketSolana~65,000~400ms$0.00025High-frequency, DePINAvalanche C~4,500~1 sec$0.01-0.10Enterprise, subnetsBNB Chain~2,000~3 sec$0.01-0.05Retail, low-costBitcoin L1~7~60 min$0.50-5+Store of value, settlementBitcoin L2 (Lightning)~1M+instant<$0.01Micropayments, P2P\n\nSelection decision tree:\n\nStore of value / settlement only? → Bitcoin\nMicropayments / instant P2P? → Lightning Network\nNeed EVM compatibility? → Yes: continue. No: consider Solana, Cosmos\nHigh-value DeFi / maximum security? → Ethereum L1\nGeneral dApp with low gas? → Arbitrum or Base\nMass-market consumer? → Base or Polygon\nEnterprise with custom rules? → Avalanche subnets or Hyperledger"
      },
      {
        "title": "Design Principles",
        "body": "Minimize on-chain state — Storage is expensive. Put data on-chain only if it needs consensus\nFail loudly — Use require() / revert() with descriptive messages, never silent failures\nImmutability by default — Upgradeability adds attack surface. Only use if genuinely needed\nSeparation of concerns — One contract per responsibility\nGas-conscious design — Every operation costs money. Optimize hot paths"
      },
      {
        "title": "Contract Architecture Patterns",
        "body": "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\""
      },
      {
        "title": "Upgrade Pattern Decision",
        "body": "PatternComplexityGas OverheadStorage Layout RiskBest ForImmutableNoneNoneNoneSimple contracts, tokensTransparent ProxyMedium+gas per callHighStandard upgradeableUUPSMediumLower than transparentHighGas-efficient upgradeableDiamond (EIP-2535)HighMediumHighLarge modular systemsBeaconMediumMediumHighMany identical instances\n\nRule: If you can avoid upgradeability, do it. If you must upgrade, use UUPS with timelock + multisig governance."
      },
      {
        "title": "Solidity Development Standards",
        "body": "// 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}"
      },
      {
        "title": "Coding Standards Checklist",
        "body": "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)"
      },
      {
        "title": "Token Type Decision",
        "body": "TypeStandardUse CaseRegulatory RiskUtility tokenERC-20Access, governance, gasMediumGovernance tokenERC-20 + votingProtocol controlMediumSecurity tokenERC-1400/3643Equity, revenue shareHIGH — requires complianceNFT (unique)ERC-721Collectibles, identity, accessLow-MediumSemi-fungibleERC-1155Gaming items, editionsLowSoulbound (SBT)ERC-5192Credentials, reputationLowStablecoinERC-20 + pegPayments, DeFi collateralHIGH — regulatory scrutiny"
      },
      {
        "title": "Token Design Framework",
        "body": "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?\""
      },
      {
        "title": "Tokenomics Red Flags",
        "body": "Red FlagWhy It's BadFix>20% team allocationCentralization, dump riskCap at 15-20%, long vestingNo cliff periodImmediate sell pressure12-month cliff minimumInflationary without utilityToken printing → zeroEmissions tied to real revenue\"Yield\" from new depositsPonzi economicsReal yield from fees onlyGovernance without timelockAdmin can rugTimelock + multisig mandatory100% unlocked at launchMassive sell pressureStaged unlock over 2-4 years"
      },
      {
        "title": "Core DeFi Primitives",
        "body": "PrimitiveWhat It DoesKey RiskExamplesAMM (DEX)Trustless token swapsImpermanent lossUniswap, CurveLendingOvercollateralized loansLiquidation cascadesAave, CompoundStablecoinPrice-stable tokenDepeg riskMakerDAO, EthenaYield aggregatorOptimize yield farmingSmart contract risk stackingYearnPerpetualsLeveraged derivativesLiquidation, oracle manipulationGMX, dYdXLiquid stakingStake + maintain liquiditySlashing, depegLido, Rocket PoolBridgesCross-chain transfersBridge exploits (billions lost)LayerZero, WormholeRestakingRe-use staked assetsCascading slashingEigenLayer"
      },
      {
        "title": "AMM Design (Uniswap V2/V3 Pattern)",
        "body": "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"
      },
      {
        "title": "DeFi Security Invariants",
        "body": "Every DeFi protocol MUST maintain these:\n\nSolvency — Total assets ≥ total liabilities (always)\nNo free tokens — No path creates tokens from nothing\nMonotonic shares — Depositing increases shares, withdrawing decreases\nOracle freshness — Price data is within acceptable staleness window\nLiquidation viability — Undercollateralized positions can always be liquidated\nAccess control — Admin functions behind timelock + multisig\nWithdrawal guarantee — Users can always withdraw their assets (no lock-up without consent)"
      },
      {
        "title": "Vulnerability Taxonomy",
        "body": "CategorySeverityCommon PatternsReentrancyCriticalExternal call before state updateOracle manipulationCriticalFlash loan → price manipulation → profitAccess controlCriticalMissing auth on privileged functionsInteger overflowHighPre-0.8 math without SafeMathFront-runningHighSandwich attacks, MEV extractionFlash loan attacksHighAtomic arbitrage exploiting price feedsLogic errorsHighWrong formula, edge cases, roundingDenial of serviceMediumGas limit exploitation, stuck statesCentralizationMediumSingle admin key, no timelockGriefingMediumMaking others' transactions fail/expensive"
      },
      {
        "title": "Security Audit Checklist (100+ Points)",
        "body": "Critical (Must Pass)\n\nReentrancy 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\nHigh Priority\n\nFront-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\nMedium Priority\n\nEvent 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"
      },
      {
        "title": "Common Attack Vectors with Mitigations",
        "body": "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"
      },
      {
        "title": "Audit Process",
        "body": "audit_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"
      },
      {
        "title": "Test Pyramid for Smart Contracts",
        "body": "/\\\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        /________________________\\"
      },
      {
        "title": "Testing Checklist",
        "body": "testing_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\"]"
      },
      {
        "title": "Foundry Test Pattern",
        "body": "// 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}"
      },
      {
        "title": "Deployment Checklist",
        "body": "pre_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"
      },
      {
        "title": "Monitoring Dashboard",
        "body": "smart_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\""
      },
      {
        "title": "Incident Response",
        "body": "SeverityResponse TimeActionsP0 — Active exploit< 5 minPause contracts, war room, post-mortemP1 — Vulnerability found< 1 hourAssess impact, prepare fix, notify teamP2 — Degraded service< 4 hoursInvestigate, fix, monitorP3 — Minor issue< 24 hoursSchedule fix in next deployment\n\nP0 Emergency Protocol:\n\nActivate circuit breaker / pause contracts\nAssess: What was exploited? What's the exposure?\nCommunicate: Alert team + trusted security researchers\nContain: Block exploit path if possible\nRecover: Plan rescue transaction if funds recoverable\nPost-mortem: Full timeline, root cause, fix, prevention"
      },
      {
        "title": "Key Hierarchy",
        "body": "Seed 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"
      },
      {
        "title": "Wallet Security Tiers",
        "body": "TierTypeUse CaseSecurity LevelHot walletBrowser extension (MetaMask)Daily interactions, small amountsLowWarm walletMobile wallet (Rainbow, Trust)Medium amounts, on-the-goMediumCold walletHardware (Ledger, Trezor)Large holdings, long-termHighAir-gappedKeystone, dedicated offlineMaximum security, institutionalVery HighMultisigSafe (Gnosis)Treasury, protocol adminHighest"
      },
      {
        "title": "Multisig Best Practices",
        "body": "multisig_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\""
      },
      {
        "title": "Self-Custody Security Rules",
        "body": "Seed phrase storage — Metal plate (Cryptosteel/Billfodl), never digital\nGeographic distribution — Copies in ≥2 physical locations\nTest recovery — Verify you can restore from seed BEFORE storing value\nPhishing defense — Bookmark official URLs, never click links, verify contract addresses\nHardware wallet firmware — Update only from official sources\nTransaction simulation — Use Tenderly/Fire before signing large transactions\nApproval hygiene — Revoke unused token approvals regularly (revoke.cash)"
      },
      {
        "title": "L2 Architecture Types",
        "body": "TypeHow It WorksData AvailabilityExamplesOptimistic RollupAssume valid, challenge periodOn-chain calldataArbitrum, Optimism, BaseZK RollupProve validity with ZK proofOn-chain calldatazkSync, StarkNet, ScrollValidiumZK proof + off-chain dataOff-chain (DAC)Immutable XPlasmaExit game mechanismOff-chain(largely deprecated)State ChannelOff-chain with on-chain settlementOff-chainLightning NetworkSidechainIndependent chain with bridgeOwn consensusPolygon PoS"
      },
      {
        "title": "Cross-Chain Bridge Security",
        "body": "Bridges are the #1 attack vector in crypto (>$2.5B lost).\n\nBridge security checklist:\n\nMultisig 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\nSafer bridging approaches:\n\nNative bridges (Arbitrum/Optimism canonical) → Slow but trustless\nLayerZero/Axelar → Decentralized messaging\nCircle CCTP → Native USDC bridging (no wrapped tokens)\nAvoid: New/unaudited bridges, single-key admin bridges"
      },
      {
        "title": "Regulatory Landscape (2025)",
        "body": "JurisdictionFrameworkToken ClassificationKey RequirementUS (SEC)Howey TestSecurity vs UtilityRegistration or exemptionUS (CFTC)CEACommodity (BTC, ETH)Derivatives regulationEU (MiCA)Markets in Crypto-AssetsUtility/E-Money/ARTLicensing, reservesUK (FCA)Financial PromotionsCrypto-assetMarketing restrictionsSingapore (MAS)Payment Services ActDigital Payment TokenLicensingJapan (FSA)FIEA/PSACrypto-assetRegistration"
      },
      {
        "title": "Compliance Checklist",
        "body": "compliance:\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"
      },
      {
        "title": "Decentralization as Compliance Strategy",
        "body": "The more decentralized a protocol, the stronger the argument it's not a security:\n\nFactorCentralized (Risky)Decentralized (Safer)DevelopmentSingle companyMultiple contributor orgsGovernanceAdmin keyToken-weighted DAOTreasuryCompany-controlledCommunity-governedRevenueFlows to teamFlows to token holdersUpgradesAdmin deploysGovernance proposal + timelockFront-endSingle websiteMultiple alternative UIs"
      },
      {
        "title": "Bitcoin Development",
        "body": "LayerPurposeKey TechnologiesL1 (Base)Settlement, store of valueScript, Taproot, SegWitLightningInstant micropaymentsPayment channels, HTLCsOrdinals/BRC-20NFTs, tokens on BitcoinInscription, witness dataStacks/LiquidSmart contracts on BitcoinClarity, Federated sidechain"
      },
      {
        "title": "Lightning Network Integration",
        "body": "lightning_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)\""
      },
      {
        "title": "Bitcoin Self-Custody Best Practices",
        "body": "UTXO management — Consolidate during low-fee periods\nAddress reuse — Never reuse addresses (privacy)\nCoin selection — Use coin control for privacy-sensitive transactions\nFee estimation — Use mempool.space for current fee rates\nMulti-sig — 2-of-3 for significant holdings (Sparrow, Nunchuk)\nVerify receive addresses — On hardware wallet screen, not just software"
      },
      {
        "title": "MEV (Maximal Extractable Value)",
        "body": "mev_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\""
      },
      {
        "title": "Account Abstraction (ERC-4337)",
        "body": "account_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)"
      },
      {
        "title": "Zero-Knowledge Applications",
        "body": "ApplicationWhat ZK ProvesExamplePrivacy transactions\"I have enough funds\" without revealing amountTornado Cash, ZcashIdentity\"I'm over 18\" without revealing agePolygon ID, WorldcoinScaling (zkRollup)\"These transactions are valid\" without re-executingzkSync, StarkNetVoting\"I voted\" without revealing choiceMACICompliance\"I passed KYC\" without sharing datazkKYC"
      },
      {
        "title": "Gas Optimization Techniques",
        "body": "TechniqueGas SavedComplexityUse calldata instead of memory for read-only params~60 per 32 bytesLowPack storage variables (<256 bit types together)~20,000 per slotLowUse immutable / constant~2,100 per SLOAD avoidedLowCustom errors vs require strings~50 per errorLowUnchecked math (when overflow impossible)~80 per operationMediumBatch operationsVaries (amortize base cost)MediumAssembly for hot paths20-50% on targeted codeHighMinimal proxy (EIP-1167) for clones~90% deployment costMedium"
      },
      {
        "title": "Quality Rubric (0-100)",
        "body": "DimensionWeightScore GuideSecurity25%0: No audit, known vulns. 50: Basic testing. 100: Full audit, bug bounty, formal verificationArchitecture15%0: Monolithic, no separation. 50: Some patterns. 100: Clean separation, upgrade path, gas-optimizedTesting15%0: No tests. 50: Unit tests. 100: Full pyramid (unit/integration/fork/fuzz/invariant)Tokenomics10%0: Ponzi mechanics. 50: Basic utility. 100: Sustainable value accrual, aligned incentivesDocumentation10%0: No docs. 50: Basic README. 100: NatSpec, architecture docs, user guidesOperations10%0: No monitoring. 50: Basic alerts. 100: Full dashboard, incident playbooks, SLOsCompliance10%0: Unaddressed. 50: Basic legal opinion. 100: Multi-jurisdictional analysis, KYC/AMLDecentralization5%0: Single admin key. 50: Multisig. 100: DAO governance, timelock, multiple UIs\n\nGrade: 80+ Excellent | 60-79 Good | 40-59 Needs Work | <40 Critical Risk"
      },
      {
        "title": "Common Mistakes",
        "body": "#MistakeFix1Shipping without auditBudget for audit from day 12Single admin keyMultisig + timelock always3Using spot price as oracleTWAP or Chainlink4Ignoring MEVPrivate mempool + slippage protection5No emergency pauseCircuit breaker on every protocol6Testing only happy pathFuzz testing + invariant tests7Unlimited token approvalsApprove exact amounts needed8Ignoring gas optimizationProfile gas costs, optimize hot paths9No upgrade plan OR reckless upgradesDecide upgrade strategy early10Building blockchain when database worksRun the Database Test first"
      },
      {
        "title": "Edge Cases",
        "body": "Startup / Hackathon:\n\nUse Foundry + OpenZeppelin for speed\nDeploy to Base (low gas, large ecosystem)\nSkip formal verification (do it pre-mainnet)\nFocus: working product > perfect security\n\nEnterprise / Institutional:\n\nHyperledger Besu or Avalanche Subnets for permissioned needs\nFormal verification for critical paths\nMulti-jurisdictional compliance from day 1\nHardware security modules (HSMs) for key management\n\nHigh-Value DeFi (>$100M TVL):\n\nMultiple independent audits (minimum 2 firms)\nFormal verification (Certora)\n$1M+ bug bounty on Immunefi\nReal-time monitoring with automatic pause triggers\nInsurance coverage (Nexus Mutual, InsurAce)\n\nNFT / Gaming:\n\nERC-1155 for gas efficiency (batch operations)\nOff-chain metadata (IPFS/Arweave for permanence)\nAccount abstraction for onboarding (gasless minting)\nConsider L2 (Immutable X, Base, Polygon) for low gas\n\nCross-Chain:\n\nStart with one chain, expand after PMF\nUse canonical bridges (slow but safe) over third-party\nImplement chain-specific parameter tuning\nMonitor bridge TVL and security track record"
      },
      {
        "title": "Natural Language Commands",
        "body": "When prompted, this skill responds to:\n\nevaluate blockchain fit — Run the Database Test decision framework\ndesign smart contract — Generate architecture brief + coding standards\ndesign tokenomics — Create token economics framework with distribution\naudit security — Run full security checklist against a contract\nplan deployment — Generate deployment + post-deployment checklist\nassess DeFi protocol — Evaluate DeFi design against security invariants\noptimize gas — Review code for gas optimization opportunities\nreview wallet security — Generate wallet + key management recommendations\nevaluate L2 — Compare Layer 2 options for specific use case\ncheck compliance — Run regulatory compliance checklist\ndesign bridge strategy — Evaluate cross-chain approach\nfull web3 review — Complete assessment across all dimensions"
      }
    ],
    "body": "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\nZero dependencies. Framework-agnostic. Works with any blockchain, any language, any AI agent.\n\nPhase 1: Should You Use Blockchain?\nThe Database Test\n\nBefore writing a single line of Solidity, answer honestly:\n\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\nDecision rules:\n\nScore ≤ 0 → Use PostgreSQL with audit logs\nScore 1-2 → Hybrid (anchoring/notarization on-chain, logic off-chain)\nScore 3+ → Blockchain is justified\nPlatform Selection Matrix\nPlatform\tTPS\tFinality\tGas Cost\tBest For\nEthereum L1\t~30\t~12 min\t$1-50+\tSettlement, high-value DeFi\nArbitrum\t~4,000\t~1 sec (soft)\t$0.01-0.10\tDeFi, general dApps\nOptimism\t~2,000\t~2 sec (soft)\t$0.01-0.15\tPublic goods, governance\nBase\t~2,000\t~2 sec (soft)\t$0.001-0.05\tConsumer apps, social\nPolygon PoS\t~7,000\t~2 sec\t$0.001-0.01\tGaming, mass-market\nSolana\t~65,000\t~400ms\t$0.00025\tHigh-frequency, DePIN\nAvalanche C\t~4,500\t~1 sec\t$0.01-0.10\tEnterprise, subnets\nBNB Chain\t~2,000\t~3 sec\t$0.01-0.05\tRetail, low-cost\nBitcoin L1\t~7\t~60 min\t$0.50-5+\tStore of value, settlement\nBitcoin L2 (Lightning)\t~1M+\tinstant\t<$0.01\tMicropayments, P2P\n\nSelection decision tree:\n\nStore of value / settlement only? → Bitcoin\nMicropayments / instant P2P? → Lightning Network\nNeed EVM compatibility? → Yes: continue. No: consider Solana, Cosmos\nHigh-value DeFi / maximum security? → Ethereum L1\nGeneral dApp with low gas? → Arbitrum or Base\nMass-market consumer? → Base or Polygon\nEnterprise with custom rules? → Avalanche subnets or Hyperledger\nPhase 2: Smart Contract Architecture\nDesign Principles\nMinimize on-chain state — Storage is expensive. Put data on-chain only if it needs consensus\nFail loudly — Use require() / revert() with descriptive messages, never silent failures\nImmutability by default — Upgradeability adds attack surface. Only use if genuinely needed\nSeparation of concerns — One contract per responsibility\nGas-conscious design — Every operation costs money. Optimize hot paths\nContract Architecture Patterns\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\nUpgrade Pattern Decision\nPattern\tComplexity\tGas Overhead\tStorage Layout Risk\tBest For\nImmutable\tNone\tNone\tNone\tSimple contracts, tokens\nTransparent Proxy\tMedium\t+gas per call\tHigh\tStandard upgradeable\nUUPS\tMedium\tLower than transparent\tHigh\tGas-efficient upgradeable\nDiamond (EIP-2535)\tHigh\tMedium\tHigh\tLarge modular systems\nBeacon\tMedium\tMedium\tHigh\tMany identical instances\n\nRule: If you can avoid upgradeability, do it. If you must upgrade, use UUPS with timelock + multisig governance.\n\nSolidity Development Standards\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\nCoding Standards Checklist\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)\nPhase 3: Token Economics (Tokenomics)\nToken Type Decision\nType\tStandard\tUse Case\tRegulatory Risk\nUtility token\tERC-20\tAccess, governance, gas\tMedium\nGovernance token\tERC-20 + voting\tProtocol control\tMedium\nSecurity token\tERC-1400/3643\tEquity, revenue share\tHIGH — requires compliance\nNFT (unique)\tERC-721\tCollectibles, identity, access\tLow-Medium\nSemi-fungible\tERC-1155\tGaming items, editions\tLow\nSoulbound (SBT)\tERC-5192\tCredentials, reputation\tLow\nStablecoin\tERC-20 + peg\tPayments, DeFi collateral\tHIGH — regulatory scrutiny\nToken Design Framework\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\nTokenomics Red Flags\nRed Flag\tWhy It's Bad\tFix\n>20% team allocation\tCentralization, dump risk\tCap at 15-20%, long vesting\nNo cliff period\tImmediate sell pressure\t12-month cliff minimum\nInflationary without utility\tToken printing → zero\tEmissions tied to real revenue\n\"Yield\" from new deposits\tPonzi economics\tReal yield from fees only\nGovernance without timelock\tAdmin can rug\tTimelock + multisig mandatory\n100% unlocked at launch\tMassive sell pressure\tStaged unlock over 2-4 years\nPhase 4: DeFi Protocol Design\nCore DeFi Primitives\nPrimitive\tWhat It Does\tKey Risk\tExamples\nAMM (DEX)\tTrustless token swaps\tImpermanent loss\tUniswap, Curve\nLending\tOvercollateralized loans\tLiquidation cascades\tAave, Compound\nStablecoin\tPrice-stable token\tDepeg risk\tMakerDAO, Ethena\nYield aggregator\tOptimize yield farming\tSmart contract risk stacking\tYearn\nPerpetuals\tLeveraged derivatives\tLiquidation, oracle manipulation\tGMX, dYdX\nLiquid staking\tStake + maintain liquidity\tSlashing, depeg\tLido, Rocket Pool\nBridges\tCross-chain transfers\tBridge exploits (billions lost)\tLayerZero, Wormhole\nRestaking\tRe-use staked assets\tCascading slashing\tEigenLayer\nAMM Design (Uniswap V2/V3 Pattern)\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\nDeFi Security Invariants\n\nEvery DeFi protocol MUST maintain these:\n\nSolvency — Total assets ≥ total liabilities (always)\nNo free tokens — No path creates tokens from nothing\nMonotonic shares — Depositing increases shares, withdrawing decreases\nOracle freshness — Price data is within acceptable staleness window\nLiquidation viability — Undercollateralized positions can always be liquidated\nAccess control — Admin functions behind timelock + multisig\nWithdrawal guarantee — Users can always withdraw their assets (no lock-up without consent)\nPhase 5: Security Auditing\nVulnerability Taxonomy\nCategory\tSeverity\tCommon Patterns\nReentrancy\tCritical\tExternal call before state update\nOracle manipulation\tCritical\tFlash loan → price manipulation → profit\nAccess control\tCritical\tMissing auth on privileged functions\nInteger overflow\tHigh\tPre-0.8 math without SafeMath\nFront-running\tHigh\tSandwich attacks, MEV extraction\nFlash loan attacks\tHigh\tAtomic arbitrage exploiting price feeds\nLogic errors\tHigh\tWrong formula, edge cases, rounding\nDenial of service\tMedium\tGas limit exploitation, stuck states\nCentralization\tMedium\tSingle admin key, no timelock\nGriefing\tMedium\tMaking others' transactions fail/expensive\nSecurity Audit Checklist (100+ Points)\nCritical (Must Pass)\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\nHigh Priority\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)\nMedium Priority\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\nCommon Attack Vectors with Mitigations\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\nAudit Process\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\nPhase 6: Testing Strategy\nTest Pyramid for Smart Contracts\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\nTesting Checklist\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\nFoundry Test Pattern\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\nPhase 7: Deployment & Operations\nDeployment Checklist\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\nMonitoring Dashboard\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\nIncident Response\nSeverity\tResponse Time\tActions\nP0 — Active exploit\t< 5 min\tPause contracts, war room, post-mortem\nP1 — Vulnerability found\t< 1 hour\tAssess impact, prepare fix, notify team\nP2 — Degraded service\t< 4 hours\tInvestigate, fix, monitor\nP3 — Minor issue\t< 24 hours\tSchedule fix in next deployment\n\nP0 Emergency Protocol:\n\nActivate circuit breaker / pause contracts\nAssess: What was exploited? What's the exposure?\nCommunicate: Alert team + trusted security researchers\nContain: Block exploit path if possible\nRecover: Plan rescue transaction if funds recoverable\nPost-mortem: Full timeline, root cause, fix, prevention\nPhase 8: Wallet & Key Management\nKey Hierarchy\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\nWallet Security Tiers\nTier\tType\tUse Case\tSecurity Level\nHot wallet\tBrowser extension (MetaMask)\tDaily interactions, small amounts\tLow\nWarm wallet\tMobile wallet (Rainbow, Trust)\tMedium amounts, on-the-go\tMedium\nCold wallet\tHardware (Ledger, Trezor)\tLarge holdings, long-term\tHigh\nAir-gapped\tKeystone, dedicated offline\tMaximum security, institutional\tVery High\nMultisig\tSafe (Gnosis)\tTreasury, protocol admin\tHighest\nMultisig Best Practices\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\nSelf-Custody Security Rules\nSeed phrase storage — Metal plate (Cryptosteel/Billfodl), never digital\nGeographic distribution — Copies in ≥2 physical locations\nTest recovery — Verify you can restore from seed BEFORE storing value\nPhishing defense — Bookmark official URLs, never click links, verify contract addresses\nHardware wallet firmware — Update only from official sources\nTransaction simulation — Use Tenderly/Fire before signing large transactions\nApproval hygiene — Revoke unused token approvals regularly (revoke.cash)\nPhase 9: Layer 2 & Scaling\nL2 Architecture Types\nType\tHow It Works\tData Availability\tExamples\nOptimistic Rollup\tAssume valid, challenge period\tOn-chain calldata\tArbitrum, Optimism, Base\nZK Rollup\tProve validity with ZK proof\tOn-chain calldata\tzkSync, StarkNet, Scroll\nValidium\tZK proof + off-chain data\tOff-chain (DAC)\tImmutable X\nPlasma\tExit game mechanism\tOff-chain\t(largely deprecated)\nState Channel\tOff-chain with on-chain settlement\tOff-chain\tLightning Network\nSidechain\tIndependent chain with bridge\tOwn consensus\tPolygon PoS\nCross-Chain Bridge Security\n\nBridges are the #1 attack vector in crypto (>$2.5B lost).\n\nBridge security checklist:\n\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\nSafer bridging approaches:\n\nNative bridges (Arbitrum/Optimism canonical) → Slow but trustless\nLayerZero/Axelar → Decentralized messaging\nCircle CCTP → Native USDC bridging (no wrapped tokens)\nAvoid: New/unaudited bridges, single-key admin bridges\nPhase 10: Regulatory & Compliance\nRegulatory Landscape (2025)\nJurisdiction\tFramework\tToken Classification\tKey Requirement\nUS (SEC)\tHowey Test\tSecurity vs Utility\tRegistration or exemption\nUS (CFTC)\tCEA\tCommodity (BTC, ETH)\tDerivatives regulation\nEU (MiCA)\tMarkets in Crypto-Assets\tUtility/E-Money/ART\tLicensing, reserves\nUK (FCA)\tFinancial Promotions\tCrypto-asset\tMarketing restrictions\nSingapore (MAS)\tPayment Services Act\tDigital Payment Token\tLicensing\nJapan (FSA)\tFIEA/PSA\tCrypto-asset\tRegistration\nCompliance Checklist\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\nDecentralization as Compliance Strategy\n\nThe more decentralized a protocol, the stronger the argument it's not a security:\n\nFactor\tCentralized (Risky)\tDecentralized (Safer)\nDevelopment\tSingle company\tMultiple contributor orgs\nGovernance\tAdmin key\tToken-weighted DAO\nTreasury\tCompany-controlled\tCommunity-governed\nRevenue\tFlows to team\tFlows to token holders\nUpgrades\tAdmin deploys\tGovernance proposal + timelock\nFront-end\tSingle website\tMultiple alternative UIs\nPhase 11: Bitcoin & Lightning Network\nBitcoin Development\nLayer\tPurpose\tKey Technologies\nL1 (Base)\tSettlement, store of value\tScript, Taproot, SegWit\nLightning\tInstant micropayments\tPayment channels, HTLCs\nOrdinals/BRC-20\tNFTs, tokens on Bitcoin\tInscription, witness data\nStacks/Liquid\tSmart contracts on Bitcoin\tClarity, Federated sidechain\nLightning Network Integration\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\nBitcoin Self-Custody Best Practices\nUTXO management — Consolidate during low-fee periods\nAddress reuse — Never reuse addresses (privacy)\nCoin selection — Use coin control for privacy-sensitive transactions\nFee estimation — Use mempool.space for current fee rates\nMulti-sig — 2-of-3 for significant holdings (Sparrow, Nunchuk)\nVerify receive addresses — On hardware wallet screen, not just software\nPhase 12: Advanced Patterns\nMEV (Maximal Extractable Value)\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\nAccount Abstraction (ERC-4337)\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\nZero-Knowledge Applications\nApplication\tWhat ZK Proves\tExample\nPrivacy transactions\t\"I have enough funds\" without revealing amount\tTornado Cash, Zcash\nIdentity\t\"I'm over 18\" without revealing age\tPolygon ID, Worldcoin\nScaling (zkRollup)\t\"These transactions are valid\" without re-executing\tzkSync, StarkNet\nVoting\t\"I voted\" without revealing choice\tMACI\nCompliance\t\"I passed KYC\" without sharing data\tzkKYC\nGas Optimization Techniques\nTechnique\tGas Saved\tComplexity\nUse calldata instead of memory for read-only params\t~60 per 32 bytes\tLow\nPack storage variables (<256 bit types together)\t~20,000 per slot\tLow\nUse immutable / constant\t~2,100 per SLOAD avoided\tLow\nCustom errors vs require strings\t~50 per error\tLow\nUnchecked math (when overflow impossible)\t~80 per operation\tMedium\nBatch operations\tVaries (amortize base cost)\tMedium\nAssembly for hot paths\t20-50% on targeted code\tHigh\nMinimal proxy (EIP-1167) for clones\t~90% deployment cost\tMedium\nQuality Rubric (0-100)\nDimension\tWeight\tScore Guide\nSecurity\t25%\t0: No audit, known vulns. 50: Basic testing. 100: Full audit, bug bounty, formal verification\nArchitecture\t15%\t0: Monolithic, no separation. 50: Some patterns. 100: Clean separation, upgrade path, gas-optimized\nTesting\t15%\t0: No tests. 50: Unit tests. 100: Full pyramid (unit/integration/fork/fuzz/invariant)\nTokenomics\t10%\t0: Ponzi mechanics. 50: Basic utility. 100: Sustainable value accrual, aligned incentives\nDocumentation\t10%\t0: No docs. 50: Basic README. 100: NatSpec, architecture docs, user guides\nOperations\t10%\t0: No monitoring. 50: Basic alerts. 100: Full dashboard, incident playbooks, SLOs\nCompliance\t10%\t0: Unaddressed. 50: Basic legal opinion. 100: Multi-jurisdictional analysis, KYC/AML\nDecentralization\t5%\t0: Single admin key. 50: Multisig. 100: DAO governance, timelock, multiple UIs\n\nGrade: 80+ Excellent | 60-79 Good | 40-59 Needs Work | <40 Critical Risk\n\nCommon Mistakes\n#\tMistake\tFix\n1\tShipping without audit\tBudget for audit from day 1\n2\tSingle admin key\tMultisig + timelock always\n3\tUsing spot price as oracle\tTWAP or Chainlink\n4\tIgnoring MEV\tPrivate mempool + slippage protection\n5\tNo emergency pause\tCircuit breaker on every protocol\n6\tTesting only happy path\tFuzz testing + invariant tests\n7\tUnlimited token approvals\tApprove exact amounts needed\n8\tIgnoring gas optimization\tProfile gas costs, optimize hot paths\n9\tNo upgrade plan OR reckless upgrades\tDecide upgrade strategy early\n10\tBuilding blockchain when database works\tRun the Database Test first\nEdge Cases\n\nStartup / Hackathon:\n\nUse Foundry + OpenZeppelin for speed\nDeploy to Base (low gas, large ecosystem)\nSkip formal verification (do it pre-mainnet)\nFocus: working product > perfect security\n\nEnterprise / Institutional:\n\nHyperledger Besu or Avalanche Subnets for permissioned needs\nFormal verification for critical paths\nMulti-jurisdictional compliance from day 1\nHardware security modules (HSMs) for key management\n\nHigh-Value DeFi (>$100M TVL):\n\nMultiple independent audits (minimum 2 firms)\nFormal verification (Certora)\n$1M+ bug bounty on Immunefi\nReal-time monitoring with automatic pause triggers\nInsurance coverage (Nexus Mutual, InsurAce)\n\nNFT / Gaming:\n\nERC-1155 for gas efficiency (batch operations)\nOff-chain metadata (IPFS/Arweave for permanence)\nAccount abstraction for onboarding (gasless minting)\nConsider L2 (Immutable X, Base, Polygon) for low gas\n\nCross-Chain:\n\nStart with one chain, expand after PMF\nUse canonical bridges (slow but safe) over third-party\nImplement chain-specific parameter tuning\nMonitor bridge TVL and security track record\nNatural Language Commands\n\nWhen prompted, this skill responds to:\n\nevaluate blockchain fit — Run the Database Test decision framework\ndesign smart contract — Generate architecture brief + coding standards\ndesign tokenomics — Create token economics framework with distribution\naudit security — Run full security checklist against a contract\nplan deployment — Generate deployment + post-deployment checklist\nassess DeFi protocol — Evaluate DeFi design against security invariants\noptimize gas — Review code for gas optimization opportunities\nreview wallet security — Generate wallet + key management recommendations\nevaluate L2 — Compare Layer 2 options for specific use case\ncheck compliance — Run regulatory compliance checklist\ndesign bridge strategy — Evaluate cross-chain approach\nfull web3 review — Complete assessment across all dimensions"
  },
  "trust": {
    "sourceLabel": "tencent",
    "provenanceUrl": "https://clawhub.ai/1kalin/afrexai-web3-engineering",
    "publisherUrl": "https://clawhub.ai/1kalin/afrexai-web3-engineering",
    "owner": "1kalin",
    "version": "1.0.0",
    "license": null,
    "verificationStatus": "Indexed source record"
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/afrexai-web3-engineering",
    "downloadUrl": "https://openagent3.xyz/downloads/afrexai-web3-engineering",
    "agentUrl": "https://openagent3.xyz/skills/afrexai-web3-engineering/agent",
    "manifestUrl": "https://openagent3.xyz/skills/afrexai-web3-engineering/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/afrexai-web3-engineering/agent.md"
  }
}