Loading...
private.me Docs
Get xSwap
PRIVATE.ME · Technical White Paper

xSwap: MEV-Resistant Atomic Swaps

Trustless cryptocurrency exchange without exposing swap parameters to miners or searchers. XorIDA threshold sharing splits swap secrets across K-of-N shares, eliminating frontrunning and sandwich attacks. Information-theoretically secure, quantum-proof, compatible with any blockchain.

v1.0.0 79 tests passing TAM: $8.2B ~5ms initiate 2-of-3 default
Section 01

Executive Summary

Centralized exchanges custody user funds. Decentralized exchanges expose swap parameters to miners. xSwap eliminates both vulnerabilities via XorIDA-split atomic swaps — trustless, MEV-resistant, and provably secure.

Atomic swaps between blockchains have existed since 2017, but every implementation exposes swap parameters to miners and searchers before execution. This creates Maximal Extractable Value (MEV) vulnerabilities — frontrunning, sandwich attacks, and trade copying extract billions in value from users annually.

xSwap solves this by splitting swap parameters (asset addresses, amounts, prices) into K-of-N XorIDA shares before broadcasting. Neither party knows the other's full parameters until settlement. Each share is independently routed via Hash Time-Locked Contracts (HTLCs) on-chain. Reconstruction requires K shares — attackers with fewer than K shares learn zero information about the plaintext. This is not computationally hard to break, it is mathematically impossible.

Result: privacy-preserving cross-chain swaps, MEV-resistant DEX trades, verifiable OTC transactions, and quantum-proof settlement.

Section 02

The Problem

Cryptocurrency trading forces users to choose between custody risk (centralized exchanges) or MEV exploitation (decentralized exchanges). Both extract value and violate user privacy.

Centralized Exchange Custody Risk

Mt. Gox (2014): $460M stolen. Coincheck (2018): $530M stolen. FTX (2022): $8B in customer funds misappropriated. When users deposit assets to a centralized exchange, they surrender custody. Exchanges can freeze accounts, restrict withdrawals, or lose funds to hacks and fraud.

Decentralized Exchange MEV Exploitation

DEXs eliminate custody but expose swap parameters to miners and searchers before execution. This creates three attack vectors:

Frontrunning: Attacker observes pending swap in mempool, submits identical swap with higher gas fee, executes before victim, profits from price movement. Example: User swaps 100 ETH to USDC at $2000. Attacker frontrunns, moves price to $1995. User receives $199,500 instead of $200,000.

Sandwich attacks: Attacker submits two transactions — one before victim's swap (frontrun), one after (backrun). Frontrun moves price against victim. Victim executes at worse rate. Backrun reverses price movement, attacker profits. Annual extracted value exceeds $600M.

Trade copying: Sophisticated traders (whales, funds) hide alpha in their swap patterns. MEV bots copy trades within milliseconds, eroding profits.

Cross-Chain Bridge Vulnerabilities

Cross-chain bridges have lost over $2.6 billion to hacks since 2021. Bridges create centralized failure points — multisig wallets, custodial intermediaries, or vulnerable smart contracts. Atomic swaps eliminate bridges by executing peer-to-peer settlement directly on each chain.

Market Impact
MEV extraction exceeds $600M annually on Ethereum alone. Cross-chain bridges have lost $2.6B+ to hacks. Users choose between custody risk or MEV exploitation — neither is acceptable for institutional adoption.
Section 03

Solution: XorIDA-Split Atomic Swaps

xSwap splits swap secrets across K-of-N shares via threshold secret sharing. Swap parameters remain private until settlement. MEV becomes mathematically impossible, not computationally hard.

How It Works

Two parties agree to exchange assets (e.g., Bitcoin to Ethereum). Instead of broadcasting swap parameters directly to the blockchain, each party splits their parameters into K-of-N XorIDA shares:

Step 1 — Initiate: Party A generates K-of-N shares of their swap parameters (send asset, send amount, receive asset, receive amount, deadline). Party A retains K shares. Remaining N-K shares distributed to independent custodians.

Step 2 — Distribute: Each share wrapped in an HTLC smart contract on the target blockchain. HTLCs lock shares with a cryptographic hash and time-bound condition. If counterparty reveals the secret before deadline, share unlocks. If deadline expires, share returns to sender.

Step 3 — Settle: At settlement, K shares from each party recombine via XorIDA reconstruction. Swap parameters verified against expected values. If valid, on-chain execution proceeds. If invalid or deadline exceeded, swaps cancel and shares return.

Information-Theoretic Security

An attacker who compromises fewer than K shares learns zero information about the plaintext swap parameters. This is Shannon's perfect secrecy — the ciphertext (shares) provides no statistical advantage for guessing the plaintext. No amount of computational power or quantum advantage breaks this. The security derives from mathematics, not key sizes or algorithmic hardness.

Key Insight
MEV attacks require reading swap parameters from the mempool. xSwap eliminates this attack surface entirely — swap parameters never exist in plaintext on-chain until settlement completes. By then, the opportunity for frontrunning or sandwiching has passed.
Section 04

Architecture

3-Step Lifecycle

1. INITIATE — Split Swap Parameters

TypeScript Example
import { initiateSwap } from '@private.me/xswap';

const initiatorParams = {
  participantDid: 'did:key:z6Mk...',
  sendAsset: USDC,
  sendAmount: BigInt('1000000000'),  // 1000 USDC
  receiveAsset: ETH,
  receiveAmount: BigInt('500000000000000000'),  // 0.5 ETH
  deadline: Date.now() + 3600000,  // 1 hour
};

const result = await initiateSwap(
  initiatorParams,
  counterpartyParams,
  { k: 2, n: 3 }  // 2-of-3 threshold
);

if (!result.ok) throw new Error(result.error);

const swap = result.value;
console.log(`Swap ID: ${swap.swapId}`);
console.log(`Shares: ${swap.initiatorShares.length}`);

2. DISTRIBUTE — HTLC On-Chain Deployment

Each share wrapped in an HTLC smart contract. HTLCs enforce atomic settlement — either both parties reveal secrets and execute, or both cancel and funds return. Time-lock prevents indefinite locking. Hash-lock ensures only the intended counterparty can unlock.

Example HTLC structure (Solidity):

Solidity HTLC
contract HTLC {
  bytes32 public hashLock;
  uint public timeLock;
  address payable public sender;
  address payable public receiver;

  function unlock(bytes memory secret) public {
    require(sha256(secret) == hashLock, "Invalid secret");
    require(block.timestamp < timeLock, "Deadline passed");
    receiver.transfer(address(this).balance);
  }

  function refund() public {
    require(block.timestamp >= timeLock, "Too early");
    sender.transfer(address(this).balance);
  }
}

3. SETTLE — Reconstruct and Execute

Settlement
import { completeSwap } from '@private.me/xswap';

const completeResult = await completeSwap(
  swap.swapId,
  swap.initiatorShares.slice(0, 2),      // K shares
  swap.counterpartyShares.slice(0, 2),
  expectedInitiatorParams,
  expectedCounterpartyParams,
);

if (!completeResult.ok) throw new Error(completeResult.error);

const completed = completeResult.value;
console.log(`Settlement TX: ${completed.txHash}`);
console.log(`Block: ${completed.blockNumber}`);

XorIDA Threshold Sharing

xSwap uses XorIDA (threshold sharing over GF(2)) to split swap parameters. Key properties:

Information-theoretic security: Attackers with fewer than K shares learn zero information. Shannon perfect secrecy.

Fast reconstruction: ~5ms for typical swap parameters (addresses, amounts, deadline). Sub-millisecond for small payloads.

Flexible thresholds: Default 2-of-3 balances security and fault tolerance. Supports up to 2-of-16 for high-assurance scenarios.

HMAC integrity: Each share includes HMAC-SHA256 tag. Tampering detected before reconstruction.

HTLC Integration

HTLCs ensure atomic settlement. If Party A reveals their secret, Party B can extract it from the blockchain and unlock their funds. If either party fails to reveal before deadline, both swaps cancel. This creates trustless coordination across independent blockchains.

Technical Detail
HTLCs were first demonstrated in Bitcoin-Ethereum atomic swaps in 2017. xSwap extends this by combining HTLCs with XorIDA threshold sharing — the secrets locked in HTLCs are themselves shares of swap parameters, not the parameters directly. This provides two layers of security: HTLC atomicity AND information-theoretic parameter privacy.
Section 05

Use Cases

🔄
Cross-Chain DeFi
Bitcoin to Ethereum Swaps

Trade BTC for ETH directly, peer-to-peer, without wrapped tokens or custodial bridges. HTLCs enforce atomicity. XorIDA prevents MEV exploitation.

$2.6B bridge hacks eliminated
🛡️
DEX Privacy
MEV-Resistant Uniswap Trades

Swap tokens on Uniswap, 0x, or Curve without exposing amounts to searchers. Share-split parameters prevent frontrunning and sandwich attacks.

$600M+ annual MEV prevented
🏦
Institutional OTC
Privacy-Preserving OTC Trades

Large trades between institutions without revealing positions to the market. xProve provides cryptographic proof of execution without exposing amounts.

Verifiable settlement
Layer 2 Bridges
Polygon to Arbitrum Swaps

Cross-rollup asset swaps without custodial bridges. Each share routed independently via L2 HTLCs. Reconstruction requires quorum across chains.

Censorship-resistant
Section 06

Security

Information-Theoretic vs Multisig Comparison

Property xSwap (XorIDA) Multisig Wallets
Plaintext secrecy Information-theoretic (cannot reconstruct with <K shares) Plaintext visible to all signers
Quantum resistance Unconditionally secure (no keys to break) ECDSA/RSA vulnerable to Shor's algorithm
MEV protection Swap parameters never in plaintext on-chain Parameters visible in mempool
Single-point failure No coordinator or trusted party Multisig wallet is single target
Custody Non-custodial throughout Shared custody among signers

Threat Model

Attacker goal: Extract value via frontrunning, sandwich attacks, or parameter manipulation.

Attacker capabilities: Read blockchain state, mempool, and transaction history. Submit transactions with arbitrary gas fees. Collude with miners or validators.

xSwap defense: Swap parameters exist only as K-of-N shares on-chain. Attacker must compromise K shares to reconstruct. With default 2-of-3, attacker must compromise both independent custodians simultaneously — coordinator alone insufficient.

HMAC Integrity Verification

Every share includes HMAC-SHA256 tag computed over share data. Before reconstruction, each HMAC verified against expected value. If any HMAC fails, reconstruction aborts. This detects tampering, corruption, or share substitution attacks.

Security Guarantee
An attacker with fewer than K shares cannot reconstruct swap parameters, even with infinite computational resources. This is Shannon's perfect secrecy — the fundamental limit of cryptography.
Section 07

Benchmarks

~5ms
initiateSwap (2-of-3)
~3ms
completeSwap
~0.2ms
Serialization
79
Tests passing

Performance Characteristics

Share generation: ~5ms for 2-of-3 split of typical swap parameters (2 assets, 2 amounts, 1 deadline, 2 DIDs). Includes XorIDA splitting + HMAC tagging.

Reconstruction: ~3ms for 2-of-3 reconstruction + verification. Includes HMAC validation, parameter comparison, and plaintext recovery.

Gas costs: HTLC deployment ~60K gas per share on Ethereum L1. L2 costs 10-100x lower. Share unlock ~40K gas. Total roundtrip ~300K gas for 2-of-3 swap on L1.

Throughput: Single-threaded Node.js processes ~200 swaps/second (initiate + complete). Parallelizable across cores.

Section 08

Integration

Installation

npm
npm install @private.me/xswap

Basic Usage

TypeScript
import { initiateSwap, completeSwap } from '@private.me/xswap';

// Define assets
const USDC = {
  address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
  symbol: 'USDC',
  decimals: 6,
};

const ETH = {
  address: '0x0000000000000000000000000000000000000000',
  symbol: 'ETH',
  decimals: 18,
};

// Initiate swap
const result = await initiateSwap(
  {
    participantDid: 'did:key:z6MkAlice...',
    sendAsset: USDC,
    sendAmount: BigInt('1000000000'),
    receiveAsset: ETH,
    receiveAmount: BigInt('500000000000000000'),
    deadline: Date.now() + 3600000,
  },
  {
    participantDid: 'did:key:z6MkBob...',
    sendAsset: ETH,
    sendAmount: BigInt('500000000000000000'),
    receiveAsset: USDC,
    receiveAmount: BigInt('1000000000'),
    deadline: Date.now() + 3600000,
  },
  { k: 2, n: 3 },
);

if (!result.ok) throw new Error(result.error);
const swap = result.value;

// [Distribute shares to HTLC contracts on-chain...]

// Complete swap at settlement
const completeResult = await completeSwap(
  swap.swapId,
  swap.initiatorShares.slice(0, 2),
  swap.counterpartyShares.slice(0, 2),
  initiatorParams,
  counterpartyParams,
);

if (!completeResult.ok) throw new Error(completeResult.error);
console.log(`Swap completed: ${completeResult.value.txHash}`);

Progress Tracking

Progress Callbacks
const result = await initiateSwap(
  initiatorParams,
  counterpartyParams,
  {
    k: 2,
    n: 3,
    onProgress: (event) => {
      console.log(`${event.stage}: ${event.progress * 100}% - ${event.message}`);
    },
  },
);
Section 09

Building Blocks

xSwap composes four PRIVATE.ME building blocks to deliver MEV-resistant atomic swaps.

@private.me/crypto

XorIDA threshold sharing over GF(2). Splits swap parameters into K-of-N shares. Information-theoretically secure reconstruction. HMAC-SHA256 integrity verification.

@private.me/shareformat

Deterministic binary serialization for shares. Cross-chain compatibility. TLV encoding for asset addresses, amounts, deadlines.

@private.me/xcompute

Privacy-preserving computation on shares. Optional integration for verifying swap fairness without exposing plaintext amounts during negotiation.

@private.me/xprove

Cryptographic proof system for verifiable execution. Generates audit trails proving swap parameters were never exposed during protocol. Publicly verifiable without parameter disclosure.

Section 10

Honest Limitations

xSwap is powerful but not a silver bullet. Understanding its constraints is critical for safe deployment.

Blockchain Oracle Requirement

xSwap splits swap parameters client-side, but settlement requires on-chain execution. HTLC contracts must exist on both blockchains. This requires blockchain oracle support or manual contract deployment. For chains without smart contract support (Bitcoin), atomic swaps use native scripting (e.g., Bitcoin Script with OP_CHECKLOCKTIMEVERIFY).

Timing Attack Considerations

If shares are distributed sequentially with observable delays, attackers may infer correlation between shares. Mitigation: batch distribution with randomized ordering. Alternatively, use onion routing or Tor for share transmission.

Deadline Immutability

Once initiated, swap deadlines cannot be extended without creating a new swap. If settlement negotiations exceed the deadline, both parties must cancel and re-initiate. This prevents indefinite locking but reduces flexibility.

K-of-N Threshold Selection

Default 2-of-3 balances security and fault tolerance. Higher thresholds (e.g., 3-of-5) increase security but require coordinating more shares. Lower thresholds (e.g., 2-of-2) eliminate fault tolerance — if one share is lost, swap cannot settle.

Gas Cost Overhead

Deploying K HTLC contracts per party increases gas costs compared to direct swaps. On Ethereum L1, this adds ~300K gas per swap (2-of-3). L2 rollups reduce this 10-100x. For high-frequency trading, gas overhead may dominate swap value.

Not a Replacement for DEX Liquidity

xSwap enables peer-to-peer swaps but does not provide liquidity pools or automated market makers. Users must find counterparties manually or via order books. For instant swaps with market liquidity, DEXs remain more efficient — xSwap optimizes for privacy and MEV resistance, not speed or convenience.

Production Checklist
Before deploying xSwap in production: (1) Verify HTLC smart contracts audited on target chains. (2) Test share distribution timing with production-like network conditions. (3) Model gas costs for target blockchains. (4) Establish counterparty discovery mechanism. (5) Implement deadline monitoring and auto-cancellation.
Advanced

Full API Surface

initiateSwap(initiatorParams, counterpartyParams, config?)

Creates K-of-N shares of swap parameters for both participants. Returns InitiatedSwap with swapId, shares, and metadata, or error string. Validates DIDs, asset addresses, amounts, and deadline.

completeSwap(swapId, initiatorShares, counterpartyShares, expectedInitiatorParams, expectedCounterpartyParams)

Reconstructs plaintext parameters from K shares and verifies against expected values. Returns CompletedSwap with reconstructed parameters, on-chain details, and proof, or error. HMAC verification mandatory.

cancelSwap(swapId, status, reason)

Cancels a swap and marks shares as invalid. Returns CancelledSwap or error. Reasons: timeout, manual, validation_failed, counterparty_unavailable.

Advanced

Type Definitions

Core Types
interface SwapParams {
  participantDid: string;      // did:key:z6Mk...
  sendAsset: Asset;
  sendAmount: bigint;
  receiveAsset: Asset;
  receiveAmount: bigint;
  deadline: number;             // Unix ms timestamp
}

interface Asset {
  address: string;              // Checksummed Ethereum address
  symbol: string;
  decimals: number;             // 0-18
}

interface SwapShare {
  index: number;                // 1-based (1..N)
  data: Uint8Array;
  hmac: Uint8Array;            // SHA-256 HMAC (32 bytes)
}

interface InitiatedSwap {
  swapId: string;
  initiatorDid: string;
  counterpartyDid: string;
  threshold: { k: number; n: number };
  initiatorShares: SwapShare[];
  counterpartyShares: SwapShare[];
  status: 'initiated' | 'confirmed' | 'completed' | 'cancelled';
  initiatedAt: number;
}

interface CompletedSwap {
  swapId: string;
  txHash: string;
  blockNumber: number;
  initiatorParams: SwapParams;
  counterpartyParams: SwapParams;
  proof: Uint8Array;
  completedAt: number;
}
Advanced

Error Taxonomy

Configuration Errors

INVALID_CONFIG:INVALID_THRESHOLD — k > n or k < 2
INVALID_CONFIG:INVALID_PARAMS — Missing required fields
INVALID_CONFIG:INVALID_ASSETS — Bad addresses/decimals
INVALID_CONFIG:INVALID_DID — DID not in did:key: format
INVALID_CONFIG:DEADLINE_IN_PAST — Deadline before now

Initiation Errors

INITIATE_FAILED:SHARE_GENERATION — XorIDA splitting failed
INITIATE_FAILED:HMAC_FAILURE — HMAC generation failed

Share Errors

SHARE_FAILED:INSUFFICIENT_SHARES — Fewer than K shares provided
SHARE_FAILED:HMAC_MISMATCH — HMAC verification failed

Completion Errors

COMPLETE_FAILED:RECONSTRUCTION_ERROR — XorIDA reconstruction failed
COMPLETE_FAILED:PARAMETER_MISMATCH — Reconstructed != expected
COMPLETE_FAILED:DEADLINE_EXCEEDED — Swap deadline passed

Cancellation Errors

CANCEL_FAILED:INVALID_STATUS — Cannot cancel completed swap
CANCEL_FAILED:SWAP_NOT_FOUND — Swap ID not found

Deployment Options

📦

SDK Integration

Embed directly in your application. Runs in your codebase with full programmatic control.

  • npm install @private.me/xswap
  • TypeScript/JavaScript SDK
  • Full source access
  • Enterprise support available
Get Started →
🏢

On-Premise Upon Request

Enterprise CLI for compliance, air-gap, or data residency requirements.

  • Complete data sovereignty
  • Air-gap capable deployment
  • Custom SLA + dedicated support
  • Professional services included
Request Quote →

Enterprise On-Premise Deployment

While xSwap is primarily delivered as SaaS or SDK, we build dedicated on-premise infrastructure for customers with:

  • Regulatory mandates — HIPAA, SOX, FedRAMP, CMMC requiring self-hosted processing
  • Air-gapped environments — SCIF, classified networks, offline operations
  • Data residency requirements — EU GDPR, China data laws, government mandates
  • Custom integration needs — Embed in proprietary platforms, specialized workflows

Includes: Enterprise CLI, Docker/Kubernetes orchestration, RBAC, audit logging, and dedicated support.

Contact sales for assessment and pricing →