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.
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.
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.
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.
Architecture
3-Step Lifecycle
1. INITIATE — Split Swap Parameters
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):
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
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.
Use Cases
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 eliminatedSwap tokens on Uniswap, 0x, or Curve without exposing amounts to searchers. Share-split parameters prevent frontrunning and sandwich attacks.
$600M+ annual MEV preventedLarge trades between institutions without revealing positions to the market. xProve provides cryptographic proof of execution without exposing amounts.
Verifiable settlementCross-rollup asset swaps without custodial bridges. Each share routed independently via L2 HTLCs. Reconstruction requires quorum across chains.
Censorship-resistantSecurity
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.
Benchmarks
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.
Integration
Installation
npm install @private.me/xswap
Basic Usage
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
const result = await initiateSwap( initiatorParams, counterpartyParams, { k: 2, n: 3, onProgress: (event) => { console.log(`${event.stage}: ${event.progress * 100}% - ${event.message}`); }, }, );
Building Blocks
xSwap composes four PRIVATE.ME building blocks to deliver MEV-resistant atomic swaps.
XorIDA threshold sharing over GF(2). Splits swap parameters into K-of-N shares. Information-theoretically secure reconstruction. HMAC-SHA256 integrity verification.
Deterministic binary serialization for shares. Cross-chain compatibility. TLV encoding for asset addresses, amounts, deadlines.
Privacy-preserving computation on shares. Optional integration for verifying swap fairness without exposing plaintext amounts during negotiation.
Cryptographic proof system for verifiable execution. Generates audit trails proving swap parameters were never exposed during protocol. Publicly verifiable without parameter disclosure.
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.
Full API Surface
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.
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.
Cancels a swap and marks shares as invalid. Returns CancelledSwap or error. Reasons: timeout, manual, validation_failed, counterparty_unavailable.
Type Definitions
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; }
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
SaaS Recommended
Fully managed infrastructure. Call our REST API, we handle scaling, updates, and operations.
- Zero infrastructure setup
- Automatic updates
- 99.9% uptime SLA
- Enterprise SLA available
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
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
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.