Created
November 16, 2024 16:35
-
-
Save k26dr/1c0af928b53b2f173fc202ce5b610dd9 to your computer and use it in GitHub Desktop.
Atomic Swap ETH
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //SPDX-License-Identifier: MIT | |
| pragma solidity ^0.8.0; | |
| contract AtomicSwapETH { | |
| // Hash Tracking for swaps | |
| // The key for the mappings is the hash | |
| struct HTLC { | |
| address initiator; | |
| address receiver; | |
| address token; | |
| uint amount; | |
| uint32 expiry; | |
| } | |
| mapping(bytes32 => HTLC) public HASHES; | |
| event HashCreated(bytes32 indexed hash, address initiator, address receiver, uint256 amount, uint32 expiry); | |
| event HashRevoked(bytes32 indexed hash); | |
| event HashProcessed(bytes32 indexed hash); | |
| function depositToHash(address token, address receiver, bytes32 hash, uint32 expiry) public payable { | |
| require(HASHES[hash].amount == 0, "hash is already funded"); | |
| HASHES[hash] = HTLC(msg.sender, receiver, token, msg.value, expiry); | |
| emit HashCreated(hash, token, msg.sender, receiver, msg.value, expiry); | |
| } | |
| function unlockHash(bytes32 hash, bytes memory preimage) public { | |
| require(sha256(preimage) == hash, "preimage does not match hash"); | |
| require(HASHES[hash].amount > 0, "hash is not funded"); | |
| require(block.timestamp < HASHES[hash].expiry, "hash expired"); | |
| HTLC memory htlc = HASHES[hash]; | |
| delete HASHES[hash]; | |
| htlc.receiver.transfer(htlc.amount); | |
| emit HashProcessed(hash); | |
| } | |
| function reclaimHash(bytes32 hash) public { | |
| require(HASHES[hash].expiry < block.timestamp, "HTLC is active"); | |
| require(HASHES[hash].amount > 0, "hash is not funded"); | |
| HTLC memory htlc = HASHES[hash]; | |
| delete HASHES[hash]; | |
| htlc.initiator.transfer(htlc.amount); | |
| emit HashRevoked(hash); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment