Dev.to Security πŸ” Cybersecurity πŸ‘ 2 πŸ“– 6 min read

Multi-Chain Address Checksums, Memo/Tag Validation & Non-Custodial Swap Architecture

Building a cross-chain swap engine that reliably handles 46 blockchains and 190+ tokens quickly teaches you one hard truth: most catastrophic user-facing failures happen before a single byte hits the mempool. When users

Building a cross-chain swap engine that reliably handles 46 blockchains and 190+ tokens quickly teaches you one hard truth: most catastrophic user-facing failures happen before a single byte hits the mempool.

When users move value across heterogeneous networksβ€”UTXO chains, EVM rollups, Solana, Cosmos appchains, and memo-based ledgersβ€”traditional regex validation is dangerously insufficient. A single transposed character, an unverified mixed-case hex string, or a dropped Destination Tag can turn an atomic user flow into an unrecoverable support ticket.

In this engineering deep dive, we break down how to architect:

  1. Deterministic multi-chain address checksum verification
  2. Typed Memo / Destination Tag validation
  3. A wallet-free, one-time deposit address flow for non-custodial swaps

1. Why Regex Fails for Multi-Chain Address Validation

A naive validator often checks /^0x[a-fA-F0-9]{40}$/ for EVM or /^[1-9A-HJ-NP-Za-km-z]{32,44}$/ for Base58 chains. That only confirms character class and lengthβ€”it provides zero protection against typos, wrong-network pasting, or cross-chain collisions.

Consider three real-world failure modes:

  • Cross-chain Base58 collisions: Legacy Bitcoin (1...), Dogecoin (D...), TRON (T...), and Solana pubkeys all use Base58 alphabets, yet their checksum rules and version bytes differ completely.
  • All-lowercase EVM addresses: 0x742d35cc6634c0532925a3b844bc454e4438f44e passes regex, but lacks EIP-55 checksum entropy. A single mistyped nibble silently burns funds.
  • Bech32 Human-Readable Part (HRP) mismatches: Bitcoin SegWit (bc1q...), Litecoin (ltc1q...), and Cosmos chains (cosmos1..., osmo1...) share Bech32 polynomial checksum math, so only HRP enforcement prevents sending assets to an incompatible chain prefix.

Checksum Families You Must Support

Chain Family Encoding Checksum Mechanism Key Validation Gotcha
EVM (ETH, Arbitrum, Base, BSC, Polygon) Hex (20 bytes) EIP-55 mixed-case Keccak-256 nibble mapping All-lowercase / all-uppercase strings bypass EIP-55 error detection unless flagged
Bitcoin Legacy / P2SH / Doge / LTC Base58Check Double SHA-256 (first 4 bytes) + version byte Version byte determines network; must match selected chain
Bitcoin SegWit / Taproot Bech32 / Bech32m BCH error-correcting polynomial (BIP-173 / BIP-350) SegWit v0 uses Bech32; Taproot v1+ requires Bech32m
TRON Base58Check 0x41 prefix byte + Double SHA-256 (4 bytes) EVM hex (0x...) vs. Base58 (T...) conversion bugs
Solana Raw Base58 No embedded checksum (32-byte Ed25519 pubkey) Must validate decoded byte length === 32
Cosmos SDK / IBC Bech32 BCH checksum + chain-specific HRP Valid checksum with wrong HRP (e.g., osmo1 on cosmos)

Designing a Deterministic Address Validator

Rather than scattering regex checks across frontend components, a swap backend should run a deterministic, chain-aware dispatcher before ever generating a quote or deposit order:

export type ValidationResult =
  | { valid: true; normalized: string; warnings: string[] }
  | { valid: false; reason: string };

export function validateDestinationAddress(
  chainId: string,
  rawAddress: string
): ValidationResult {
  const address = rawAddress.trim();
  if (!address) {
    return { valid: false, reason: "Empty destination address" };
  }

  switch (chainId) {
    case "ethereum":
    case "arbitrum":
    case "base":
    case "polygon":
    case "bsc":
      return verifyEip55OrFlagLowercase(address);

    case "bitcoin":
      return verifyBtcAddress(address, {
        bech32Hrp: "bc",
        base58Prefixes: [0x00, 0x05], // P2PKH, P2SH
      });

    case "tron":
      return verifyBase58Check(address, { expectedPrefix: 0x41, length: 21 });

    case "solana":
      return verifyEd25519Base58(address, { expectedBytes: 32 });

    case "cosmos":
      return verifyBech32Hrp(address, "cosmos");

    default:
      return verifyChainSpecificCodec(chainId, address);
  }
}

Notice the warnings array in the EVM branch: if a user pastes an all-lowercase 0x... address, EIP-55 cannot prove the address is typo-free. Surfacing a non-blocking checksum warning (or auto-converting and asking the user to verify the checksummed representation) catches copy-paste truncation early.

2. The Silent Failure Mode: Memo, Destination Tag & Payment ID Validation

Account-based chains that rely on shared omnibus hot walletsβ€”such as XRP (Destination Tag), Stellar / XLM (Memo), TON (Comment/Memo), EOS, Hedera (HBAR), and Cosmos-based hubsβ€”introduce a second validation dimension.

On these networks, the address identifies the custodian or protocol endpoint, while the Memo/Tag identifies the beneficiary sub-account. Treating memos as generic optional strings causes three classic production bugs:

  1. Integer overflow or non-numeric XRP tags: An XRP Destination Tag must be an unsigned 32-bit integer (0 to 4294967295). Passing a string with spaces, hyphens, or >32-bit values fails at broadcast or gets silently truncated.
  2. Stellar Memo type mismatch: XLM supports MEMO_TEXT (max 28 UTF-8 bytes, not 28 characters!), MEMO_ID (uint64), MEMO_HASH (32-byte hex), and MEMO_RETURN. Validating character count instead of Buffer.byteLength(memo, 'utf8') <= 28 breaks multi-byte inputs.
  3. Missing-tag swaps to centralized endpoints: When a user swaps to an exchange deposit address without providing the required Memo/Tag, the on-chain transaction succeedsβ€”yet the recipient platform cannot credit the user automatically.

Clear pre-flight validation and recovery documentation (such as CoingoSwap's guide on handling wrong or missing address details) dramatically reduce operational friction before transactions become immutable.

3. Non-Custodial Swap Architecture Without Wallet Connection

Most browser-based DEX interfaces force a tightly coupled execution model:

  • Inject window.ethereum or a WalletConnect session
  • Request unlimited or scoped ERC-20 approve() / Permit2 signatures
  • Restrict routing to a single VM family (e.g., EVM-only)

That model breaks down immediately when a user wants to swap BTC -> SOL, XMR -> USDT (TRC-20), or ETH -> XRP from cold storage, a mobile wallet, or a hardware device without exposing browser signing keys.

The One-Time Deposit Address Pattern

In a wallet-free non-custodial architecture like CoingoSwap's instant crypto exchange, the swap lifecycle decouples order creation from transaction signing:

[Client] ──(1) Quote + Validated Dest Address (+ Memo)──▢ [Order Engine]
                                                                β”‚
[Client] ◀─(2) Ephemeral 1-Time Source Deposit Address β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
   β”‚
   β–Ό (3) User sends funds from ANY wallet (Hardware / Mobile / CEX)
[Source Chain] ──▢ [Chain Watcher / Indexer] ──▢ [Confirmation Gate]
                                                        β”‚
[Dest Address] ◀──(5) Broadcast Payout ◀── [Liquidity Router] (4)

Let's examine the engineering invariants behind each stage (see also how non-custodial cross-chain swaps work):

1. Pre-Order Validation & Deterministic Order Binding

Before issuing a deposit address, the order service validates:

  • Source and destination chain availability across all 46 supported blockchains and 190+ tokens
  • Destination address checksum + HRP/prefix match
  • Memo/Tag type constraints if the destination network requires or supports tags
  • Minimum/maximum liquidity bounds and floating vs. fixed rate lock parameters

2. Ephemeral One-Time Deposit Address Derivation

Rather than reusing a global hot-wallet address (which complicates deposit attribution on UTXO/EVM chains), the backend derives an isolated, single-use deposit address bound strictly to order_id.

  • For HD-supported chains, derivation paths like m/purpose'/coin_type'/0'/0/order_sequence guarantee cryptographic isolation and clean reconciliation.
  • For memo-capable source chains where address creation carries reserve costs (e.g., Stellar/XRP account reserves), the order engine can pair a monitored deposit address with a unique order-bound numeric Tag/Memo.

3. Zero-Approval Execution Surface

Because the user simply sends a standard native transfer or token transfer to the one-time deposit address:

  • No eth_requestAccounts or wallet extension connection is needed.
  • No lingering ERC-20 token approvals remain on-chain after the swap completes.
  • Users can fund the swap from Ledger, Trezor, mobile wallets, or any external custody account.

4. Idempotent Chain Watchers & State Machine Transitions

Your deposit listener must treat blockchain reorgs and partial deposits as first-class edge cases:

  • State Machine: WAITING_DEPOSIT -> CONFIRMING -> EXCHANGING -> SENDING -> FINISHED (with explicit EXPIRED, UNDERPAID, and REFUNDED branches).
  • Reorg Safety: Never trigger liquidity execution on 0-conf mempool events for high-value swaps; enforce chain-specific finality thresholds (e.g., 1–2 confirmations on Bitcoin for smaller tiers or higher thresholds for large transfers, deterministic finality on Cosmos/Solana).
  • Idempotency Keys: Payout broadcasters must key off (order_id, settlement_tx_attempt) so network retries never double-send output assets.

4. Production Checklist for Multi-Chain Swap Engineers

If you are building or auditing a cross-chain swap pipeline, verify these five controls:

  1. Enforce server-side checksum decoding (EIP-55, Base58Check, Bech32/Bech32m, Ed25519 byte length)β€”never rely solely on frontend regex.
  2. Validate Memos/Tags with chain-native types (uint32 for XRP, UTF-8 byte length <= 28 for Stellar text memos) and block obvious structural mismatches before order creation.
  3. Bind each swap to a one-time deposit address (or unique order-bound tag) to eliminate deposit attribution ambiguity and remove wallet-connection attack surfaces.
  4. Separate confirmation watching from payout execution via an idempotent state machine resilient to RPC timeouts and block reorgs.
  5. Surface transparent status tracking and TXIDs for both the inbound deposit and outbound settlement leg.

By combining strict cryptographic address validation with a clean one-time deposit architecture, cross-chain swaps can support dozens of heterogeneous networks while keeping the user experience fast, private, and non-custodial.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.