Skip to content

fix: handle Stellar tx_bad_seq errors with sequence refresh and retry (#141) - #158

Merged
Tybravo merged 2 commits into
SwiftChainn:mainfrom
mmotunrayo:fix/stellar-bad-seq
Aug 28, 2026
Merged

fix: handle Stellar tx_bad_seq errors with sequence refresh and retry (#141)#158
Tybravo merged 2 commits into
SwiftChainn:mainfrom
mmotunrayo:fix/stellar-bad-seq

Conversation

@mmotunrayo

Copy link
Copy Markdown
Contributor

Closes #141

Problem

Stellar transaction submissions could fail with tx_bad_seq (sequence number mismatch) when a concurrent submission from the same account incremented the sequence number between the XDR build and the submission. The error was not caught or retried, causing permanent transaction failures under concurrent load.

Solution

Created src/services/stellarService.ts (the implementation directory per issue), which provides a dedicated submitEscrowLock() method with:

  • Two-path tx_bad_seq detection (XDR decode via xdr.TransactionResult + string-match fallback) covering all SDK error shapes.
  • Automatic sequence refresh: on tx_bad_seq the account is re-fetched from the RPC node to obtain the current sequence number.
  • Full transaction rebuild: the operation is reconstructed from live DB data (no hardcoded values) and re-simulated via prepareTransaction to attach updated resource fees and footprint.
  • Bounded retry loop capped by STELLAR_BAD_SEQ_MAX_RETRIES (default 3).
  • pollForCompletion(): polls getTransaction() with exponential back-off (500 ms -> 5 s cap) until SUCCESS, FAILED, or polling window exhausted.

Changes

src/services/stellarService.ts (NEW — implementation directory)

  • StellarService class with:
    • submitEscrowLock(input) — submit signed XDR with bad-seq retry
    • rebuildWithFreshSequence() — public helper, re-fetches account + rebuilds from DB + re-simulates
    • pollForCompletion(hash) — waits for ledger inclusion
    • isBadSeqError() — detects tx_bad_seq in both response and thrown error shapes
  • SubmitEscrowLockInput and SubmitEscrowLockResult interfaces exported.
  • All delivery/contract data sourced from MongoDB (no inline mocks).

src/config/env.ts

  • Added 4 env vars to EnvConfig interface and Zod envSchema:

    Variable Default
    SOROBAN_RPC_MAX_RETRIES 3
    SOROBAN_RPC_RETRY_BASE_MS 250
    SOROBAN_RPC_RETRY_MAX_MS 8000
    STELLAR_BAD_SEQ_MAX_RETRIES 3
  • Fixes the pre-existing gap where soroban.service.ts referenced these vars but they were absent from the validated schema.

src/validators/transactionValidator.ts

  • Added submitTransactionSchema (deliveryId, payerAddress, signedXdr).
  • Added SubmitTransactionBody type export.

src/controllers/transactionController.ts

  • Imported stellarService and SubmitTransactionBody.
  • Added submitEscrowLockTransaction() handler (POST /transactions/submit).

src/routes/transactionRoutes.ts

  • Added POST /api/v1/transactions/submit route:

…SwiftChainn#141)

Closes SwiftChainn#141

## Problem
Stellar transaction submissions could fail with tx_bad_seq (sequence number
mismatch) when a concurrent submission from the same account incremented the
sequence number between the XDR build and the submission. The error was not
caught or retried, causing permanent transaction failures under concurrent load.

## Solution
Created src/services/stellarService.ts (the implementation directory per
issue), which provides a dedicated submitEscrowLock() method with:
  - Two-path tx_bad_seq detection (XDR decode via xdr.TransactionResult +
    string-match fallback) covering all SDK error shapes.
  - Automatic sequence refresh: on tx_bad_seq the account is re-fetched from
    the RPC node to obtain the current sequence number.
  - Full transaction rebuild: the operation is reconstructed from live DB data
    (no hardcoded values) and re-simulated via prepareTransaction to attach
    updated resource fees and footprint.
  - Bounded retry loop capped by STELLAR_BAD_SEQ_MAX_RETRIES (default 3).
  - pollForCompletion(): polls getTransaction() with exponential back-off
    (500 ms -> 5 s cap) until SUCCESS, FAILED, or polling window exhausted.

## Changes

### src/services/stellarService.ts  (NEW — implementation directory)
  - StellarService class with:
      submitEscrowLock(input)       — submit signed XDR with bad-seq retry
      rebuildWithFreshSequence()    — public helper, re-fetches account +
                                      rebuilds from DB + re-simulates
      pollForCompletion(hash)       — waits for ledger inclusion
      isBadSeqError()               — detects tx_bad_seq in both response
                                      and thrown error shapes
  - SubmitEscrowLockInput and SubmitEscrowLockResult interfaces exported.
  - All delivery/contract data sourced from MongoDB (no inline mocks).

### src/config/env.ts
  - Added 4 env vars to EnvConfig interface and Zod envSchema:
      SOROBAN_RPC_MAX_RETRIES        (default 3)
      SOROBAN_RPC_RETRY_BASE_MS      (default 250)
      SOROBAN_RPC_RETRY_MAX_MS       (default 8000)
      STELLAR_BAD_SEQ_MAX_RETRIES    (default 3)
  - Fixes the pre-existing gap where soroban.service.ts referenced these
    vars but they were absent from the validated schema.

### src/validators/transactionValidator.ts
  - Added submitTransactionSchema (deliveryId, payerAddress, signedXdr).
  - Added SubmitTransactionBody type export.

### src/controllers/transactionController.ts
  - Imported stellarService and SubmitTransactionBody.
  - Added submitEscrowLockTransaction() handler (POST /transactions/submit).

### src/routes/transactionRoutes.ts
  - Added POST /api/v1/transactions/submit route:
      apiLimiter -> validateRequest(submitTransactionSchema)
      -> transactionController.submitEscrowLockTransaction
  - Full OpenAPI doc comment with all response codes.

### .env.example
  - Documented all 4 new env vars with explanations.

## Retry behaviour

| Scenario                        | Result                                    |
|---------------------------------|-------------------------------------------|
| First submission succeeds       | 200 with hash + ledger                    |
| tx_bad_seq, retry succeeds      | 200 with retriedOnBadSeq=true             |
| tx_bad_seq exhausts all retries | 409 Conflict                              |
| Other submission error          | 502 Bad Gateway                           |
| Not confirmed in poll window    | 504 Gateway Timeout                       |
@drips-wave

drips-wave Bot commented Aug 28, 2026

Copy link
Copy Markdown

@mmotunrayo Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

@Tybravo
Tybravo merged commit d2414e6 into SwiftChainn:main Aug 28, 2026
1 check failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Handle Stellar transaction submission failures gracefully when sequence numbers mismatch

2 participants