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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
# API Reference

Complete API documentation for Blockchain Runtime.

## Core Trait

### BlockchainRuntime

Main trait for blockchain runtime implementations.

```rust
#[async_trait]
pub trait BlockchainRuntime: Send + Sync
```

#### Required Methods

##### `blockchain_id()`

```rust
fn blockchain_id(&self) -> &str
```

Get the blockchain identifier.

**Returns:** Blockchain ID (e.g., "ethereum", "solana", "near")

**Example:**
```rust
assert_eq!(runtime.blockchain_id(), "ethereum");
```

---

##### `create_environment()`

```rust
async fn create_environment(&self, config: RuntimeConfig) -> Result<RuntimeEnvironment>
```

Create a new runtime environment.

**Parameters:**
- `config` - Configuration for the environment

**Returns:** `Result<RuntimeEnvironment>` - Created environment

**Example:**
```rust
let config = RuntimeConfig::default();
let env = runtime.create_environment(config).await?;
```

---

##### `execute()`

```rust
async fn execute(
    &self,
    env: &RuntimeEnvironment,
    code_path: &Path,
    inputs: &ExecutionInputs,
) -> Result<ExecutionResult>
```

Execute code in the runtime environment.

**Parameters:**
- `env` - Runtime environment
- `code_path` - Path to code file
- `inputs` - Execution inputs

**Returns:** `Result<ExecutionResult>` - Execution results with metrics

**Example:**
```rust
let inputs = ExecutionInputs {
    target_function: "test".to_string(),
    parameters: HashMap::new(),
    context: ExecutionContext::default(),
};

let result = runtime.execute(&env, Path::new("contract.sol"), &inputs).await?;
println!("Success: {}", result.success);
```

---

##### `deploy_contract()`

```rust
async fn deploy_contract(
    &self,
    env: &RuntimeEnvironment,
    bytecode: &[u8],
    constructor_args: &[u8],
) -> Result<String>
```

Deploy a contract to the blockchain.

**Parameters:**
- `env` - Runtime environment
- `bytecode` - Compiled contract bytecode
- `constructor_args` - ABI-encoded constructor arguments

**Returns:** `Result<String>` - Deployed contract address

**Example:**
```rust
let bytecode = std::fs::read("contract.bin")?;
let address = runtime.deploy_contract(&env, &bytecode, &[]).await?;
println!("Deployed at: {}", address);
```

---

##### `call_function()`

```rust
async fn call_function(
    &self,
    env: &RuntimeEnvironment,
    contract_address: &str,
    function: &str,
    args: &[u8],
) -> Result<Vec<u8>>
```

Call a contract function.

**Parameters:**
- `env` - Runtime environment
- `contract_address` - Contract address
- `function` - Function name
- `args` - ABI-encoded function arguments

**Returns:** `Result<Vec<u8>>` - Raw return value

**Example:**
```rust
let result = runtime.call_function(
    &env,
    "0x742d35Cc...",
    "transfer",
    &encoded_args,
).await?;
```

---

##### `metrics_definition()`

```rust
fn metrics_definition(&self) -> Vec<RuntimeMetricDefinition>
```

Get definitions of metrics this runtime can provide.

**Returns:** `Vec<RuntimeMetricDefinition>` - Available metrics

**Example:**
```rust
let metrics = runtime.metrics_definition();
for metric in metrics {
    println!("{}: {} ({})", metric.name, metric.description, metric.unit);
}
```

---

##### `monitor()`

```rust
async fn monitor(
    &self,
    env: &RuntimeEnvironment,
    execution_id: &str,
) -> Result<Vec<RuntimeEvent>>
```

Monitor runtime events for an execution.

**Parameters:**
- `env` - Runtime environment
- `execution_id` - Execution to monitor

**Returns:** `Result<Vec<RuntimeEvent>>` - Captured events

**Example:**
```rust
let events = runtime.monitor(&env, &execution_id).await?;
for event in events {
    println!("Event: {}", event.event_type);
}
```

---

##### `destroy()`

```rust
async fn destroy(&self, env: RuntimeEnvironment) -> Result<()>
```

Destroy a runtime environment and clean up resources.

**Parameters:**
- `env` - Environment to destroy

**Returns:** `Result<()>`

**Example:**
```rust
runtime.destroy(env).await?;
```

---

##### `is_available()`

```rust
async fn is_available(&self) -> bool
```

Check if runtime is available and functional.

**Returns:** `bool` - true if available

**Example:**
```rust
if runtime.is_available().await {
    println!("Runtime is ready");
}
```

---

##### `capabilities()`

```rust
fn capabilities(&self) -> RuntimeCapabilities
```

Get runtime capabilities.

**Returns:** `RuntimeCapabilities` - What this runtime can do

**Example:**
```rust
let caps = runtime.capabilities();
if caps.supports_gas_estimation {
    // Use gas estimation features
}
```

---

## Configuration Types

### RuntimeConfig

```rust
pub struct RuntimeConfig {
    pub timeout_seconds: u64,
    pub memory_limit_mb: u64,
    pub network_mode: NetworkMode,
    pub enable_monitoring: bool,
    pub blockchain_config: HashMap<String, serde_json::Value>,
}
```

**Default:**
```rust
RuntimeConfig {
    timeout_seconds: 300,
    memory_limit_mb: 1024,
    network_mode: NetworkMode::Local,
    enable_monitoring: true,
    blockchain_config: HashMap::new(),
}
```

### NetworkMode

```rust
pub enum NetworkMode {
    Local,          // Local test network
    Testnet,        // Public testnet
    MainnetFork,    // Mainnet fork
}
```

### RuntimeType

```rust
pub enum RuntimeType {
    Docker,         // Containerized
    LocalProcess,   // Native process
    CloudInstance,  // Cloud-hosted
    InMemory,       // In-memory simulation
}
```

### EnvironmentState

```rust
pub enum EnvironmentState {
    Creating,       // Being created
    Ready,          // Ready for use
    Running,        // Currently executing
    Stopped,        // Stopped
    Error,          // Error state
}
```

---

## Result Types

### ExecutionResult

```rust
pub struct ExecutionResult {
    pub execution_id: String,
    pub success: bool,
    pub return_value: Option<serde_json::Value>,
    pub error: Option<String>,
    pub metrics: HashMap<String, serde_json::Value>,
    pub state_changes: Vec<StateChange>,
    pub events: Vec<RuntimeEvent>,
    pub execution_time_ms: u64,
}
```

### StateChange

```rust
pub struct StateChange {
    pub key: String,
    pub old_value: Option<serde_json::Value>,
    pub new_value: serde_json::Value,
    pub change_type: StateChangeType,
}

pub enum StateChangeType {
    Created,
    Updated,
    Deleted,
}
```

### RuntimeEvent

```rust
pub struct RuntimeEvent {
    pub event_id: String,
    pub event_type: String,
    pub timestamp: u64,
    pub data: HashMap<String, serde_json::Value>,
}
```

---

## Input Types

### ExecutionInputs

```rust
pub struct ExecutionInputs {
    pub target_function: String,
    pub parameters: HashMap<String, serde_json::Value>,
    pub context: ExecutionContext,
}
```

### ExecutionContext

```rust
pub struct ExecutionContext {
    pub sender: Option<String>,           // Calling address
    pub block_number: Option<u64>,        // Block number
    pub timestamp: Option<u64>,           // Block timestamp
    pub extra: HashMap<String, serde_json::Value>, // Extra context
}
```

---

## Capability Types

### RuntimeCapabilities

```rust
pub struct RuntimeCapabilities {
    pub supports_contract_deployment: bool,
    pub supports_function_calls: bool,
    pub supports_state_inspection: bool,
    pub supports_event_monitoring: bool,
    pub supports_gas_estimation: bool,
    pub supports_time_travel: bool,
    pub max_execution_time_seconds: u64,
}
```

### RuntimeMetricDefinition

```rust
pub struct RuntimeMetricDefinition {
    pub name: String,
    pub description: String,
    pub unit: String,
    pub metric_type: MetricType,
}

pub enum MetricType {
    Gas,
    ComputeUnits,
    StorageBytes,
    Time,
    Custom(String),
}
```

---

## Thread Safety

All trait methods are async and require `Send + Sync`:

```rust
pub trait BlockchainRuntime: Send + Sync {
    // All methods can be called from any thread
}
```

Safe for concurrent operations across threads.

---

## Performance Characteristics

| Operation | Typical Time | Notes |
|-----------|-------------|-------|
| `create_environment()` | 1-5s | Depends on runtime type |
| `deploy_contract()` | 0.5-2s | Network dependent |
| `call_function()` | 100-500ms | Function complexity |
| `execute()` | 200ms-2s | Code complexity |
| `monitor()` | 100ms-1s | Event count |
| `destroy()` | 500ms-2s | Cleanup overhead |

---

## Example Patterns

### Resource Management

```rust
struct ManagedRuntime {
    runtime: Box<dyn BlockchainRuntime>,
}

impl ManagedRuntime {
    async fn with_environment<F, T>(&self, f: F) -> anyhow::Result<T>
    where
        F: FnOnce(&blockchain_runtime::RuntimeEnvironment) -> anyhow::Result<T>,
    {
        let config = RuntimeConfig::default();
        let env = self.runtime.create_environment(config).await?;
        
        let result = f(&env)?;
        
        self.runtime.destroy(env).await?;
        
        Ok(result)
    }
}
```

### Error Recovery

```rust
async fn robust_execution(runtime: &dyn BlockchainRuntime) -> anyhow::Result<()> {
    let config = RuntimeConfig::default();
    
    let env = match runtime.create_environment(config).await {
        Ok(e) => e,
        Err(e) => {
            eprintln!("Failed to create environment: {}", e);
            return Err(e);
        }
    };
    
    // Use environment...
    
    // Always clean up
    if let Err(e) = runtime.destroy(env).await {
        eprintln!("Warning: Failed to destroy environment: {}", e);
    }
    
    Ok(())
}
```

---

## Version Compatibility

Current version: `0.1.0`

**Breaking changes:** Will use semantic versioning (0.x.0 for breaking changes)

**Stability:** API is in development, expect changes in v0.x releases