|
| 1 | +# Soroban Cost Model - GasGuard Engine |
| 2 | + |
| 3 | +> **Status**: Complete and Ready for Integration |
| 4 | +> **Version**: 1.0 |
| 5 | +> **Author**: GasGuard Engineering |
| 6 | +
|
| 7 | +--- |
| 8 | + |
| 9 | +## Overview |
| 10 | + |
| 11 | +This cost model enables the **GasGuard engine** to analyze Soroban smart contract resource consumption across three dimensions: |
| 12 | + |
| 13 | +1. **CPU** – Instruction execution metering |
| 14 | +2. **Memory** – Transaction memory limits |
| 15 | +3. **Ledger** – Disk I/O (reads/writes) and bandwidth |
| 16 | + |
| 17 | +The model provides: |
| 18 | +- **Fee estimation** based on Soroban network configuration |
| 19 | +- **Efficiency scoring** (0–100 scale) |
| 20 | +- **Optimization hints** with severity levels |
| 21 | +- **Safety violation detection** (95% limit threshold) |
| 22 | + |
| 23 | +--- |
| 24 | + |
| 25 | +## Documentation |
| 26 | + |
| 27 | +### Primary Documents |
| 28 | + |
| 29 | +| Document | Description | Location | |
| 30 | +|----------|-------------|----------| |
| 31 | +| **Specification** | Complete cost model formulas, constant mappings, scoring functions | [`docs/soroban-cost-model-spec.md`](docs/soroban-cost-model-spec.md) | |
| 32 | +| **Walkthrough** | Implementation summary, verification results, next steps | [Brain: walkthrough.md](../.gemini/antigravity/brain/582bc740-fa6d-4da6-864f-c6c06bc76032/walkthrough.md) | |
| 33 | +| **Task Plan** | Development checklist (all tasks complete) | [Brain: task.md](../.gemini/antigravity/brain/582bc740-fa6d-4da6-864f-c6c06bc76032/task.md) | |
| 34 | + |
| 35 | +### Quick Links |
| 36 | + |
| 37 | +- **[Cost Model Formulas →](docs/soroban-cost-model-spec.md#cpu-cost-model)** |
| 38 | +- **[Constant Mapping Table →](docs/soroban-cost-model-spec.md#constant-mapping-to-soroban-limits)** |
| 39 | +- **[Scoring Function →](docs/soroban-cost-model-spec.md#engine-scoring-function--pseudocode)** |
| 40 | +- **[Worked Examples →](docs/soroban-cost-model-spec.md#worked-examples)** |
| 41 | + |
| 42 | +--- |
| 43 | + |
| 44 | +## Quick Start |
| 45 | + |
| 46 | +### Run Examples |
| 47 | + |
| 48 | +```bash |
| 49 | +cd /home/misty-waters/Gas-guard/GasGuard-1 |
| 50 | +python3 src/cost_model.py |
| 51 | +``` |
| 52 | + |
| 53 | +**Output**: Analyzes two transactions (simple token transfer + complex marketplace call) with full cost breakdown and scores. |
| 54 | + |
| 55 | +### Run Tests |
| 56 | + |
| 57 | +```bash |
| 58 | +python3 -m pytest tests/test_cost_model.py -v |
| 59 | +``` |
| 60 | + |
| 61 | +**Coverage**: 25+ test cases covering CPU, memory, ledger costs, scoring, and hints. |
| 62 | + |
| 63 | +### Analyze a Transaction |
| 64 | + |
| 65 | +```python |
| 66 | +from src.cost_model import SorobanConfig, SimulationResult, analyze_transaction |
| 67 | + |
| 68 | +# 1. Load network config (or use defaults) |
| 69 | +config = SorobanConfig() |
| 70 | + |
| 71 | +# 2. Get simulation data from Soroban RPC |
| 72 | +sim = SimulationResult( |
| 73 | + instructions=10_000_000, |
| 74 | + memoryBytes=5_000_000, |
| 75 | + resources=SorobanResources(...), |
| 76 | + transactionSizeBytes=8192 |
| 77 | +) |
| 78 | + |
| 79 | +# 3. Analyze |
| 80 | +analysis = analyze_transaction(sim, config) |
| 81 | + |
| 82 | +# 4. Use results |
| 83 | +print(f"Score: {analysis.scores.total}/100") |
| 84 | +print(f"Fee: {analysis.costs['cpu'].fee + analysis.costs['ledger'].fee:.6f} XLM") |
| 85 | +for hint in analysis.hints: |
| 86 | + print(hint) |
| 87 | +``` |
| 88 | + |
| 89 | +--- |
| 90 | + |
| 91 | +## Cost Model Summary |
| 92 | + |
| 93 | +### CPU Cost |
| 94 | + |
| 95 | +**Formula**: |
| 96 | +``` |
| 97 | +C_cpu = ⌈I / R_cpu⌉ × F_cpu × (1 + w_ledger × (I / I_ledger)^2) |
| 98 | +``` |
| 99 | + |
| 100 | +**Limits**: |
| 101 | +- Per-tx: 100M instructions |
| 102 | +- Per-ledger: 1B instructions |
| 103 | + |
| 104 | +**Scoring**: Linear up to 50% utilization, then penalized. |
| 105 | + |
| 106 | +--- |
| 107 | + |
| 108 | +### Memory Cost |
| 109 | + |
| 110 | +**Formula**: |
| 111 | +``` |
| 112 | +C_mem = k_mem × e^(5 × M / M_tx) |
| 113 | +``` |
| 114 | + |
| 115 | +**Limit**: 41,943,040 bytes per transaction |
| 116 | + |
| 117 | +**Scoring**: Exponential penalty above 70% (no direct fees, limit-only). |
| 118 | + |
| 119 | +--- |
| 120 | + |
| 121 | +### Ledger Cost |
| 122 | + |
| 123 | +**Dimensions**: |
| 124 | +1. **Read entries** (limit: 40/tx, 20K/ledger) |
| 125 | +2. **Read bytes** (limit: 200KB/tx, 100MB/ledger) |
| 126 | +3. **Write entries** (limit: 25/tx, 10K/ledger) |
| 127 | +4. **Write bytes** (limit: 100KB/tx, 50MB/ledger) |
| 128 | +5. **Bandwidth** (limit: 100KB/tx, 1MB/ledger) |
| 129 | + |
| 130 | +**Formula**: Sum of per-entry fees + per-KB fees for each dimension. |
| 131 | + |
| 132 | +**Scoring**: Composite weighted average of all five dimensions. |
| 133 | + |
| 134 | +--- |
| 135 | + |
| 136 | +## 🔧 Configuration |
| 137 | + |
| 138 | +### Default Constants |
| 139 | + |
| 140 | +Loaded from `SorobanConfig` class (matches Soroban mainnet v20): |
| 141 | + |
| 142 | +```python |
| 143 | +config = SorobanConfig( |
| 144 | + txMaxInstructions=100_000_000, |
| 145 | + ledgerMaxInstructions=1_000_000_000, |
| 146 | + feeRatePerInstructionsIncrement=10_000, |
| 147 | + txMemoryLimit=41_943_040, |
| 148 | + txMaxReadLedgerEntries=40, |
| 149 | + txMaxWriteLedgerEntries=25, |
| 150 | + # ... (see src/cost_model.py for full list) |
| 151 | +) |
| 152 | +``` |
| 153 | + |
| 154 | +### Tunable Parameters |
| 155 | + |
| 156 | +| Parameter | Default | Adjust For | |
| 157 | +|-----------|---------|------------| |
| 158 | +| `w_ledger` | 0.5 | Ledger congestion sensitivity | |
| 159 | +| `k_mem` | 100 | Memory penalty severity | |
| 160 | +| Score thresholds | 50%, 80% | UX sensitivity | |
| 161 | +| Safety margin | 95% | Deployment risk tolerance | |
| 162 | + |
| 163 | +--- |
| 164 | + |
| 165 | +##Example Results |
| 166 | + |
| 167 | +### Simple Token Transfer |
| 168 | + |
| 169 | +``` |
| 170 | +Instructions: 1.25M (1.25% of limit) |
| 171 | +Memory: 2MB (5% of limit) |
| 172 | +Score: 99/100 |
| 173 | +Fee: 0.00184 XLM (~$0.0002) |
| 174 | +``` |
| 175 | + |
| 176 | +### Complex Multi-Contract Call |
| 177 | + |
| 178 | +``` |
| 179 | +Instructions: 75M (75% of limit) |
| 180 | +Memory: 32MB (76% of limit) |
| 181 | +Score: 70/100 |
| 182 | +Fee: 0.08018 XLM (~$0.0088) |
| 183 | +
|
| 184 | +Hints: |
| 185 | +HIGH CPU: Optimize loops and host function calls |
| 186 | +CRITICAL: Memory usage at 76%. Optimize allocations |
| 187 | +``` |
| 188 | + |
| 189 | +--- |
| 190 | + |
| 191 | +## Testing |
| 192 | + |
| 193 | +**Test Suite**: [`tests/test_cost_model.py`](tests/test_cost_model.py) |
| 194 | + |
| 195 | +### Test Categories |
| 196 | + |
| 197 | +- CPU cost (minimal, high, ledger pressure) |
| 198 | +- Memory cost (low, high, exponential growth) |
| 199 | +- Ledger cost (reads, writes, bandwidth) |
| 200 | +- Scoring function (all bands, monotonicity) |
| 201 | +- Optimization hints (efficient, critical) |
| 202 | +- Full pipeline (simple tx, complex tx, safety violations) |
| 203 | + |
| 204 | +**Run with**: `pytest tests/test_cost_model.py -v` |
| 205 | + |
| 206 | +--- |
| 207 | + |
| 208 | +## Integration Checklist |
| 209 | + |
| 210 | +For integrating this model into your GasGuard engine: |
| 211 | + |
| 212 | +- [ ] **Fetch Network Config** – Load from Soroban RPC `getLedgerEntries` |
| 213 | +- [ ] **Simulate Transactions** – Call `simulateTransaction` RPC method |
| 214 | +- [ ] **Track Memory** – Implement custom profiling or footprint estimation |
| 215 | +- [ ] **Compute Costs** – Use `analyze_transaction()` function |
| 216 | +- [ ] **Store Scores** – Save to analytics DB for historical tracking |
| 217 | +- [ ] **CI/CD Integration** – Gate deploys on score <50 or safety violations |
| 218 | +- [ ] **PR Comments** – Auto-post optimization hints |
| 219 | + |
| 220 | +See [Walkthrough: Implementation Checklist](../.gemini/antigravity/brain/582bc740-fa6d-4da6-864f-c6c06bc76032/walkthrough.md#implementation-checklist-for-developers) for details. |
| 221 | + |
| 222 | +--- |
| 223 | + |
| 224 | +##Files Structure |
| 225 | + |
| 226 | +``` |
| 227 | +GasGuard-1/ |
| 228 | +├── docs/ |
| 229 | +│ ├── soroban-cost-model-spec.md # Complete specification (600+ lines) |
| 230 | +│ └── README.md # This file |
| 231 | +├── src/ |
| 232 | +│ └── cost_model.py # Reference implementation (700+ lines) |
| 233 | +└── tests/ |
| 234 | + └── test_cost_model.py # Test suite (400+ lines) |
| 235 | +``` |
| 236 | + |
| 237 | +--- |
| 238 | + |
| 239 | +##Key Concepts |
| 240 | + |
| 241 | +### Soroban Resource Metering |
| 242 | + |
| 243 | +Soroban tracks resources at two levels: |
| 244 | + |
| 245 | +1. **Per-Transaction**: Hard limits that cannot be exceeded |
| 246 | +2. **Per-Ledger**: Aggregate limits across all txs in a ledger close |
| 247 | + |
| 248 | +**Configuration Sources**: |
| 249 | +- `ConfigSettingContractComputeV0` – CPU and memory |
| 250 | +- `ConfigSettingContractLedgerCostV0` – Ledger I/O |
| 251 | +- `ConfigSettingContractBandwidthV0` – Tx size |
| 252 | + |
| 253 | +### Scoring Philosophy |
| 254 | + |
| 255 | +**Lower resource usage → Higher score → Better efficiency** |
| 256 | + |
| 257 | +- **100–80**: Excellent (0–50% utilization) |
| 258 | +- **80–50**: Good (50–80% utilization) |
| 259 | +- **50–0**: Poor (80–100% utilization) |
| 260 | + |
| 261 | +Aggregate score weights critical resources (CPU, ledger) higher than memory. |
| 262 | + |
| 263 | +### Safety Margins |
| 264 | + |
| 265 | +Transactions approaching **95% of any limit** trigger safety violations and should be blocked from deployment to prevent on-chain failures due to: |
| 266 | +- Network config changes |
| 267 | +- Simulation imprecision |
| 268 | +- Concurrent ledger congestion |
| 269 | + |
| 270 | +--- |
| 271 | + |
| 272 | +## 🔗 References |
| 273 | + |
| 274 | +- **Soroban Docs**: [Resource Limits & Fees](https://soroban.stellar.org/docs/fundamentals-and-concepts/fees-and-metering) |
| 275 | +- **Stellar Configuration**: [CAP-46 Smart Contract Standardized Asset](https://stellar.org/protocol/cap-46) |
| 276 | +- **Soroban RPC**: [`simulateTransaction` API](https://soroban.stellar.org/api/methods/simulateTransaction) |
| 277 | + |
| 278 | +--- |
| 279 | + |
| 280 | +## License |
| 281 | + |
| 282 | +MIT License - GasGuard Engineering |
| 283 | + |
| 284 | +--- |
| 285 | + |
| 286 | +**Questions?** See the [full specification](docs/soroban-cost-model-spec.md) or contact GasGuard Engineering. |
0 commit comments