Skip to main content
Consolidated architecture for LumenWipe, an open-source tool that cleanly closes a Stellar account and recovers its locked reserves. Reference implementation extended by this project: stellar.expert/demolisher/public by Orbit Lens.

Contents

  1. What this is
  2. The problem
  3. How a Stellar account closes
  4. System architecture
  5. Data sources, and why we run no indexer
  6. Frontend architecture
  7. The API service
  8. The execution plan
  9. Closing positions: classic and Soroban DeFi
  10. Asset conversion and routing
  11. The mediator account flow for exchanges
  12. Allowance inspection
  13. Security model
  14. Trust minimization and decentralization
  15. Infrastructure and deployment
  16. User protection and privacy
  17. Testing strategy
  18. Maintenance after launch
  19. Roadmap
  20. What runs today
  21. Technology stack and standards
  22. Failure modes and recovery
  23. Open questions and known risks
  24. Glossary
  25. References
Companion documents sit alongside this one:

1. What this is

LumenWipe is a guided, non-custodial tool that walks a user through closing a Stellar account from start to finish. It removes everything that holds an account open, converts leftover assets to XLM, and merges the account into a destination address, returning the locked reserves to the user. “Closing” a Stellar account is not a single operation. An account can only be merged once it holds no subentries apart from its signers and sponsors no other account. Getting there means unwinding whatever the account accumulated over its life: trustlines, open DEX offers, data entries, extra signers, liquidity pool shares, and positions in DeFi protocols such as Blend, Aquarius, Soroswap, Phoenix, and FxDAO (testnet only, Section 9.7). Each of those steps is its own transaction, with its own ordering constraints and its own failure modes. The project extends the public-domain stellar.expert/demolisher/public tool built by Orbit Lens. That tool handles the classic case well: it cancels offers, sells assets on the SDEX, removes trustlines and data entries, works with multisig accounts, and can merge into exchange addresses through an intermediary account. It does not support Soroban, so any account with a Blend loan, an Aquarius LP position, or a Soroswap pair share cannot be closed with it today. This project keeps the parts that work, rebuilds them on the current Stellar stack, and adds full Soroban and DeFi parity, an API-first backend that builds the wind-down, an allowance inspector, and a production-grade UX designed for irreversible actions. Beyond the guided UI, two things widen who can use it: sponsored fees close accounts that hold only their locked reserves and cannot pay their own transaction fees (Section 8.1), and a REST API plus a TypeScript SDK let wallets and platforms drive the same wind-down programmatically (Section 7.3). An API service builds every unsigned transaction; the browser independently verifies each one against the user’s own stated intent before it signs, and your account’s secret keys never reach a server. The API holds no user funds and no user keys. It holds two signing keys: the shared exchange mediator, used solely to co-sign the forwarding payment to an exchange (see section 11), and the fee-bump sponsor, used solely to pay network fees. The codebase is a Bun-workspaces monorepo: a NestJS API service (the product), a thin Next.js web client, a testnet playground, and two published packages: the TypeScript SDK (@lumenwipe/sdk, a fetch client for the API) and the standalone verifier (@lumenwipe/verify). A private @lumenwipe/types package ships inside the SDK. The web reaches the API only through a server-side proxy, so a browser never holds an API key. Core stack at a glance:

2. The problem

Stellar has more than ten million accounts on mainnet, and a large share of them are stale, abandoned, or effectively locked. Two structural facts create the problem. First, every account locks XLM in reserve. The base reserve is currently 0.5 XLM (a network-voted parameter). Since CAP-33, an account’s minimum balance is (2 + numSubEntries + numSponsoring - numSponsored) × base reserve: two base reserves for the account itself, one per subentry it owns (each trustline, offer, data entry, and extra signer), plus one per entry it sponsors for others, minus one per entry of its own that someone else sponsors. A pool-share trustline counts as two base reserves. So an account with four trustlines, two offers, one data entry, and one extra signer locks (2 + 8) * 0.5 = 5 XLM that the user cannot spend until the entries are removed. Across millions of accounts, this is a meaningful amount of capital frozen in the ledger. Second, closing an account cleanly is a manual, multi-step process that most users cannot perform. Any leftover entry causes the final ACCOUNT_MERGE to fail with ACCOUNT_MERGE_HAS_SUB_ENTRIES. A user has to know to cancel every offer, exit every DeFi position, sell every asset, remove every trustline, and clear every data entry, in a valid order, before the merge will succeed. Miss one and the merge reverts. (Extra signers are the one kind of subentry that does not block the merge: the protocol’s check excludes them, and they are deleted with the account.) Centralized exchanges make it worse. No major exchange supports ACCOUNT_MERGE. A user who wants to send their remaining XLM to an exchange cannot merge directly into a deposit address, so the final 1 XLM minimum balance stays frozen on the ledger. The reference demolisher solves this with an intermediary account, and this project keeps that approach. Three groups of users feel this most: individuals consolidating or abandoning wallets, exchanges that need to help users recover funds, and DeFi users with open positions across Stellar protocols. The last group has no tool today, because the existing demolisher has no Soroban support.

3. How a Stellar account closes

ACCOUNT_MERGE transfers the entire XLM balance of the source account to a destination and deletes the source account from the ledger. The protocol enforces strict preconditions. The pre-flight analysis in this tool exists to detect and clear every one of them before it builds a merge transaction. The merge fails with one of these result codes if a precondition is unmet: The pre-flight checks map directly onto these codes. Sponsorship detection and revocation resolve ACCOUNT_MERGE_IS_SPONSOR for every sponsored entry kind that can be revoked. Subentry enumeration and removal prevent ACCOUNT_MERGE_HAS_SUB_ENTRIES. Destination verification prevents ACCOUNT_MERGE_NO_ACCOUNT. The tool never submits a merge it expects to fail. Note that being a claimant of a claimable balance does not block the merge, but sponsoring one does, because the sponsor carries its reserve (one base reserve per claimant, not per balance). An account that created claimable balances is their sponsor unless the sponsorship was later transferred, so those must be resolved first. Claimable-balance sponsorships cannot be self-revoked. CAP-33’s RevokeSponsorshipOp fails with REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE when applied to a CLAIMABLE_BALANCE ledger entry unless a cooperating new sponsor is sandwiched around it via BeginSponsoringFutureReserves / EndSponsoringFutureReserves in the same transaction - every other sponsorable entry kind (account, trustline, offer, data entry, signer) instead reverts to its own owning account’s default sponsorship, which is what this tool’s REVOKE_SPONSORSHIP step relies on. A guided close has no third party willing to become that new sponsor, so a claimable balance this account sponsors is a permanent blocker until a claimant claims it (removing the entry, and its sponsorship, entirely) - there is no self-service remediation. See issue #72’s implementation plan for the full CAP-33 citation.

4. System architecture

The system has three layers: an API service that reads account state, aggregates data, and builds every unsigned transaction (and signs two narrow things, the exchange forwarding payment and the fee-bump envelope); a browser client that verifies each unsigned transaction against the user’s own choices and signs it locally; and the Stellar network plus the external data services the API reads from. The trust boundary is still the browser, but the guarantee is sharpened: a user’s account keys and signing live entirely on the client side, and the browser never signs bytes it has not first verified. The API builds the transaction, but a client-side verify() decides whether it gets signed, and it checks the transaction against the user’s own stated intent rather than trusting the API’s word. The API’s two keys are the shared mediator, which can co-sign the exchange forwarding payment but cannot sign for a user’s account, change a destination, or move a user’s funds, and the fee-bump sponsor, which only pays network fees. Three-layer system architecture: API service builds transactions, browser trust boundary verifies and signs, and Stellar network with external data services Two things to read off this diagram. The unsigned XDR is built by the API and returned to the client; the client verifies it, signs it, and submission is routed back through the API. The API is not in the signing path for a user’s account - it can build and propose a transaction, but only a client-side signature (applied after verify() passes) makes it valid, and its only signatures of its own are the shared mediator’s co-signature on the exchange forwarding payment (section 11) and the fee-bump sponsor’s signature on the outer envelope (Section 8.1). And every external read source is pluggable: RPC, the indexer, the routing API, and the DeFi position API can each be swapped for another provider without touching the transaction logic.

5. Data sources, and why we run no indexer

Building LumenWipe requires reading account state, and that state lives in two places the same way the network splits its tooling: classic ledger state, and live or Soroban state. A practical constraint shapes the whole data design. Stellar RPC’s getLedgerEntries can only return entries whose keys you already know. You pass it serialized LedgerKey values (up to 200 per request) and it returns those exact entries. It has no scan, filter, or “list all trustlines for this account” capability. To build a trustline LedgerKey you already need the asset; to read an offer you already need the offer ID. RPC alone therefore cannot tell you what an unknown account holds. Enumerating an account’s subentries (every trustline, offer, data entry, claimable balance, pool share, signer, and sponsorship relationship) requires an indexer. The project takes a clear position here: we do not build or operate an indexer. Stellar RPC is used wherever it serves the read, and everything it cannot serve comes from a single Horizon-compatible endpoint. This is not a preference: getAccount returns only the sequence number and base reserve, and getLedgerEntries fetches a ledger entry whose key is already known but cannot enumerate an account’s trustlines or offers. Horizon’s deprecation in favor of Stellar RPC does not change that, because its named successor cannot do this job. The provider is set by configuration (PATH_ROUTING_API_*), so moving between SDF’s public instance, Blockdaemon, Validation Cloud, QuickNode or a self-hosted Horizon is a config change rather than a code change. SDF reduced its hosted Horizon to one year of history in August 2024 and steers integrators toward Stellar RPC plus ecosystem data services; the reads this tool takes from Horizon-compatible endpoints are current-state queries, unaffected by that history truncation. Running a bespoke indexer (Captive Core, Galexie, a database) is not the problem this project exists to solve, and it would be operational weight with no payoff for the tool. Instead the tool reads from existing, production-grade sources through pluggable adapters. This section is the one place the production data sources are described; other sections and documents refer back to it. The split is deliberate. An indexer answers “what does this account hold”. RPC answers “what is the exact current state of this specific entry, right now, and will this transaction succeed”. The tool enumerates through one Horizon-compatible provider at a time. The reads behind one enumeration (the account, its offers and its claimable balances) must reflect ledgers at most two apart; otherwise they are read once more, and refused as state_changed if they still do not settle. Immediately before building each round, the API reads the account entry and every enumerated trustline (pool shares included), offer and data entry over RPC in one batched getLedgerEntries call, chunked at 200 keys, and compares them with the enumeration: the sequence, the sub-entry count, the XLM balance, the signers and thresholds, each trustline’s balance and limit, each offer’s amount and assets, and each data entry’s value. Any difference refuses the round with state_changed (409) and the client plans again, and a failed read refuses it too. The claimable-balance existence check before a claim round fails closed the same way. As a completeness check, the enumeration is also reconciled against the provider’s subentry_count: if the counts disagree, the tool surfaces a blocker instead of building a plan that would miss an entry.

Provider failover

Each network’s RPC and Horizon-compatible settings take one URL or an ordered, comma-separated list, with a separate auth header per URL. A one-entry list behaves as a single endpoint always has: no probe, no extra read, no new gate, and a lagging lone provider still ends in state_changed. Everything below applies only to a list with more than one entry. Each rule keeps the same property: a provider’s outage may become a retryable 503, but it must never become a wrong answer about the account.
  • One provider per request. The first RPC use in a request walks the list with getHealth (falling back to getLatestLedger when the answer carries no ledger close time) and pins the first healthy provider whose newest ledger closed within the last 30 seconds. Every later call of that request stays on the pin, even if it dies mid-request, so one round never reads two RPC providers. Outside a request the primary is used.
  • A rate-limited provider is skipped by the next requests. A read or simulation that the pinned provider answers with 429, a 5xx, or a 200 whose body is not a JSON-RPC envelope (empty, cut off before it arrived, or not JSON) ends the request with 503 service_unavailable and Retry-After, and that provider cools down for RPC_PROVIDER_COOLDOWN_MS (70 seconds: the 30-second Retry-After plus the 40-second request deadline, since the 503 can leave that long after the failure and a shorter window would end before the client’s retry arrives): later probes try every provider that is not cooling before it, so the client’s retry pins the next one, and a cooling provider is still probed when every other one fails. A timeout is a 503 too but starts no cooldown, and a send never starts one.
  • The first-party clients make that retry once, and only for reads. The web’s analyze account read and plans, its destination check and the review’s check wait the Retry-After, at most 30 seconds, with a notice the user can stop, then ask once more; the playground’s session-state and batch-plan reads do the same through the SDK’s retry option. A build, a submit or a signature is never repeated.
  • A Horizon-compatible read restarts whole. When a provider fails, the collections and the span check start again on the next one with nothing carried over, so a snapshot is always one provider’s. The sponsorship reads that complete the snapshot use the provider it came from, and never move on their own.
  • Only an outage moves on. Failover is an allowlist: a typed upstream failure, or a body that fails the conformance check (a missing subentry_count or flags). state_changed, a truncated collection and a primary’s “account not found” are answers, and stop the walk, so a caller cannot shop for a provider that has not seen a change yet. A 404 from a later provider means unavailable, because it may simply be behind, and the mediator’s destination probe must not read that as an unfunded account.
  • Lag is an outage, not a change. A snapshot whose oldest read is more than two ledgers behind the pinned RPC, or whose account, offer or claimable-balance response carries no Latest-Ledger header, is unavailable on that provider. This runs before the span check and before the plan-hash check, both of which would otherwise read old state as a changed account. A disagreement from a pinned RPC still behind the snapshot is a 503 as well; once the RPC has reached the snapshot, a disagreement is a real state_changed.
  • The issuer check never fails over. A provider with asset statistics disabled answers 200 with no records, which reads as “issues nothing”, so moving to another provider after an outage would trade a refusal for an open gate. It reads the provider the snapshot came from, or the primary when no snapshot pinned one, and any failure refuses the round. Every provider in a list must run with asset statistics enabled.
  • The budget reaches the last provider. Providers before the last get no retries, and each attempt is capped at an even share of what is left of the 40 second deadline. All providers failing is the typed unavailable.
  • A send never fails over. sendTransaction runs once, on the pinned provider. After an ambiguous failure the API makes one getTransaction call on the next provider: success is reported as success, a failure as a rejection, and anything else leaves the original error. It never sends again.
A Horizon-compatible provider that answers 429 is held, whatever the length of the list, and the refusal is never retried. Until its Retry-After passes (30 seconds, RATE_LIMIT_HOLD_MS, when it sends none; 5 minutes at most), every read to that origin from any request fails as rate_limited without being sent, and a fallback, if any, is tried as for any outage (upstreamGetJson in apps/api/src/lib/stellar/upstream-client.ts). A plan whose route lookup meets the hold answers 503 service_unavailable with Retry-After rather than a plan blocked on prices, and /health/user-path reports the step as rate_limited. Retrying a refusal, or letting the rest of a plan’s lookups go on, only spends more of the budget the whole service shares and keeps the provider refusing longer. close/plan also runs one plan at a time per network and source account (PlanLanes in apps/api/src/lib/close-api/plan-lanes.ts), since each plan prices every asset the account holds and a page re-plans on every answer the user changes. A request that arrives while one is running waits for it, only the newest waiting request runs next, and one replaced before it starts answers 429 plan_superseded having read nothing. The lane is per process, which covers every caller while the service runs as one instance. A plan prices its assets through cachedConversionPath (apps/api/src/lib/stellar/path-quote-cache.ts): a route answer for the same network, asset and amount is reused for 15 seconds (PATH_QUOTE_TTL_MS), lookups of one key already in flight share one request, and an unavailable answer is never kept. A re-plan whose answers leave an asset’s amount unchanged makes no lookup for it. Building the transactions does not use it: it quotes live right before it builds and refuses a route that fell below the plan’s floor. In production the API refuses to start while STELLAR_RPC_MAINNET or PATH_ROUTING_API_MAINNET is unset, so a mainnet service never runs on a compiled-in default. A list with a non-https entry, a duplicate or a header name without its value refuses to start. The boot log prints effective hostnames only: a provider URL can carry a key in its path. Each move to another provider increments a process counter and writes a structured log line.

Horizon-compatible exit plan

Horizon is deprecated upstream and a provider can change or withdraw an endpoint without notice, so the dependency is a recorded decision with a way out rather than a default. The provider contract check runs daily against every configured provider, and a finding is the trigger to act on this table. The fallback for everything RPC cannot enumerate is one indexer or ledger-archive source behind the existing provider seam (horizon-http.ts), chosen when the check or a provider’s notice forces it. Until then a second provider in the failover list covers an outage, not a deprecation: both would drift together. Section 5’s position stands: the project does not run its own indexer unless no provider remains.

Accounts of any age

Account age never limits this design, and that is worth stating precisely because Stellar RPC does have a retention window. The window (at most 7 days) applies only to history-shaped methods: getTransactions, getTransaction, and getEvents. It does not apply to getLedgerEntries, which reads the current ledger snapshot: a trustline created in 2015 and a trustline created yesterday are the same read. Closing an account needs no transaction history at all; it needs current state, which RPC serves for any account regardless of age, and enumeration, which the indexer serves from full history. The one age-correlated wrinkle is Soroban state archival: a long-dormant account’s contract entries (a DeFi position, a token balance) may have expired to the archive. Since Protocol 23, getLedgerEntries still returns an archived entry, with its value and a liveUntilLedgerSeq below the latest ledger (0 once evicted), so the tool reads it as held, the same as a live one. The exit that withdraws it also restores it, in the same transaction: the exit’s simulation marks the archived entries for automatic restore (CAP-66) instead of returning a restore preamble, the signed exit carries that, and its fee stays under the exit fee cap. No separate RestoreFootprint transaction is built. Classic entries never archive. Data flow: enumerate through a Horizon-compatible provider, cross-check over RPC, build and simulate the execution plan, then submit

Trust boundaries and data entities

The diagram above shows the close flow by phase. The same flow, stated as the trust boundaries it crosses and the data entities it carries, plus the integrator session layer that manages self-serve API keys outside the close flow (it is not drawn in the diagram, since it never builds or signs a transaction): Trust boundaries.
  1. The user’s browser. Everything that can authorize a transaction lives here and nowhere else: the wallet (or the in-memory secret key), verify(), and signing. What crosses in is untrusted, API-built unsigned XDR, checked against the user’s own inputs before any signature. What crosses out is signed XDR, and nothing else that could move funds.
  2. The web server. A proxy between the browser and the API that holds the API key (LUMENWIPE_API_KEY) so the browser never does, and the Upstash Redis credentials and hash key for its per-IP rate limit. It builds no transaction and holds no signing key.
  3. The LumenWipe API. Reads state, builds every unsigned transaction and simulates the Soroban ones, and relays submissions. It holds the system’s only two server-side signing keys, the mediator and the fee-bump sponsor (Surfaces 4a and 4b of the threat model), and, in Firestore, the hashes of self-serve API keys, the public merge counter and per-integrator request counts. At its edge sits the integrator session layer (Surface 8): a wallet signs a SEP-53 challenge, or a contract account signs a SEP-45 style authorization, and gets a 30-minute session token that can only list, create, rotate and revoke that account’s own keys. Challenges and tokens are stateless HMACs under INTEGRATOR_AUTH_SECRET, so nothing about a session is stored; a challenge is recorded once used, as a hash with an expiry, so it cannot be used again. It is not trusted to decide what the user signs; that is boundary 1’s job.
  4. External data services. The Horizon-compatible enumeration endpoint, Stellar RPC, OctoPos, the Soroswap and xBull quote APIs, and StellarIndex. Everything they return is untrusted input to the API: enumerated entries are re-read live over RPC, a protocol contract is used only when its live code hash matches the contract registry, and a quote-built swap is decoded and held to a fixed shape before it is offered. The registry gate is per adapter and per network: the position’s contract and every other contract an exit step calls (a Phoenix pool’s stake contract, for example) must resolve to that protocol before anything is built against it, and an entry with no code hash, such as FxDAO’s mainnet vault, matches nothing, so no exit is built against it.
  5. The Stellar network. The authoritative ledger. It enforces signatures, thresholds, sequence numbers, time bounds, and contract-level minimums, whatever any component above it claims.
Data entities. The threat model takes boundaries 1 and 3 surface by surface: key handling and the session layer on the browser side, transaction construction, the two signing keys and the integrator session layer on the API side, and the allowance, conversion, and DeFi-exit flows that cross between them, with Phoenix, FxDAO and xBull each given their own pass. Boundary 2 holds no key that can move funds. Boundary 4 is not given its own pass: it cannot move funds, and its integrity and disclosure risks are covered where its output is consumed, bounded by the live re-reads and registry checks above (the xBull quote source, for example, in Section 9.3 of the threat model).

Data freshness and consistency

DeFi position data is a snapshot, and acting on a stale snapshot would build a wrong exit. The position API returns freshness metadata with every response: a staleness value in seconds, the last indexed ledger, and a partial-result flag when some protocols could not be read. The tool uses this directly. If position data is older than a short threshold it refreshes before building the plan, and it shows the ledger and staleness so the user knows how fresh the view is. Consistency across the boundary between enumeration and execution is the harder problem. Enumeration says a trustline or position exists; the exact amount can move before the user signs. The tool’s guarantee is the live cross-check: every round confirms the entries it was planned from against a fresh getLedgerEntries read taken immediately before construction and refuses to build on any difference, and Soroban exits are simulated against current state before signing. Enumeration decides what to do; a live read decides the exact parameters. That keeps the tool from acting on data that moved.

6. Frontend architecture

The frontend is a Next.js application in TypeScript, and a thin client of the API. It owns no transaction construction: it requests unsigned transactions from the API, verifies each one locally, signs it, and submits it back through the API. A no-restricted-imports boundary lint forbids the web from importing any transaction-building code, so this stays true. It drives the flow through an explicit state machine held in memory, and keeps a small record of a confirmed close so a user can resume it, which matters because a full close is several sequential transactions, not one. The user-facing flow asks for one thing at a time, in the order the work actually needs it. Entry collects only the source account’s public key, nothing else - supplied either by pasting it or by connecting a wallet. The analyze stage reads the account and presents a grouped accordion preview of everything that has to be unwound, and for each non-XLM balance the user makes a per-asset decision: swap it to XLM when a route exists, return it to its issuer, or transfer it intact to an account they name. The return-to-issuer choice is always an explicit confirmation, never a default, and the tool never labels it as a conversion; a transfer is likewise never a default, since it is the one choice that cannot be resolved without an address the user supplies. The destination address and an optional memo are entered last, on the same screen, once the user has decided what the close will do. Exchange detection happens at that point, because it depends on the destination. Only then does the tool build and run the close, and the completion page shows a grouped summary of what happened to each balance and where the reserves went.

6.1 State machine

Demolish flow state machine: Idle → Analyzing → PreflightComplete → StepExecuting ↔ StepFailed → Complete The phase itself lives in memory only. Once the user confirms on the review page, IndexedDB keeps a small close record (SessionRecord in apps/web/types/session.ts; see how closing works for the full rule): the source and destination addresses, the network, the memo, whether an exchange destination routes through the shared mediator (the mediator’s own address is deliberately not stored - verification asserts the hand-off structurally, so a resumed close cannot go stale on a rotation), its status, how many plan steps confirmed with each confirmed transaction’s hash, and the hash of a submission whose outcome is not known yet. It never holds keys, signatures, transaction envelopes or the plan. Before that confirmation, the tab’s sessionStorage keeps the user’s inputs (per-asset choices, transfer destinations, claim answers, destination, memo and the destination acknowledgement, tied to the address it was given for), so a reload of analyze or review hands them back to analyze. Consent to leave a DeFi position behind or to the account’s own checks is never kept, since it is bound to no amount, and the inputs are dropped at the review confirm, so none outlives the consent given there; they are put back only for assets the fresh read still shows unchanged, and the plan is always built again through analyze and reviewed again. On resume the tool re-reads the account and builds a fresh plan for what remains, which the user reviews and signs again. Work that already confirmed is not repeated because it is no longer on the account, not because a step is skipped, and a submission that may still be pending is checked by its hash first.

6.2 Client-side verification (the trust anchor)

The transaction builder lives in the API, not the browser (Section 7). What runs client-side is its counterpart: verify(), the trust anchor. Before the browser signs any API-built transaction, it decodes the XDR and asserts, against the user’s own choices and a bundled exchange registry, that the transaction does exactly what the user asked and nothing more - a merge only to the stated destination, or - for an exchange - into an intermediary that forwards the observed balance straight on to that destination in the same transaction (accepted only for a destination the bundled registry lists as needing it, or that a served registry with a verified maintainer signature adds), payments only as the mediator forward or the payment the user chose for that asset: a transfer whose asset, destination and amount all match their choice, or a return to the issuer of an asset they chose to return - and, in every case, sent by the account being closed rather than by some other account the user’s key happens to sign for, conversions that sell only an asset the user chose to convert, into the account itself and settling in XLM, for at least the minimum the plan showed beside that asset (less 1% for the market to move; an asset only an exit pays in has no quote and is held to a positive minimum), only removals of trustlines, data entries, and offers, SetOptions that never adds a signer or raises thresholds and only ever removes a signer that is genuinely on the account, a matching memo value and type, and no unrecognized operation. Any mismatch aborts before signing. Most of what verify() checks - destination, memo, the trustlines the user chose to claim, and each transfer’s destination - comes from the user’s own inputs, never from the API response, so a compromised API cannot talk the client into diverting funds on those axes. The transfer is the sharpest case: a return to the issuer and the mediator forward have fixed destinations, since the issuer is derivable from the asset and the forward’s destination is the address the user typed, but a return is still accepted only for an asset the user chose to return, and a transfer’s destination is an arbitrary address - exactly the shape of a fund diversion - and the only thing separating a legitimate one from an attack is that the expected value came from the user. Its amount is checked as a floor rather than an exact figure, because a claim round can legitimately raise the balance between the client’s read and the build; paying more to an already-pinned destination is not a loss, while paying less would mean part of the balance went elsewhere. The one exception is the account’s real signer set, used only to confirm a SetOptions signer removal targets a signer that actually exists: that value is sourced from a separate account-state read (GET /v1/:network/account/:address), the same trust domain as the transaction being verified, so it hardens against transaction-builder bugs and partial compromise rather than a wholly hostile API, which could in principle keep that read and the transaction mutually consistent. The pure core is unit-tested against hostile XDR. The served exchange registry carries a detached Ed25519 signature made by a maintainer key held offline, never on the API host, and the web and @lumenwipe/verify verify it against two keys pinned in their releases. A signature that verifies, is not older than the registry bundled in the client and has not expired lets the served registry add an exchange that needs the mediated shape; a missing or failing signature leaves it stricter-only, exactly as before. A signed registry only adds exchanges: it never changes a bundled entry, a memo type or a network scope, and it gates the mediated shape without vouching for the account the merge pays into. The format, the procedure and the rotation story are in docs/security-scope.md. The served exchange registry never decides a memo type. A memo sent under the wrong type reaches the exchange’s address and is credited to nobody, and the served copy is not authenticated, so a served memoType is neither adopted nor silently ignored. For an exchange the bundled registry lists, the bundled type is the one shown and verified, and a served copy that gives it another type blocks the close (registry_memo_type_conflict, and a plain-language block on the plan page) until the two agree. Refusing was chosen over ignoring from the registry data: every listed exchange asks for a text or an id memo, no entry’s type has changed since the registry was added, and the web bundle and the API read the same file, so the two copies disagree only while one deploy is behind the other or when the API is compromised. In the first case the served type may be the current one, and ignoring it would send the deposit under the stale type, while refusing costs a retry; in the second a refusal gives the API nothing it could not already do by declining to build. An integrator on an older @lumenwipe/verify is refused the same way until it upgrades. For an address only the served copy lists, the type the user confirmed is the one verified, and a served type that differs from it refuses the close (registry_memo_type_unconfirmed) instead of replacing it. The web never shows that served type as fixed: the plan page asks the user to choose the memo type for such an address, with nothing chosen until they do, sends the type they chose, and blocks the close on the page when the served copy gives another. The builder it verifies (server-side) enforces the 100-operations-per-transaction protocol limit and splits oversized work into the fewest transactions that limit allows; for Soroban steps it assembles InvokeHostFunction operations and defers footprint, authorization, and resource fee to RPC simulation.

6.3 Wallet integration and signing

Signing has two paths. The primary path, implemented as the default wallet tab in the ExecutionWizard, is stellar-wallets-kit, which provides a unified interface across Varial (formerly Freighter), xBull, Albedo, Rabet, Hana, Ledger (over WebUSB), and WalletConnect; the same connection can also be initiated earlier at account entry, persists to the signing step, and is automatically selected as the active signer once the session is checked and the address and network match. A restored session counts as connected only after the wallet answers with the same address without a prompt (today only Varial can be asked that way); any other restored session shows “Reconnect wallet”. A wallet that does not report its network must be confirmed by the user to be on the page’s network, and a wallet that reports signing with another account, or whose signature only verifies for the other network, is refused before its signature is used. The session is read again right before each signature of a run, so a wallet that went stale or moved network mid-run is not asked again. The checks after signing stay the authority: the signed transaction keeps the approved hash, the named signer’s own key added a signature, and the signing weight rose. (LOBSTR’s own kit module is disabled because it cannot sign transactions; LOBSTR users are reached via WalletConnect instead.) The application passes an unsigned XDR and receives a signed XDR through signTransaction; the underlying private key never enters the application. For Soroban operations the kit also exposes signAuthEntry, though wallet support varies (Varial, Hana, WalletConnect, and Ledger implement it; several others do not), so the tool builds its Soroban exits with source-account authorization, which the plain signTransaction path covers on every wallet, and reserves signAuthEntry for the cases that genuinely need a separate auth entry. The secondary path is an advanced secret-key mode for users whose keys are not in any wallet. In that mode the key lives only in memory for the duration of the execution session, never in any persisted storage and never in a network request, and is wiped on completion, on abort, on navigation away from the flow, or when the user explicitly clicks “Forget key”. Section 13 details the handling. Signing flow: XDR review, wallet or secret-key path, irreversibility confirmation, submit and poll until confirmed For multisig accounts the kit and secret-key paths both support accumulating signatures: the tool collects signatures from several keypairs or wallets in sequence on the same envelope until the account thresholds are met, then submits. Exactly one signer is active at a time, and it is the one the screen names. Each time a transaction pauses for more weight the active signer resets: an entered secret key is wiped and has to be entered again if a later transaction needs it, and a connected wallet stays connected but is offered again only for a transaction that still needs its signature. A signer that already signed the paused transaction cannot start another prompt for it. Otherwise each wallet or key keeps the same session-scoped lifetime as the single-signer case above, and is replaced by disconnecting, clicking “Forget key,” or connecting a different signer.

6.4 Web proxy rate limit

The browser reaches the web’s proxy routes with no API key, and the proxy attaches the first-party key server-side, so apps/web/lib/api/rate-limit.ts caps each client IP per day before anything is forwarded. The counter is a daily key per route in Upstash Redis (apps/web/lib/upstash-redis.ts), holding the IP only as a keyed hash: the first 16 hex characters of an HMAC-SHA-256, under the server-side RATE_LIMIT_HASH_KEY, of the route’s namespace, the UTC date and the IP. Without the key the hash cannot be reversed by enumerating addresses, and the same IP hashes differently on each route and each day, so counters cannot be linked across either. The default bucket is 500 requests a day per route; the landing page’s recovery estimate has its own bucket of 50, since each estimate costs two full account reads. An unknown network is answered 400 before anything is counted. A caller over the limit gets a 429 rate_limited in the { error: { code, message } } envelope, on every limited route, /api/integrator/* included. It carries Retry-After with the seconds left until the next 00:00 UTC (1 to 86 400) and Cache-Control: no-store, so no intermediary can keep it and serve it to another caller. The counter’s key ends in the UTC date, so that boundary is when the count starts again; the key’s 24-hour expiry, renewed on each request, only clears the previous day’s key, and is not the reset. The date in the key and the Retry-After are taken from the same instant, so a request counted just before midnight is never told to wait a whole day. The limiter gives one of four verdicts: allowed, limited (429), unavailable, or disabled. It waits at most one second on Upstash, with no retries, so a hanging backend cannot hold a request until the function’s deadline. A reply it cannot read counts as unavailable, not as over the limit. Credentials are the Upstash URL and token and a RATE_LIMIT_HASH_KEY of at least 32 characters. Without them it is disabled (nothing is counted, with one warning per process) only outside a Vercel deployment: local development and CI. On a Vercel production or preview deployment, which VERCEL_ENV identifies, missing credentials or a missing or short hash key count as unavailable. NODE_ENV is not used, because CI runs a production build with no Redis. What an unavailable limiter means is chosen per route. The default lets the request through, because refusing a step of the close would strand a user part way through an irreversible flow; the API’s own per-key limit on the first-party key still bounds what gets through. Two optional routes with a high upstream cost per request refuse instead, with a 503 service_unavailable in the { error: { code, message } } envelope, Retry-After: 30 and Cache-Control: no-store, and the API is never called: A failure is logged with the route’s namespace and the kind of failure (timeout, error, bad_reply or unconfigured) and at most the error’s name, never the IP, its hash or the error’s message.

7. The API service

The API is a NestJS service and the product itself. It is stateless across a close (it tracks no per-user progress) and keeps only small per-process state (Section 15). It reads account state, aggregates the data the client cannot efficiently fetch, builds the minimal set of unsigned transactions that close an account, and caches its reads. It runs as its own service, deployed separately from the web (Section 15), and every request carries an API key. It accepts no user keys and holds no user funds, and every transaction it returns is unsigned: only the user’s browser can turn one into something the network will accept. Its two signing keys are the shared mediator, which co-signs the exchange forwarding payment only after validating the transaction shape (operation one merges into the mediator, operation two is a payment from the mediator of at least 1 XLM), and cannot change that payment’s destination or amount, and the fee-bump sponsor, which only pays network fees for a transaction the user already signed. If the API were fully compromised it could return a wrong transaction or wrong read data, but the client-side verify() refuses to sign anything that does not match the user’s intent (Section 6.2), and reads are backed by confirmations and on-chain simulation, so it could never sign for or move a user’s account. Building the transactions server-side shapes the rest of the design. The API re-reads live on-chain state itself right before it builds, so it never emits a transaction based on stale data. It stays stateless across a multi-round close by re-deriving the remaining work from current state on each call rather than tracking per-user progress, which is why an interrupted close resumes by simply asking again. And it validates every request, rejecting a bad memo or an unsupported destination with a typed error the client relays in plain language. The web never calls the API directly from the browser; it goes through a server-side proxy that injects the API key, so no key ever reaches the client. The SDK wraps the same surface for programmatic callers (Section 7.3). The REST surface, generated from docs/api-reference/openapi.json by bun scripts/supported-matrix.ts --write: Requests are authenticated with an API key and rate-limited per key, or per client IP when no valid key is sent; the web’s proxy holds the key server-side and applies its own per-IP limit on top, so the shared key can never be turned into an anonymous amplifier. Every API response, errors and early responses such as the rate limiter’s 429 included, carries X-Request-Id, Cache-Control: no-store, X-Content-Type-Options: nosniff and Strict-Transport-Security: max-age=63072000; includeSubDomains, the web’s HSTS value, not preloaded. The request-context middleware sets them before anything else can answer the request (apps/api/src/common/request-context.ts). No response carries X-Powered-By: configureApp turns off Express’s setting. Keys are either manually provisioned (API_KEYS, label=key pairs - the first-party web app and internal partners) or self-serve, backed by a Firestore-native collection keyed by each key’s own SHA-256 hash rather than a separate lookup field, so resolving a key is a single indexed read and the raw secret is never a queryable value. Only the hash is ever persisted or logged; the raw key is returned to its owner exactly once, at issuance or rotation. A self-serve key can carry its own rate-limit override, otherwise the service-wide default applies. A self-serve key can also carry a label and a network scope, both fixed at creation and kept on rotation, and a lastUsedAt time written in batches at most once a minute rather than on every request (Section 13.5). Usage is counted per key as well as per owner: a key’s successful requests ride in the same write as the owner’s daily count, and its 429s are counted in memory and added at most once a minute, never into the total that billing reads. Only counts are kept per key, never a path or an address. Manually provisioned keys stay with the operator, and the admin routes are gated by a separate operator token distinct from any integrator key. Self-serve keys are issued, listed, rotated and revoked by their owner after a wallet sign-in (a SEP-53 signed challenge, apps/api/src/integrator/). On lumenwipe.com the web proxy keeps the resulting session token in an httpOnly cookie and sends it upstream as the bearer credential, so page script never holds it. A contract account (C..., such as a passkey smart wallet) has no key that could sign a SEP-53 message, so it signs in after SEP-45 (v0.1.1, Draft, read 2026-11-19) instead: POST /v1/integrator/auth/contract/{network}/challenge returns two Soroban authorization entries for web_auth_verify on the web authentication contract, the account’s unsigned and the server account’s signed, and POST /v1/integrator/auth/contract/{network}/session takes them back with the account’s entry signed (apps/api/src/integrator/contract-auth.ts). The arguments name the account, lumenwipe.com, api.lumenwipe.com, the server account and a nonce; the nonce is an HMAC under INTEGRATOR_AUTH_SECRET of those, the network, the contract, the issue time and the issue ledger, so a challenge cannot be moved to another account, network or contract. The session is issued only when all of this holds, in order:
  1. The returned list decodes, holds at most two entries, and every entry is the account’s or the server account’s. The account’s credentials are of a kind in CREDENTIAL_READERS, a table with one row per kind the SDK knows (legacy and CAP-71 v2 address credentials are read; source-account and CAP-71 delegated-signers credentials are refused), so a kind a later SDK adds (Protocol 31 proposes two, CAP-90, Draft) does not compile until it has a row. A refused kind answers 401 invalid_challenge with a message naming it, before the nonce is read and without using up the challenge. Delegated signers are refused because the account’s own __check_auth decides who must have signed, through delegates the entry names, and each delegate runs its own code on every provider. That decision rests on CAP-71’s text and the SDK 17.4.0 structure, not on observed host behavior. Conditions to accept it later: a real testnet end to end with a deployed delegating account, a cap on the count and depth of delegates, and a reviewed model of the host in FakeWebAuthRpc.
  2. The nonce verifies, is less than five minutes old by the server’s clock, and the account’s entry authorizes exactly the call it implies: that contract, web_auth_verify, those arguments, no sub-invocation.
  3. The account’s signature expires no later than 70 ledgers after the issue ledger, so a captured signature is useless on-chain soon after the challenge itself.
  4. On every RPC provider configured for the network, the server account exists and the contract runs the attested build, and an enforcing simulation (authMode: "enforce") of web_auth_verify, with the account’s entry and a server entry signed again, succeeds. One refusal refuses; a provider that cannot answer, or answers with a restore, withholds the session.
  5. The nonce is claimed in Firestore with a create that fails when it exists, so a challenge is exchanged once (used-challenge-store.ts, built to serve the classic sign-in too).
The host runs the account’s own __check_auth; nobody can call it directly (“can’t invoke a reserved function directly”, soroban-env-host/src/host/frame.rs), which is why the check goes through a contract call that requires the account’s authorization rather than through a hash the account signs on its own. That contract is SDF’s SEP-45 reference, stellar/sep45-reference@3dcabc96 contracts/web_auth, built by its attested release (Wasm hash 3c8d0b8b…54cc): it calls require_auth on the account and on the server account and keeps no state. On mainnet it is SDF’s own deployment, CALI6JC3MSNDGFRP7Z2OKUEPREHOJRRXKMJEWQDEFZPFGXALA45RAUTH, listed in SEP-45; on testnet, which resets, it is an instance of the same Wasm named by INTEGRATOR_WEB_AUTH_CONTRACT_TESTNET. The server account is the key INTEGRATOR_WEB_AUTH_SIGNING_SEED holds, and must exist on the network, because the host loads an account to check its signature. Without the seed, the testnet contract, the account on the ledger or the attested code, the routes answer 503 contract_sign_in_unavailable. What this trusts:
  • Every configured RPC provider. The verdict is the providers’ simulation, not a check the API runs itself. Requiring all of them to agree means a single lying provider can withhold a session but not grant one; providers that all lie together can grant a session for any contract account. They are the same providers every account read already trusts.
  • The ledger at the simulated ledger. The account’s code and signers are read as they are then. An account that changes its signers keeps a session issued before the change for up to 30 minutes.
  • The account’s own code. Ownership means what the account’s __check_auth accepts. An account whose check accepts anyone can be signed in as by anyone, exactly as anyone can move its funds; that reaches only the keys that account owns, since the nonce binds the account and every keys route is scoped to the session’s address. A check that panics or refuses gives a 401.
  • Testnet resets. A contract address is derived from the network, so a mainnet account can never be claimed through testnet. After a testnet reset, whoever controls a testnet contract’s deployer and salt can deploy it again at the same address and so manage the keys that testnet address owned.
A sign-in costs one ledger read per provider (cached ten minutes once it succeeds) and one RPC health read for the challenge, and one simulation per provider and one Firestore write for the session.

7.1 DeFi position adapter

The API consumes OctoPos behind one adapter interface, so the rest of the system never sees provider-specific shapes. OctoPos is an existing DeFi Position API in the Stellar ecosystem, and the API builds on it rather than reinventing protocol indexing. The adapter keeps the provider pluggable: it can be pointed at any compatible provider, and if OctoPos is unavailable the tool enters a degraded mode: classic entries process normally, and the user is warned that DeFi positions could not be detected and must be checked manually. OctoPos covers position detection across Blend, Aquarius, Soroswap, Phoenix, and FxDAO (exit testnet only), plus native wallet balances, and reports claimable AQUA rewards and pending Phoenix rewards alongside the positions. It also exposes two pieces the tool leans on directly: for unsubscribed addresses it returns queryKeys (ready-made ledger keys plus pool and pair metadata) so positions can be read straight over RPC getLedgerEntries without OctoPos storing anything server-side, which fits this tool’s live re-read invariant exactly. One boundary matters for planning: OctoPos serves mainnet only. On testnet the tool discovers DeFi positions through direct contract reads driven by the contract registry, which is the same code path the degraded mode uses, so the fallback stays exercised by every test run. The provider returns a position payload, an enrichment dictionary (asset symbols, decimals, USD prices and their source, contract names and versions), and a meta block with freshness and confidence fields. The adapter maps these onto one normalized model so the transaction builder sees a single contract: The adapter uses the authenticated tier where an API key is configured and the public tier otherwise. It sends only the address it was asked to analyze, and it caches only public position data. DeFi position adapter: OctoPos query with freshness gate and degraded-mode fallback when the provider is unavailable

7.2 Caching

The API keeps no read cache for account state, positions or routes: every plan and every build reads live. Caching happens in the web’s proxy, on five routes, and holds public read-only data with no keys and no user identity. A cached response never becomes an input to a signed or verified value; apps/web/tests/unit/cached-response-boundary.test.ts and apps/web/tests/unit/cached-routes.test.ts enforce that and this table. Every other route is no-store. That includes /api/[network]/paths, whose amount may be a user’s balance, /api/[network]/estimate, the landing page’s recovery estimate, whose read is keyed by an address and which takes that address in a POST body (its own rate-limit bucket, 50 requests per IP per day), and the routes that do feed verify() by design: close/plan for conversion floors and account for the balance, signers and thresholds. Those are read fresh and carry the trust limits described in Section 13. The exchange registry is also uncached, and it can only tighten what the bundled copy allows.

7.3 Integration surfaces: API and SDK

The API is the product, and the guided web app is just its first consumer: it drives the whole wind-down through the same public surface any integrator would use, which is the standing proof that surface is complete. The audiences that close accounts at scale are not clicking through a wizard:
  • REST API: analysis, plan generation, per-round unsigned-transaction building, mediator co-signing, and submission, so a platform can drive a wind-down from its own backend, verify and sign with its own keys, and submit. It is stateless across a close - each call re-derives the remaining work from live on-chain state - so an operator decommissioning a fleet of deposit or payout accounts just calls again, per account and per round.
  • TypeScript SDK (@lumenwipe/sdk): a thin, dependency-light fetch client over that API that does not bundle the Stellar SDK, so a wallet can embed a “close account” flow inside its own UI and signer. A shared @lumenwipe/types package keeps request and response types identical across the API, the SDK, and the web.
The design cost of this is near zero, because the split makes the public surface the only surface: the transaction-building logic lives in one place (the API), the web is a thin client whose lint boundary forbids it from re-implementing any of it, and signing was never coupled to the UI. The audiences are concrete: wallets offering account closure as a feature, platforms with per-user Stellar accounts (payouts, remittances, embedded wallets) recovering sponsored reserves when users churn, and exchanges or anchors giving customers a clean off-boarding path.

8. The execution plan

From the analysis the tool generates a deterministic, ordered plan. Same account state, same plan. The order satisfies ledger constraints: you cannot withdraw collateral while a loan is open, you cannot remove a trustline while it holds a balance, and you cannot merge while any subentry remains. Ordered close execution plan: normalize signers first when no single key can sign → exit DeFi → move Soroban tokens → withdraw pool shares → claim balances → normalize signers → revoke sponsorships → remove data entries → cancel offers → handle assets → remove trustlines → merge account, through the mediator last for an exchange A few details that matter for correctness:
  • DeFi exits come first, before any classic step, and the plan lists them in that order; only a signer normalization that has to run first precedes them (below). Each is its own Soroban transaction, and what it withdraws lands in a trustline the classic steps then dispose of and remove. Because the exit round runs before offers are cancelled, a repay can only spend what is not held back by an open offer or the minimum reserve; a debt the spendable balance cannot cover blocks with the exact shortfall rather than building a transaction that would fail. The Soroban token rounds follow, each token its own transaction: every transfer first, then every conversion to XLM.
  • Signer normalization opens the close when extra signers exist, after the exit, token and claim rounds, so a single key can authorize every later step. It removes each extra signer with SetOptions weight 0 and sets the low, medium, and high thresholds to 0/1/1. This step is a usability and efficiency choice, not a merge precondition: the protocol’s subentry check excludes signers, so an account could merge with them in place. Removing them early collapses a multisig flow to one key for the remaining transactions and turns each signer’s 0.5 XLM reserve into spendable balance mid-flow, where it can cover fees. When no single key of the account reaches every threshold, normalization is instead the close’s own first transaction, ahead of the DeFi exits and every other round, and holds only the signer removals and the threshold reset: the master key signs it with enough co-signers, and then signs every later transaction alone (multisig cosigning). It does not close the account, so the API emits it only while no later refusal is already known from the state it reads.
  • Claimable balances are claimed in a round of their own, after the token rounds and before the close that removes signers, data entries and offers, so the plan lists the claim steps there too. The plan’s step order is the order the transactions run, and the review screen’s “In order” list shows it unchanged (how closing works).
  • Classic liquidity pool shares are withdrawn in a round of their own, after the token rounds and before the claims (Section 9.2). What a pool returns depends on its reserves when the round lands, so the steps that dispose of it are built from the balances the next round reads.
  • Steps with more than 100 operations split into batches of 100, the protocol limit per transaction.
  • A step that turns out to be a no-op (no offers, no data entries) is skipped, not submitted.
  • Soroban steps are one InvokeHostFunction per transaction, because each needs its own RPC simulation for footprint, authorization, and resource fee.
  • The plan is recomputed when a confirmed session resumes, so external changes between sessions are reconciled rather than blindly repeated.
There is no separate “fast path”: producing the minimal set of transactions is simply how the tool closes. For most accounts that minimum is a single transaction, signed once - signer normalization, sponsorship revocation, data removal, offer cancellation, per-asset disposition (each balance swapped to XLM, returned to its issuer, or paid to an account the user named), trustline removal, and the account merge, applied atomically in that order. An exchange destination adds one transaction, the co-signed mediator transfer, since exchanges do not accept a direct merge. Some situations inherently need more than one: a claimable-balance account claims first and closes second so the proceeds are not lost; a Soroswap-aggregator swap is a Soroban InvokeHostFunction, which a transaction may not mix with other operations, so that conversion becomes its own transaction; and work exceeding one transaction’s worth of operations splits across the fewest transactions the 100-operation limit allows. The API re-quotes swap routes at build time, and if an asset has lost its route between analysis and signing it refuses the build with a quote_drifted error naming the asset, rather than emitting a transaction that would fail - or silently re-deciding the asset for the user. Re-deciding it to a return-to-issuer would destroy a balance on the tool’s own initiative, which the “never silently skipped” invariant exists to prevent; the user re-decides that asset themselves, and since the transfer disposition needs no route, losing one no longer forces a choice between burning the balance and abandoning the close. Because the API re-derives the remaining work from live state on every round, these multi-transaction closes need no server-side progress tracking: the client verifies and signs what it is given, submits, and asks for the next round until none remains. Because a wind-down can be several sequential transactions, a single end-to-end dry run is not always feasible. The tool’s preview approach is two-tiered: a grouped accordion preview up front that gathers everything to be unwound into sections (signers, data entries, offers, positions, and the per-asset dispositions), with the estimated fee and the estimated final XLM that reaches the destination, and a simulation immediately before each signature using simulateTransaction for Soroban steps and a build-and-validate check for classic steps. Any simulation failure is surfaced in plain language before the user is asked to sign, never after. The completion page mirrors the preview: a grouped summary of what happened to each balance, the transactions that ran, and where the reserves went.

8.1 Sponsored fees: closing accounts that cannot pay their own way

The accounts that most need closing are often the ones that technically cannot start. An account sitting at exactly its minimum balance (the bare 1 XLM minimum, or more XLM locked entirely in subentry reserves) cannot pay even the 100-stroop base fee: the network rejects the transaction with txINSUFFICIENT_BALANCE because the fee would take the account below its reserve. Without help, these accounts are stuck holding their own reserves hostage. The fix is the protocol’s fee-bump transaction (CAP-15). The user builds and signs the inner transaction in the browser exactly as in every other step, with its inner fee set to zero. The API (POST /v1/:network/fee-bump/sponsor, apps/api/src/fee-bump/) wraps it in a fee-bump envelope whose fee source is a dedicated, lightly funded fee account and signs only the outer envelope - it does not submit; like the mediator’s own co-sign step, it hands the fully-signed envelope back for the client to submit through the same /submit endpoint every other step already uses, rather than duplicating that retry-and-confirm logic a second time. The semantics are exact: the fee account pays the entire fee, the inner source pays nothing, and the inner transaction’s signature covers its contents, so the API cannot alter an operation, an amount, or a destination without invalidating the user’s signature. The fee account cannot move user funds; the only thing it can spend is its own XLM, on fees. Availability by network (as of 2026-10-10): sponsored fees are available on testnet; mainnet availability follows the deployment status in the monitoring plan, and without a configured mainnet fee account the API reports sponsored closes on mainnet as unavailable. Because this adds a second funded key to an API that otherwise holds only the mediator co-sign key, the surface is deliberately narrow, mirroring the mediator co-sign validation:
  • The API decodes the inner transaction and sponsors it only if every operation matches the wind-down shapes (ChangeTrust with limit 0, ManageSellOffer/ManageBuyOffer with amount 0, ManageData removals, SetOptions signer normalization, ClaimClaimableBalance, conversion payments, AccountMerge).
  • A transaction with any operation outside those shapes (revoking a sponsorship, paying an asset to its issuer or to another account, opening a trustline) is the account’s own. The build keeps what the account holds above its reserve for those fees first, and for the ones later rounds will need, and sponsors any other transaction it cannot pay from what is left. The plan and every round report a close the account cannot pay that way (close_fee_balance_short, with the amount) before the first round is built.
  • The outer fee is capped per transaction (MAX_FEE_BUMP_STROOPS), and the sponsor keeps a daily budget per inner source account, per API key and in total, refusing with sponsorship_budget_exhausted (429) once one is spent. The inner transaction must expire within MAX_SIGNED_VALIDITY_SECONDS and be the next transaction of an existing account (sponsor_source_unusable otherwise), so a transaction that can never land is neither signed nor charged. Balance alerting on the fee account runs hourly on the deployed testnet sponsor (S4b.Denial.1.M.1 in the monitoring plan); its rate half waits for a usage baseline. Replay is structurally impossible: the inner transaction consumes the source account’s sequence number, and the fee-bump wrapper carries no sequence number of its own.
The reserves released by the wind-down repay the sponsorship many times over, so the feature funds itself at the account level. On infrastructure, the ecosystem context is precise and worth stating: SDF deprecated the Launchtube service in March 2026 and designates the OpenZeppelin Relayer as its successor. OpenZeppelin’s hosted Channels service requires no infrastructure, but as of mid-2026 it accepts only transactions containing a single invokeHostFunction operation, so it can sponsor Soroban steps and nothing else; the fee-bump wrap for classic operations (which is most of a wind-down) exists only in the self-hosted relayer’s sponsored-transactions mode. The tool therefore implements the classic fee-bump endpoint inside its own API, which is small (build the envelope, validate, sign the outer layer, submit), and treats the self-hosted OpenZeppelin Relayer as the drop-in alternative for operators who prefer audited policy infrastructure, with the hosted Channels service usable for Soroban-only steps. Fee sponsorship covers transaction fees only; it is distinct from CAP-33 reserve sponsorship, which this flow does not need.

9. Closing positions: classic and Soroban DeFi

This is the part the existing reference tool cannot do, and the core of the technical work. Detection and unwinding are separated. OctoPos tells the tool what positions exist across every supported protocol, along with the contract addresses and pool metadata behind them. The tool then constructs every exit transaction itself, reading exact on-chain state over RPC and simulating before signing. It integrates each protocol through its published SDK, public API, or contract interface; it does not guess at contract shapes. A versioned contract registry maps each pool or vault contract’s wasmHash to a known protocol version. An unknown wasmHash flags that position for manual review rather than risking an exit transaction built against the wrong interface. The code a contract runs is read from its live instance: either the Wasm hash the instance carries, or, for a CAP-85 external reference, the hash its owner contract’s tag entry holds, re-read on every resolution. A referenced contract matches only an entry that pins the same owner and tag, and the owner’s own code is registered and verified too, since it can repoint every contract that references it. The same registry also vouches for the routers Section 10’s conversion path is allowed to call: Soroswap’s aggregator and router, and, mainnet-only and opt-in (XBULL_CONVERSION_ENABLED), xBull’s PathPayment router - a second, best-effort quote source raced alongside Soroswap’s, never in place of it. The protocols and their exit mechanics at a glance: Coverage is driven by what users actually hold, not by market share. By current activity, Blend is the largest lending market and Aquarius the largest AMM, and Soroswap and Phoenix are smaller. FxDAO, a CDP protocol, has stopped operating on mainnet (Section 9.7), so its exit runs on testnet only and a mainnet FxDAO position is surfaced as a blocker. The tool supports all of them because a user with a position in any of them needs to close it to merge. A position in a frozen, deprecated, or winding-down contract must stay exitable: closing a position is exactly the withdraw-and-repay path such a contract still allows, so the tool reads contract status, surfaces it to the user, and never hides a position because its protocol changed state. The user’s funds are still there.

9.1 Classic DEX offers

Open offers are cancelled with ManageSellOffer or ManageBuyOffer carrying the existing offer ID and amount = 0, which deletes the offer and frees its 0.5 XLM reserve. Passive sell offers, created with CreatePassiveSellOffer, are cancelled the same way. Offers batch at up to 100 per transaction. No external integration is needed; offers are enumerated from the indexer.

9.2 Classic Stellar liquidity pools

Stellar’s native AMM (CAP-38, protocol 18 and later) holds a user’s stake as a pool-share trustline, which costs two base reserves. The only operation that reduces shares is LiquidityPoolWithdraw, which burns shares and returns both reserve assets, and a pool-share trustline cannot be removed while shares remain. An asset trustline cannot be removed while a pool-share trustline uses it either (CHANGE_TRUST_CANNOT_DELETE), so the pool comes out first. The account read takes the share balance from the Horizon-compatible endpoint and each pool’s ledger entry (its asset pair, fee, reserves and total shares) over RPC, in one batched getLedgerEntries. The withdrawal is its own round, after the Soroban token rounds and before the claims: per pool, one LiquidityPoolWithdraw of the whole share balance, then a ChangeTrust with limit 0 on the pool-share asset, built from the pool’s own parameters. stellar-core pays out floor(shares × reserve / totalShares) of each asset, so each minimum is that amount, read from the pool’s ledger entry when the round is built, less 1%, and at least one stroop while the pool gives any. A pool that moves further before the round lands fails with LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM, and the whole transaction, the line’s removal included, fails with it: nothing is withdrawn, and the next call builds again from the ledger. An empty share line is only removed, since the ledger refuses a withdrawal of zero shares as malformed. What the pool pays in lands in the account’s own trustlines, and the next round converts, sends or returns it as the user chose, with every other balance. XLM lands in the account’s balance; an asset the account issues is retired, since an issuer holds no trustline for its own asset. A pool-share trustline sponsored by another account is removed the same way, and the sponsor gets its two reserves back. The plan refuses a pool, with the liquidity_pool_shares_held blocker, only when the withdrawal cannot land safely: the pool’s entry could not be read, an asset’s trustline is not fully authorized (a line the issuer only lets keep its offers would receive the withdrawal and then hold a balance it can neither spend nor remove), or an asset’s trustline limit leaves no room for what the pool pays. The fee sponsor does not accept a withdrawal (Section 8.1), so the account pays the pool round’s fee itself, and the plan’s fee projection counts it. verify() accepts a withdrawal only for a pool the account read shows it holding shares in, for exactly those shares, with each minimum above zero while the pool gives any, no lower than 98% and no higher than 101% of what the read’s reserves give. The lower bound protects the user; the upper bound is a sanity limit, since a minimum the pool cannot meet only fails the transaction. A pool-share trustline removal is accepted only for a held pool, with the pool id derived from the asset pair and fee the operation itself carries.

9.3 Blend (lending and borrowing)

Blend positions are detected by OctoPos: supply held as bTokens, debt as dTokens, with per-position health factors. The tool builds the exit itself with the official @blend-capital/blend-sdk through the Pool.submit entry point, which takes a list of typed requests, each a { request_type, address, amount }. The relevant request types are Repay (5), Withdraw (1), and WithdrawCollateral (3); supplied and collateralized balances are tracked separately, so the exit uses the request type matching how each position is held. For withdrawals, passing an amount larger than the position clamps down to the actual balance, which the tool uses to fully exit without dust. Repay behaves differently: the pool pulls the full stated amount from the account and refunds any excess in the same transaction, so the tool pads the repay only by a small accrual margin (the pool refunds it) and caps it at what the account actually holds. (OctoPos ships a Transaction Builder that can construct Blend exits server-side, but its own documentation marks it experimental and unmaintained, so the tool does not depend on it.) Blend unwind: detect position, resolve pool version, repay dToken debt, verify health factor, withdraw bToken supply, handle backstop Q4W queue The order is enforced: repay all dToken debt first, then withdraw bToken supply, because the protocol rejects collateral withdrawal that would leave a position undercollateralized. When the account lacks the asset to repay, the tool routes and acquires it first (Section 10). Two Blend details round out the exit. BLND emissions are not reported by OctoPos, so the tool reads unclaimed emissions through the Blend SDK’s emission data - per reserve token, for supplied, collateralized, and borrowed balances alike - and claims them with the pool’s claim(from, reserve_token_ids, to) as the first step of the exit, because a merged account can never come back for them. Emissions accrue every second a balance exists, so the same fifteen-minute rule as Aquarius applies: emissions worth less than that of the position’s own accrual are what the close itself produced and are left with the pool rather than claimed round after round. Receiving BLND through its Stellar Asset Contract needs a trustline; without one the exit blocks and says so. And Blend’s backstop module uses a queue-for-withdrawal (Q4W) cooldown, 21 days on V1 and 17 days on V2 (the backstop token is the BLND:USDC 80/20 Comet LP share on both). The tool reads the account’s deposit in the pool’s backstop alongside the pool position - on testnet, detection reads the backstop’s UserBalance(pool, user) for every registered pool - and handles it by its queue state: shares whose queue has run out are withdrawn as a step against the backstop contract (withdraw(from, pool_address, amount)) once the close can carry the LP token they pay out in - a Soroban token the conversion step does not handle yet (§10, #161), so until then they block with instructions; shares still cooling down, or never queued, block the exit by name with the time left. An earlier draft of this design warned and proceeded instead, but a merge with shares still in the backstop forfeits them, so a cooldown the tool cannot skip is a reason to wait, not to lose the deposit. BLND emissions accrued to the deposit itself block the same way: the tool does not claim them, because on V2 a backstop claim re-deposits them as LP shares rather than paying them out. Blend has V1 and V2 pools on mainnet, and the SDK ships both contract clients, so the tool resolves the pool version per position before building the exit. A repay spends XLM or a classic asset, which the browser lets an exit move only through a contract the bundled registry names, so the registry lists the live mainnet Blend pools by address, each confirmed on-chain to run the registered V1 or V2 pool code and to be a pool its factory deployed; a repay into any other pool is refused at signing.

9.4 Aquarius (AMM)

Aquarius is a Soroban AMM whose router deploys pools in three codes: constant-product, stableswap, and concentrated-liquidity. Each pool’s LP shares live in a separate share-token contract. A share-based position (constant-product or stableswap) is withdrawn by calling the pool’s own withdraw(user, share_amount, min_amounts), which burns the account’s shares and pays every reserve back pro rata, bounded by one floor per token in the pool’s own token order; the floors are the account’s share of each reserve less the slippage tolerance, read from the pool’s instance at build time. Accrued AQUA rewards are read through a simulated get_rewards_info(user) and claimed with claim(user) as their own step before the withdrawal: a merged account can never come back for them. Rewards accrue for every second the account holds shares, so a claim always leaves a fresh, tiny reward behind by the time the next round reads the position; a reward worth less than fifteen minutes of the position’s own emissions is taken to be what accrued during the close itself and is left with the pool rather than claimed again without end. Two conditions stop the exit with an explanation rather than lose the rewards silently - the pool’s administrator has paused claiming (kill_claim), or the account has no authorized AQUA trustline to receive them. Concentrated-liquidity pools keep positions as tick ranges without shares and are refused by name until they have their own adapter. Pools share one code hash per type, so the registry lists the router and one representative pool per code; on testnet, where there is no position indexer, detection enumerates the router’s pools and reads the account’s balance in each share token. Aquarius is also the one protocol whose execution is known to diverge from its simulation. Both withdraw and claim checkpoint the account’s rewards in the pool’s reward gauges, and that checkpoint writes the account’s per-gauge reward entry only once the reward period has moved on since the account’s last interaction. A simulation run inside the same period reads the entry and never writes it, so the footprint records it read-only, and the execution a few ledgers later traps on a write outside the footprint. The adapter’s post-assembly hook (hardenBuilt, optional on the adapter contract) moves the account’s own reward entries to the read-write footprint and adds the write capacity and fee they need. The runner requires the transaction to come back byte-for-byte identical outside its fee and Soroban resource data - source, sequence, bounds, memo, operation, arguments, authorization tree, network - and still applies the fee cap, so the hook can widen what the transaction may touch but never change what it does. It can only move keys the simulation already read; pool-level reward data is written by every simulation and needs no help.

9.5 Soroswap

Soroswap is a Soroban AMM. LP withdrawal calls the router’s remove_liquidity(token_a, token_b, liquidity, amount_a_min, amount_b_min, to, deadline), which pulls the account’s LP tokens into the pair and pays both reserves back to to. The tool builds that call itself, against the router the contract registry vouches for, and simulates it like every other exit; the public Soroswap API (which needs an API key and would hand back bytes the tool did not build) is not used. Everything the plan needs is read from the ledger: the pair’s instance holds its two tokens, both reserves, and the LP supply, and the account’s shares are the pair’s SEP-41 balance. The floors passed to the router are the account’s share of each reserve less the slippage tolerance, a fresh quote from the very state the exit executes against. Pairs share one code hash, so the registry lists the factory, the router, and one representative pair; on testnet, where there is no position indexer, detection enumerates the factory’s pairs (TotalPairs, PairAddressesNIndexed(i)) and sweeps the account’s share balance across them in chunked reads. Receiving a classic asset through its Stellar Asset Contract needs a trustline; a withdrawal into an account without one is refused with the asset named rather than left to fail at the ledger.

9.6 Phoenix

Phoenix is a Soroban AMM. The pool contract exposes withdraw_liquidity(sender, share_amount, min_a, min_b, deadline, auto_unstake): six arguments in every mainnet pool code’s own contract spec, sent with deadline and auto_unstake both None. A pool given another argument count fails at the ledger. The project’s testnet pool and stake run the mainnet v1 pool and stake code, created, seeded and kept from archiving by apps/api/scripts/phoenix-testnet-pool.ts, so the testnet suite and the playground exercise the call mainnet receives. A read-only mainnet integration check simulates the withdrawal against one listed pool of each code. Staking itself lives in a separate contract whose entry points are bond and unbond, and unbond requires the original stake’s timestamp, so the tool enumerates individual stakes to exit a staked position. It withdraws the full share balance with a minimum-received bound, unbonding every stake first where a position is staked. The withdrawal moves the account’s shares in the pool’s share token, a separate contract the pool’s CONFIG names as share_token: the pool is not its own share token. Detection reads it there (completing an OctoPos LP or stake position, or, in the direct read, reading the shares on it together with the stake contract’s BondingInfo, so an account that bonded every share is still found by its stakes) and every Phoenix position carries it as shareToken, so the browser admits the withdrawal’s share transfer without any token-balance indexer, and Soroban token discovery never lists the shares as a token of their own. The registry lists each mainnet Phoenix pool that runs a registered pool code by address. Each pool has its own stake contract, named in the pool’s CONFIG, and the browser lets unbond run only on a stake contract the registry names, so the registry lists every listed pool’s stake contract too, each confirmed on-chain to run the registered v1 or v2 stake code or another build of either with the same unbond and stake layout. The one pool without a stake contract runs Phoenix’s pool_blended code (registry version blended): it names itself as its stake contract and rejects auto_unstake, so its positions exit through withdraw_liquidity only and no unbond is ever planned against it, and since its delegate may lend reserves to Blend, no withdrawal larger than what the pool still holds is built.

9.7 FxDAO

FxDAO is a CDP protocol: a user locks XLM collateral in a vault and mints a stablecoin (USDx, EURx, or GBPx, one denomination per vault). Vaults open at a 115% collateral ratio and liquidate below the 110% minimum, both admin-configurable per denomination. Closing a vault means repaying the stablecoin debt and withdrawing the XLM collateral. The vault contract tracks vaults in a sorted linked list, so debt repayment through pay_debt requires passing the neighboring vault keys, and vaults are enumerated through get_vaults. When the account does not hold enough stablecoin to repay, the tool acquires it through routing first. If a vault is undercollateralized at close time, automatic closure is not safe (it would invite liquidation), so the tool surfaces a clear error and asks the user to manage that vault manually. A denomination is the symbol the vault contract keys its storage by, not the stablecoin’s ticker: the mainnet vault stores USD, EUR and GBP, and the testnet reference deployment usd. Detection reads the denominations from the vault’s own instance (every Currency(denomination) and VaultsInfo(denomination) key) and probes Vault(account, denomination) under each, so no symbol is pinned in code. The position carries the stablecoin the vault registers for its denomination (Currency(denomination).contract, read from the vault’s instance) as debtToken: the token the repay burns, which the browser admits from the position itself and Soroban token discovery confirms on the ledger as a balance. Current mainnet status: FxDAO has stopped operating, and closing an FxDAO vault on mainnet is not available as a result. This is a fact about FxDAO, not a gap in this integration. FxDAO’s own documented mainnet Vaults contract now runs code that exposes only evict and upgrade on-chain - not pay_debt or any other vault-management entrypoint - confirmed by reading its live interface directly rather than trusting its docs. Its instance also reports panic_mode in its core state, and every denomination’s VaultsInfo records zero open vaults (read on 2026-11-08). Independently, DeFiLlama shows FxDAO’s Stellar TVL dropping to $0 on 2026-05-20 and staying there, and the FxDAO team confirmed directly that the protocol is no longer operating. The contract registry (§9.9) pins FxDAO’s mainnet entry to that live code hash under its own version, wind-down, and lists the version in noExitVersions: the adapter repays only on the version pay_debt was verified on and refuses any other before reading it (fxdao_vault_no_repay, which the user may choose to leave behind), and no list of contracts an exit or a conversion may touch, in the API or in the web’s bundled copy, names a contract running a no-exit version. A mainnet account holding an FxDAO position is surfaced as a clear blocker rather than an attempted transaction that could never succeed, and the mainnet canary keeps re-reading the pinned hash, so a code change under that address is caught. Testnet is unaffected: this codebase runs its own reference deployment of FxDAO’s real open-source vault contract there (plus its own oracle and stablecoin, so nothing outside this repo needs to stay fresh), and a close against it runs end to end in CI on every PR (issue #286: tests/integration/fxdao-exit-adapter.integration.test.ts, alongside Phoenix’s own equivalent), so the adapter itself is proven correct and will work again if FxDAO redeploys on mainnet.

9.8 What a protocol exit looks like end to end

For every Soroban exit the shape is the same: detect the position from the DeFi Position API, resolve the contract version from the registry by wasmHash, read exact on-chain amounts over RPC getLedgerEntries with ScVal decoding, build the InvokeHostFunction operation, simulate it over RPC to fill in footprint, authorization, and resource fee, present the simulation result to the user, sign client-side, submit, and poll for confirmation. The same adapter pattern that keeps the position provider pluggable isolates each protocol’s contract interface, so a protocol upgrade is a registry and adapter change, not a rewrite.

9.9 Exit adapter invariants

Because the operations are irreversible, every protocol exit adapter must satisfy the same invariants before its output is signed. These are the contract the adapters are held to, and what the test suite checks. These invariants aren’t scoped to Soroban exits alone. The two classic-op builders that resolve the merge preconditions from Section 3 hold to the same contract by different means: the REVOKE_SPONSORSHIP step re-reads each owner’s live sponsorship and reserve headroom immediately before building - a dedicated call, separate from the plan-time affordability check, since minutes can pass between them - and an owner that can no longer absorb the shifted reserve simply drops out of that build rather than failing partway, because it was already surfaced as a sponsorship_unaffordable blocker at plan time. The claimable-balance trustline-remediation path reads from the same fresh per-request account state the round already re-read, and a balance that’s no longer claimable likewise surfaces as a blocker (claimable_balance_unclaimable) or a deliberate, recorded no-op (claimable_balance_forfeited) rather than disappearing quietly.

10. Asset conversion and routing

After positions are unwound, the account may hold several classic and Soroban tokens. Each non-XLM balance gets an explicit, per-asset disposition the user makes in the accordion preview, because “swap everything” is the common case but not the only one the ledger allows:
  • Swap to XLM (offered whenever a route exists): swap through the best available route, then remove the trustline. This is the disposition the tool selects for any asset that has a route, and the user can leave it as is.
  • Return to issuer: send the balance back to its issuer, which clears it from the account. This is the right call for spam tokens and worthless dust. It is never the default and never labeled as a conversion: the user confirms it explicitly, and the tool states plainly that it is irreversible.
  • Transfer to another account: pay the balance, as the asset, to an account the user names. The other two both end the close with the position destroyed - swapped away at whatever the market gives, or burned - so this is the only disposition that keeps the asset. It is offered whether or not a route exists, and for an asset with no market it is the only choice that does not destroy the balance.
Three constraints on the transfer are worth stating, because each is a consequence of the ledger rather than a product decision: The amount is the full trustline balance, never a user-chosen figure. The ChangeTrust that removes the trustline runs immediately after and fails on a non-zero balance, so a partial transfer would strand the close midway with the account still open. The destination must already hold a trustline for that exact asset, and this is checked against live ledger state before anything is built. LumenWipe cannot add it: creating a trustline needs the destination account’s own signature, which the tool never has. A destination that does not exist, does not trust the asset, holds an unauthorized trustline, has no room under its limit, is the account being closed, or is a recognized exchange deposit address surfaces as a blocker naming the working alternatives - never a silent fallback. The exchange case is refused outright rather than acknowledged: a close carries one transaction-level memo, reserved for the merge, so a token payment cannot carry the deposit memo an exchange needs to credit it, and the balance would be lost exactly as a direct merge into a deposit address is. A claimable balance is not an acceptable fallback for a destination that cannot receive the asset, and this is written down so nobody later “fixes” the blocker that way. It looks like the obvious way to send the asset anyway, and it is a trap: creating a claimable balance makes the source account the sponsor of a new ledger entry, pushing numSponsoring to 1, and ACCOUNT_MERGE fails with ACCOUNT_MERGE_IS_SPONSOR while numSponsoring > 0. The helpful-looking fallback would make the close structurally impossible and leave the account worse off than before. The destination is arbitrary and per asset at the API level: each asset carries its own params.destination on its DecisionAnswer, so an SDK consumer can send each balance somewhere different. The web UI offers “use the same account I’m merging into” as a shortcut that prefills an editable field, rather than constraining the choice to one address.

10.1 Soroban token balances

A Soroban (SEP-41) token balance is not a trustline. It lives in the token contract’s own storage, keyed by holder, so no classic read shows it, and it does not stop ACCOUNT_MERGE: an account can be merged away with the tokens still bound to its key, recoverable only by funding that address again. That is the whole danger. A trustline with a balance makes the close fail loudly; a token balance lets it succeed silently and lose the value. So the tool treats these balances as first-class assets with their own discovery, their own decision, and their own transaction shape. Discovery is a union of proposers confirmed by the ledger. There is no per-account index of token balances, and the public RPC’s getEvents has a processing cap that makes scanning its retention window infeasible on mainnet. The API therefore gathers candidate contracts from StellarIndex and from the sources it can check itself - the Soroban-native tokens in the account’s received movements on StellarIndex when STELLARINDEX_API_KEY is set (a third party that only proposes, read 4 pages of 200 at most within 4 seconds, so a busy account’s oldest tokens can be missed; its outage changes only its coverage entry, and close rounds do not call it), the tokens of the account’s detected DeFi positions (what an exit pays out, a Blend reserve, and an FxDAO vault’s stablecoin, which a repay spends), bundled lists of Soroban-native tokens with known liquidity, transfer and mint events crediting the account in the most recent window of about 5.5 hours (4,000 ledgers), and contracts the user adds by hand (GET /account/:address?tokens=C...,C...) - and then confirms every candidate by simulating balance(account) on the RPC, reading symbol() and decimals() the same way. A Stellar asset’s contract is excluded (for an account its balance is the trustline), and so is every position’s own contract and share token (the position is exited by its adapter, not listed twice): a Soroswap pair is its own share token, while an Aquarius or Phoenix pool keeps its shares in a separate contract the position names. Every source is time-boxed inside one overall budget; what could not be read is reported as unreadable or skipped and becomes a warning, never a silent zero. A close round re-reads state without the event scan, re-confirming the balances the analysis named and the contracts the caller’s answers name. No third-party index is consulted: the stellar.expert per-account listing was dropped once its API began answering 402 Payment Required on every request. The accepted gap is a token outside the bundled lists and every detected position that the account received before the event window and that StellarIndex does not propose (no key configured, an outage, or older than the pages read): nothing proposes it, and the user adds it by contract address. Every held token needs an answer, and leaving is explicit. Each token with a balance is a required asset_disposition decision (token:<contract>) with three choices: convert to XLM (offered only when a route exists and the token reports symbol and decimals - a swap amount nobody can read is not a decision anyone can make), send the balance as the token to an account the user names (transfer_to_account), or acknowledge that it stays with the address (acknowledge_residue). The last is never pre-selected, and the API holds the plan at needs_decisions and refuses /transactions until every token has an answer. A left balance still appears as a step with nothing to sign, and on the receipt, so the record of an irreversible close carries what was left behind. There is no burn and no return-to-issuer for a Soroban-native token: it has no issuer, and a transfer to the contract itself would only strand the balance somewhere less recoverable. A transfer is one plain call, and only that. The token round runs after the exit round (an exit can pay a token out) and before anything classic: one transaction per token, token.transfer(account, destination, live_balance), simulated against the current ledger and assembled. Before it is offered, the API asserts its shape - exactly one operation, that contract, that function, those three arguments, every authorization entry under the account’s own source-account credentials, none with a nested call, a fee within the cap - and refuses by name otherwise, because the token is the user’s own arbitrary contract and can never be vouched for by the registry the exit runner gates on. The web anchor re-checks the same shape from the user’s own inputs: the destination they typed, at least the balance they were shown, authDepth of zero, no account named beyond the account and its destination, no contract beyond the token. Destinations are validated live like classic transfers, minus the trustline: the account must exist, and it may be neither the account being closed nor a recognized exchange deposit address (a token transfer carries no deposit memo). The recipient needs no trustline at all. Conversion goes through the Soroswap API, and the API is trusted for nothing. When conversion is enabled (SOROBAN_CONVERSION_ENABLED with a SOROSWAP_API_KEY), the plan asks the API for a quote of each held token’s whole balance into XLM across the Soroswap, Phoenix, and Aquarius pools (not the classic order book: the API fills that with a classic path payment, which a Soroban-native token cannot take). A route makes the token convertible and the card shows the quoted XLM and a floor: the quote less the slippage margin, computed by LumenWipe - the API’s own threshold has been observed equal to the quote itself. The convert answer carries that floor (params.minAmountOut), so the round that builds the swap can refuse a route that drifted under it (quote_drifted, 409: re-plan and accept the new rate) instead of swapping at a rate nobody agreed to. The API builds the swap for the live balance; the bytes are then decoded and held to the one shape a conversion may have before they are offered: the account’s own next transaction, no memo, one swap_exact_in on the registry’s Soroswap aggregator or swap_exact_tokens_for_tokens on its router - confirmed by the contract’s live code hash, not just its address - spending exactly the live balance of that token into XLM paid to the account itself, with a minimum no lower than the floor and no partner fee, and an authorization tree that invokes nothing but the aggregator, the router, and the token, every transfer of the token the account’s own and to a contract, none to a Stellar account, and no more of the token leaving than the swap spends. The browser re-checks what it can from the user’s own inputs before signing: the call must be the transaction’s only operation, act as the account being closed, be swap_exact_in or swap_exact_tokens_for_tokens on a contract from its own bundled registry, charge no partner fee, spend a token the user chose to convert, pay the proceeds to that same account, and set a minimum no lower than the figure they accepted. It does not re-check which pools the route passes through - those addresses are route-dependent and unbounded, and the browser cannot enumerate them - so that pinning is the API’s, and the residual is bounded by the floor: a route through hostile pools still cannot deliver less XLM than the user agreed to. The aggregator (redeployed 2026-09-14) takes a 10 bps fee from the token spent, already reflected in the quote; a fee partner would replace it with 25 bps to 10%, which is why both sides refuse one. Since the aggregator’s 2026-11-23 upgrade the Soroswap API names a 0-bps partner on every keyed build; at 0 bps it only labels the swap and the aggregator still charges its own 10 bps and pays no partner (confirmed by read-only mainnet simulation against partner ids that charge 100 bps elsewhere), so both sides accept exactly { bps: 0, id } and trust the id for nothing. The API indexes no testnet protocol, so the conversion path is exercised by unit tests over both swap shapes and a read-only mainnet integration check of the API’s own build for a real holder; a low-value mainnet close is the acceptance test. xBull’s strict_send shape is read through a bundled asset table. Unlike Soroswap’s path, which names token addresses inline, xBull’s path argument carries indices into the router’s own on-chain asset map. The API resolves each index with a live storage read immediately before building and asserts the route against the built call. The browser does not take the API’s word for it: it reads the token spent and the token bought through a bundled copy of that map (apps/web/config/xbull-asset-map.json), refuses an index the copy does not hold or a route that breaks between hops, and holds the router call’s authorization to paying in at most the amount sold of the token sold. refs must always be empty - a non-empty refs would divert part of the swap to a referral address nobody agreed to. Claimable balances follow the same explicit-choice pattern through a distinct DecisionPoint (type: "claimable_balance", resolved to a ClaimableBalanceSelection in @lumenwipe/types), since a balance the account is claimant of is a separate ledger entry, not a balance the account already holds:
  • Claim: submit ClaimClaimableBalance for the balance now. Offered, and the opt-out default, whenever the account can already claim it - the asset is native XLM, or an authorized trustline already exists.
  • Add a trustline, then claim: add the missing trustline first, then claim in the same round. The only path to claiming a balance in an asset the account doesn’t yet trust.
  • Forfeit: leave the balance unclaimed and proceed with the rest of the close. No operation is built; the choice is recorded as an acknowledged blocker so the plan stays auditable about what it chose not to do.
There is no default when a balance isn’t currently claimable: the user must pick add-trustline-then-claim or forfeit explicitly, and the API holds the plan at needs_decisions until every such balance has an answer. Routing for the convert path has two engines, by asset kind. Classic assets convert through strict-send path finding from a Horizon-compatible endpoint, executed with PathPaymentStrictSend across SDEX order books and classic liquidity pools (up to six hops). Soroban tokens convert through the Soroswap API across Soroswap, Phoenix and Aquarius pools, and on mainnet optionally through xBull’s router. Like every server-built transaction, each swap is decoded and verified client-side before signing (Section 9.9). Either way the tool computes a minimum-received amount from the quoted output and a slippage tolerance, and passes it as the destination minimum so a sudden price move cannot fill the swap at a bad rate. Asset conversion routing: Soroswap Aggregator as primary route with SDEX PathPayment fallback, minimum-received bound, and return-to-issuer when no route exists The user keeps control. A trustline is only removed once the protocol’s full deletion preconditions hold: zero balance, zero buying liabilities (every open offer buying the asset cancelled, which the step order guarantees), and no pool-share trustline still referencing the asset (pool exits run earlier for the same reason). If a residual balance remains after a swap, the tool offers the return-to-issuer disposition or lets the user lower slippage and retry, rather than silently failing the later merge.

11. The mediator account flow for exchanges

Exchanges do not support ACCOUNT_MERGE, and their crediting systems only recognize Payment operations with a memo, so a user cannot merge directly into a deposit address (a direct merge is typically lost). The tool bridges this with a single shared mediator account, the same pattern the reference demolisher uses, in one atomic transaction. Availability by network (as of 2026-10-10): the mediator flow is available on testnet. Mainnet availability follows the deployment status in the monitoring plan; without a configured mainnet mediator key the API reports a mainnet exchange close as blocked (mediator_not_configured) in its plan, and close/transactions refuses it before any cleanup transaction is built, so an account is never emptied for a forward that cannot follow. An operator can also pause the forward without a deploy (MEDIATOR_FORWARD_ENABLED=false, see RELEASING.md), which blocks the same way with exchange_forward_paused. Mediator account flow for exchange destinations: one atomic transaction where the user signs the AccountMerge and the API co-signs the forwarding Payment with memo The mediator is a single, persistent account that the operator funds once; it is one of the API’s two signing keys, alongside the fee-bump sponsor. Its ~1 XLM minimum balance is paid once and reused for every close, so the user recovers essentially all of their XLM, including the source account’s freed reserves; only standard network fees apply. This is the key difference from a throwaway per-user intermediary, which would sacrifice ~1 XLM on every close. The transaction is built by the API and verified in the user’s browser, where the user signs its merge half. The API then co-signs only the mediator’s forward payment, after validating the exact shape: operation one must be an account merge into the mediator, and operation two a payment from the mediator to the user’s chosen destination of at least 1 XLM. Because it is one atomic transaction with a fixed destination and amount, the API cannot change where the funds go or divert them; it can only co-sign or refuse. The fee-bump sponsor is the only other server-side signing key in the system (see the security model). When the destination is a known exchange or anchor, the tool requires the correct memo and blocks submission without it, because funds sent to an exchange without a memo are typically lost. A registry of known exchange and anchor addresses, sourced from the stellar.expert directory, drives two decisions: whether a destination needs the mediator flow, and whether it requires a memo and of which type (text, id, or hash). The registry is a curated list, not a complete one, so its silence carries no information: an address it does not list may still be an exchange deposit address it has simply never been told about, and every deposit address issued from now on is unlisted by default. Because a direct merge into such an address is unrecoverable, an unrecognized destination is not assumed to be a personal wallet. The close API emits a required confirmation decision point, keyed by the address (destination:G...), and close/transactions refuses to build until it is answered (422 destination_not_acknowledged). The decision id names the address so an answer cannot be replayed for a different destination, and the refusal lives on the build endpoint rather than only in the plan because the plan is advisory - an API or SDK caller can reach the build without ever requesting one. Only the user knows where an address came from, so the tool asks them rather than guessing.

12. Allowance inspection

Independent of closing an account, the tool offers a read-only allowance inspector. This is a security utility: a user who has approved token spending to DeFi contracts can audit and revoke those approvals, which limits exposure if a protocol is later exploited. Soroban tokens follow the SEP-41 interface, including approve(from, spender, amount, expiration_ledger) and allowance(from, spender). There is no on-chain way to list every spender an account has approved, so the inspector discovers candidate (token, spender) pairs and reads allowance(owner, spender) for each. When STELLARINDEX_API_KEY is set and StellarIndex answers, its pairs are the only candidates: approve calls at any depth of the account’s operations, each with the expiration its newest approve set. Past the first page of 200, the rest of the history, back to the account’s creation ledger (read from its sequence number), is split into 8 ledger windows read in parallel with up to 4 pages each, all within 8 seconds, so an account with up to about 6,000 operations is read in full; a window left unfinished or a cursor StellarIndex does not honor is reported. It runs a ledger or two behind the tip, so recent approvals are covered too, and a pair that already expired is not read. That keeps a request to a few simulations instead of the ~50 the fallback costs, which a public RPC answers with rate limiting. A scan that stops early is a warning. When it is not configured or fails, the inspector falls back to approve events (RPC getEvents, about the last 33 hours) and the known DeFi contract registry crossed with the bundled token list. Non-zero allowances are shown with the token, the spender contract and its protocol name when recognized, the approved amount, and the expiration ledger. Revoking sets the allowance to zero with approve(owner, spender, 0, ledger), one InvokeHostFunction per revocation, and requires no full wind-down.

13. Security model

The tool builds transactions that drain an account irreversibly, so its security model starts from the assumption that only the user’s own machine should ever be able to sign.

13.1 What is at risk and who attacks it

A compromised API cannot change where a payment, transfer or merge goes. It builds the transactions, but the browser verifies each one before signing (verify(), Section 6.2) against the user’s own inputs - destination, memo, per-asset choices, transfer destinations and the trustlines they chose to claim - and against the bundled exchange and contract registries and the xBull asset table, none of which the API supplies. Other expected values come from the API’s own account read and plan, which the user reviews but did not type: the native balance the exchange forward is held to, transfer floors, the account’s signers and thresholds, the DeFi positions an exit may call, and the quotes that swap and conversion minimums are taken from. Those catch a transaction-builder bug or a partial compromise; a wholly compromised API could in principle keep them and its transactions consistent with each other. Every transaction must also expire within 15 minutes and, for a classic transaction, pay at most ten times the base fee per operation. Its two signing keys are the shared mediator, which can co-sign only a payment whose destination and amount the user already fixed in an atomic transaction, so it can neither sign for a user’s account nor redirect the forward payment, and the fee-bump sponsor, which only pays network fees for a transaction the user already signed. Wrong read data is caught by that same verification, on-chain simulation, and explicit confirmation of every destructive step. A DeFi exit is the one operation for which that guarantee is weaker, and it is stated here so nobody mistakes it for the same one. The client does not know a protocol’s ABI, so verify() checks structure: the exit must be the transaction’s only operation, act as the account being closed, invoke only a contract the account’s own analysis showed a position in - or, for an AMM withdrawal, that protocol’s router as listed in the contract registry bundled with the web (never a served copy: an entry there names a contract the user will authorize, so it reaches the list only through a code review and a deploy) - and call, on that contract, the one function that leaves the protocol (a Blend pool’s submit, a Soroswap router’s remove_liquidity), name no account other than the one being closed and no contract other than those positions, the token contracts of assets the account holds, and the tokens of those positions, anywhere in its arguments or in the authorization tree the signature will satisfy, carry no authorization for any other party, and pay a bounded fee. Every call the signature authorizes below the root, at any depth, must be a SEP-41 call on a token the account holds or a position names; the one other call allowed is Soroswap’s router paying the removed amount of LP share into the pair it lives in, as that removal’s only authorized call and with the account as its to. Through a contract the registry names, an exit may authorize spending XLM, or a classic asset the read lists, only as a plain transfer from the account into the pool being called, of a token the account read shows a Blend borrow position in for that pool. A Blend submit must name the account as from, spender and to and carry only withdraw, collateral-withdraw and repay requests, and a claim must name the account as both the claimer and the recipient. It does not check the amount an exit names, in the root call or in the token calls under it. The honest limit: the position contracts and their tokens come from the API’s own account read, which the user reviews but did not type. A compromised API could therefore name a contract of its choosing as a “position”; what bounds the damage is that the function it may be asked to call is fixed per protocol, that the call may act for and pay to nobody but the account, and that a contract the bundled registry does not name may touch only the tokens the account read lists as that position’s own, and never XLM or a classic asset the read lists, so a repay into a pool outside the registry is refused. XLM’s contract is known without the read; a classic asset’s is not, so that protection reaches only the trustlines the read shows. Such a contract can still be handed, or burn, the tokens the read names as its own. Closing the gap fully - an independent read of the positions’ code - is open work (Section 23). A passive network observer sees only TLS-protected traffic. An XSS attacker is blocked by a strict Content Security Policy with no 'unsafe-inline' and no 'unsafe-eval' in script-src (an inline script runs only when the policy names it: by its hash on prerendered marketing pages, by a per-request nonce with 'strict-dynamic' elsewhere) and no external script origins, with one intentional exception: style-src 'self' 'unsafe-inline' (required by stellar-wallets-kit’s runtime style injection). A supply-chain attacker is constrained by lockfile-pinned dependencies, audited in CI, with no dependency permitted that needs dynamic code execution.

13.2 Key handling

The wallet path is primary: through stellar-wallets-kit the private key never enters the application. The secret-key advanced mode is for keys not held in any wallet, and is constrained: the input is a password field, the key is held only in memory (never in localStorage, sessionStorage, IndexedDB, cookies, or any network request) for the duration of the execution session, and it is wiped on completion, on abort, on navigation away from the flow, or when the user explicitly clicks “Forget key”. The component holding it is also unmounted when the user leaves the signing step. For multisig, keys are gathered one at a time - the active key signs, and it is cleared when its transaction pauses for more weight, when the user switches to a different wallet or secret key, or when they click “Forget key”; the underlying memory lifetime is otherwise the same one described above for the single-signer case. Signing from another device is not supported yet; the reviewed design is in multisig cosigning. The shared mediator’s secret is the system’s one server-side signing key; it lives only in the API’s environment, never in the browser, and is used solely to co-sign the exchange forwarding payment (Sections 7 and 11).

13.3 Confirmation and irreversibility controls

Every destructive step requires an explicit acknowledgment that states what will happen, shows the affected entry or balance, and warns that it cannot be undone. The tool never auto-submits; the user triggers each submission. The merge gets its own full-screen confirmation with the destination shown in full, a ledger existence check, and memo validation for exchange destinations. A third layer sits above these two: before any transaction is built or signed, the whole plan is shown at once on a dedicated review step. The client-side DemolishPhase state machine (Section 6.1) gates this explicitly - the plan-generation phase (PREFLIGHT_COMPLETE) only advances to execution (STEP_EXECUTING) through that page’s own confirmation, and nothing is written to the resumable session store before it fires (the rule is stated in full in how closing works). This is additive to the per-step and per-merge confirmations, not a replacement - confirming the whole plan doesn’t skip confirming each step and the merge itself as they happen.

13.4 Security reviews

The codebase undergoes internal security reviews as part of our development process. External security audits will be conducted when possible.

13.5 API key network scope

A self-serve key can be limited to testnet, to mainnet, or left valid on both. ApiKeyGuard enforces the scope right after it resolves the key and before any pipe or handler runs, so a key limited to testnet is refused (403 key_network_not_allowed) on a mainnet route without a single upstream read, and the refusal is not metered. The check reads the route’s :network param, so a deprecated alias path is refused the same way as its /v1 path. It fails closed: a keyed route without :network refuses every scoped key unless it is marked @NetworkAgnostic(), and a test walks every registered route so that a new keyed route has to take a network or be marked. No route takes the network from its body or query. A key without a scope, which includes every key created before scopes existed and every manually provisioned key, behaves exactly as before. The scope narrows what a key can do and never widens it: it adds no access the key did not already have.

14. Trust minimization and decentralization

For a tool that closes accounts, decentralization is first a matter of custody and control, and second a matter of how little anyone has to trust the operator. Custody and control. The tool is non-custodial by construction. A user’s account signing is client-side and their keys never reach a server. The API holds two signing keys. The shared exchange mediator co-signs only a forwarding payment the user has already authorized in an atomic transaction; the fee-bump sponsor signs only the fee-bump envelope that pays network fees for a transaction the user has already signed. No operator of any component, including the maintainers, can change a destination, move a user’s account funds, or close their account without the user’s own signature. The user authorizes every transaction. Open code, open surfaces. The whole project is open source under a permissive license. The API that builds the transactions and the client-side verify() that guards signing are both open and auditable, and the signing itself runs in the user’s browser where anyone can read it. Integrators do not have to go through our UI at all: the REST API and the TypeScript SDK (Section 7.3) let a wallet or platform drive the same wind-down with its own interface and its own signers, so the security-critical path is auditable and embeddable rather than locked behind a hosted product. Every external read source sits behind a pluggable adapter, so the deployment can be pointed at any Stellar RPC provider, indexer, or DeFi Position API instance. Where centralization remains, and why. The remaining centralized pieces are all read-only data sources: RPC providers, the indexer, the routing API, and the DeFi Position API. None can affect custody. Each is pluggable and has multiple independent providers in the Stellar ecosystem, and the RPC and Horizon-compatible settings take an ordered list, so with more than one configured neither is a hard dependency. The DeFi Position API (OctoPos) is a deliberate dependency, kept behind an adapter with an explicit degraded mode, so even there an outage limits functionality rather than breaking the tool. Nothing here can move a user’s funds: the API builds transactions but cannot sign for a user’s account, and signing lives only in the browser behind verify(). Everything in the external rows is read-only and replaceable.

15. Infrastructure and deployment

The tool runs on light, replaceable infrastructure, which follows from the non-custodial design. The codebase is a Bun-workspaces monorepo - apps/{web,api,playground} and packages/{sdk,types,verify} - with per-package CI so each artifact builds and tests independently.
  • API service: a NestJS service that reads state and builds transactions. It holds no per-user state and no user keys (only the shared mediator co-sign key and the fee-bump sponsor key, MEDIATOR_SECRET_* and FEE_ACCOUNT_SECRET_*, injected from the environment as managed secrets). It deploys as a container to Google Cloud Run, and scripts/deploy-api.sh (which .github/workflows/deploy-api.yml runs) sets every capacity flag explicitly on each candidate and restore revision. MIN_INSTANCES in that file is the number of instances kept allocated while the service is idle. At 0 no instance exists while idle, and the first request after an idle period pays a cold start: Cloud Run measured 12.2 s at p50 and 15.2 s at p95 for this service over the 14 days to 2026-11-19. At 1 one instance stays allocated, so a request after an idle period does not wait for a start, and the instance’s in-memory state (below) survives idle gaps; a new revision still starts cold once. The script’s current value is the only place the number is written, and a test keeps this section in step with it.
    • Instance cap: the deployment pins --max-instances=1. The close path and the mediator co-sign keep no per-process state, but four pieces of the API do, and each degrades once there is more than one instance. Raise the cap only after: (1) the per-API-key rate limit, held in @nestjs/throttler’s default in-memory storage, moves to a shared store, since otherwise each instance enforces its own window and the effective limit multiplies by the instance count; (2) the revoke and rotate lag of the ApiKeyDirectory cache (up to its cacheTtlMs, because an invalidation reaches only the instance that served the admin request) is accepted or removed; (3) FIRESTORE_PROJECT_ID is set in every environment that runs more than one instance, because without it usage metering, the merge counter and the single-use record of exchanged sign-in challenges fall back to the in-memory InMemoryUsageStore, InMemoryMergeStatsStore and InMemoryUsedChallengeStore, which are neither shared nor durable (with the last, a challenge could be exchanged once on each instance); (4) the fee-bump sponsor’s daily budget (SponsorshipBudget) moves to a shared store, since each instance otherwise grants its own full budget. Even at one instance that budget lives only as long as the process: a restart or a new revision starts the day’s budget over, so the daily cap bounds one process lifetime, not one calendar day. Other in-memory state does not limit the cap: the Soroban inclusion-fee cache in apps/api/src/lib/stellar/soroban-fee.ts is a read cache (5 s, SOROBAN_FEE_STATS_TTL_MS) that a second instance just fills for itself, and the upstream request counts are flushed to Firestore, where each instance’s counts add up.
    • Concurrency: one instance takes at most 8 requests in flight (--concurrency=8). The value comes from a load ramp on 2026-11-19 (bun run lab load, read-only testnet analyses and plans against a copy of the service with production’s image and limits). The ramp holds 1, 2, 4, 8, 16 and more requests in flight and stops at the first sustained upstream refusal, so the setting is the last stage held without one. At 8 in flight, 121 of 123 requests succeeded, at 1.9 a second, with p95 at 6.6 s, 15 percent above one request at a time. At 16, the testnet providers refused more than half the requests, so the ramp stopped. The refusals came from the providers, not from the instance: p95 never doubled and CPU and memory were not the limit, so 8 is the highest stage the providers sustained. Mainnet reads go to different providers with their own limits, so the mainnet ceiling has not been measured. A ninth concurrent request does not reach the API: with no second instance allowed, Cloud Run holds it until a slot frees and answers 429 if none frees in time. Re-run the ramp before changing the provider lists or raising the cap.
    • CPU: billed per request (--cpu-throttling), so Cloud Run gives the instance CPU only while a request is in flight. Nothing in the API needs CPU between requests: there is no timer, the upstream counts and key activity are written inside a request at most once a minute, and the last of them on SIGTERM, which Cloud Run gives CPU to. Billing CPU for the instance’s whole life would add nothing: the counts and key activity are written by the request that finds them due or by the shutdown hook (UpstreamMetricsService and KeyActivityService), never by a timer, so a warm instance needs request-billed CPU as much as a cold one.
    • Every deploy and restore sets these flags (RESOURCE_FLAGS in scripts/deploy-api.sh) instead of leaving them on the service, so a hand edit on the service is undone by the next deploy rather than drifting.
  • Web client: the Next.js app, deployed to Vercel. It reaches the API only through its own server-side proxy routes, which inject the API key, so the browser never holds one.
  • Cache: short-lived public read data only, held in the web proxy on three routes (Section 7.2). The API keeps no read cache.
  • Stellar access: Stellar RPC through ecosystem providers, configurable per deployment.
  • Data services: see Section 5.
The two services are kept deliberately platform-agnostic - the API is a plain container backed by external, portable data services - so the deployment target stays reversible. The project commits to using the current stable Stellar stack: the latest @stellar/stellar-sdk, Stellar RPC, stellar-wallets-kit, and the live network protocol (Protocol 30, Bell, on mainnet since November 2026). On Protocol 30 it depends on two things: the pinned @stellar/stellar-sdk decodes Protocol 30 ledger headers, including the millisecond close-time arm of CAP-88 (stellarValueSignedMs) in the StellarValue a header carries, and the API refuses contract (C...) and muxed contract (W..., CAP-84) addresses with unsupported_address_type instead of building anything for them. The contract registry and protocol adapters are versioned so the tool tracks protocol and DeFi upgrades without a rebuild of its core logic.

16. User protection and privacy

The tool protects users on two fronts: their funds and their privacy. Funds. The irreversibility controls in Section 13 are the protection: explicit per-step confirmations, no auto-submission, destination verification, memo validation for exchanges, simulation of Soroban steps before signing, and a resume flow that reconciles against on-chain state so an interrupted wind-down never double-acts. Privacy. The tool asks for no personal information and requires no account. Secret keys never leave the browser and are never logged. The API handles only public addresses and keeps none of them beyond cache TTLs, with one exception: a self-serve API key’s record and its owner’s per-day usage store that owner’s wallet address (Section 7). No address is stored with a counted close, which keeps only its transaction hash, network, account count, amount and time, and expires 400 days after the close. Apart from a key’s owner, the API associates no identity with a request. Data handling lists everything the API stores and how long it keeps it. Abuse protection is rate limiting by API key (per-key, optionally overridden for a self-serve key - Section 7) at the service and by IP at the web proxy, neither of which needs a stored identity. API keys themselves are never stored or logged in plaintext - only their hash is persisted (Section 7). Page analytics. The document every web root layout renders (apps/web/app/root-document.tsx) loads Vercel Web Analytics on every page. The marketing root layouts alone (apps/web/app/(marketing)/layout.tsx, apps/web/app/(marketing-es)/layout.tsx) also load Umami Cloud, from a pinned copy of its tracker served by the site itself (apps/web/public/a/), only when the deployment sets NEXT_PUBLIC_UMAMI_WEBSITE_ID, so it never loads on the app, API keys or cosign pages or a 404, where a wallet connects or a transaction is signed. Each tool reports the address of the page viewed, and Umami also the page the visitor came from. Every address is redacted in the browser before an event is sent (apps/web/lib/analytics/redact.ts): the query string and the fragment are dropped, and a saved receipt’s id is replaced with [id]. Umami’s script is also configured to leave out the query and the fragment itself. The web app sends no custom events, so no account address, transaction data, memo or key reaches either tool. The Content Security Policy runs a script only when it carries the per-request nonce or was loaded by one that does, on the app and sign-in routes, and only when its exact hash came from the page’s build output or it is a same-origin script file, on the prerendered marketing pages, which may send requests to no third party except Umami’s collector, and only when the page carries the Umami tag, whose policy the build writes into the Build Output config the deployment serves (INV-26). The logging and privacy reference (docs/reference/logging-and-privacy.mdx) lists what each tool receives.

17. Testing strategy

Testing matters more than usual here because the operations are irreversible and touch real balances. The suite has four tiers; automated tests do not use mainnet. Unit and adversarial/edge-case tests are deterministic fixtures. Unit, adversarial and integration tests run in CI on every change; integration runs against live testnet in two jobs, read-only and funded. Playwright end-to-end runs nightly against testnet (.github/workflows/e2e-nightly.yml), and a separate Playwright accessibility check, which never touches testnet, runs on every PR. Because the codebase is a monorepo, CI runs every package’s checks on each change as a matrix, so a shared type change is validated against every consumer rather than skipped by a path filter.
  • Unit: pure logic with deterministic fixtures. Transaction construction, fee estimation, reserve and balance math, routing parameter derivation, state machine transitions, input validation, and batching. The transaction builder is the highest-coverage module.
  • Integration: against Stellar testnet with accounts funded by Friendbot at the start of each run. Account analysis, signer removal, offer cancellation, trustline removal, asset conversion, the merge, and each DeFi protocol exit. DeFi detection in these tests runs through the direct contract-read path, since OctoPos serves mainnet only; that keeps the degraded-mode code under permanent test coverage.
  • Adversarial and edge case: deliberately unusual or hostile account states. Sponsoring accounts, the 1000-subentry maximum, revoked trustlines, multisig with hash(x) and pre-auth signers, undercollateralized vaults, queued backstop withdrawals, high-slippage conversions, and network failures such as a confirmed transaction whose response is lost (detected on retry through getTransaction so the step is not resubmitted).
  • End to end: Playwright drives a real browser against testnet through the full flow, including the multisig path, the mediator path for exchange destinations, session recovery, and the allowance inspector.

18. Maintenance after launch

The design isolates the parts most likely to change. Protocols upgrade, and DeFi contracts get redeployed. The versioned contract registry maps wasmHash to protocol version, so a new protocol version is a registry update (a reviewed pull request), not a code change. An unknown wasmHash degrades gracefully: the affected position is flagged for manual review instead of risking a wrong exit. Each protocol and each data provider sits behind an adapter, so adding a protocol or swapping a provider is a contained change. Dependencies are pinned and audited in CI, with weekly update pull requests. The repository carries a security policy and a responsible-disclosure process. Maintenance commitments, the cadence of protocol-coverage review, and the community update rhythm are detailed in the community and communications document.

19. Roadmap

The work is built in three cumulative phases, each a working, independently verifiable artifact. Phases 1 and 2 are complete; Phase 3 is in progress, and its live status is the Phase 3 milestone.

20. What runs today

The full wind-down runs in a working monorepo: a NestJS API, a thin Next.js client and a testnet playground. On both networks the API reads account state over Stellar RPC and one Horizon-compatible endpoint, detects DeFi positions, and builds every unsigned transaction; the browser verifies and signs it. That covers the classic path (signer normalization, sponsorship revocation, data entry removal, offer cancellation, claimable balances, classic liquidity pool withdrawal, asset conversion, trustline removal, and AccountMerge), exits from Blend, Aquarius, Soroswap, Phoenix, and FxDAO (testnet only), Soroban token conversion, and the allowance inspector. Each protocol exit is exercised against testnet by integration tests. The mediator flow for exchange destinations and sponsored fees are available on testnet; mainnet follows the monitoring plan, and the supported matrix is the source for availability by network. Integrators reach the same wind-down through the public REST API, the @lumenwipe/sdk client and the standalone @lumenwipe/verify package.

21. Technology stack and standards

Plain-English summary of what the tool is built from and why.
  • Frontend: Next.js and TypeScript, a thin open source web client that verifies and signs, with TypeScript’s type safety guarding the verification and signing path.
  • API: NestJS and TypeScript, a service that is stateless across a close and reads state and builds transactions, with a short-TTL cache for public read data; API-key auth with per-key rate limiting. Its durable state - self-serve API keys, the public merge counter and per-integrator usage - lives in Google Cloud Firestore (Native mode), accessed via the Cloud Run service account’s IAM role rather than a separate stored credential.
  • Packaging: a Bun-workspaces monorepo (apps/{web,api,playground}, packages/{sdk,types,verify}); @lumenwipe/sdk is a thin fetch client over the API, @lumenwipe/verify is the standalone verify() integrators run before signing (how it is built from the web’s own verifier, who consumes it and what is still open: the verify package), and @lumenwipe/types is shared across the API, the SDK, and the web.
  • Stellar SDK: @stellar/stellar-sdk, the official SDK, which covers classic and Soroban, used by the API to build, read and submit, by the web client to parse, verify and sign (never to build a transaction or read chain state), and by the testnet playground. @lumenwipe/sdk does not bundle it, and the dual-build hazard (mixing require() and import of the SDK in one runtime) applies in every runtime that imports it.
  • Wallets: stellar-wallets-kit (Varial, formerly Freighter, xBull, Albedo, Rabet, Hana, Ledger, WalletConnect; LOBSTR is accessible via WalletConnect). The web app signs transactions only; it never signs Soroban authorization entries.
  • Network access: Stellar RPC for live reads, simulation, submission, and events; a Horizon-compatible provider for subentry enumeration; the Soroswap API for routing; OctoPos for DeFi position detection.
  • DeFi integration: the official Blend SDK, the Soroswap API, and the published contract interfaces for Aquarius, Phoenix, and FxDAO, behind per-protocol adapters and a versioned contract registry.
  • State and storage: Zustand for the wizard state machine, IndexedDB for resumable sessions (never keys).
  • Testing: the Bun test runner for units, Playwright for end-to-end on testnet, with per-package CI across the monorepo.

Standards we build on

The tool tracks the current stable protocol (Protocol 30, Bell, on mainnet since November 2026) and the latest @stellar/stellar-sdk. It builds on these ecosystem standards:

22. Failure modes and recovery

The tool never leaves the user guessing. Every failure is either retryable with a clear path or surfaced as a blocker with a manual resolution, and partial progress is always recoverable from on-chain state.

Following a close from outside

A platform closing many accounts needs to see outcomes without holding a connection open, and the API keeps nothing per close. Two options were weighed.
  • Polling, chosen. GET /v1/{network}/transactions/{hash} resolves one transaction, and GET /v1/{network}/close/status?source= reports a phase and the remaining work from live state. Both re-read the chain on every call, so they cannot drift from it, and an outage loses nothing: the next call answers.
  • Webhooks, declined. A webhook needs a durable record of who wants which close, a delivery queue with retries, and a signing secret per subscriber. That is server-side progress per close, which the API deliberately does not have, and a missed delivery would still need the polling route to recover from. There is no follow-up issue: a platform that wants a push can poll and fan out on its own side.
close/status is informational. A close is complete only when the hash of the merge the client signed is confirmed by hash. GET /v1/{network}/close/delivered reports the XLM confirmed close transactions delivered to their destination, and keeps nothing between calls either. The figure comes from the ledger’s result for each transaction, never from the plan. Each transaction is read by its hash from RPC, and from Horizon when RPC no longer holds it. Both return the applied envelope and the TransactionResult, which is the only data both serve: Horizon no longer returns the result meta, and only Horizon has effects. The parsed envelope must hash to the requested hash under the network’s passphrase (the outer or inner hash of a fee-bump), and a fee-bump result must name that inner transaction, or the read is a 503. A merge into the destination counts the sourceAccountBalance its result reports. A native payment to the destination counts only as the forward of a relay close: its source is the account a successful merge earlier in the same transaction went into, at most one forward per merge, and never more than that merge carried. Nothing else counts. Responses are no-store and nothing is cached server side: a confirmed result cannot change, but the route stays as stateless as the other lookups, and a cap of 20 hashes per request with 5 read at a time bounds what one call costs upstream.

23. Open questions and known risks

These are the items the team is actively resolving. Listing them is deliberate: a tool that drains accounts should be honest about what is still being pinned down.

24. Glossary

  • Base reserve: the unit of locked XLM, currently 0.5 XLM (network-voted). An account’s minimum balance is two base reserves plus one per subentry, adjusted by sponsorship (+ numSponsoring - numSponsored).
  • Subentry: a trustline, offer, data entry, or signer attached to an account. Each adds one base reserve to the minimum balance; a pool-share trustline adds two.
  • ACCOUNT_MERGE: the operation that transfers an account’s full XLM balance to a destination and deletes the source account. Requires no subentries apart from signers, and no sponsorships.
  • Sponsorship: an arrangement where one account pays the reserve for another account’s entry. A sponsoring account cannot be merged until it stops sponsoring; for most entry kinds this tool revokes the sponsorship automatically when the entry’s owner can absorb the shifted reserve, but a sponsored claimable balance has no self-service revocation path (§3) and remains a permanent blocker until claimed.
  • Trustline: an account’s declared ability to hold a given asset, with a balance and a limit. Removed with ChangeTrust set to limit 0 once the balance is zero.
  • Stellar RPC: the JSON-RPC interface for live ledger reads (getLedgerEntries), Soroban simulation (simulateTransaction), submission (sendTransaction), confirmation (getTransaction), and events (getEvents). It cannot enumerate an account’s unknown subentries.
  • Indexer: a service that indexes ledger history and exposes enumeration, such as a Horizon-compatible provider. The tool reads enumeration from an existing indexer rather than running its own.
  • InvokeHostFunction: the Stellar operation that calls a Soroban smart contract. Each one is simulated over RPC to determine its footprint, authorization, and resource fee.
  • ScVal: the value encoding used by Soroban contracts. The tool decodes ScVal results when reading on-chain position state.
  • wasmHash: the hash identifying a deployed contract’s code. The tool maps it to a known protocol version to pick the correct exit interface.
  • bToken / dToken: Blend’s representations of a supply position (bToken) and a debt position (dToken).
  • Q4W: Blend’s queue-for-withdrawal cooldown on backstop deposits: 21 days on V1 pools, 17 days on V2.
  • CDP: a collateralized debt position, the FxDAO model where XLM collateral backs minted stablecoin.
  • SAC: the Stellar Asset Contract, which lets a classic asset (and XLM) be used inside Soroban contracts. It implements the SEP-41 token interface.
  • Mediator account: a shared, persistent account, funded once by the operator, used to forward funds to a destination that does not support ACCOUNT_MERGE, such as an exchange.

25. References