AgentSkillsCN

design-web3

Web3系统设计——区块链架构、链上与链下决策,以及智能合约模式。

SKILL.md
--- frontmatter
name: design-web3
description: Web3 system design — blockchain architecture, on-chain/off-chain decisions, and smart contract patterns

What I do

  • Bridge traditional system design concepts to blockchain-specific constraints
  • Provide decision frameworks for on-chain vs off-chain placement
  • Document smart contract architecture patterns and gas optimization
  • Cover finality models, cross-chain communication, and state management

When to use me

Use this skill when designing blockchain-based systems or migrating traditional architectures to Web3. Pair with design-core for foundational design principles and decision frameworks.

Traditional to Web3 Paradigm Translation

Traditional ConceptWeb3 EquivalentKey Difference
DatabaseSmart contract storageWrites cost gas; storage is permanent and public
API serverSmart contract functionsExecution is trustless but expensive and rate-limited by block space
AuthenticationWallet signatures (ECDSA)Self-sovereign identity; no password resets
AuthorizationOn-chain access controlEnforced by consensus, not by a server you control
Message queueEvents / logsAppend-only, indexed, but not readable by contracts
Cron jobKeeper networks (Chainlink, Gelato)No native scheduling; external actors trigger execution
Load balancerMultiple RPC endpointsDecentralized but variable latency and reliability
Database migrationContract upgrade patternImmutable by default; upgrades require proxy patterns
Caching layerIndexer (The Graph, Subsquid)On-chain reads are slow; indexers denormalize for query speed
CI/CD pipelineDeployment scripts + verificationDeployed code is immutable; verify source on block explorer

On-chain / Off-chain Decision Framework

code
Does the data need trustless verification?
  YES --> On-chain (or commit hash on-chain, data off-chain)
  NO  |
      v
Does the operation need atomic composability with other contracts?
  YES --> On-chain
  NO  |
      v
Can the operation tolerate >12s latency (block time)?
  NO  --> Off-chain with on-chain settlement
  YES |
      v
Is the data larger than 1 KB per transaction?
  YES --> Off-chain storage (IPFS, Arweave) with on-chain hash
  NO  |
      v
Does the computation cost >500K gas?
  YES --> Off-chain compute with on-chain proof (ZK or optimistic)
  NO  --> On-chain is viable; evaluate gas cost vs trust benefit

Smart Contract Architecture Patterns

PatternUse CaseTrade-off
Transparent proxyUpgradeable contractsAdmin key risk; storage collision possible
UUPS proxyUpgradeable with lower gasUpgrade logic in implementation; bricking risk
Diamond (EIP-2535)Large contracts exceeding size limitComplexity; harder to audit and verify
Minimal proxy (EIP-1167)Deploying many identical contracts cheaplyCannot be upgraded; fixed logic
Beacon proxyUpgrading many proxies atomicallySingle point of upgrade; centralization risk
ImmutableMaximum trust and simplicityNo bug fixes; must get it right the first time

Default choice: Immutable for simple contracts. UUPS proxy when upgrades are genuinely needed. Avoid Diamond unless contract size forces it.

Gas Optimization as Architectural Constraint

Design-level decisions that dominate gas costs (not code-level tricks):

  1. Storage layout -- Pack variables into 32-byte slots. One SSTORE costs 20K gas (cold) or 5K gas (warm). Minimize storage writes.
  2. Batch operations -- Amortize fixed costs across multiple operations. One transaction with N transfers beats N transactions.
  3. Off-chain computation -- Move computation off-chain; submit only results and proofs on-chain.
  4. Event-driven reads -- Use events for data that only needs to be read off-chain. Events cost ~375 gas per topic vs 20K for storage.
  5. Lazy evaluation -- Defer computation until the result is needed. Distribute gas cost across multiple transactions.

Finality Models

Chain TypeFinalityTimeDesign Implication
Ethereum (PoS)Probabilistic then finalized~15 min (2 epochs)Wait for finalization for high-value operations
L2 RollupsSoft confirmation, then L1 finalitySeconds (soft), hours (hard)Design for two-tier confirmation UX
SolanaOptimistic confirmation~400msFast but reorgs possible; confirm for value transfers
Cosmos (Tendermint)Instant finality~6sNo reorgs; safe to act on first confirmation
BitcoinProbabilistic~60 min (6 blocks)Wait for depth proportional to transaction value

Cross-chain Communication Patterns

PatternTrust ModelLatencyBest For
Hash time-locked contracts (HTLC)TrustlessMinutes-hoursAtomic swaps between chains
Light client bridgesTrust chain consensusMinutesHigh-security cross-chain messaging
Optimistic bridgesTrust + fraud proof window7+ daysL2-to-L1 withdrawals
Oracle-based bridgesTrust oracle setSeconds-minutesSpeed-critical cross-chain transfers
ZK bridgesTrust math (proof verification)MinutesHigh-security with faster finality than optimistic

Default choice: Use canonical bridges when available. For custom bridges, prefer ZK or light client approaches over oracle-based for security.

State Management on Blockchains

  • On-chain state -- Minimal, critical data only (balances, ownership, protocol parameters). Expensive to write, cheap to verify.
  • Events as state -- Emit events for historical data. Reconstruct state off-chain via indexers. Cannot be read by other contracts.
  • Off-chain indexing -- Use The Graph or custom indexers for complex queries. Treat as a read cache, not source of truth.
  • Hybrid state -- Merkle roots on-chain, full data off-chain (calldata, IPFS, DA layers). Verify inclusion proofs on-chain.

Anti-Patterns

Anti-PatternWhy It FailsWhat To Do Instead
Storing everything on-chainGas costs explode; blockchain is not a databaseStore hashes on-chain, data off-chain
Ignoring MEVTransactions are reordered for profit; users get worse pricesDesign with MEV awareness; use private mempools or batch auctions
Treating blockchain as a databaseQueries are expensive; no native indexing or joinsUse indexers for reads; blockchain is for verification
Single-chain lock-inChains evolve; users exist across ecosystemsAbstract chain-specific logic behind interfaces
Unbounded loops in contractsGas limit exceeded; transaction revertsUse pagination or off-chain computation with proofs
Admin keys without timelockRug pull risk; single point of trust failureTimelock + multi-sig for all privileged operations
Ignoring upgrade pathImmutable bugs with no recovery mechanismDecide upgrade strategy before deployment; document it