DeFi Primitives
Intermediate
2-4 hoursCross-Chain Atomic Swap Pattern
Trustless swap between ERG and another chain using HTLC-style contracts
Problem
You want to exchange ERG for BTC/ETH/other chain assets without trusting a centralized exchange or bridge.
Solution
Hash Time-Locked Contracts (HTLCs) enable atomic swaps. Both parties lock funds with the same hash lock. Revealing the preimage on one chain allows claiming on both.
How It Works
- 1Party A generates a secret and its hash
- 2Party A locks ERG in HTLC with hash lock + timeout
- 3Party B sees the hash and locks BTC in matching HTLC
- 4Party A claims BTC by revealing secret (preimage)
- 5Party B uses revealed secret to claim ERG
- 6If timeout expires, both parties can refund
Code Examples
{
// Hash Time-Locked Contract for atomic swaps
// R4: Hash of secret (blake2b256)
// R5: Recipient public key (Party B)
// R6: Refund public key (Party A)
// R7: Timeout block height
val secretHash = SELF.R4[Coll[Byte]].get
val recipient = SELF.R5[SigmaProp].get
val refundTo = SELF.R6[SigmaProp].get
val timeout = SELF.R7[Int].get
// Claim path: provide preimage that hashes to secretHash
val preimage = getVar[Coll[Byte]](0).get
val validPreimage = blake2b256(preimage) == secretHash
val claim = validPreimage && recipient
// Refund path: after timeout, original sender can reclaim
val refund = HEIGHT > timeout && refundTo
claim || refund
}HTLC on Ergo. Recipient can claim with secret preimage. Sender can refund after timeout.
Use Cases
- →Cross-chain trading (ERG/BTC, ERG/ETH)
- →OTC deals without intermediaries
- →Decentralized exchange between chains
- →Trustless bridge alternatives
- →P2P trading
Security Considerations
- !Initiator's timeout must be longer than responder's
- !Verify hash algorithm matches on both chains
- !Monitor both chains for claim transactions
- !Use secure random for secret generation
- !Consider griefing attacks (locking funds without completing)
Resources
Fee Considerations
Two transactions on each chain. Budget for fees on both networks.