Lendasat LogoLendasat Docs

Atomic Swap Protocol

Understanding trustless Bitcoin to stablecoin swaps

LendaSwap uses atomic swaps to enable trustless exchanges between Bitcoin and stablecoins. Either both parties receive their funds, or neither does—there's no scenario where one party can steal from the other.

TL;DR: You send BTC, you receive USDC. If anything goes wrong, you get your BTC back. No trust required.

What is an Atomic Swap?

An atomic swap is a peer-to-peer exchange of cryptocurrencies across different blockchains without requiring a trusted third party. The "atomic" property means the swap either:

  1. Completes fully - Both parties get their funds
  2. Doesn't happen at all - Both parties keep their original funds

There is no middle ground where one party receives funds but the other doesn't.


Why Atomic Swaps?

FeatureTraditional SwapAtomic Swap
Trust RequiredHigh (centralized exchange)None (trustless)
CustodyExchange holds your fundsYou control your funds
KYCRequiredNot required
SpeedVariable (withdrawals)Fast (1-2 minutes)
FeesTrading fee + withdrawalOnly network fees
Censorship ResistanceLow (can freeze accounts)High (unstoppable)
Counterparty RiskHigh (exchange can be hacked)None (cryptographic guarantees)

How It Works

LendaSwap's atomic swap protocol combines three key technologies:

1. Hash Time-Locked Contracts (HTLCs)

HTLCs are smart contracts with two conditions:

Hash Lock - Funds can only be claimed by revealing a secret (preimage)

  • Service generates a random 32-byte secret
  • Hash of secret is used to lock funds
  • Only the party with the secret can claim

Time Lock - Funds are automatically refunded after a timeout

  • Default timeout: 10 minutes for fast swaps
  • After timeout, original sender can reclaim funds
  • Prevents funds from being locked forever

2. Secret Revelation Mechanism

The atomic swap uses a secret-sharing mechanism:

1. Service generates secret S
2. Service computes hash H = SHA256(S)
3. Service locks WBTC in HTLC with hash H
4. User reveals secret S to claim USDC
5. Secret S is now public on-chain
6. Service uses S to claim BTC

This ensures atomicity:

  • User can't claim without revealing S
  • Service can't claim BTC without S
  • Once S is revealed, service can always claim BTC

3. Cross-Chain Coordination

The protocol coordinates between Bitcoin (Lightning/Arkade) and Polygon:

Bitcoin Side:

  • User sends BTC via Lightning or Arkade
  • Service receives BTC
  • Service has secret to claim BTC once revealed

Polygon Side:

  • Service locks WBTC in HTLC smart contract
  • HTLC swaps WBTC → USDC when claimed
  • User claims USDC by revealing secret
  • Secret is extracted from claim transaction

Swap Flow

┌──────────┐                    ┌──────────┐
│   User   │                    │ Service  │
│  (Bob)   │                    │ (Alice)  │
└────┬─────┘                    └────┬─────┘
     │                               │
     │  1. Request swap for $100     │
     │──────────────────────────────>│
     │                               │
     │  2. Generate secret S         │
     │  3. Compute hash H = SHA256(S)│
     │                               │
     │  4. Lightning invoice          │
     │     Arkade address            │
     │     sats_required: 155,000    │
     │<──────────────────────────────│
     │                               │
     │  5. Pay 155,000 sats          │
     │     via Lightning/Arkade      │
     │──────────────────────────────>│
     │                               │
     │                    6. Receive BTC
     │                    7. Lock WBTC in HTLC
     │                       with hash H
     │                       timeout: 10 min
     │                               │
     │  8. HTLC created              │
     │     Claim with secret S       │
     │<──────────────────────────────│
     │                               │
     │  9. Reveal S, claim USDC      │
     │     (gasless transaction)     │
     │──────────────────────────────>│
     │                               │
     │ 10. Receive 100 USDC    11. Extract S
     │<────────────────────    from blockchain
     │                               │
     │                    12. Use S to claim BTC
     │                        (if needed)
     │                               │
     │  ✓ Swap Complete              │
     │  Bob: 100 USDC       Alice: BTC

Security Properties

Trustlessness

Neither party needs to trust the other:

User Security:

  • Can't lose BTC without receiving USDC
  • If service doesn't create HTLC, can refund BTC
  • If HTLC times out, service refunds WBTC

Service Security:

  • Can't lose WBTC without receiving BTC
  • User must reveal secret to claim USDC
  • Once secret is revealed, service can claim BTC

Atomicity Guarantee

The protocol ensures atomicity through cryptographic hash locks:

  1. User can't claim USDC without revealing secret - Smart contract requires secret as input, transaction fails if secret is wrong

  2. Service learns secret when user claims - Secret is visible in blockchain transaction, service monitors for claim transactions

  3. Service can always claim BTC after user claims - Lightning/Arkade payment uses same hash lock, service has secret after user reveals it

Timeout Safety

Timelocks prevent funds from being locked forever:

TimeoutDurationPurpose
Polygon HTLC10 minUser has 10 min to claim USDC
Lightning Invoice30 minPayment window for Lightning
ArkadeVariableCan be refunded if HTLC not created

Critical Rule: Bitcoin timeout must be greater than Polygon timeout. This ensures user can't claim both BTC and USDC, and service always has time to claim BTC after user claims USDC.


State Transitions

The swap goes through several states. See State Machine for the complete diagram.

Normal Flow (Success)

Pending → ClientFunded → ServerFunded → Done

Refund Flow (Timeout)

Pending → Expired (30 min timeout, no payment)
ClientFunded → ClientRefunded (user refunds before HTLC)
ServerFunded → ClientFundedServerRefunded (HTLC timeout)

Advantages

For Users

  1. No Trust Required - Don't need to trust the service
  2. Guaranteed Delivery - Either get USDC or keep BTC
  3. No Gas Fees - Gasless claiming via Gelato Relay
  4. Fast - Typical swap takes 1-2 minutes
  5. Privacy - No KYC required

For Service

  1. No Counterparty Risk - Can't lose funds to dishonest users
  2. Automated - Entire process is automated
  3. Scalable - Can handle many swaps simultaneously
  4. Transparent - All operations on-chain, auditable

Technical Implementation

Smart Contract (Polygon)

function createSwap(
    bytes32 swapId,
    address recipient,
    address tokenOut,
    uint256 amountWBTCIn,
    uint256 minAmountOut,
    bytes32 hashLock,
    uint256 timelock
) external

function claimSwap(
    bytes32 swapId,
    bytes32 secret
) external

function refundSwap(bytes32 swapId) external

See HTLC Protocol for detailed contract documentation.

Backend (Rust)

The LendaSwap backend handles:

  1. Arkade Integration - Generate addresses, monitor payments
  2. Lightning Integration - Create invoices via Boltz
  3. HTLC Management - Create, monitor, and process swaps
  4. Secret Management - Generate and store secrets securely
  5. Claim Processing - Submit gasless claims via Gelato

Limitations

  1. Amount Limits - Currently $1 - $1,000 per swap (configurable)
  2. Supported Tokens - Only USDC and USDT on Polygon and Ethereum
  3. Network Dependency - Requires Lightning/Arkade functionality
  4. Time Sensitive - User must claim within timeout period

Resources

Learn More: