ERGO
DeFi Primitives
Intermediate
2-4 hours

Cross-Chain Atomic Swap Pattern

Trustless swap between ERG and another chain using HTLC-style contracts

Problème

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.

Fonctionnement

  1. 1Party A generates a secret and its hash
  2. 2Party A locks ERG in HTLC with hash lock + timeout
  3. 3Party B sees the hash and locks BTC in matching HTLC
  4. 4Party A claims BTC by revealing secret (preimage)
  5. 5Party B uses revealed secret to claim ERG
  6. 6If timeout expires, both parties can refund

Exemples de code

{
  // 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.

Cas d'utilisation

  • Cross-chain trading (ERG/BTC, ERG/ETH)
  • OTC deals without intermediaries
  • Decentralized exchange between chains
  • Trustless bridge alternatives
  • P2P trading

Considérations de sécurité

  • !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)

Ressources

Considérations de frais

Two transactions on each chain. Budget for fees on both networks.

Améliorez vos compétences ErgoScript

Recevez des notifications sur les nouveaux patterns, tutoriels et ressources développeur.

Follow for daily updates