# QWVM Overview

## What is QWVM?

**QWVM (QuantumWing Virtual Machine)** is a WebAssembly-based smart contract execution environment with quantum-safe host functions and metered gas execution.

{% hint style="info" %}
**Status**: Production-ready (87/100) | **Gas Model**: EVM-compatible | **Language**: WebAssembly (Wasm)
{% endhint %}

## Why WebAssembly?

| Feature              | WebAssembly                      | EVM                  |
| -------------------- | -------------------------------- | -------------------- |
| **Performance**      | Near-native speed                | Interpreted bytecode |
| **Language Support** | Rust, C, C++, Go, AssemblyScript | Solidity only        |
| **Security**         | Sandboxed by design              | Custom VM            |
| **Tooling**          | LLVM ecosystem                   | Custom toolchain     |
| **Binary Size**      | Compact (10-100 KB)              | Larger bytecode      |

## Architecture

```
┌─────────────────────────────────────────────────────┐
│              QWVM EXECUTION ENVIRONMENT             │
│                                                     │
│  ┌───────────────────────────────────────────────┐ │
│  │  Smart Contract (WebAssembly Module)         │ │
│  │                                               │ │
│  │  ┌─────────────┐    ┌──────────────┐        │ │
│  │  │   Memory    │    │   Imports    │        │ │
│  │  │  (Linear)   │    │ (Host Funcs) │        │ │
│  │  └─────────────┘    └──────────────┘        │ │
│  │                                               │ │
│  │  ┌─────────────────────────────────────────┐ │ │
│  │  │  Exported Functions:                    │ │ │
│  │  │  • init()                               │ │ │
│  │  │  • execute(method, args)                │ │ │
│  │  │  • query(method, args)                  │ │ │
│  │  └─────────────────────────────────────────┘ │ │
│  └───────────────────────────────────────────────┘ │
│                          │                          │
│                          ▼                          │
│  ┌───────────────────────────────────────────────┐ │
│  │        Wasmer Runtime (JIT Compiler)          │ │
│  │  • Memory management                          │ │
│  │  • Gas metering                               │ │
│  │  • Stack overflow protection                  │ │
│  └───────────────────────────────────────────────┘ │
│                          │                          │
└──────────────────────────┼──────────────────────────┘
                           ▼
┌─────────────────────────────────────────────────────┐
│              QUANTUM-SAFE HOST FUNCTIONS            │
│                                                     │
│  • qw_storage_read(key) → value                    │
│  • qw_storage_write(key, value)                    │
│  • qw_dilithium_verify(msg, sig, pubkey) → bool   │
│  • qw_sha3_256(data) → hash                        │
│  • qw_get_caller() → address                       │
│  • qw_get_balance(address) → uint256               │
│  • qw_transfer(to, amount)                         │
│  • qw_emit_event(topic, data)                      │
│  • qw_call_contract(addr, method, args) → result   │
└─────────────────────────────────────────────────────┘
```

## Gas Metering

Every Wasm instruction consumes gas to prevent infinite loops:

```go
// Gas costs (in gas units)
const (
    GasPerWasmInstruction = 1      // Base instruction cost
    GasPerMemoryGrow      = 100    // Growing Wasm memory
    GasPerStorageRead     = 200    // Reading from state
    GasPerStorageWrite    = 5000   // Writing to state
    GasPerDilithiumVerify = 50000  // Signature verification
    GasPerSHA3            = 30     // Hashing per byte
    GasPerTransfer        = 21000  // Token transfer
)
```

### Example: Gas Calculation

```rust
// Rust smart contract
#[no_mangle]
pub extern "C" fn execute() {
    let caller = qw_get_caller();        // 200 gas (storage read)
    let balance = qw_get_balance(caller); // 200 gas (storage read)
    
    // Loop costs: 10 * (1 + 30) = 310 gas
    for i in 0..10 {
        qw_sha3_256(&[i]);               // 30 gas per iteration
    }
    
    qw_storage_write(key, value);        // 5000 gas (storage write)
    
    // Total: 200 + 200 + 310 + 5000 = 5710 gas
}
```

## Contract Lifecycle

### 1. **Compilation**

```bash
# Compile Rust to Wasm
cargo build --target wasm32-unknown-unknown --release

# Optimize Wasm binary (reduce size by ~70%)
wasm-opt -Oz -o counter_opt.wasm target/wasm32-unknown-unknown/release/counter.wasm
```

### 2. **Deployment**

```bash
# Deploy contract to QuantumWing
quantum-wing contract deploy \
  --wasm counter_opt.wasm \
  --init-args '{"initial_value": 0}' \
  --gas-limit 1000000 \
  --from wallet.json
```

**Output**:

```json
{
  "tx_hash": "0xabcd1234...",
  "contract_address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5",
  "gas_used": 234567,
  "status": "success"
}
```

### 3. **Execution**

```bash
# Call contract method
quantum-wing contract call \
  --address 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5 \
  --method "increment" \
  --args '{"amount": 5}' \
  --gas-limit 100000 \
  --from wallet.json
```

### 4. **Query (Read-Only)**

```bash
# Query contract state (no gas cost)
quantum-wing contract query \
  --address 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5 \
  --method "get_count"
```

**Output**:

```json
{
  "result": 42,
  "type": "uint64"
}
```

## Contract Metadata (On-Chain)

**Status**: ✅ Production-ready (November 2025)

### Purpose

Contract metadata is stored **on-chain in contract storage** (not hardcoded in explorer), making it verifiable and decentralized.

### Metadata Keys

```
metadata:name         → Contract human-readable name
metadata:symbol       → Token symbol (for ERC-20/721)
metadata:type         → Contract type (erc20, erc721, governance, etc.)
metadata:decimals     → Token decimals (for ERC-20)
metadata:description  → Contract purpose description
```

### Deployment with Metadata

**Deploy QWETH Example:**

```bash
quantum-wing contract deploy \
  --wasm qweth.wasm \
  --metadata name="Quantum Wrapped ETH" \
  --metadata symbol="QWETH" \
  --metadata type="erc20" \
  --metadata decimals="18" \
  --metadata description="ERC-20 wrapped Ethereum bridged from Sepolia" \
  --from bridge-operator.json
```

### Querying Metadata

**Via API:**

```bash
curl http://localhost:8546/api/v1/contract/0x742d35.../metadata
```

**Response:**

```json
{
  "success": true,
  "metadata": {
    "name": "Quantum Wrapped ETH",
    "symbol": "QWETH",
    "type": "erc20",
    "decimals": "18",
    "description": "ERC-20 wrapped Ethereum bridged from Sepolia"
  }
}
```

### Storage Format

* **Keys**: UTF-8 string with `metadata:` prefix, hex-encoded for API
* **Values**: UTF-8 string, base64-encoded in contract storage
* **Retrieval**: Standard storage query (`qw_storage_read("metadata:name")`)

### Benefits

* ✅ **Decentralized** - No hardcoded explorer files
* ✅ **Verifiable** - Anyone can query on-chain
* ✅ **Flexible** - Add custom metadata keys
* ✅ **Standard** - Etherscan-style metadata format

## Example Contract: Counter

### Rust Source Code

```rust
use std::collections::HashMap;

// Import host functions
extern "C" {
    fn qw_storage_read(key_ptr: *const u8, key_len: u32) -> i64;
    fn qw_storage_write(key_ptr: *const u8, key_len: u32, value_ptr: *const u8, value_len: u32);
    fn qw_get_caller(ptr: *mut u8);
}

// Global state (stored in Wasm memory)
static mut COUNTER: u64 = 0;

#[no_mangle]
pub extern "C" fn init() {
    unsafe {
        COUNTER = 0;
    }
}

#[no_mangle]
pub extern "C" fn increment(amount: u64) {
    unsafe {
        COUNTER += amount;
        
        // Persist to blockchain storage
        let key = b"counter";
        let value = COUNTER.to_le_bytes();
        qw_storage_write(
            key.as_ptr(), key.len() as u32,
            value.as_ptr(), value.len() as u32
        );
    }
}

#[no_mangle]
pub extern "C" fn get_count() -> u64 {
    unsafe { COUNTER }
}

#[no_mangle]
pub extern "C" fn execute(method_ptr: *const u8, method_len: u32, args_ptr: *const u8, args_len: u32) {
    let method = unsafe {
        std::str::from_utf8_unchecked(std::slice::from_raw_parts(method_ptr, method_len as usize))
    };
    
    match method {
        "increment" => {
            let amount = u64::from_le_bytes([/* parse args */]);
            increment(amount);
        },
        _ => panic!("Unknown method"),
    }
}

#[no_mangle]
pub extern "C" fn query(method_ptr: *const u8, method_len: u32) -> u64 {
    let method = unsafe {
        std::str::from_utf8_unchecked(std::slice::from_raw_parts(method_ptr, method_len as usize))
    };
    
    match method {
        "get_count" => get_count(),
        _ => 0,
    }
}
```

### Compile & Deploy

```bash
# 1. Build
cargo build --target wasm32-unknown-unknown --release

# 2. Optimize
wasm-opt -Oz -o counter.wasm target/wasm32-unknown-unknown/release/counter.wasm

# 3. Deploy
quantum-wing contract deploy \
  --wasm counter.wasm \
  --init-args '{}' \
  --gas-limit 1000000 \
  --from wallet.json

# 4. Interact
quantum-wing contract call \
  --address 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5 \
  --method increment \
  --args '{"amount": 10}' \
  --gas-limit 50000
```

## Quantum-Safe Host Functions

### 1. **Dilithium Signature Verification**

```rust
extern "C" {
    fn qw_dilithium_verify(
        msg_ptr: *const u8,
        msg_len: u32,
        sig_ptr: *const u8,
        sig_len: u32,
        pubkey_ptr: *const u8,
        pubkey_len: u32
    ) -> i32;  // Returns 1 if valid, 0 if invalid
}

pub fn verify_signature(message: &[u8], signature: &[u8], public_key: &[u8]) -> bool {
    unsafe {
        qw_dilithium_verify(
            message.as_ptr(), message.len() as u32,
            signature.as_ptr(), signature.len() as u32,
            public_key.as_ptr(), public_key.len() as u32
        ) == 1
    }
}
```

**Gas Cost**: 50,000 gas (expensive, use sparingly)

### 2. **SHA3-256 Hashing**

```rust
extern "C" {
    fn qw_sha3_256(data_ptr: *const u8, data_len: u32, output_ptr: *mut u8);
}

pub fn hash_data(data: &[u8]) -> [u8; 32] {
    let mut output = [0u8; 32];
    unsafe {
        qw_sha3_256(data.as_ptr(), data.len() as u32, output.as_mut_ptr());
    }
    output
}
```

**Gas Cost**: 30 gas per byte

### 3. **Storage Access**

```rust
extern "C" {
    fn qw_storage_read(key_ptr: *const u8, key_len: u32, value_ptr: *mut u8, value_len: u32) -> i32;
    fn qw_storage_write(key_ptr: *const u8, key_len: u32, value_ptr: *const u8, value_len: u32);
}

pub fn read_storage(key: &[u8]) -> Option<Vec<u8>> {
    let mut buffer = vec![0u8; 1024];  // Max 1 KB
    let len = unsafe {
        qw_storage_read(key.as_ptr(), key.len() as u32, buffer.as_mut_ptr(), buffer.len() as u32)
    };
    
    if len > 0 {
        buffer.truncate(len as usize);
        Some(buffer)
    } else {
        None
    }
}

pub fn write_storage(key: &[u8], value: &[u8]) {
    unsafe {
        qw_storage_write(key.as_ptr(), key.len() as u32, value.as_ptr(), value.len() as u32);
    }
}
```

**Gas Cost**:

* Read: 200 gas + 3 gas/byte
* Write: 5,000 gas + 20 gas/byte

## Security Features

### 1. **Memory Isolation**

Each contract runs in isolated Wasm linear memory:

* ✅ Cannot access other contracts' memory
* ✅ Cannot read host memory
* ✅ Limited to 16 MB max (configurable)

### 2. **Stack Overflow Protection**

```go
// In QWVM runtime
maxStackDepth := 65536  // 64 KB stack
if currentStackDepth > maxStackDepth {
    return ErrStackOverflow
}
```

### 3. **Gas Limit Enforcement**

```go
func (vm *QWVM) ExecuteWithGasLimit(contract []byte, gasLimit uint64) error {
    vm.gasRemaining = gasLimit
    
    // Inject gas metering into Wasm
    for _, instruction := range wasmInstructions {
        vm.gasRemaining -= gasCost(instruction)
        if vm.gasRemaining <= 0 {
            return ErrOutOfGas
        }
    }
    
    return nil
}
```

### 4. **Deterministic Execution**

All operations are deterministic:

* ❌ No `random()` function (use VRF from beacon)
* ❌ No `time.Now()` (use block timestamp)
* ❌ No network I/O
* ✅ Pure computation only

## Performance Benchmarks

| Operation            | Gas Cost        | Wall Time | Throughput   |
| -------------------- | --------------- | --------- | ------------ |
| **Simple Transfer**  | 21,000          | 0.5 ms    | 2000 TPS     |
| **Storage Write**    | 5,000 + data    | 2 ms      | 500 TPS      |
| **SHA3-256 (1 KB)**  | 30,000          | 0.1 ms    | 10,000 ops/s |
| **Dilithium Verify** | 50,000          | 0.2 ms    | 5,000 ops/s  |
| **Contract Call**    | 100,000 + logic | 5 ms      | 200 TPS      |

## Comparison with EVM

| Feature             | QWVM                       | EVM                 |
| ------------------- | -------------------------- | ------------------- |
| **Execution Speed** | 10-50x faster              | Baseline            |
| **Languages**       | Rust, C, C++, Go           | Solidity only       |
| **Binary Size**     | 10-100 KB                  | 100-500 KB          |
| **Quantum-Safe**    | ✅ Dilithium host functions | ❌ ECDSA             |
| **Tooling**         | LLVM, Rust ecosystem       | Custom              |
| **Learning Curve**  | Low (familiar languages)   | High (new language) |

## Use Cases

### 1. **DeFi Protocols**

```rust
// AMM liquidity pool
pub fn swap(token_in: Address, token_out: Address, amount_in: u64) -> u64 {
    let reserve_in = get_reserve(token_in);
    let reserve_out = get_reserve(token_out);
    
    // Constant product formula: x * y = k
    let amount_out = (amount_in * reserve_out) / (reserve_in + amount_in);
    
    update_reserves(token_in, reserve_in + amount_in);
    update_reserves(token_out, reserve_out - amount_out);
    
    amount_out
}
```

### 2. **NFT Marketplace**

```rust
pub fn mint_nft(metadata: String) -> u64 {
    let token_id = next_token_id();
    let caller = qw_get_caller();
    
    set_owner(token_id, caller);
    set_metadata(token_id, metadata);
    
    emit_event("NFTMinted", token_id);
    
    token_id
}
```

### 3. **Governance**

```rust
pub fn vote(proposal_id: u64, vote: bool) {
    let caller = qw_get_caller();
    let voting_power = get_voting_power(caller);
    
    let mut proposal = get_proposal(proposal_id);
    if vote {
        proposal.yes_votes += voting_power;
    } else {
        proposal.no_votes += voting_power;
    }
    
    save_proposal(proposal_id, proposal);
}
```

## Development Tools

### SDK (Rust)

```bash
# Add QWVM SDK to Cargo.toml
[dependencies]
qwvm-sdk = "1.0"
```

```rust
use qwvm_sdk::prelude::*;

#[qwvm_contract]
pub struct MyContract {
    owner: Address,
    balance: u64,
}

#[qwvm_init]
fn init(owner: Address) -> MyContract {
    MyContract { owner, balance: 0 }
}

#[qwvm_execute]
fn deposit(&mut self, amount: u64) {
    self.balance += amount;
}

#[qwvm_query]
fn get_balance(&self) -> u64 {
    self.balance
}
```

### Testing Framework

```rust
#[cfg(test)]
mod tests {
    use super::*;
    use qwvm_sdk::testing::*;
    
    #[test]
    fn test_deposit() {
        let mut contract = init(address("alice"));
        contract.deposit(100);
        assert_eq!(contract.get_balance(), 100);
    }
}
```

## Further Reading

<table data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>🌐 WebAssembly VM</strong></td><td>Deep dive into Wasmer runtime</td><td><a href="https://github.com/dolfrin/QuantumWing/blob/master/docs/smart-contracts/webassembly.md">https://github.com/dolfrin/QuantumWing/blob/master/docs/smart-contracts/webassembly.md</a></td></tr><tr><td><strong>⚙️ Host Functions</strong></td><td>Complete host function reference</td><td><a href="https://github.com/dolfrin/QuantumWing/blob/master/docs/smart-contracts/host-functions.md">https://github.com/dolfrin/QuantumWing/blob/master/docs/smart-contracts/host-functions.md</a></td></tr><tr><td><strong>🚀 Contract Deployment</strong></td><td>Step-by-step deployment guide</td><td><a href="https://github.com/dolfrin/QuantumWing/blob/master/docs/smart-contracts/deployment.md">https://github.com/dolfrin/QuantumWing/blob/master/docs/smart-contracts/deployment.md</a></td></tr></tbody></table>
