# Send Web3 & Blockchain Engineering to your agent
Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.
## Fast path
- 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.
## Suggested prompts
### New install

```text
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.
```
### Upgrade existing

```text
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.
```
## Machine-readable fields
```json
{
  "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": {
    "downloadUrl": "/downloads/afrexai-web3-engineering",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=afrexai-web3-engineering",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "packageFormat": "ZIP package",
    "primaryDoc": "SKILL.md",
    "includedAssets": [
      "README.md",
      "SKILL.md"
    ],
    "downloadMode": "redirect",
    "sourceHealth": {
      "source": "tencent",
      "slug": "afrexai-web3-engineering",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-04-29T06:00:13.069Z",
      "expiresAt": "2026-05-06T06:00:13.069Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=afrexai-web3-engineering",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=afrexai-web3-engineering",
        "contentDisposition": "attachment; filename=\"afrexai-web3-engineering-1.0.0.zip\"",
        "redirectLocation": null,
        "bodySnippet": null,
        "slug": "afrexai-web3-engineering"
      },
      "scope": "item",
      "summary": "Item download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this item.",
      "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."
      ]
    }
  },
  "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"
  }
}
```
## Documentation

### 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.

### The Database Test

Before writing a single line of Solidity, answer honestly:

blockchain_evaluation:
  problem: "[describe the core problem]"
  
  requirements:
    multiple_untrusting_parties: true/false    # >1 org needs shared truth
    no_trusted_authority: true/false            # no single party everyone trusts
    immutability_critical: true/false           # history must be tamper-proof
    censorship_resistance_needed: true/false    # no entity should block access
    value_transfer_required: true/false         # moving assets between parties
    transparency_required: true/false           # all parties need verifiable state
  
  disqualifiers:
    single_org_controls_data: true/false        # → use a database
    data_deletion_required: true/false          # → GDPR conflict, careful
    high_throughput_low_latency: true/false     # → >10K TPS? consider L2 or database
    users_cant_manage_wallets: true/false       # → account abstraction or custodial
    trusted_authority_exists: true/false        # → database with audit log
  
  score: "[count true requirements - count true disqualifiers]"
  verdict: "blockchain / hybrid / database"

Decision rules:

Score ≤ 0 → Use PostgreSQL with audit logs
Score 1-2 → Hybrid (anchoring/notarization on-chain, logic off-chain)
Score 3+ → Blockchain is justified

### Platform Selection Matrix

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

Selection decision tree:

Store of value / settlement only? → Bitcoin
Micropayments / instant P2P? → Lightning Network
Need EVM compatibility? → Yes: continue. No: consider Solana, Cosmos
High-value DeFi / maximum security? → Ethereum L1
General dApp with low gas? → Arbitrum or Base
Mass-market consumer? → Base or Polygon
Enterprise with custom rules? → Avalanche subnets or Hyperledger

### Design Principles

Minimize on-chain state — Storage is expensive. Put data on-chain only if it needs consensus
Fail loudly — Use require() / revert() with descriptive messages, never silent failures
Immutability by default — Upgradeability adds attack surface. Only use if genuinely needed
Separation of concerns — One contract per responsibility
Gas-conscious design — Every operation costs money. Optimize hot paths

### Contract Architecture Patterns

architecture_brief:
  project: "[name]"
  type: "DeFi / NFT / DAO / Token / Marketplace / Infrastructure"
  
  contracts:
    core:
      - name: "[MainContract]"
        responsibility: "[single clear purpose]"
        state_variables: ["list key storage"]
        external_calls: ["contracts it calls"]
    
    periphery:
      - name: "[Router/Helper]"
        responsibility: "[user-facing convenience]"
    
    libraries:
      - name: "[MathLib/SafeLib]"
        responsibility: "[shared pure functions]"
  
  upgrade_strategy: "immutable / transparent-proxy / UUPS / diamond / beacon"
  access_control: "Ownable / AccessControl / Timelock+Multisig / DAO"

### Upgrade Pattern Decision

PatternComplexityGas OverheadStorage Layout RiskBest ForImmutableNoneNoneNoneSimple contracts, tokensTransparent ProxyMedium+gas per callHighStandard upgradeableUUPSMediumLower than transparentHighGas-efficient upgradeableDiamond (EIP-2535)HighMediumHighLarge modular systemsBeaconMediumMediumHighMany identical instances

Rule: If you can avoid upgradeability, do it. If you must upgrade, use UUPS with timelock + multisig governance.

### Solidity Development Standards

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

// — IMPORTS: Use named imports, pin versions —
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

/// @title VaultV1
/// @notice Single-asset vault with deposit/withdraw
/// @dev Uses SafeERC20 for all token transfers
contract VaultV1 is ReentrancyGuard {
    using SafeERC20 for IERC20;

    // — STATE: Group by slot for packing —
    IERC20 public immutable asset;       // slot 0
    uint128 public totalDeposits;        // slot 1 (packed)
    uint128 public totalShares;          // slot 1 (packed)
    
    mapping(address => uint256) public shares;

    // — EVENTS: Index searchable fields —
    event Deposited(address indexed user, uint256 amount, uint256 shares);
    event Withdrawn(address indexed user, uint256 amount, uint256 shares);

    // — ERRORS: Custom errors save gas vs strings —
    error ZeroAmount();
    error InsufficientShares(uint256 requested, uint256 available);

    constructor(IERC20 _asset) {
        asset = _asset;
    }

    /// @notice Deposit assets, receive proportional shares
    /// @param amount Asset amount to deposit
    /// @return mintedShares Shares minted to caller
    function deposit(uint256 amount) external nonReentrant returns (uint256 mintedShares) {
        if (amount == 0) revert ZeroAmount();
        
        // Calculate shares BEFORE transfer (prevent manipulation)
        mintedShares = totalDeposits == 0
            ? amount
            : (amount * totalShares) / totalDeposits;
        
        // Effects before interactions (CEI pattern)
        totalDeposits += uint128(amount);
        totalShares += uint128(mintedShares);
        shares[msg.sender] += mintedShares;
        
        // Interaction last
        asset.safeTransferFrom(msg.sender, address(this), amount);
        
        emit Deposited(msg.sender, amount, mintedShares);
    }
}

### Coding Standards Checklist

NatSpec on every public/external function
 Custom errors instead of require strings (saves ~50 gas each)
 Events for every state change
 CEI pattern (Checks-Effects-Interactions) on every external call
 nonReentrant on functions with external calls
 immutable / constant where possible
 SafeERC20 for all token transfers
 No tx.origin for auth (phishing vector)
 Explicit visibility on all functions and state variables
 Storage variable packing (group smaller types together)

### Token Type Decision

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

### Token Design Framework

tokenomics:
  token_name: "[Name]"
  symbol: "[SYM]"
  standard: "ERC-20 / ERC-721 / ERC-1155"
  total_supply: "[fixed / capped / inflationary]"
  
  distribution:
    team: "[%] — [vesting schedule]"
    investors: "[%] — [vesting schedule]"
    community: "[%] — [distribution mechanism]"
    treasury: "[%] — [governance-controlled]"
    ecosystem: "[%] — [grants, incentives]"
    liquidity: "[%] — [DEX pairs, market making]"
  
  vesting:
    team_cliff: "12 months minimum"
    team_linear: "24-48 months after cliff"
    investor_cliff: "6-12 months"
    investor_linear: "12-36 months"
  
  value_accrual:
    mechanism: "[fee sharing / buyback-burn / staking yield / utility demand]"
    fee_structure: "[% of protocol revenue → token holders]"
    burn_mechanism: "[deflationary pressure source]"
  
  governance:
    voting_power: "1 token = 1 vote / quadratic / conviction"
    quorum: "[% of supply needed]"
    timelock: "[delay between vote and execution]"
    
  inflation_schedule:
    year_1: "[%]"
    year_2: "[%]"
    long_term: "[target %/year]"
    
  sustainability_test:
    without_new_buyers: "Does the token have utility even if price = 0?"
    revenue_source: "Where does yield come from? (real yield vs emissions)"
    death_spiral_risk: "Can selling pressure create feedback loop?"

### Tokenomics Red Flags

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

### Core DeFi Primitives

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

### AMM Design (Uniswap V2/V3 Pattern)

Constant Product: x * y = k
Price Impact: Δy = y - k/(x + Δx)
Slippage: (expected_price - actual_price) / expected_price

V3 Concentrated Liquidity:
- LPs choose price range [Pa, Pb]
- Capital efficiency: up to 4000x vs V2
- Trade-off: must actively manage positions

### DeFi Security Invariants

Every DeFi protocol MUST maintain these:

Solvency — Total assets ≥ total liabilities (always)
No free tokens — No path creates tokens from nothing
Monotonic shares — Depositing increases shares, withdrawing decreases
Oracle freshness — Price data is within acceptable staleness window
Liquidation viability — Undercollateralized positions can always be liquidated
Access control — Admin functions behind timelock + multisig
Withdrawal guarantee — Users can always withdraw their assets (no lock-up without consent)

### Vulnerability Taxonomy

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

### Security Audit Checklist (100+ Points)

Critical (Must Pass)

Reentrancy protection — All external calls follow CEI pattern OR use nonReentrant
 Access control — Every privileged function has appropriate modifier
 Oracle security — Price feeds have freshness checks, manipulation resistance
 Integer safety — Solidity ≥0.8 (built-in overflow checks) or SafeMath
 Flash loan resistance — Protocol functions work correctly within single transaction
 Approval hygiene — No unlimited approvals to untrusted contracts
 Initialization — Proxy contracts can only be initialized once
 Self-destruct protection — No selfdestruct in implementation contracts
 Signature replay — Nonces prevent signature reuse across chains/contracts

High Priority

Front-running protection — Commit-reveal or deadline parameters on sensitive operations
 Slippage protection — Min output amounts on swaps/withdrawals
 Rounding direction — Always round in protocol's favor (against user)
 Gas griefing — External calls can't force excessive gas consumption
 Token compatibility — Handles fee-on-transfer, rebasing, and missing-return tokens
 Withdrawal path — Users can always exit, even if admin functions fail
 Timelock on admin — Governance changes have delay period
 Key management — Multisig for all admin functions, no single points of failure
 Upgrade safety — Storage layout preserved across upgrades (no slot collision)

Medium Priority

Event emission — All state changes emit events for off-chain tracking
 Input validation — Zero address checks, bounds checking on parameters
 Dust attacks — Small deposits can't grief the accounting
 Block timestamp — No reliance on exact block.timestamp (manipulable ±15s)
 Gas optimization — No unbounded loops, batch operations have limits
 Error messages — Custom errors with meaningful context
 Test coverage — >95% line coverage, 100% on critical paths

### Common Attack Vectors with Mitigations

1. Reentrancy
   Attack: Call back into contract before state is updated
   Fix: CEI pattern + ReentrancyGuard
   
2. Oracle Manipulation (Flash Loan)
   Attack: Borrow → manipulate price → exploit → repay (atomic)
   Fix: TWAP oracles, Chainlink price feeds, manipulation-resistant design
   
3. Sandwich Attack (MEV)
   Attack: Front-run user's swap → inflate price → back-run to profit
   Fix: Deadline parameter, max slippage, private mempools (Flashbots)
   
4. Governance Attack
   Attack: Flash-borrow governance tokens → vote → execute
   Fix: Snapshot at proposal creation, timelock, vote escrow (ve-model)
   
5. Price Oracle Stale Data
   Attack: Use outdated price to exploit arbitrage
   Fix: Chainlink heartbeat check, staleness threshold, circuit breakers

### Audit Process

audit_checklist:
  pre_audit:
    - [ ] Code freeze — no changes during audit
    - [ ] Documentation complete (spec, architecture, flow diagrams)
    - [ ] Test suite passing with >95% coverage
    - [ ] Known issues documented
    - [ ] Deployment scripts tested on testnet
    
  audit_scope:
    contracts: ["list all in-scope contracts"]
    lines_of_code: "[total Solidity LoC]"
    complexity: "low / medium / high / critical"
    prior_audits: "[list previous audit firms]"
    
  recommended_firms:
    tier_1: ["Trail of Bits", "OpenZeppelin", "Consensys Diligence"]
    tier_2: ["Spearbit", "Code4rena", "Sherlock"]
    bug_bounty: ["Immunefi (post-deployment)"]
    
  budget_guide:
    simple_token: "$5K-15K"
    defi_protocol: "$50K-200K"
    complex_system: "$200K-500K+"
    
  post_audit:
    - [ ] All critical/high findings fixed
    - [ ] Fix review by auditor
    - [ ] Audit report published (transparency)
    - [ ] Bug bounty program launched

### Test Pyramid for Smart Contracts

/\\
                   /  \\        Mainnet Fork Tests
                  /    \\       (real state, real tokens)
                 /------\\
                /        \\     Integration Tests
               /          \\    (multi-contract interactions)
              /------------\\
             /              \\   Unit Tests
            /                \\  (single function, isolated)
           /------------------\\
          /                    \\ Static Analysis
         /                      \\ (Slither, Mythril, Aderyn)
        /________________________\\

### Testing Checklist

testing_requirements:
  static_analysis:
    tools: ["Slither", "Mythril", "Aderyn"]
    run: "On every commit (CI)"
    
  unit_tests:
    coverage_target: ">95% line, 100% critical paths"
    framework: "Foundry (preferred) or Hardhat"
    must_test:
      - All require/revert conditions
      - Boundary values (0, 1, max_uint256)
      - Access control on every privileged function
      - Math precision and rounding
      
  integration_tests:
    must_test:
      - Full user flows (deposit → earn → withdraw)
      - Multi-contract interactions
      - Upgrade paths (storage layout preservation)
      - Governance proposal → execution flow
      
  fork_tests:
    must_test:
      - Real mainnet state interactions
      - Oracle price feed behavior
      - Token compatibility (USDT, USDC, DAI, etc.)
      - Gas costs with real-world state size
      
  fuzz_tests:
    tool: "Foundry fuzz / Echidna / Medusa"
    invariants:
      - "Total supply == sum of all balances"
      - "Total assets >= total liabilities"
      - "Share price monotonically increases (yield vaults)"
      - "No function creates tokens from nothing"
      
  formal_verification:
    when: "Critical DeFi with >$10M TVL"
    tools: ["Certora", "Halmos", "KEVM"]

### Foundry Test Pattern

// test/VaultV1.t.sol
contract VaultV1Test is Test {
    VaultV1 vault;
    MockERC20 token;
    address alice = makeAddr("alice");
    
    function setUp() public {
        token = new MockERC20("Test", "TST", 18);
        vault = new VaultV1(IERC20(address(token)));
        token.mint(alice, 1000e18);
        vm.prank(alice);
        token.approve(address(vault), type(uint256).max);
    }
    
    function test_deposit_mintsShares() public {
        vm.prank(alice);
        uint256 shares = vault.deposit(100e18);
        
        assertEq(shares, 100e18, "First deposit: 1:1 shares");
        assertEq(vault.shares(alice), 100e18);
        assertEq(vault.totalDeposits(), 100e18);
    }
    
    function test_deposit_revertsOnZero() public {
        vm.prank(alice);
        vm.expectRevert(VaultV1.ZeroAmount.selector);
        vault.deposit(0);
    }
    
    // Fuzz test: any deposit amount preserves invariants
    function testFuzz_deposit_invariants(uint128 amount) public {
        vm.assume(amount > 0 && amount <= token.balanceOf(alice));
        
        uint256 prevTotal = vault.totalDeposits();
        vm.prank(alice);
        vault.deposit(amount);
        
        assertEq(vault.totalDeposits(), prevTotal + amount);
        assertTrue(vault.totalShares() > 0);
    }
}

### Deployment Checklist

pre_deployment:
  - [ ] All tests passing (unit, integration, fork, fuzz)
  - [ ] Static analysis clean (no high/critical findings)
  - [ ] Audit complete, all findings addressed
  - [ ] Deployment scripts tested on testnet (exact same flow)
  - [ ] Multisig wallets created and configured
  - [ ] Timelock contracts deployed and tested
  - [ ] Constructor arguments verified
  - [ ] Gas estimates confirmed within budget
  
deployment:
  - [ ] Deploy to mainnet from hardened machine
  - [ ] Verify source on block explorer (Etherscan)
  - [ ] Transfer ownership to multisig/timelock
  - [ ] Renounce deployer privileges
  - [ ] Test all functions with small amounts
  - [ ] Set initial parameters (fees, limits, oracles)
  
post_deployment:
  - [ ] Bug bounty program live (Immunefi)
  - [ ] Monitoring dashboards deployed
  - [ ] Alert rules configured
  - [ ] Documentation published
  - [ ] Community announcement

### Monitoring Dashboard

smart_contract_monitoring:
  on_chain:
    - metric: "TVL (Total Value Locked)"
      alert: "Drop >10% in 1 hour"
      severity: "P0"
    - metric: "Unique active users (daily)"
      alert: "Drop >50% vs 7-day avg"
      severity: "P1"
    - metric: "Gas costs per transaction"
      alert: "Spike >3x average"
      severity: "P2"
    - metric: "Admin function calls"
      alert: "ANY unexpected admin call"
      severity: "P0"
    - metric: "Large withdrawals"
      alert: ">5% of TVL in single tx"
      severity: "P1"
      
  oracle:
    - metric: "Price feed freshness"
      alert: "Stale >30 minutes"
      severity: "P0"
    - metric: "Price deviation vs CEX"
      alert: ">2% deviation"
      severity: "P1"
      
  infrastructure:
    - metric: "RPC node health"
      alert: "Latency >500ms or errors"
      severity: "P1"
    - metric: "Indexer sync status"
      alert: ">100 blocks behind"
      severity: "P1"

### Incident Response

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

P0 Emergency Protocol:

Activate circuit breaker / pause contracts
Assess: What was exploited? What's the exposure?
Communicate: Alert team + trusted security researchers
Contain: Block exploit path if possible
Recover: Plan rescue transaction if funds recoverable
Post-mortem: Full timeline, root cause, fix, prevention

### Key Hierarchy

Seed Phrase (BIP-39)
  └── Master Key
      ├── m/44'/60'/0'/0/0  → Ethereum Account 0
      ├── m/44'/60'/0'/0/1  → Ethereum Account 1
      ├── m/44'/0'/0'/0/0   → Bitcoin Account 0
      └── m/84'/0'/0'/0/0   → Bitcoin SegWit Account 0

### Wallet Security Tiers

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

### Multisig Best Practices

multisig_config:
  protocol_treasury:
    signers: 5
    threshold: 3  # 3-of-5
    signer_diversity:
      - Different devices/locations
      - Different key types (hardware + mobile)
      - No single point of failure
    timelock: "48 hours for >$100K"
    
  operational:
    signers: 3
    threshold: 2  # 2-of-3
    use_case: "Day-to-day parameter changes"
    timelock: "24 hours"

### Self-Custody Security Rules

Seed phrase storage — Metal plate (Cryptosteel/Billfodl), never digital
Geographic distribution — Copies in ≥2 physical locations
Test recovery — Verify you can restore from seed BEFORE storing value
Phishing defense — Bookmark official URLs, never click links, verify contract addresses
Hardware wallet firmware — Update only from official sources
Transaction simulation — Use Tenderly/Fire before signing large transactions
Approval hygiene — Revoke unused token approvals regularly (revoke.cash)

### L2 Architecture Types

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

### Cross-Chain Bridge Security

Bridges are the #1 attack vector in crypto (>$2.5B lost).

Bridge security checklist:

Multisig or decentralized validator set (not single key)
 Rate limiting on bridge transfers
 Monitoring for unusual withdrawal patterns
 Emergency pause functionality
 Regular security audits
 Insurance fund for bridge exploits

Safer bridging approaches:

Native bridges (Arbitrum/Optimism canonical) → Slow but trustless
LayerZero/Axelar → Decentralized messaging
Circle CCTP → Native USDC bridging (no wrapped tokens)
Avoid: New/unaudited bridges, single-key admin bridges

### Regulatory Landscape (2025)

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

### Compliance Checklist

compliance:
  token_classification:
    - [ ] Legal opinion on token classification (security vs utility)
    - [ ] Howey test analysis documented
    - [ ] Jurisdictional analysis complete
    
  aml_kyc:
    - [ ] KYC/AML provider integrated (if applicable)
    - [ ] Sanctions screening (OFAC, EU, UN)
    - [ ] Transaction monitoring for suspicious activity
    - [ ] SAR (Suspicious Activity Report) filing process
    
  mca_eu:
    - [ ] Whitepaper published (if issuing tokens)
    - [ ] Notification to competent authority
    - [ ] Reserve requirements (for stablecoins)
    
  tax:
    - [ ] Tax treatment documented per jurisdiction
    - [ ] Reporting infrastructure (1099/DAC8)
    - [ ] Cost basis tracking for users

### Decentralization as Compliance Strategy

The more decentralized a protocol, the stronger the argument it's not a security:

FactorCentralized (Risky)Decentralized (Safer)DevelopmentSingle companyMultiple contributor orgsGovernanceAdmin keyToken-weighted DAOTreasuryCompany-controlledCommunity-governedRevenueFlows to teamFlows to token holdersUpgradesAdmin deploysGovernance proposal + timelockFront-endSingle websiteMultiple alternative UIs

### Bitcoin Development

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

### Lightning Network Integration

lightning_integration:
  use_cases:
    - Micropayments (<$1)
    - Point-of-sale payments
    - Streaming payments (per-second)
    - Machine-to-machine payments
    - Tipping / donations
    
  implementation:
    self_hosted:
      options: ["LND", "CLN (Core Lightning)", "Eclair"]
      requirements: "Bitcoin full node + Lightning node"
      complexity: "High"
      
    hosted_api:
      options: ["Strike API", "Voltage", "LNbits", "BTCPay Server"]
      requirements: "API key"
      complexity: "Low-Medium"
      
    standards:
      invoices: "BOLT11 (payment request)"
      keysend: "Spontaneous payments (no invoice)"
      lnurl: "User-friendly payment flows"
      bolt12: "Reusable offers (emerging)"

### Bitcoin Self-Custody Best Practices

UTXO management — Consolidate during low-fee periods
Address reuse — Never reuse addresses (privacy)
Coin selection — Use coin control for privacy-sensitive transactions
Fee estimation — Use mempool.space for current fee rates
Multi-sig — 2-of-3 for significant holdings (Sparrow, Nunchuk)
Verify receive addresses — On hardware wallet screen, not just software

### MEV (Maximal Extractable Value)

mev_awareness:
  what: "Value extracted by block producers reordering/inserting transactions"
  
  types:
    - sandwich_attack: "Front-run + back-run user's swap"
    - arbitrage: "Cross-DEX price differences"  
    - liquidation: "Race to liquidate undercollateralized positions"
    - jit_liquidity: "Just-in-time LP provision around large swaps"
    
  protection:
    users:
      - "Use private mempools (Flashbots Protect, MEV Blocker)"
      - "Set tight slippage limits"
      - "Use DEX aggregators with MEV protection (CoW Swap)"
      - "Submit transactions through RPC endpoints with MEV protection"
    developers:
      - "Commit-reveal schemes for sensitive operations"
      - "Batch auctions instead of continuous swaps"
      - "Deadline parameters on all swap functions"
      - "Internal oracle (TWAP) instead of spot price"

### Account Abstraction (ERC-4337)

account_abstraction:
  what: "Smart contract wallets as first-class citizens"
  
  benefits:
    - Social recovery (friends can help recover account)
    - Gas sponsorship (app pays gas for users)
    - Batch transactions (multiple actions in one click)
    - Session keys (limited permissions for games/dApps)
    - Any token for gas (pay gas in USDC)
    
  implementation:
    frameworks: ["Safe{Core}", "ZeroDev", "Biconomy", "Alchemy AA"]
    bundlers: ["Pimlico", "Stackup", "Alchemy"]
    paymasters: ["Pimlico Verifying Paymaster", "Alchemy Gas Manager"]
    
  when_to_use:
    - Consumer-facing dApps (abstract wallet complexity)
    - Games (session keys, gasless)
    - B2B (multisig, spending policies)

### Zero-Knowledge Applications

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

### Gas Optimization Techniques

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

### Quality Rubric (0-100)

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

Grade: 80+ Excellent | 60-79 Good | 40-59 Needs Work | <40 Critical Risk

### Common Mistakes

#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

### Edge Cases

Startup / Hackathon:

Use Foundry + OpenZeppelin for speed
Deploy to Base (low gas, large ecosystem)
Skip formal verification (do it pre-mainnet)
Focus: working product > perfect security

Enterprise / Institutional:

Hyperledger Besu or Avalanche Subnets for permissioned needs
Formal verification for critical paths
Multi-jurisdictional compliance from day 1
Hardware security modules (HSMs) for key management

High-Value DeFi (>$100M TVL):

Multiple independent audits (minimum 2 firms)
Formal verification (Certora)
$1M+ bug bounty on Immunefi
Real-time monitoring with automatic pause triggers
Insurance coverage (Nexus Mutual, InsurAce)

NFT / Gaming:

ERC-1155 for gas efficiency (batch operations)
Off-chain metadata (IPFS/Arweave for permanence)
Account abstraction for onboarding (gasless minting)
Consider L2 (Immutable X, Base, Polygon) for low gas

Cross-Chain:

Start with one chain, expand after PMF
Use canonical bridges (slow but safe) over third-party
Implement chain-specific parameter tuning
Monitor bridge TVL and security track record

### Natural Language Commands

When prompted, this skill responds to:

evaluate blockchain fit — Run the Database Test decision framework
design smart contract — Generate architecture brief + coding standards
design tokenomics — Create token economics framework with distribution
audit security — Run full security checklist against a contract
plan deployment — Generate deployment + post-deployment checklist
assess DeFi protocol — Evaluate DeFi design against security invariants
optimize gas — Review code for gas optimization opportunities
review wallet security — Generate wallet + key management recommendations
evaluate L2 — Compare Layer 2 options for specific use case
check compliance — Run regulatory compliance checklist
design bridge strategy — Evaluate cross-chain approach
full web3 review — Complete assessment across all dimensions
## Trust
- Source: tencent
- Verification: Indexed source record
- Publisher: 1kalin
- Version: 1.0.0
## Source health
- Status: healthy
- Item download looks usable.
- Yavira can redirect you to the upstream package for this item.
- Health scope: item
- Reason: direct_download_ok
- Checked at: 2026-04-29T06:00:13.069Z
- Expires at: 2026-05-06T06:00:13.069Z
- Recommended action: Download for OpenClaw
## Links
- [Detail page](https://openagent3.xyz/skills/afrexai-web3-engineering)
- [Send to Agent page](https://openagent3.xyz/skills/afrexai-web3-engineering/agent)
- [JSON manifest](https://openagent3.xyz/skills/afrexai-web3-engineering/agent.json)
- [Markdown brief](https://openagent3.xyz/skills/afrexai-web3-engineering/agent.md)
- [Download page](https://openagent3.xyz/downloads/afrexai-web3-engineering)