DEV Community

Verixia
Verixia

Posted on

Stateless Swap Infrastructure: Building Accountless On-Chain Execution Pipelines

The assumption that executing a token swap requires maintaining backend user databases, session tokens, or account credentials is a legacy software anti-pattern. On public blockchains like Solana and Ethereum, modern liquidity protocols render centralized state tracking entirely unnecessary. By leveraging client-side keypair signatures and atomic on-chain routing, engineers can construct completely stateless execution pipelines that require no signups, no email tracking, and no custodial database storage.

The Problem with Stateful Swap Architecture

Traditional financial applications and early crypto interfaces rely heavily on centralized databases to manage state. In a typical stateful design, the system flow follows these steps:

  1. User creates an account via email or OAuth, writing a record to a relational database.
  2. User deposits assets into a platform-controlled custodial vault or smart contract wallet.
  3. Internal off-chain databases update user balances in a private ledger.
  4. Swaps execute as internal database writes, requiring periodic reconciliation with the underlying blockchain.

This model introduces severe engineering costs. It creates high custodial risk, introduces database synchronization failure modes during peak market volatility, and forces developers to build complex user authentication, password reset, and session management infrastructure. Furthermore, storing user identity data alongside transaction logs introduces significant privacy liabilities.

Atomic Execution and Stateless Routing Mechanics

In a stateless decentralized swap pipeline, the application backend acts purely as a deterministic instruction builder rather than a state engine. The blockchain itself serves as the single source of truth, while user wallets hold keypair authority.

The execution lifecycle follows four atomic steps:

  1. Route Calculation: The client application queries liquidity aggregators via lightweight RPC queries to calculate optimal execution routes across automated market makers (AMMs).
  2. Instruction Assembly: The aggregator returns an unsigned, raw transaction payload. This binary contains the exact instruction array, compute budget allocations, priority fee parameters, and required account public keys.
  3. Local Signature: The user signs the serialized transaction payload locally within their wallet extension or burner keypair. Private keys never leave the client environment.
  4. Direct RPC Broadcast: The signed transaction payload is submitted directly to network RPC validator nodes for block inclusion.

Because the swap instruction contains pre-transaction balance checks and slippage tolerances enforced by smart contract logic, the transaction either succeeds completely or reverts atomically. There is no intermediate state where funds remain stuck in a database buffer.

Implementation: Building a Stateless Swap Gateway

The following TypeScript implementation demonstrates how to build a stateless Solana swap execution pipeline using direct RPC routing without user database dependencies:

import { Connection, VersionedTransaction, PublicKey } from "@solana/web3.js";

interface SwapQuoteRequest {
  inputMint: string;
  outputMint: string;
  amount: number;
  slippageBps: number;
}

export class StatelessSwapEngine {
  private connection: Connection;
  private quoteApiUrl: string;

  constructor(rpcEndpoint: string, quoteApiUrl: string) {
    this.connection = new Connection(rpcEndpoint, "confirmed");
    this.quoteApiUrl = quoteApiUrl;
  }

  async buildUnsignedSwapTransaction(
    userPublicKey: PublicKey,
    request: SwapQuoteRequest
  ): Promise<VersionedTransaction> {
    const quoteUrl = `${this.quoteApiUrl}/quote?inputMint=${request.inputMint}&outputMint=${request.outputMint}&amount=${request.amount}&slippageBps=${request.slippageBps}`;
    const quoteResponse = await fetch(quoteUrl);
    const quoteData = await quoteResponse.json();

    if (!quoteData || quoteData.error) {
      throw new Error(`Quote generation failed: ${quoteData?.error || "Unknown error"}`);
    }

    const swapResponse = await fetch(`${this.quoteApiUrl}/swap`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        quoteResponse: quoteData,
        userPublicKey: userPublicKey.toBase58(),
        wrapAndUnwrapSol: true,
        dynamicComputeUnitLimit: true,
        prioritizationFeeLamports: "auto",
      }),
    });

    const { swapTransaction } = await swapResponse.json();
    const transactionBuffer = Buffer.from(swapTransaction, "base64");
    return VersionedTransaction.deserialize(transactionBuffer);
  }

  async broadcastSignedTransaction(
    signedTransaction: VersionedTransaction
  ): Promise<string> {
    const rawTransaction = signedTransaction.serialize();
    const txid = await this.connection.sendRawTransaction(rawTransaction, {
      skipPreflight: false,
      maxRetries: 3,
      preflightCommitment: "confirmed",
    });

    return txid;
  }
}
Enter fullscreen mode Exit fullscreen mode

Engineering Advantages of Zero-State Architecture

Eliminating backend user databases alters the infrastructure overhead:

  • Infinite Horizontal Scalability: Because the application backend holds no user session state or database write locks, the API layer can scale horizontally behind a stateless load balancer.
  • Zero Custodial Liability: The platform never takes custody of funds or private keys, shifting security enforcement directly to on-chain smart contracts.
  • Enhanced Uptime and Resiliency: System availability is decoupled from database uptime. If an RPC node degrades, client traffic seamlessly fails over to alternative RPC endpoints.

When building Verixia, we implemented this exact stateless engineering philosophy across our product surfaces. Routing trades through decentralized aggregators like Jupiter without account signups or centralized registration allows developers to deliver high-throughput DeFi tools while upholding user privacy and security by default.


Written by the team at Verixia, a Solana swap interface routing through Jupiter.

Top comments (0)