How to Build a Bridge Between Two Blockchains with Different Scripting Languages (Using HTLCs)
A practical guide to bridging two L1 blockchains with different scripting languages using hash time-locked contracts: design, timelocks, code and pitfalls.
Two blockchains can't talk to each other. Each one only knows its own state, runs its own rules and often speaks a completely different programming language: a stack-based script on one side, a smart-contract VM on the other. So how do you move value from one to the other without trusting a middleman with your coins?
One of the oldest answers is still one of the most elegant: the hash time-locked contract (HTLC). It needs very little from each chain (check a hash, check the time, release funds) which is why it works even when the two chains share almost nothing else. This guide explains how HTLCs work, how to use them to build a bridge between two different L1 networks, which problems show up when the scripting languages differ, and what to watch out for.
If you're new to the basics, start with How Blockchains Actually Work.
The two building blocks
An HTLC locks funds so that they can be spent in exactly two ways:
- The hash lock: the recipient can claim the funds by revealing a secret (the preimage) whose hash matches a value committed when the funds were locked.
- The time lock: if nobody claims before a deadline, the original sender can take the funds back.
The magic is that revealing the secret on one chain makes it public, so anyone watching can use the same secret on another chain. That's how a payment on chain B can be made conditional on a payment on chain A, with no one in the middle holding the money. (The Lightning Network uses the same primitive to route payments across many hops.)
The atomic swap, step by step
Suppose Alice holds coin A on chain A and Bob holds coin B on chain B, and they want to trade. Neither trusts the other.
1. Alice picks a random secret S and computes H = SHA-256(S).
2. Alice locks her coins on chain A: "Bob can claim with S before T_A, else Alice refunds."
3. Bob sees the lock on chain A, checks the amount, hash and deadline, then
locks his coins on chain B with the SAME H: "Alice can claim with S before T_B, else Bob refunds."
4. Alice claims Bob's coins on chain B. That reveals S on chain B.
5. Bob reads S from chain B and claims Alice's coins on chain A.
T_A must be later than T_B (by a safe margin).
Either both transfers happen or neither does: that's the "atomic" part. If Alice never reveals S, both sides refund after their deadlines. If Alice reveals S to claim, Bob learns it at the same moment and can claim too.
Why the timelocks must be staggered
Alice's lock must expire later than Bob's. Otherwise Alice could wait until her own lock on chain A is about to expire, reveal S on chain B to claim Bob's coins, and leave Bob too little time to use the secret on chain A, after which Alice would also refund her original coins and keep everything. With T_A > T_B, Bob always has a window after S is revealed.
How much later? The gap T_A − T_B must cover, in the worst case:
- the time for Bob's claim to be included and safely confirmed on chain A (confirmations or finality);
- a reorganisation margin on both chains;
- fee spikes or congestion delaying a transaction;
- Bob's watcher software being briefly offline.
As an illustration only: with a slow chain A and a faster chain B, you might choose T_A = 24 h and T_B = 12 h, leaving 12 hours for Bob to claim after the secret is revealed. Real values depend on each chain's block time, finality rules and your risk tolerance, so derive them for your pair of chains and write the inequality down in your design.
When the scripting languages differ
An HTLC needs the same logical contract on both sides, but each chain expresses it in its own language. These are the details that bite:
| Concern | What to decide |
|---|---|
| Hash function | Both chains must be able to compute the same hash. A chain that only offers one function (say, keccak-256) can't verify a lock built on another unless it exposes both. SHA-256 is widely available as an opcode or precompile, which is why it's the common choice. |
| Preimage size | Fix the secret to a set length (32 bytes is typical) and enforce it. Chains differ in stack and data limits, and an unconstrained length can break claims on one side. |
| Time source | One chain may measure time in block height, another in timestamps; some offer relative locks, others absolute. Convert deliberately and add margin, because block times vary. |
| Finality | Probabilistic finality (wait for N blocks) versus explicit finality changes how long you wait before acting on a lock or a revealed secret. |
| Signatures and addresses | Different curves and address formats. The recipient on each chain must be expressed in that chain's terms, and fixed at lock time. |
| Amounts | Different decimals and units. Define the exchange and rounding rules once, off-chain, and test the edge cases. |
| Fees | Claims cost fees. A claim that becomes uneconomic or impossible during a fee spike can run out the clock. |
The practical test for whether HTLCs are even possible between two chains is whether both can: (1) hash a value, (2) compare it with a stored one, (3) check the current time or height, and (4) release funds conditionally. If one chain lacks any of these, you need a different bridge design.
The same contract in two languages
A script-based chain (Bitcoin-style)
On a UTXO chain with a stack-based script, the HTLC is a script with two branches:
OP_IF
OP_SIZE 32 OP_EQUALVERIFY # secret must be exactly 32 bytes
OP_SHA256 <hash> OP_EQUALVERIFY
<recipient_pubkey> OP_CHECKSIG
OP_ELSE
<expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
<sender_pubkey> OP_CHECKSIG
OP_ENDIF
# claim: <recipient_sig> <secret> OP_TRUE
# refund: <sender_sig> OP_FALSE (only valid after expiry)
The secret appears in the claiming transaction's data, where the counterparty's watcher can read it. A standard for this pattern exists for Bitcoin: BIP-199.
A smart-contract chain (EVM / Solidity)
On an EVM chain the same logic becomes a contract. This minimal version for native ETH compiles with the Solidity compiler; it is a teaching example, not audited code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract HashTimeLock {
struct Lock {
address payable sender; // can refund after expiry
address payable recipient; // gets the funds when the preimage is revealed
uint256 amount;
bytes32 hashLock; // sha256(preimage), same hash the other chain checks
uint64 expiry; // unix timestamp
bool settled;
}
mapping(bytes32 => Lock) public locks;
event Locked(bytes32 indexed id, address indexed sender, address indexed recipient,
uint256 amount, bytes32 hashLock, uint64 expiry);
event Claimed(bytes32 indexed id, bytes32 preimage); // watchers read the secret here
event Refunded(bytes32 indexed id);
function lock(address payable recipient, bytes32 hashLock, uint64 expiry)
external payable returns (bytes32 id)
{
require(msg.value > 0, "no value");
require(expiry > block.timestamp, "expiry in the past");
id = keccak256(abi.encode(msg.sender, recipient, hashLock, expiry, msg.value, block.number));
require(locks[id].amount == 0, "lock exists");
locks[id] = Lock(payable(msg.sender), recipient, msg.value, hashLock, expiry, false);
emit Locked(id, msg.sender, recipient, msg.value, hashLock, expiry);
}
// Anyone may submit the preimage, but funds always go to the recipient fixed at lock time,
// so a bot that sees the secret in the mempool cannot redirect the payout.
function claim(bytes32 id, bytes32 preimage) external {
Lock storage l = locks[id];
require(l.amount != 0 && !l.settled, "not claimable");
require(block.timestamp < l.expiry, "expired");
require(sha256(abi.encodePacked(preimage)) == l.hashLock, "bad preimage");
l.settled = true; // effects before interaction
emit Claimed(id, preimage);
(bool ok, ) = l.recipient.call{value: l.amount}("");
require(ok, "transfer failed");
}
function refund(bytes32 id) external {
Lock storage l = locks[id];
require(l.amount != 0 && !l.settled, "not refundable");
require(block.timestamp >= l.expiry, "not expired");
l.settled = true;
emit Refunded(id);
(bool ok, ) = l.sender.call{value: l.amount}("");
require(ok, "transfer failed");
}
}
Notice what they share: the same hash (sha256 on both), a fixed-size secret, a recipient fixed at lock time, and a deadline. The languages look nothing alike, but the logic matches. That's the whole trick of bridging dissimilar chains with HTLCs.
For tokens instead of the native coin, the same pattern works with an approval and a token transfer in place of msg.value, plus the usual care around non-standard token behaviour.
The watcher: the off-chain half
The contracts only enforce the rules. Something has to watch both chains and act in time. A bridge built on HTLCs is therefore a pair of contracts plus a service. In an LP-backed bridge, where a user locks on chain A and a liquidity provider mirrors on chain B, the service does this:
loop forever:
for lock in chain_a.new_locks(since=cursor_a):
if valid(lock): # amount, hash, recipient, enough time left
chain_b.lock(recipient=lock.counterparty,
amount=convert(lock.amount),
hash=lock.hash,
expiry=lock.expiry - SAFETY_MARGIN) # T_B < T_A
save(lock.hash, "mirrored")
for claim in chain_b.new_claims(since=cursor_b): # the secret was revealed
chain_a.claim(claim.hash, preimage=claim.preimage)
save(claim.hash, "settled")
for lk in unclaimed_and_expired():
refund(lk)
Treat this service like critical infrastructure: persist state so a restart doesn't forget a pending swap, make every action idempotent, wait for sufficient confirmations before reacting, alert on stuck swaps, and have a second instance or an on-call procedure. Most real losses in HTLC systems come from a watcher that was down at the wrong moment, not from broken cryptography.
From a swap to a bridge
A plain atomic swap needs a counterparty who happens to hold what you want. A bridge built from HTLCs removes the search by using liquidity providers who hold funds on both chains and quote a price. The user locks on chain A, the provider mirrors on chain B, and the secret settles both. Users receive native assets on the destination chain, not wrapped tokens, which is a real advantage.
The costs are liquidity (providers must pre-fund both sides), liveness (the user must claim in time, and wallets or a helper service must be online), and capacity (you can only move what the pool holds). If you need to move an asset that has no native form on the destination chain, you need a lock-and-mint design, which has different trust assumptions:
| Design | Trust model | Main trade-off |
|---|---|---|
| HTLC / atomic swap | Trust-minimised: funds are never in anyone's custody | Needs liquidity and liveness; native assets only |
| Multisig or MPC validators | Trust a set of signers | Flexible and fast, but the signer set is the attack surface |
| Light-client bridge | Trust the source chain's consensus, verified on the other chain | Strong guarantees, but expensive and complex to build |
| Optimistic bridge | Trust that someone will challenge fraud in time | Cheap, but needs a challenge window and active watchers |
| Zero-knowledge proof bridge | Trust a proof system verified on-chain | Strong guarantees; heavy engineering and proving cost |
Security checklist
- Timelock inequality:
T_A − T_Bmust exceed confirmation time plus reorg, congestion and downtime margins. Write the calculation down and review it. - Never reuse a hash. One secret per swap, generated with a cryptographically secure random source.
- Fix the recipient at lock time, so that revealing the secret in a public mempool can't be front-run to a different address.
- Handle the free option. The party who can choose when to reveal holds a free option on the price. Keep windows short, quote conservatively, and consider a small premium or deposit.
- Watch for griefing: someone locking funds and never completing ties up provider liquidity until expiry. Use minimums and rate limits.
- Reentrancy and standard bugs on the contract side: update state before external calls, and use the established libraries and an audit before holding real value.
- Units and decimals: test every edge case in your conversion function; rounding errors are value leaks.
- Reorg and finality handling: don't mirror a lock that can still be undone.
- Operational monitoring: alert on any swap approaching its deadline without a claim.
How to test it
- Unit-test each contract for every path: claim, wrong secret, early refund, late claim, double settle.
- Run both chains locally (a local node or regtest setup for each) and exercise the full swap end to end, including the unhappy paths: the user never reveals, the watcher is offline, one chain halts for a while.
- Property-test the timelock logic: for random block-time and delay scenarios, assert that no party can end up with both sides.
- Use public testnets to see real fee and congestion behaviour before mainnet.
- Get an independent audit of both contracts and the watcher's decision logic.
When HTLCs are the wrong tool
For a real-world example of an operated bridge, with its own custody and a contract-enforced refund path, see How I Built a USDT Bridge Between Minima and Ethereum. If one of the chains can't hash and time-lock, HTLCs are out. If you need to move arbitrary assets or messages rather than swap native coins, or you can't rely on liquidity providers and users staying online, a validator-set, light-client or proof-based design is more suitable, accepting its different trust assumptions. And if you only need to swap occasionally, an existing audited protocol may be safer than writing your own.
The short version
- An HTLC locks funds behind a hash and a deadline; revealing the secret on one chain lets someone claim on the other.
- Use the same hash function and a fixed-size secret on both chains.
- Make the first lock expire later than the second, with a margin that covers confirmations, reorgs, congestion and downtime.
- The languages can differ completely as long as both chains can hash, compare, check time and release funds conditionally.
- A bridge adds liquidity providers and a watcher service on top of the contracts. Build the watcher like critical infrastructure.
- Test the unhappy paths and get an audit before real money is involved.
If you're designing cross-chain infrastructure and want a second pair of eyes on the timelocks, the threat model or the watcher, say hello.
Keep reading
-
How I Built a USDT Bridge Between Minima and Ethereum
Inside a USDT bridge between Minima and Ethereum: the contract, monitors, queues, batching, refunds, alerting, the outages that shaped it, and an honest trust model.
-
How Blockchains Actually Work: A Developer's Mental Model
Skip the hype. A developer's mental model of blockchains: replicated state machines, hash-linked blocks, consensus, finality, fees and where smart contracts fit.
-
Expo Exact vs Expo and React Native: What's Different and What the Performance Numbers Show
Expo's experimental Exact framework compared with Expo, React Native and React: the Contract language, native rendering, and which performance claims hold up.