Blockchain Application
Purpose
Guide smart contract development across all major blockchain platforms. Covers language selection, contract architecture, security patterns, gas optimization, deployment, and cross-contract communication. Platform-agnostic at the protocol layer; chain-specific at the language and VM layer.
Agent Protocol
Trigger
"smart contract", "solidity", "vyper", "evm", "rust smart contract", "solana contract", "anchor framework", "cardano", "plutus", "haskell contract", "cairo", "starknet", "sierra", "hardhat", "foundry", "truffle", "dapp backend", "contract deployment", "gas optimization", "contract security", "cross-contract call", "chainlink", "oracle contract", "defi contract", "nft contract", "move language", "sui contract", "aptos contract"
Input Context
- Target blockchain and VM type (EVM/SVM/eUTxO/StarkNet/MoveVM)
- Contract purpose (token/DeFi/NFT/oracle/governance/bridge)
- Upgradeability requirements (proxy/non-upgradeable/beacon)
- Security requirements (audit level, formal verification need)
- Performance constraints (gas budget, compute units, TPS needs)
- Existing dependencies (OpenZeppelin, Anchor libraries, Plutus contracts)
Output Artifact
Complete contract architecture specification: platform selection, contract design, implementation approach, testing strategy, deployment plan, security analysis.
Response Format
- Platform selection: chain type + VM + language + framework + toolchain
- Contract architecture: entry points, storage layout, external dependencies, upgradeability
- Implementation: key functions with gas considerations and security annotations
- Testing strategy: unit, integration, fuzz, invariant, testnet deployment
- Deployment: constructor args, verification, proxy setup, multi-sig ownership
- Risk analysis: known vulnerabilities specific to this platform/pattern
Completion Criteria
- Contract architecture follows platform best practices (checks-effects-interactions, access control)
- Storage layout compatible with upgradeability pattern (if upgradeable)
- Gas optimization applied: storage reads minimized, calldata over memory where possible
- Security review covers platform-specific attack vectors (reentrancy, oracle manipulation, flash loans)
- Deployment plan includes verification, multi-sig ownership, and monitoring
Max Response Length
5000 tokens
Decision Trees
Platform Selection
Smart contract platform:
├── Need EVM compatibility?
│ ├── YES → Solidity or Vyper
│ │ ├── Solidity: EVM chains (Ethereum, Polygon, Arbitrum, Optimism, Base, BSC)
│ │ │ ├── Toolchain: Foundry (default), Hardhat (complex workflows)
│ │ │ └── Libraries: OpenZeppelin, Solady
│ │ └── Vyper: Simple contracts, audit-friendliness prioritized
│ │ └── Toolchain: ape, brownie
│ ├── NO → Evaluate non-EVM chains
│ │ ├── Solana → Rust + Anchor framework
│ │ │ └── Toolchain: Anchor CLI, Solana CLI
│ │ ├── Cardano → Haskell (Plutus) or Aiken
│ │ │ └── Toolchain: Plutus Tx, cardano-cli
│ │ ├── StarkNet → Cairo
│ │ │ └── Toolchain: Scarb, Starkli
│ │ ├── Sui/Aptos → Move
│ │ │ └── Toolchain: sui CLI / aptos CLI
│ │ └── NEAR/Polkadot → Rust (ink!)
│ │ └── Toolchain: cargo-contract
│ └── Cross-chain? → Consider platform-agnostic architecture
│ └── Abstract core logic, deploy adapters per chain
Upgradeability Decision
Need upgradeable contract?
├── YES:
│ ├── UUPS → Default for new projects (gas-efficient, clean storage)
│ ├── Transparent → Legacy projects, many upgrade functions
│ └── Beacon → Many child contracts (ERC-1167 clones)
├── NO → Immutable contract
│ └── Better security posture, no upgrade governance overhead
└── Hybrid → Immutable core + upgradeable periphery
Language Selection for EVM
EVM language choice:
├── Solidity (default for most projects)
│ ├── Pros: Largest ecosystem, most tutorials, OpenZeppelin libs
│ ├── Cons: More attack surface (implicit behavior, inheritance)
│ └── Best for: Complex protocols, composability-focused
├── Vyper (audit-first projects)
│ ├── Pros: Simpler, fewer foot-guns, explicit behavior
│ ├── Cons: Smaller ecosystem, limited libraries
│ └── Best for: Simple contracts, high-value vaults, DAO treasuries
└── Huff (low-level EVM)
├── Pros: Full control over bytecode, optimal gas
├── Cons: No safety rails, manual memory management
└── Best for: Gas-critical operations, precompile-like contracts
Architecture Patterns
Checks-Effects-Interactions (Mandatory)
function withdraw(uint256 amount) external {
// 1. CHECKS: validate conditions
require(balanceOf[msg.sender] >= amount, "insufficient balance");
// 2. EFFECTS: update state first
balanceOf[msg.sender] -= amount;
// 3. INTERACTIONS: external calls last
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "transfer failed");
}
Access Control Patterns
- Ownable: Single owner, simplest model
- Roles (OpenZeppelin AccessControl): DEFAULT_ADMIN_ROLE + specific roles (MINTER_ROLE, PAUSER_ROLE)
- Timelock: All sensitive operations delayed by 48h-7d
- Multi-sig: M-of-N signers for admin operations
Storage Layout Patterns
// Upgrade-safe storage layout
// 1. Always append new variables at the end
// 2. Never reorder or delete existing variables
// 3. Use gap arrays for future storage slots
contract BaseV1 {
uint256 public value1;
uint256 public value2;
uint256[50] private __gap; // Reserved for future upgrades
}
contract BaseV2 is BaseV1 {
uint256 public value3; // Appended, safe
uint256[49] private __gap; // Reduced by 1
}
Solidity Gas Optimization Patterns
// BAD: reads storage repeatedly
function sum() external view returns (uint) {
uint total = 0;
for (uint i = 0; i < arr.length; i++) {
total += arr[i]; // SLOAD every iteration
}
return total;
}
// GOOD: cache array length and use unchecked
function sum() external view returns (uint) {
uint len = arr.length;
uint total = 0;
for (uint i = 0; i < len; i++) {
unchecked { total += arr[i]; }
}
return total;
}
// Gas optimization techniques:
// 1. Use calldata instead of memory for read-only function params
// 2. Pack structs tightly (uint128 + uint128 saves slot)
// 3. Use custom errors instead of require strings
// 4. Short-circuit: check cheapest conditions first in require
// 5. Use Solady's LibString over OpenZeppelin for simple ops
error InsufficientBalance(uint256 available, uint256 required);
function optimizedTransfer(address to, uint256 amount) external {
uint256 bal = balanceOf[msg.sender]; // Cache storage
if (bal < amount) {
revert InsufficientBalance(bal, amount);
}
unchecked {
balanceOf[msg.sender] = bal - amount; // Safe due to check above
balanceOf[to] += amount;
}
}
Factory Pattern (Minimal Proxy)
// EIP-1167: Deploy minimal proxies (costs ~200 gas vs 500K for full contract)
contract Factory {
event CloneDeployed(address indexed clone, address indexed creator);
function createClone(address implementation) external returns (address clone) {
// ERC-1167 bytecode: 3D602D8060... (20 bytes implementation address embedded)
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
clone := create(0, ptr, 0x37)
}
require(clone != address(0), "CLONE_FAILED");
emit CloneDeployed(clone, msg.sender);
}
}
Cross-Contract Communication
EVM Call Patterns
EVM:
├── Direct call: Interface(target).function(args) — simple, synchronous
├── Delegatecall: Proxy pattern, upgradeable storage
├── Staticcall: Read-only external call (EIP-214)
└── Low-level: address.call{value, gas}(data) — for arbitrary calls
Solana:
├── CPI (Cross-Program Invocation): invoke() or invoke_signed()
└── PDA signing: Programs sign for PDAs via invoke_signed()
Cardano:
├── Script-to-script: Redeemer-based validation
└── One-shot contracts: eUTxO model, no persistent state
Move (Sui/Aptos):
├── Module imports: direct function calls within VM
└── Object transfers: sui::transfer for object ownership
Cross-Contract Error Handling
// Solidity: handle external call failures
function safeBatchTransfer(address[] calldata targets, bytes[] calldata data)
external returns (bool[] memory successes)
{
successes = new bool[](targets.length);
for (uint i = 0; i < targets.length; i++) {
(successes[i], ) = targets[i].call{gas: 10000}(data[i]);
// Don't revert on individual failure
}
}
Platform-Specific Patterns
EVM (Solidity)
- Storage: 32-byte slot-based, SSTORE costs 20K (cold) / 2.9K (warm)
- Events: emit for off-chain indexing, topics up to 4 (3 indexed + 1 non-indexed)
- ABI encoding: abi.encode (padded) vs abi.encodePacked (tight)
- Precompiles: ecrecover (0x01), SHA-256 (0x02), RIPEMD-160 (0x03), identity (0x04), modexp (0x05), BN254 (0x06, 0x07, 0x08), BLS12-381 (0x0a-0x0d)
- CREATE2: deterministic address deployment (same address across chains)
Solana (Rust + Anchor)
#[derive(Accounts)]
pub struct CreateUser<'info> {
#[account(init, payer = user, space = 8 + User::INIT_SPACE)]
pub user_account: Account<'info, User>,
#[account(mut)]
pub user: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[account]
pub struct User {
pub name: String,
pub age: u8,
}
Cardano (Plutus)
- eUTxO model: no global state, contracts are validators
- Datum: on-chain data locked at script address
- Redeemer: spending condition
- Script context: entire transaction context available to validator
- Plutus Tx: compile Haskell to Plutus Core (UPLC)
- Aiken: Rust-like language for Cardano (simpler than Haskell)
StarkNet (Cairo)
- Storage: contract-level storage variables, accessed via read()/write()
- UDC (Universal Deployer Contract): standardized contract deployment
- L1<>L2 messaging: send_message_to_l1, consume_message_from_l1
- Sierra: intermediate representation between Cairo and CASM
- Contract class: immutable code, deployed as instances
Move (Sui/Aptos)
- Resource-oriented: assets are resources, cannot be copied or dropped
- Object-centric (Sui): objects, not accounts, are the unit of storage
- Global storage (Aptos): Move modules manage access to globally stored resources
- Abilities: copy, drop, store, key — define what operations are allowed on a type
- Move Prover: formal verification for Move contracts
Security Patterns
Common Vulnerability Mitigations
| Vulnerability |
Mitigation |
| Reentrancy |
Checks-effects-interactions, ReentrancyGuard |
| Flash loan manipulation |
TWAP pricing, min/max output constraints |
| Oracle manipulation |
Redundant oracles, stale price checks, circuit breakers |
| Frontrunning |
Commit-reveal, submarine sends, FCFS ordering |
| Signature replay |
Include chain ID, contract address, nonce in EIP-712 |
| Access control |
Timelock + multi-sig, not single admin key |
| Integer overflow |
Solidity 0.8+ built-in checks, SafeMath for older |
| Uninitialized proxy |
Constructor + disableInitializers() |
| Storage collision |
EIP-1967 structured storage, no gap variables |
| ERC-4626 inflation |
Virtual shares + assets on first deposit |
Production Considerations
Deployment Checklist
Multi-Chain Deployment
- Deterministic addresses via CREATE2 (same address on all EVM chains)
- Proxy admin same address on all chains via CREATE2
- Deployment scripts idempotent (check if already deployed)
- Cross-chain governance for upgrade coordination
- L1 as source of truth, L2 as execution layer
Gas Budget Guidelines (EVM)
- Simple transfer: 21,000 gas
- ERC-20 transfer: ~50,000 gas
- ERC-721 mint: ~100,000 gas
- Uniswap swap: ~150,000 gas
- Complex AMM operation: ~300,000 gas
- L1 block gas limit: 30M (Ethereum)
- L2 block gas limit: 30M-1B (depends on L2)
Rules
- Use Solidity for EVM chains (Ethereum, Polygon, Arbitrum, Optimism, Base, BSC)
- Use Rust for Solana (Anchor framework as default), NEAR, and Polkadot ink!
- Use Haskell/Plutus for Cardano smart contracts
- Always follow checks-effects-interactions pattern regardless of language
- Use Foundry (forge) for Solidity development and testing as default toolchain
- Include gas optimization in every code review — storage is expensive, calldata is cheaper
- Never hardcode sensitive parameters — use constructor args, setters with timelock
- Default to UUPS for upgradeable contracts over transparent proxy
- Use OpenZeppelin audited libraries over custom implementations
- Always use explicit visibility (public, external, internal, private)
- Avoid tx.origin for authentication — use msg.sender
- Validate all external inputs with require or custom errors
- Emit events for all state-changing operations
- Test on testnet with real conditions before mainnet
- Transfer ownership to multi-sig or timelock, not EOA
- Use calldata over memory for read-only function parameters
- Pack storage variables tightly (uint128 + uint128, address + uint64)
- Prefer ERC-1167 minimal proxies for cheap contract cloning
- Use CREATE2 for deterministic addresses across chains
- Always include reentrancy guards on cross-chain message handlers
References
- references/blockchain-application-advanced.md — Blockchain Application Advanced Topics
- references/blockchain-application-fundamentals.md — Blockchain Application Fundamentals
- references/cairo-language.md — Cairo Language (StarkNet)
- references/contract-security.md — Smart Contract Security
- references/haskell-plutus.md — Haskell & Plutus (Cardano)
- references/move-language.md — Move Language (Sui & Aptos)
- references/rust-smart-contracts.md — Rust Smart Contracts
- references/smart-contract-patterns.md — Smart Contract Design Patterns
- references/solidity-evm.md — Solidity & EVM Deep Dive
- references/vyper-language.md — Vyper Language
- references/cross-chain-deployment.md — Cross-Chain Deployment Strategy
- references/gas-optimization-patterns.md — Gas Optimization Techniques
Implementation Examples
Solidity — Gas-Optimized ERC-20
contract OptimizedToken {
uint256 public totalSupply;
string public name;
string public symbol;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
constructor(string memory _name, string memory _symbol) {
name = _name; symbol = _symbol;
}
function transfer(address to, uint256 amount) external returns (bool) {
balanceOf[msg.sender] -= amount;
balanceOf[to] += amount;
emit Transfer(msg.sender, to, amount);
return true;
}
event Transfer(address indexed from, address indexed to, uint256 amount);
}
Solana Anchor Program
use anchor_lang::prelude::*;
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
#[program]
pub mod counter {
use super::*;
pub fn increment(ctx: Context<Increment>) -> Result<()> {
ctx.accounts.counter.count += 1;
Ok(())
}
}
#[derive(Accounts)]
pub struct Increment<'info> {
#[account(mut, seeds = [b"counter", authority.key().as_ref()], bump)]
pub counter: Account<'info, CounterState>,
pub authority: Signer<'info>,
}
#[account]
pub struct CounterState { pub count: u64, pub authority: Pubkey }
Phase
blockchain → blockchain-application
Architecture Decision Trees
Blockchain Application Design
├── Application type?
│ ├── DeFi → DEX, lending, yield aggregator
│ ├── NFT → Marketplace, collection, gaming
│ ├── DAO → Governance, treasury, voting
│ └── Identity → SSI, verifiable credentials, attestations
├── Smart contract language?
│ ├── Solidity (most mature) → EVM chains (Ethereum, Polygon, Arbitrum)
│ ├── Rust → Solana / NEAR / Polkadot (high performance)
│ └── Move → Sui / Aptos (parallel execution)
├── Upgradeability?
│ ├── Yes → UUPS / Transparent proxy pattern
│ ├── Yes (immutable core) → Diamond pattern (EIP-2535)
│ └── No → Minimal proxy + migration strategy
└── Gas optimization priority?
├── Critical → Optimize storage layout, batch operations, use ERC-2612
├── Moderate → Standard patterns, avoid loops
└── Low → Focus on correctness first
Decision criteria: Evaluate target chain, development team experience, security requirements, and upgrade path.
Implementation Patterns
UUPS Upgradeable Contract
// blockchain-application/contracts/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract MyApp is UUPSUpgradeable, OwnableUpgradeable {
uint256 public value;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() { _disableInitializers(); }
function initialize(address owner_) initializer external {
__UUPSUpgradeable_init();
__Ownable_init(owner_);
}
function setValue(uint256 _value) external onlyOwner { value = _value; }
function _authorizeUpgrade(address) internal override onlyOwner {}
}
Minimal Proxy (EIP-1167)
// blockchain-application/contracts/CloneFactory.sol
contract CloneFactory {
event CloneCreated(address indexed clone, address indexed implementation);
function createClone(address implementation) external returns (address) {
bytes20 implBytes = bytes20(implementation);
address clone;
assembly {
let cloneData := mload(0x40)
mstore(cloneData, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(cloneData, 0x14), implBytes)
mstore(add(cloneData, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
clone := create(0, cloneData, 0x37)
}
emit CloneCreated(clone, implementation);
}
}
Production Considerations
- Proxy admin: Use TimelockController for proxy upgrades; require multisig approval for production.
- Pausability: Implement OpenZeppelin Pausable; pause on critical vulnerability detection.
- Emergency stop: Circuit breaker pattern; owner can halt critical functions in case of exploit.
- Gas limits: Test on testnet with realistic gas prices; monitor gas consumption on mainnet.
- Event emissions: Emit events for all state-changing operations; index address and uint256 parameters.
- Fork detection: Use VRF or Chainlink to detect L1 reorgs on L2 deployments.
Anti-Patterns
| Anti-Pattern |
Consequence |
Solution |
Using tx.origin for auth |
Phishing attacks |
Use msg.sender always |
| Unchecked external calls |
Silent failures |
Check return values of .call{value: }() |
| Storage collision in upgrades |
Corrupted state |
Use structured storage (EIP-1967, UUPS) |
| Owner-only functions without timelock |
Single-key compromise risk |
Use multisig + timelock |
| No reentrancy guard |
Reentrancy exploits |
Apply ReentrancyGuard on all external functions |
Performance Optimization
- Storage packing: Pack related variables in same slot (
uint128 + uint128); use struct for related fields.
- Batch operations: Batch transfers (Multicall, batch ERC-20 transfers) to amortize overhead.
- Calldata optimization: Use
calldata instead of memory for read-only function parameters.
- Immutable variables: Use
immutable for constructor-set constants to save SSTORE costs.
- EIP-2612 permits: Use permit() for gasless approvals; batch approve + transferFrom.
Security Considerations
- Access control: Use OpenZeppelin
AccessControl with roles; never rely on onlyOwner alone.
- Oracle manipulation: Use TWAP or multiple oracle sources for price feeds; never single source.
- Flash loan resistance: Check oracle price deviation; use time-weighted average prices.
- Signature replay: Include
nonce, deadline, and chainId in EIP-712 signatures.
- Upgrade safety: Test upgrades on fork; use
oz upgrade validator; never upgrade without timelock.
Handoff
blockchain-application → blockchain-testing (for test strategy implementation)
blockchain-application → blockchain-security (for pre-audit review)
1---2name: blockchain-application3description: Use this skill when asked about smart contract development, Solidity, Vyper, Rust smart contracts (Solana, NEAR, Polkadot), Haskell/Plutus (Cardano), Cairo/StarkNet, dApp backend development, Truffle, Hardhat, Foundry, Anchor, and blockchain application patterns. Languages: Solidity, Vyper, Rust, Haskell, Cairo, Move. Covers EVM-based development (Ethereum, Polygon, Arbitrum, Optimism), SVM-based development (Solana), eUTxO-based development (Cardano), StarkNet/STARK-based development (Cairo), smart contract security, gas optimization, upgradeable contracts, and cross-contract communication. Do NOT use for: blockchain core protocol (use blockchain-core), web3 frontend (use blockchain-web3), or testing (use blockchain-testing).4license: MIT5---67# Blockchain Application89## Purpose10Guide smart contract development across all major blockchain platforms. Covers language selection, contract architecture, security patterns, gas optimization, deployment, and cross-contract communication. Platform-agnostic at the protocol layer; chain-specific at the language and VM layer.1112## Agent Protocol1314### Trigger15"smart contract", "solidity", "vyper", "evm", "rust smart contract", "solana contract", "anchor framework", "cardano", "plutus", "haskell contract", "cairo", "starknet", "sierra", "hardhat", "foundry", "truffle", "dapp backend", "contract deployment", "gas optimization", "contract security", "cross-contract call", "chainlink", "oracle contract", "defi contract", "nft contract", "move language", "sui contract", "aptos contract"1617### Input Context18- Target blockchain and VM type (EVM/SVM/eUTxO/StarkNet/MoveVM)19- Contract purpose (token/DeFi/NFT/oracle/governance/bridge)20- Upgradeability requirements (proxy/non-upgradeable/beacon)21- Security requirements (audit level, formal verification need)22- Performance constraints (gas budget, compute units, TPS needs)23- Existing dependencies (OpenZeppelin, Anchor libraries, Plutus contracts)2425### Output Artifact26Complete contract architecture specification: platform selection, contract design, implementation approach, testing strategy, deployment plan, security analysis.2728### Response Format291. **Platform selection**: chain type + VM + language + framework + toolchain302. **Contract architecture**: entry points, storage layout, external dependencies, upgradeability313. **Implementation**: key functions with gas considerations and security annotations324. **Testing strategy**: unit, integration, fuzz, invariant, testnet deployment335. **Deployment**: constructor args, verification, proxy setup, multi-sig ownership346. **Risk analysis**: known vulnerabilities specific to this platform/pattern3536### Completion Criteria37- Contract architecture follows platform best practices (checks-effects-interactions, access control)38- Storage layout compatible with upgradeability pattern (if upgradeable)39- Gas optimization applied: storage reads minimized, calldata over memory where possible40- Security review covers platform-specific attack vectors (reentrancy, oracle manipulation, flash loans)41- Deployment plan includes verification, multi-sig ownership, and monitoring4243### Max Response Length445000 tokens4546## Decision Trees4748### Platform Selection49```50Smart contract platform:51├── Need EVM compatibility?52│ ├── YES → Solidity or Vyper53│ │ ├── Solidity: EVM chains (Ethereum, Polygon, Arbitrum, Optimism, Base, BSC)54│ │ │ ├── Toolchain: Foundry (default), Hardhat (complex workflows)55│ │ │ └── Libraries: OpenZeppelin, Solady56│ │ └── Vyper: Simple contracts, audit-friendliness prioritized57│ │ └── Toolchain: ape, brownie58│ ├── NO → Evaluate non-EVM chains59│ │ ├── Solana → Rust + Anchor framework60│ │ │ └── Toolchain: Anchor CLI, Solana CLI61│ │ ├── Cardano → Haskell (Plutus) or Aiken62│ │ │ └── Toolchain: Plutus Tx, cardano-cli63│ │ ├── StarkNet → Cairo64│ │ │ └── Toolchain: Scarb, Starkli65│ │ ├── Sui/Aptos → Move66│ │ │ └── Toolchain: sui CLI / aptos CLI67│ │ └── NEAR/Polkadot → Rust (ink!)68│ │ └── Toolchain: cargo-contract69│ └── Cross-chain? → Consider platform-agnostic architecture70│ └── Abstract core logic, deploy adapters per chain71```7273### Upgradeability Decision74```75Need upgradeable contract?76├── YES:77│ ├── UUPS → Default for new projects (gas-efficient, clean storage)78│ ├── Transparent → Legacy projects, many upgrade functions79│ └── Beacon → Many child contracts (ERC-1167 clones)80├── NO → Immutable contract81│ └── Better security posture, no upgrade governance overhead82└── Hybrid → Immutable core + upgradeable periphery83```8485### Language Selection for EVM86```87EVM language choice:88├── Solidity (default for most projects)89│ ├── Pros: Largest ecosystem, most tutorials, OpenZeppelin libs90│ ├── Cons: More attack surface (implicit behavior, inheritance)91│ └── Best for: Complex protocols, composability-focused92├── Vyper (audit-first projects)93│ ├── Pros: Simpler, fewer foot-guns, explicit behavior94│ ├── Cons: Smaller ecosystem, limited libraries95│ └── Best for: Simple contracts, high-value vaults, DAO treasuries96└── Huff (low-level EVM)97 ├── Pros: Full control over bytecode, optimal gas98 ├── Cons: No safety rails, manual memory management99 └── Best for: Gas-critical operations, precompile-like contracts100```101102## Architecture Patterns103104### Checks-Effects-Interactions (Mandatory)105```solidity106function withdraw(uint256 amount) external {107 // 1. CHECKS: validate conditions108 require(balanceOf[msg.sender] >= amount, "insufficient balance");109110 // 2. EFFECTS: update state first111 balanceOf[msg.sender] -= amount;112113 // 3. INTERACTIONS: external calls last114 (bool ok, ) = msg.sender.call{value: amount}("");115 require(ok, "transfer failed");116}117```118119### Access Control Patterns120- **Ownable**: Single owner, simplest model121- **Roles (OpenZeppelin AccessControl)**: DEFAULT_ADMIN_ROLE + specific roles (MINTER_ROLE, PAUSER_ROLE)122- **Timelock**: All sensitive operations delayed by 48h-7d123- **Multi-sig**: M-of-N signers for admin operations124125### Storage Layout Patterns126```solidity127// Upgrade-safe storage layout128// 1. Always append new variables at the end129// 2. Never reorder or delete existing variables130// 3. Use gap arrays for future storage slots131132contract BaseV1 {133 uint256 public value1;134 uint256 public value2;135 uint256[50] private __gap; // Reserved for future upgrades136}137138contract BaseV2 is BaseV1 {139 uint256 public value3; // Appended, safe140 uint256[49] private __gap; // Reduced by 1141}142```143144### Solidity Gas Optimization Patterns145```solidity146// BAD: reads storage repeatedly147function sum() external view returns (uint) {148 uint total = 0;149 for (uint i = 0; i < arr.length; i++) {150 total += arr[i]; // SLOAD every iteration151 }152 return total;153}154155// GOOD: cache array length and use unchecked156function sum() external view returns (uint) {157 uint len = arr.length;158 uint total = 0;159 for (uint i = 0; i < len; i++) {160 unchecked { total += arr[i]; }161 }162 return total;163}164165// Gas optimization techniques:166// 1. Use calldata instead of memory for read-only function params167// 2. Pack structs tightly (uint128 + uint128 saves slot)168// 3. Use custom errors instead of require strings169// 4. Short-circuit: check cheapest conditions first in require170// 5. Use Solady's LibString over OpenZeppelin for simple ops171172error InsufficientBalance(uint256 available, uint256 required);173174function optimizedTransfer(address to, uint256 amount) external {175 uint256 bal = balanceOf[msg.sender]; // Cache storage176 if (bal < amount) {177 revert InsufficientBalance(bal, amount);178 }179 unchecked {180 balanceOf[msg.sender] = bal - amount; // Safe due to check above181 balanceOf[to] += amount;182 }183}184```185186### Factory Pattern (Minimal Proxy)187```solidity188// EIP-1167: Deploy minimal proxies (costs ~200 gas vs 500K for full contract)189contract Factory {190 event CloneDeployed(address indexed clone, address indexed creator);191192 function createClone(address implementation) external returns (address clone) {193 // ERC-1167 bytecode: 3D602D8060... (20 bytes implementation address embedded)194 assembly {195 let ptr := mload(0x40)196 mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)197 mstore(add(ptr, 0x14), shl(0x60, implementation))198 mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)199 clone := create(0, ptr, 0x37)200 }201 require(clone != address(0), "CLONE_FAILED");202 emit CloneDeployed(clone, msg.sender);203 }204}205```206207## Cross-Contract Communication208209### EVM Call Patterns210```211EVM:212├── Direct call: Interface(target).function(args) — simple, synchronous213├── Delegatecall: Proxy pattern, upgradeable storage214├── Staticcall: Read-only external call (EIP-214)215└── Low-level: address.call{value, gas}(data) — for arbitrary calls216217Solana:218├── CPI (Cross-Program Invocation): invoke() or invoke_signed()219└── PDA signing: Programs sign for PDAs via invoke_signed()220221Cardano:222├── Script-to-script: Redeemer-based validation223└── One-shot contracts: eUTxO model, no persistent state224225Move (Sui/Aptos):226├── Module imports: direct function calls within VM227└── Object transfers: sui::transfer for object ownership228```229230### Cross-Contract Error Handling231```solidity232// Solidity: handle external call failures233function safeBatchTransfer(address[] calldata targets, bytes[] calldata data)234 external returns (bool[] memory successes)235{236 successes = new bool[](targets.length);237 for (uint i = 0; i < targets.length; i++) {238 (successes[i], ) = targets[i].call{gas: 10000}(data[i]);239 // Don't revert on individual failure240 }241}242```243244## Platform-Specific Patterns245246### EVM (Solidity)247- Storage: 32-byte slot-based, SSTORE costs 20K (cold) / 2.9K (warm)248- Events: emit for off-chain indexing, topics up to 4 (3 indexed + 1 non-indexed)249- ABI encoding: abi.encode (padded) vs abi.encodePacked (tight)250- Precompiles: ecrecover (0x01), SHA-256 (0x02), RIPEMD-160 (0x03), identity (0x04), modexp (0x05), BN254 (0x06, 0x07, 0x08), BLS12-381 (0x0a-0x0d)251- CREATE2: deterministic address deployment (same address across chains)252253### Solana (Rust + Anchor)254```rust255#[derive(Accounts)]256pub struct CreateUser<'info> {257 #[account(init, payer = user, space = 8 + User::INIT_SPACE)]258 pub user_account: Account<'info, User>,259 #[account(mut)]260 pub user: Signer<'info>,261 pub system_program: Program<'info, System>,262}263264#[account]265pub struct User {266 pub name: String,267 pub age: u8,268}269```270271### Cardano (Plutus)272- eUTxO model: no global state, contracts are validators273- Datum: on-chain data locked at script address274- Redeemer: spending condition275- Script context: entire transaction context available to validator276- Plutus Tx: compile Haskell to Plutus Core (UPLC)277- Aiken: Rust-like language for Cardano (simpler than Haskell)278279### StarkNet (Cairo)280- Storage: contract-level storage variables, accessed via read()/write()281- UDC (Universal Deployer Contract): standardized contract deployment282- L1<>L2 messaging: send_message_to_l1, consume_message_from_l1283- Sierra: intermediate representation between Cairo and CASM284- Contract class: immutable code, deployed as instances285286### Move (Sui/Aptos)287- Resource-oriented: assets are resources, cannot be copied or dropped288- Object-centric (Sui): objects, not accounts, are the unit of storage289- Global storage (Aptos): Move modules manage access to globally stored resources290- Abilities: copy, drop, store, key — define what operations are allowed on a type291- Move Prover: formal verification for Move contracts292293## Security Patterns294295### Common Vulnerability Mitigations296| Vulnerability | Mitigation |297|---|---|298| Reentrancy | Checks-effects-interactions, ReentrancyGuard |299| Flash loan manipulation | TWAP pricing, min/max output constraints |300| Oracle manipulation | Redundant oracles, stale price checks, circuit breakers |301| Frontrunning | Commit-reveal, submarine sends, FCFS ordering |302| Signature replay | Include chain ID, contract address, nonce in EIP-712 |303| Access control | Timelock + multi-sig, not single admin key |304| Integer overflow | Solidity 0.8+ built-in checks, SafeMath for older |305| Uninitialized proxy | Constructor + disableInitializers() |306| Storage collision | EIP-1967 structured storage, no gap variables |307| ERC-4626 inflation | Virtual shares + assets on first deposit |308309## Production Considerations310311### Deployment Checklist312- [ ] Constructor args verified and tested313- [ ] Proxy admin transferred to multi-sig (not deployer EOA)314- [ ] Implementation contract initialized and disabled315- [ ] Contract verified on block explorer316- [ ] Ownership transferred to timelock + governance317- [ ] Emergency pause mechanism tested318- [ ] Rate limits configured for high-value functions319- [ ] Monitoring alerts set up for suspicious activity320321### Multi-Chain Deployment322- Deterministic addresses via CREATE2 (same address on all EVM chains)323- Proxy admin same address on all chains via CREATE2324- Deployment scripts idempotent (check if already deployed)325- Cross-chain governance for upgrade coordination326- L1 as source of truth, L2 as execution layer327328### Gas Budget Guidelines (EVM)329- Simple transfer: 21,000 gas330- ERC-20 transfer: ~50,000 gas331- ERC-721 mint: ~100,000 gas332- Uniswap swap: ~150,000 gas333- Complex AMM operation: ~300,000 gas334- L1 block gas limit: 30M (Ethereum)335- L2 block gas limit: 30M-1B (depends on L2)336337## Rules3381. Use Solidity for EVM chains (Ethereum, Polygon, Arbitrum, Optimism, Base, BSC)3392. Use Rust for Solana (Anchor framework as default), NEAR, and Polkadot ink!3403. Use Haskell/Plutus for Cardano smart contracts3414. Always follow checks-effects-interactions pattern regardless of language3425. Use Foundry (forge) for Solidity development and testing as default toolchain3436. Include gas optimization in every code review — storage is expensive, calldata is cheaper3447. Never hardcode sensitive parameters — use constructor args, setters with timelock3458. Default to UUPS for upgradeable contracts over transparent proxy3469. Use OpenZeppelin audited libraries over custom implementations34710. Always use explicit visibility (public, external, internal, private)34811. Avoid tx.origin for authentication — use msg.sender34912. Validate all external inputs with require or custom errors35013. Emit events for all state-changing operations35114. Test on testnet with real conditions before mainnet35215. Transfer ownership to multi-sig or timelock, not EOA35316. Use calldata over memory for read-only function parameters35417. Pack storage variables tightly (uint128 + uint128, address + uint64)35518. Prefer ERC-1167 minimal proxies for cheap contract cloning35619. Use CREATE2 for deterministic addresses across chains35720. Always include reentrancy guards on cross-chain message handlers358359## References360 - references/blockchain-application-advanced.md — Blockchain Application Advanced Topics361 - references/blockchain-application-fundamentals.md — Blockchain Application Fundamentals362 - references/cairo-language.md — Cairo Language (StarkNet)363 - references/contract-security.md — Smart Contract Security364 - references/haskell-plutus.md — Haskell & Plutus (Cardano)365 - references/move-language.md — Move Language (Sui & Aptos)366 - references/rust-smart-contracts.md — Rust Smart Contracts367 - references/smart-contract-patterns.md — Smart Contract Design Patterns368 - references/solidity-evm.md — Solidity & EVM Deep Dive369 - references/vyper-language.md — Vyper Language370 - references/cross-chain-deployment.md — Cross-Chain Deployment Strategy371 - references/gas-optimization-patterns.md — Gas Optimization Techniques372373## Implementation Examples374375### Solidity — Gas-Optimized ERC-20376```solidity377contract OptimizedToken {378 uint256 public totalSupply;379 string public name;380 string public symbol;381 mapping(address => uint256) public balanceOf;382 mapping(address => mapping(address => uint256)) public allowance;383384 constructor(string memory _name, string memory _symbol) {385 name = _name; symbol = _symbol;386 }387388 function transfer(address to, uint256 amount) external returns (bool) {389 balanceOf[msg.sender] -= amount;390 balanceOf[to] += amount;391 emit Transfer(msg.sender, to, amount);392 return true;393 }394 event Transfer(address indexed from, address indexed to, uint256 amount);395}396```397398### Solana Anchor Program399```rust400use anchor_lang::prelude::*;401declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");402403#[program]404pub mod counter {405 use super::*;406 pub fn increment(ctx: Context<Increment>) -> Result<()> {407 ctx.accounts.counter.count += 1;408 Ok(())409 }410}411412#[derive(Accounts)]413pub struct Increment<'info> {414 #[account(mut, seeds = [b"counter", authority.key().as_ref()], bump)]415 pub counter: Account<'info, CounterState>,416 pub authority: Signer<'info>,417}418419#[account]420pub struct CounterState { pub count: u64, pub authority: Pubkey }421```422423## Phase424blockchain → blockchain-application425426## Architecture Decision Trees427428```429Blockchain Application Design430├── Application type?431│ ├── DeFi → DEX, lending, yield aggregator432│ ├── NFT → Marketplace, collection, gaming433│ ├── DAO → Governance, treasury, voting434│ └── Identity → SSI, verifiable credentials, attestations435├── Smart contract language?436│ ├── Solidity (most mature) → EVM chains (Ethereum, Polygon, Arbitrum)437│ ├── Rust → Solana / NEAR / Polkadot (high performance)438│ └── Move → Sui / Aptos (parallel execution)439├── Upgradeability?440│ ├── Yes → UUPS / Transparent proxy pattern441│ ├── Yes (immutable core) → Diamond pattern (EIP-2535)442│ └── No → Minimal proxy + migration strategy443└── Gas optimization priority?444 ├── Critical → Optimize storage layout, batch operations, use ERC-2612445 ├── Moderate → Standard patterns, avoid loops446 └── Low → Focus on correctness first447```448449**Decision criteria**: Evaluate target chain, development team experience, security requirements, and upgrade path.450451## Implementation Patterns452453### UUPS Upgradeable Contract454```solidity455// blockchain-application/contracts/UUPSUpgradeable.sol456// SPDX-License-Identifier: MIT457pragma solidity ^0.8.20;458459import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";460import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";461462contract MyApp is UUPSUpgradeable, OwnableUpgradeable {463 uint256 public value;464465 /// @custom:oz-upgrades-unsafe-allow constructor466 constructor() { _disableInitializers(); }467468 function initialize(address owner_) initializer external {469 __UUPSUpgradeable_init();470 __Ownable_init(owner_);471 }472473 function setValue(uint256 _value) external onlyOwner { value = _value; }474475 function _authorizeUpgrade(address) internal override onlyOwner {}476}477```478479### Minimal Proxy (EIP-1167)480```solidity481// blockchain-application/contracts/CloneFactory.sol482contract CloneFactory {483 event CloneCreated(address indexed clone, address indexed implementation);484485 function createClone(address implementation) external returns (address) {486 bytes20 implBytes = bytes20(implementation);487 address clone;488 assembly {489 let cloneData := mload(0x40)490 mstore(cloneData, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)491 mstore(add(cloneData, 0x14), implBytes)492 mstore(add(cloneData, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)493 clone := create(0, cloneData, 0x37)494 }495 emit CloneCreated(clone, implementation);496 }497}498```499500## Production Considerations501502- **Proxy admin**: Use TimelockController for proxy upgrades; require multisig approval for production.503- **Pausability**: Implement OpenZeppelin Pausable; pause on critical vulnerability detection.504- **Emergency stop**: Circuit breaker pattern; owner can halt critical functions in case of exploit.505- **Gas limits**: Test on testnet with realistic gas prices; monitor gas consumption on mainnet.506- **Event emissions**: Emit events for all state-changing operations; index address and uint256 parameters.507- **Fork detection**: Use VRF or Chainlink to detect L1 reorgs on L2 deployments.508509## Anti-Patterns510511| Anti-Pattern | Consequence | Solution |512|---|---|---|513| Using `tx.origin` for auth | Phishing attacks | Use `msg.sender` always |514| Unchecked external calls | Silent failures | Check return values of `.call{value: }()` |515| Storage collision in upgrades | Corrupted state | Use structured storage (EIP-1967, UUPS) |516| Owner-only functions without timelock | Single-key compromise risk | Use multisig + timelock |517| No reentrancy guard | Reentrancy exploits | Apply `ReentrancyGuard` on all external functions |518519## Performance Optimization520521- **Storage packing**: Pack related variables in same slot (`uint128 + uint128`); use `struct` for related fields.522- **Batch operations**: Batch transfers (Multicall, batch ERC-20 transfers) to amortize overhead.523- **Calldata optimization**: Use `calldata` instead of `memory` for read-only function parameters.524- **Immutable variables**: Use `immutable` for constructor-set constants to save SSTORE costs.525- **EIP-2612 permits**: Use permit() for gasless approvals; batch approve + transferFrom.526527## Security Considerations528529- **Access control**: Use OpenZeppelin `AccessControl` with roles; never rely on `onlyOwner` alone.530- **Oracle manipulation**: Use TWAP or multiple oracle sources for price feeds; never single source.531- **Flash loan resistance**: Check oracle price deviation; use time-weighted average prices.532- **Signature replay**: Include `nonce`, `deadline`, and `chainId` in EIP-712 signatures.533- **Upgrade safety**: Test upgrades on fork; use `oz upgrade` validator; never upgrade without timelock.534535## Handoff536blockchain-application → blockchain-testing (for test strategy implementation)537blockchain-application → blockchain-security (for pre-audit review)