> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/dotandev/hintents/llms.txt
> Use this file to discover all available pages before exploring further.

# Error suggestion engine

> Heuristic-based system that analyzes Soroban transaction failures and provides actionable fix suggestions

The Error Suggestion Engine is a heuristic-based system that analyzes Soroban transaction failures and provides actionable suggestions to help developers fix common errors. This feature is particularly valuable for developers transitioning to Stellar development.

## Features

* **Heuristic analysis**: Pattern matching against common error scenarios
* **Confidence levels**: Each suggestion includes a confidence rating (high, medium, low)
* * **Call tree analysis**: Analyzes entire execution traces including nested contract calls
* **Clear marking**: All suggestions are clearly marked as "Potential Fixes"

<Note>
  Suggestions are heuristic-based and may not always be accurate. Always verify before applying fixes.
</Note>

## How it works

The suggestion engine automatically integrates with the `erst debug` command:

```bash theme={null}
erst debug <transaction-hash> --network testnet
```

Example output:

```
=== Potential Fixes (Heuristic Analysis) ===
⚠️  These are suggestions based on common error patterns. Always verify before applying.

1. 🔴 [Confidence: high]
   Potential Fix: Ensure you have called initialize() on this contract before invoking other functions.

2. 🟡 [Confidence: medium]
   Potential Fix: Optimize your contract code to reduce CPU/memory usage, or increase resource limits in the transaction.
```

## Built-in error patterns

The engine includes seven built-in rules that detect common Soroban errors:

### 1. Uninitialized contract

<ParamField path="Confidence" type="string" default="high">
  High confidence rule
</ParamField>

**Triggers when**:

* Events contain keywords: `empty`, `not found`, `missing`, `null`
* Storage-related events indicate empty state

**Suggestion**:

```
Potential Fix: Ensure you have called initialize() on this contract 
before invoking other functions.
```

### 2. Missing authorization

<ParamField path="Confidence" type="string" default="high">
  High confidence rule
</ParamField>

**Triggers when**:

* Events contain keywords: `auth`, `unauthorized`, `permission`, `signature`
* Authorization-related failures detected

**Suggestion**:

```
Potential Fix: Verify that all required signatures are present and 
the invoker has proper authorization.
```

### 3. Insufficient balance

<ParamField path="Confidence" type="string" default="high">
  High confidence rule
</ParamField>

**Triggers when**:

* Events contain keywords: `balance`, `insufficient`, `underfunded`, `funds`
* Balance-related errors detected

**Suggestion**:

```
Potential Fix: Ensure the account has sufficient balance to cover 
the transaction and maintain minimum reserves.
```

### 4. Invalid parameters

<ParamField path="Confidence" type="string" default="medium">
  Medium confidence rule
</ParamField>

**Triggers when**:

* Events contain keywords: `invalid`, `malformed`, `bad`, `parameter`
* Parameter validation failures detected

**Suggestion**:

```
Potential Fix: Check that all function parameters match the expected 
types and constraints.
```

### 5. Contract not found

<ParamField path="Confidence" type="string" default="high">
  High confidence rule
</ParamField>

**Triggers when**:

* Contract ID is empty or all zeros
* Events indicate missing contract

**Suggestion**:

```
Potential Fix: Verify the contract ID is correct and the contract 
has been deployed to the network.
```

### 6. Resource limit exceeded

<ParamField path="Confidence" type="string" default="medium">
  Medium confidence rule
</ParamField>

**Triggers when**:

* Events contain keywords: `limit`, `exceeded`, `quota`, `budget`
* Resource exhaustion detected

**Suggestion**:

```
Potential Fix: Optimize your contract code to reduce CPU/memory usage, 
or increase resource limits in the transaction.
```

### 7. Reentrancy detected

<ParamField path="Confidence" type="string" default="medium">
  Medium confidence rule
</ParamField>

**Triggers when**:

* Events contain keywords: `reentrant`, `recursive`, `loop`
* Reentrancy patterns detected

**Suggestion**:

```
Potential Fix: Implement reentrancy guards or use the 
checks-effects-interactions pattern to prevent recursive calls.
```

## Confidence levels

Each suggestion includes a confidence indicator:

### 🔴 High confidence

* Strong pattern match with well-known error scenarios
* Multiple indicators point to the same issue
* Solution is straightforward and commonly applicable

### 🟡 Medium confidence

* Partial pattern match or ambiguous indicators
* Multiple possible causes
* Solution may require additional investigation

### 🟢 Low confidence

* Weak pattern match or speculative
* Limited evidence
* Suggestion is exploratory

## Programmatic usage

### Basic usage

```go theme={null}
import "github.com/dotandev/hintents/internal/decoder"

// Create engine
engine := decoder.NewSuggestionEngine()

// Analyze events
events := []decoder.DecodedEvent{
    {
        ContractID: "abc123",
        Topics:     []string{"storage_empty", "error"},
        Data:       "ScvVoid",
    },
}

suggestions := engine.AnalyzeEvents(events)

// Format and display
output := decoder.FormatSuggestions(suggestions)
fmt.Println(output)
```

### Analyzing call trees

For comprehensive analysis of nested contract calls:

```go theme={null}
// Decode events into a call tree
callTree, err := decoder.DecodeEvents(eventsXdr)
if err != nil {
    log.Fatal(err)
}

// Analyze the entire call tree
suggestions := engine.AnalyzeCallTree(callTree)
```

### Adding custom rules

Extend the engine with project-specific error patterns:

```go theme={null}
customRule := decoder.ErrorPattern{
    Name:     "custom_timeout",
    Keywords: []string{"timeout", "deadline", "expired"},
    EventChecks: []func(decoder.DecodedEvent) bool{
        func(e decoder.DecodedEvent) bool {
            // Custom logic to detect timeout
            return strings.Contains(e.Data, "timeout")
        },
    },
    Suggestion: decoder.Suggestion{
        Rule:        "custom_timeout",
        Description: "Potential Fix: Increase the transaction timeout or optimize contract execution time.",
        Confidence:  "medium",
    },
}

engine.AddCustomRule(customRule)
```

## Architecture

The suggestion engine follows a clean, extensible architecture:

```
SuggestionEngine
├── rules []ErrorPattern
│   ├── Name
│   ├── Keywords
│   ├── EventChecks
│   └── Suggestion
└── Methods
    ├── AnalyzeEvents()
    ├── AnalyzeCallTree()
    └── AddCustomRule()
```

### Processing flow

1. **Event collection**: Gather all diagnostic events from transaction
2. **Pattern matching**: Check each event against rule keywords and conditions
3. **Deduplication**: Ensure each rule triggers only once
4. **Formatting**: Present suggestions with confidence indicators
5. **Display**: Show suggestions before security analysis

## Best practices

### For users

<Accordion title="Always verify suggestions">
  Suggestions are heuristic-based and may not always be accurate. Review each suggestion in the context of your specific contract logic.
</Accordion>

<Accordion title="Check confidence levels">
  Prioritize high-confidence suggestions first. Medium and low confidence suggestions may require more investigation.
</Accordion>

<Accordion title="Consider your context">
  Suggestions are general-purpose. Consider your specific contract logic and use case when applying fixes.
</Accordion>

<Accordion title="Combine with other tools">
  Use suggestions alongside trace analysis and security findings for a complete picture of the issue.
</Accordion>

### For developers

<Accordion title="Keep rules focused">
  Each rule should target a specific error pattern. Avoid overly broad matching.
</Accordion>

<Accordion title="Avoid false positives">
  Test rules against various scenarios to minimize false positive suggestions.
</Accordion>

<Accordion title="Document patterns">
  Clearly document what triggers each rule and why it suggests a particular fix.
</Accordion>

<Accordion title="Update regularly">
  Add new rules as common error patterns emerge from the community.
</Accordion>

## Testing

Run the suggestion engine test suite:

```bash theme={null}
go test ./internal/decoder/suggestions_test.go -v
```

Test coverage includes:

* All built-in rules
* Custom rule addition
* Call tree analysis
* Deduplication logic
* Formatting output
* Edge cases (empty events, no matches, etc.)

## Example scenarios

### Scenario 1: Uninitialized contract

```bash theme={null}
erst debug abc123... --network testnet
```

Output:

```
=== Potential Fixes ===
🔴 [Confidence: high]
   Potential Fix: Ensure you have called initialize() on this contract 
   before invoking other functions.
```

**Resolution**: Call the contract's `initialize()` function before other operations.

### Scenario 2: Multiple issues detected

```bash theme={null}
erst debug def456... --network testnet
```

Output:

```
=== Potential Fixes ===
🔴 [Confidence: high]
   Potential Fix: Verify that all required signatures are present and 
   the invoker has proper authorization.

🟡 [Confidence: medium]
   Potential Fix: Optimize your contract code to reduce CPU/memory usage, 
   or increase resource limits in the transaction.
```

**Resolution**: Address authorization first (high confidence), then optimize resources if needed.

### Scenario 3: No suggestions

If no patterns match, the engine provides no suggestions, allowing you to focus on manual debugging.

## Contributing

To add new error detection rules:

1. Identify a common error pattern from community issues
2. Define keywords and event checks
3. Write a clear, actionable suggestion
4. Add comprehensive test cases
5. Document the rule in this guide
6. Submit a PR with real-world examples

<Info>
  Contributions of new error patterns are welcome! Help make Erst smarter for the entire community.
</Info>

## Future enhancements

* Machine learning-based pattern detection
* Integration with contract source code for context-aware suggestions
* Suggestion ranking based on historical accuracy
* Community-contributed rule database
* Multi-language support for suggestions
* Interactive suggestion refinement
* Link suggestions directly to relevant documentation

## Next steps

<CardGroup cols={2}>
  <Card title="Configuration overview" icon="gear" href="/configuration/overview">
    Learn about all configuration methods
  </Card>

  <Card title="Environment variables" icon="terminal" href="/configuration/environment-variables">
    Configure using environment variables
  </Card>
</CardGroup>
