blockchain-runtime 0.1.0

Blockchain-agnostic runtime abstraction for dynamic analysis, testing, and simulation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# User Guide

Comprehensive guide for using Blockchain Runtime.

## Environment Management

### Creating Environments

```rust
use blockchain_runtime::{RuntimeConfig, NetworkMode};

// Basic environment
let config = RuntimeConfig::default();
let env = runtime.create_environment(config).await?;

// Custom configuration
let config = RuntimeConfig {
    timeout_seconds: 600,      // 10 minutes
    memory_limit_mb: 2048,     // 2GB
    network_mode: NetworkMode::Local,
    enable_monitoring: true,
    blockchain_config: {
        let mut map = HashMap::new();
        map.insert("chain_id".to_string(), serde_json::json!(1337));
        map
    },
};

let env = runtime.create_environment(config).await?;
```

### Environment Lifecycle

```rust
// Create
let env = runtime.create_environment(config).await?;
assert_eq!(env.state, EnvironmentState::Ready);

// Use
let result = runtime.execute(&env, code, &inputs).await?;

// Destroy
runtime.destroy(env).await?;
```

## Contract Operations

### Deploying Contracts

```rust
// Read compiled bytecode
let bytecode = std::fs::read("MyContract.bin")?;

// Encode constructor arguments (blockchain-specific)
let constructor_args = encode_constructor_args(&[
    "initial_supply".to_string(),
    "1000000".to_string(),
])?;

// Deploy
let address = runtime.deploy_contract(&env, &bytecode, &constructor_args).await?;

println!("Contract deployed at: {}", address);
```

### Calling Functions

```rust
// Encode function call (blockchain-specific)
let args = encode_function_args("transfer", &[
    "recipient_address",
    "amount",
])?;

// Call function
let result = runtime.call_function(&env, &contract_address, "transfer", &args).await?;

// Decode result (blockchain-specific)
let decoded = decode_return_value(&result)?;
println!("Transfer result: {:?}", decoded);
```

### State Queries

```rust
// Call view/read-only function
let balance_args = encode_function_args("balanceOf", &["address"])?;

let result = runtime.call_function(&env, &contract_address, "balanceOf", &balance_args).await?;

let balance: u64 = decode_u64(&result)?;
println!("Balance: {}", balance);
```

## Execution and Monitoring

### Full Execution Flow

```rust
use blockchain_runtime::{ExecutionInputs, ExecutionContext};
use std::path::Path;

let inputs = ExecutionInputs {
    target_function: "complex_function".to_string(),
    parameters: {
        let mut params = HashMap::new();
        params.insert("amount".to_string(), serde_json::json!(1000));
        params.insert("recipient".to_string(), serde_json::json!("0x..."));
        params
    },
    context: ExecutionContext {
        sender: Some("0x1234...".to_string()),
        block_number: Some(1000),
        timestamp: Some(1698000000),
        extra: HashMap::new(),
    },
};

let result = runtime.execute(&env, Path::new("contract.sol"), &inputs).await?;

// Analyze results
if result.success {
    println!("✓ Execution successful");
    
    // Metrics
    if let Some(gas) = result.metrics.get("gas_used") {
        println!("Gas: {}", gas);
    }
    
    // State changes
    println!("State changes: {}", result.state_changes.len());
    for change in &result.state_changes {
        match change.change_type {
            blockchain_runtime::StateChangeType::Created => {
                println!("  Created: {} = {:?}", change.key, change.new_value);
            }
            blockchain_runtime::StateChangeType::Updated => {
                println!("  Updated: {} ({:?} → {:?})", 
                    change.key, change.old_value, change.new_value);
            }
            blockchain_runtime::StateChangeType::Deleted => {
                println!("  Deleted: {}", change.key);
            }
        }
    }
    
    // Events
    println!("Events: {}", result.events.len());
    for event in &result.events {
        println!("  {}: {:?}", event.event_type, event.data);
    }
} else {
    println!("✗ Execution failed: {:?}", result.error);
}
```

### Event Monitoring

```rust
// Execute contract
let result = runtime.execute(&env, code_path, &inputs).await?;

// Monitor events
let events = runtime.monitor(&env, &result.execution_id).await?;

for event in events {
    println!("Event: {} at timestamp {}", event.event_type, event.timestamp);
    
    // Process event data
    match event.event_type.as_str() {
        "Transfer" => {
            let from = event.data.get("from");
            let to = event.data.get("to");
            let amount = event.data.get("amount");
            println!("  Transfer: {:?} -> {:?}, amount: {:?}", from, to, amount);
        }
        "Approval" => {
            // Handle approval event
        }
        _ => {
            println!("  Unknown event: {:?}", event.data);
        }
    }
}
```

## Metrics Collection

### Available Metrics

```rust
// Get metric definitions
let metrics = runtime.metrics_definition();

for metric in metrics {
    println!("Metric: {}", metric.name);
    println!("  Description: {}", metric.description);
    println!("  Unit: {}", metric.unit);
    println!("  Type: {:?}", metric.metric_type);
}

// Common metrics:
// - gas_used (Ethereum, Polygon, BSC)
// - compute_units (Solana)
// - storage_delta (all chains)
// - execution_time (all chains)
```

### Using Metrics

```rust
let result = runtime.execute(&env, code, &inputs).await?;

// Gas used (Ethereum)
if let Some(gas) = result.metrics.get("gas_used") {
    let gas_value = gas.as_u64().unwrap_or(0);
    println!("Gas used: {} units", gas_value);
    
    // Estimate cost
    let gas_price_gwei = 20;
    let cost_gwei = gas_value * gas_price_gwei;
    println!("Estimated cost: {} gwei", cost_gwei);
}

// Compute units (Solana)
if let Some(compute) = result.metrics.get("compute_units") {
    println!("Compute units: {}", compute);
}

// Storage delta (all)
if let Some(storage) = result.metrics.get("storage_delta") {
    println!("Storage change: {} bytes", storage);
}

// Execution time (all)
println!("Execution time: {}ms", result.execution_time_ms);
```

## Runtime Capabilities

### Checking Capabilities

```rust
let caps = runtime.capabilities();

// Feature detection
if caps.supports_contract_deployment {
    // Can deploy contracts
    let address = runtime.deploy_contract(&env, bytecode, &args).await?;
}

if caps.supports_gas_estimation {
    // Can estimate gas
    // (implementation specific)
}

if caps.supports_time_travel {
    // Can manipulate blockchain time
    // (useful for testing time-dependent contracts)
}

if caps.supports_state_inspection {
    // Can inspect contract state
}

if caps.supports_event_monitoring {
    // Can monitor events
}

// Limits
println!("Max execution time: {}s", caps.max_execution_time_seconds);
```

### Conditional Features

```rust
async fn smart_execution(runtime: &dyn BlockchainRuntime) -> Result<()> {
    let caps = runtime.capabilities();
    
    if caps.supports_gas_estimation {
        // Estimate gas first
        // let gas_estimate = runtime.estimate_gas(...).await?;
        // println!("Estimated gas: {}", gas_estimate);
    }
    
    // Execute
    let result = runtime.execute(&env, code, &inputs).await?;
    
    if caps.supports_event_monitoring {
        // Monitor detailed events
        let events = runtime.monitor(&env, &result.execution_id).await?;
        // Process events...
    }
    
    Ok(())
}
```

## Network Modes

### Local Development

```rust
let config = RuntimeConfig {
    network_mode: NetworkMode::Local,
    ..Default::default()
};

// Benefits:
// - Fast
// - Free
// - Deterministic
// - Full control
```

### Testnet Testing

```rust
let mut blockchain_config = HashMap::new();
blockchain_config.insert("network".to_string(), serde_json::json!("goerli"));

let config = RuntimeConfig {
    network_mode: NetworkMode::Testnet,
    blockchain_config,
    ..Default::default()
};

// Benefits:
// - Realistic network conditions
// - Free test tokens
// - Public visibility
// - Integration testing
```

### Mainnet Forking

```rust
let mut blockchain_config = HashMap::new();
blockchain_config.insert("fork_url".to_string(), 
    serde_json::json!("https://eth-mainnet.alchemyapi.io/v2/YOUR_KEY"));
blockchain_config.insert("fork_block".to_string(), serde_json::json!(17000000));

let config = RuntimeConfig {
    network_mode: NetworkMode::MainnetFork,
    blockchain_config,
    ..Default::default()
};

// Benefits:
// - Real contract state
// - Realistic testing
// - No real funds spent
// - Test against live contracts
```

## Error Handling

### Graceful Degradation

```rust
async fn robust_execution(runtime: &dyn BlockchainRuntime) -> anyhow::Result<()> {
    // Check availability
    if !runtime.is_available().await {
        anyhow::bail!("Runtime not available");
    }
    
    // Create environment with retry
    let env = retry_async(|| runtime.create_environment(config.clone()), 3).await?;
    
    // Execute with timeout
    let result = timeout(
        Duration::from_secs(300),
        runtime.execute(&env, code, &inputs)
    ).await??;
    
    // Always clean up, even on error
    let _ = runtime.destroy(env).await; // Ignore cleanup errors
    
    Ok(())
}

async fn retry_async<F, T>(f: F, retries: usize) -> anyhow::Result<T>
where
    F: Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<T>>>>,
{
    for attempt in 0..retries {
        match f().await {
            Ok(result) => return Ok(result),
            Err(e) if attempt < retries - 1 => {
                tokio::time::sleep(Duration::from_secs(2u64.pow(attempt as u32))).await;
                continue;
            }
            Err(e) => return Err(e),
        }
    }
    unreachable!()
}
```

## Best Practices

### 1. Always Clean Up

```rust
async fn use_runtime(runtime: &dyn BlockchainRuntime) -> Result<()> {
    let env = runtime.create_environment(config).await?;
    
    // Use environment...
    
    // ALWAYS destroy, even on error
    runtime.destroy(env).await?;
    Ok(())
}
```

### 2. Check Availability First

```rust
if !runtime.is_available().await {
    anyhow::bail!("Runtime not available");
}
```

### 3. Use Appropriate Timeouts

```rust
let config = RuntimeConfig {
    timeout_seconds: match complexity {
        Complexity::Simple => 60,
        Complexity::Medium => 300,
        Complexity::Complex => 600,
    },
    ..Default::default()
};
```

### 4. Monitor Important Executions

```rust
let config = RuntimeConfig {
    enable_monitoring: is_production,
    ..Default::default()
};
```

## Next Steps

- Explore [Use Cases]./use-cases.md for practical examples
- Read [Implementation Guide]./implementation-guide.md to create custom runtimes
- Check [API Reference]./api-reference.md for detailed documentation
- See [Testing Guide]./testing.md for testing strategies