Skip to content

Instantly share code, notes, and snippets.

@hihiben
Last active December 17, 2019 07:24
Show Gist options
  • Save hihiben/6d868fa519db88f50fe9cf319d494a57 to your computer and use it in GitHub Desktop.
Save hihiben/6d868fa519db88f50fe9cf319d494a57 to your computer and use it in GitHub Desktop.
Basic implementation of HTLC
pragma solidity ^0.5.0;
contract HTLC {
address payable public sender;
address payable public receiver;
bytes32 public hashlock;
uint256 public timelock;
bytes32 public preimage;
constructor(address payable _receiver, bytes32 _hashlock, uint256 _timelock) public payable {
sender = msg.sender;
receiver = _receiver;
hashlock = _hashlock;
timelock = _timelock;
}
function redeem(bytes32 _preimage) external returns (bool) {
require(address(this).balance != 0);
require(msg.sender == receiver);
// Check hashlock
require(hashlock == sha256(abi.encodePacked(preimage)),
"hashlock unlock failed"
);
// Redeem
preimage = _preimage;
msg.sender.transfer(address(this).balance);
return true;
}
function refund() external returns (bool) {
require(address(this).balance != 0);
require(msg.sender == sender);
// Check timelock
require(timelock <= now, "timelock unlock failed");
// Refund
msg.sender.transfer(address(this).balance);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment