decoder

package
v0.0.0-...-4b2a75f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 4, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

README

XDR Result Code Decoder

Overview

The XDR Result Code Decoder translates binary Stellar XDR error codes into human-readable error messages with detailed explanations. This eliminates the need for developers to manually look up error codes like tx_failed (-1) or op_underfunded.

Features

  • Transaction-Level Error Codes: Comprehensive mapping of all TransactionResultCode values
  • Operation-Level Error Codes: Detailed mappings for operation-specific errors
  • Human-Readable Messages: Clear descriptions and explanations for each error
  • Actionable Guidance: Explanations include suggestions on how to fix the issue

Usage

Basic Usage
import "github.com/dotandev/hintents/internal/decoder"

// Decode a transaction result code
txCodeInfo := decoder.DecodeTransactionResultCode(xdr.TransactionResultCodeTxInsufficientBalance)
fmt.Printf("Error: %s (%s)\n", txCodeInfo.Description, txCodeInfo.Code)
fmt.Printf("Explanation: %s\n", txCodeInfo.Explanation)

// Output:
// Error: Insufficient Balance (tx_insufficient_balance)
// Explanation: Fee would bring account below minimum reserve. Account needs more XLM
Decode from XDR String
// Decode a base64-encoded TransactionResult XDR
output, err := decoder.DecodeResultXDR(resultXDRBase64)
if err != nil {
    log.Fatal(err)
}
fmt.Println(output)
Format Complete Transaction Result
// Format a complete transaction result with all operation results
formatted := decoder.FormatTransactionResult(transactionResult)
fmt.Println(formatted)

// Output:
// Transaction Result: Transaction Failed
// Code: tx_failed
// Explanation: One or more operations failed. Check individual operation results for details
//
// Operation Results:
//   Operation 0: Insufficient Funds (payment_underfunded)
//     Source account doesn't have enough of the asset to send

Supported Error Codes

Transaction-Level Codes
Code Description Common Cause
tx_success Transaction Successful All operations completed successfully
tx_failed Transaction Failed One or more operations failed
tx_insufficient_balance Insufficient Balance Fee would bring account below minimum reserve
tx_bad_seq Bad Sequence Number Sequence number doesn't match account
tx_bad_auth Bad Authentication Invalid or missing signatures
tx_insufficient_fee Insufficient Fee Fee is too low
tx_no_account Source Account Not Found Account doesn't exist
tx_too_early Transaction Too Early Before minTime
tx_too_late Transaction Too Late After maxTime (expired)
tx_malformed Malformed Transaction Invalid parameters
tx_soroban_invalid Soroban Invalid Soroban-specific validation failed
Operation-Level Codes
Code Description Common Cause
op_bad_auth Bad Authentication Missing signatures for operation
op_no_account Source Account Not Found Operation source doesn't exist
op_too_many_subentries Too Many Subentries Account has 1000+ subentries
op_exceeded_work_limit Exceeded Work Limit Computational limit exceeded
Payment Operation Codes
Code Description Common Cause
payment_underfunded Insufficient Funds Not enough of the asset
payment_no_trust No Trustline Destination lacks trustline
payment_not_authorized Not Authorized Asset authorization required
payment_line_full Trustline Full Would exceed trustline limit
payment_no_issuer Issuer Not Found Asset issuer doesn't exist
Create Account Operation Codes
Code Description Common Cause
create_account_underfunded Insufficient Funds Not enough XLM to create account
create_account_already_exist Account Already Exists Destination already exists
create_account_low_reserve Low Reserve Starting balance < 1 XLM

Integration with CLI

The decoder is integrated into the erst debug command to automatically display human-readable errors:

$ erst debug abc123...def789

Transaction Result: Insufficient Balance (tx_insufficient_balance)
Explanation: Fee would bring account below minimum reserve. Account needs more XLM

[INFO] Tip: Add more XLM to your account to cover the transaction fee and maintain the minimum balance.

Architecture

Package Structure
internal/decoder/
├── result_codes.go       # Main decoder implementation
├── result_codes_test.go  # Comprehensive test suite
├── examples.go           # Usage examples
└── README.md            # This file
Key Functions
  • DecodeTransactionResultCode(code) - Decode transaction-level codes
  • DecodeOperationResultCode(code) - Decode operation-level codes
  • DecodePaymentResultCode(code) - Decode payment-specific codes
  • DecodeCreateAccountResultCode(code) - Decode create account codes
  • FormatTransactionResult(result) - Format complete transaction result
  • DecodeResultXDR(xdrString) - Decode from base64 XDR string

Testing

Run the test suite:

go test ./internal/decoder/...

Expected output:

PASS
ok      github.com/dotandev/hintents/internal/decoder    0.123s

Future Enhancements

  • Add more operation-specific decoders (ManageOffer, ChangeTrust, etc.)
  • Include links to Stellar documentation for each error
  • Add suggested fixes/remediation steps
  • Support for Soroban-specific error codes
  • Localization support for multiple languages

References

Contributing

When adding new error code mappings:

  1. Add the mapping to the appropriate function in result_codes.go
  2. Include a clear description and actionable explanation
  3. Add test cases in result_codes_test.go
  4. Update this README with the new codes
  5. Run tests to ensure everything works

License

Copyright 2026 Erst Users
SPDX-License-Identifier: Apache-2.0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecodeEnvelope

func DecodeEnvelope(envelopeXdr string) (*xdr.TransactionEnvelope, error)

DecodeEnvelope decodes a base64-encoded XDR transaction envelope

func DecodeResultXDR

func DecodeResultXDR(resultXDR string) (string, error)

DecodeResultXDR decodes a base64-encoded TransactionResult XDR and returns human-readable output

func DecodeXDRBase64AsDiagnosticEvent

func DecodeXDRBase64AsDiagnosticEvent(data string) (*xdr.DiagnosticEvent, error)

func DecodeXDRBase64AsLedgerEntry

func DecodeXDRBase64AsLedgerEntry(data string) (*xdr.LedgerEntry, error)

func Example

func Example()

Example demonstrates how to use the decoder

func ExampleSuggestionEngine

func ExampleSuggestionEngine()

ExampleSuggestionEngine demonstrates how to use the suggestion engine

func FormatSuggestions

func FormatSuggestions(suggestions []Suggestion) string

FormatSuggestions formats suggestions for display

func FormatTransactionResult

func FormatTransactionResult(result xdr.TransactionResult) string

FormatTransactionResult formats a complete transaction result with human-readable errors

func PrintEnvelope

func PrintEnvelope(d *DecodedEnvelope)

func SummarizeXDRObject

func SummarizeXDRObject(data interface{}) string

Types

type CallNode

type CallNode struct {
	ContractID      string         `json:"contract_id"`
	Function        string         `json:"function,omitempty"`
	Events          []DecodedEvent `json:"events,omitempty"`
	SubCalls        []*CallNode    `json:"sub_calls,omitempty"`
	CPUInstructions uint64         `json:"cpu,omitempty"`
	MemoryBytes     uint64         `json:"mem,omitempty"`
	// contains filtered or unexported fields
}

CallNode represents a node in the execution call tree

func DecodeDiagnosticEvents

func DecodeDiagnosticEvents(events []simulator.DiagnosticEvent, maxDepth int) (*CallNode, error)

DecodeDiagnosticEvents builds a call hierarchy from a list of decoded simulator DiagnosticEvents

func DecodeEvents

func DecodeEvents(eventsXdr []string, maxDepth int) (*CallNode, error)

DecodeEvents builds a call hierarchy from a list of base64-encoded XDR DiagnosticEvents. Deprecated: use DecodeDiagnosticEvents instead for gas-aware traces.

type DecodedEnvelope

type DecodedEnvelope struct {
	Type       string
	Source     string
	Fee        int64
	Operations []xdr.Operation
	InnerTx    *DecodedEnvelope // for FeeBump
}

func AnalyzeEnvelope

func AnalyzeEnvelope(b64 string) (*DecodedEnvelope, error)

func DecodeEnvelopeFromInner

func DecodeEnvelopeFromInner(inner xdr.FeeBumpTransactionInnerTx) (*DecodedEnvelope, error)

type DecodedEvent

type DecodedEvent struct {
	ContractID string   `json:"contract_id"`
	Topics     []string `json:"topics"`
	Data       string   `json:"data"`
	CPU        uint64   `json:"cpu,omitempty"`
	Memory     uint64   `json:"mem,omitempty"`
}

DecodedEvent is a human-friendly representation of a DiagnosticEvent

type ErrorPattern

type ErrorPattern struct {
	Name        string
	Keywords    []string
	EventChecks []func(DecodedEvent) bool
	Suggestion  Suggestion
}

ErrorPattern defines a heuristic rule for error detection

type FormatType

type FormatType string
const (
	FormatJSON  FormatType = "json"
	FormatTable FormatType = "table"
)

type OperationResultCodeInfo

type OperationResultCodeInfo struct {
	Code        string
	Description string
	Explanation string
}

OperationResultCodeInfo contains human-readable information about an operation result code

func DecodeCreateAccountResultCode

func DecodeCreateAccountResultCode(code xdr.CreateAccountResultCode) OperationResultCodeInfo

DecodeCreateAccountResultCode decodes CreateAccount operation specific codes

func DecodeOperationResultCode

func DecodeOperationResultCode(code xdr.OperationResultCode) OperationResultCodeInfo

DecodeOperationResultCode converts an OperationResultCode to human-readable format

func DecodePaymentResultCode

func DecodePaymentResultCode(code xdr.PaymentResultCode) OperationResultCodeInfo

DecodePaymentResultCode decodes Payment operation specific codes

type Suggestion

type Suggestion struct {
	Rule        string
	Description string
	Confidence  string // Derived from match specificity: "high", "medium", "low"
}

Suggestion represents a potential fix for a Soroban error

type SuggestionEngine

type SuggestionEngine struct {
	// contains filtered or unexported fields
}

SuggestionEngine provides heuristic-based error suggestions

func NewSuggestionEngine

func NewSuggestionEngine() *SuggestionEngine

NewSuggestionEngine creates a new suggestion engine with predefined rules

func (*SuggestionEngine) AddCustomRule

func (e *SuggestionEngine) AddCustomRule(pattern ErrorPattern)

AddCustomRule allows adding custom heuristic rules

func (*SuggestionEngine) AnalyzeCallTree

func (e *SuggestionEngine) AnalyzeCallTree(root *CallNode) []Suggestion

AnalyzeCallTree analyzes a call tree and returns suggestions

func (*SuggestionEngine) AnalyzeEvents

func (e *SuggestionEngine) AnalyzeEvents(events []DecodedEvent) []Suggestion

AnalyzeEvents analyzes decoded events and returns suggestions

type TransactionResultCodeInfo

type TransactionResultCodeInfo struct {
	Code        string
	Description string
	Explanation string
}

TransactionResultCodeInfo contains human-readable information about a transaction result code

func DecodeTransactionResultCode

func DecodeTransactionResultCode(code xdr.TransactionResultCode) TransactionResultCodeInfo

DecodeTransactionResultCode converts a TransactionResultCode to human-readable format

type XDRFormatter

type XDRFormatter struct {
	// contains filtered or unexported fields
}

func NewXDRFormatter

func NewXDRFormatter(format FormatType) *XDRFormatter

func (*XDRFormatter) Format

func (f *XDRFormatter) Format(data interface{}) (string, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL