# HTLC implementation

In ATOMICS, an HTLC is not merely a contract template but a **protocol primitive** used to encode conditional ownership transfer.

Each HTLC enforces the following rule:

> Ownership of an asset may be transferred **if and only if** a specific cryptographic secret is revealed before a predefined expiration time; otherwise, ownership reverts to the original holder.

This conditional logic is sufficient to enforce atomic settlement across independent execution environments when properly composed.

HTLCs allow us to replace:

* trusted escrow agents,
* custodial bridges,
* and discretionary arbitration

with **deterministic, cryptographic enforcement**.

***

#### Secret Generation and Hash Commitment

Every atomic swap begins with the generation of a cryptographically secure random secret `s`, sampled uniformly from a sufficiently large domain (typically 256 bits).

A cryptographic hash function `H` is applied to produce a hash commitment:

```
h = H(s)
```

Properties required of `H`:

* preimage resistance,
* second-preimage resistance,
* collision resistance.

The hash `h` is shared with all counterparties and embedded into each HTLC instance across all involved blockchains. The secret `s` is kept private until settlement.

The **single shared hash commitment** is the cryptographic link that binds all HTLCs together across chains.

***

#### HTLC Deployment Across Chains

For a cross-chain swap involving multiple assets on different chains, ATOMICS deploys **one HTLC per asset per chain**.

Each HTLC is parameterized with:

* sender address,
* receiver address,
* asset identifier and quantity,
* hash commitment `h`,
* expiration time `T`.

Although implementations differ across environments (EVM, SVM, UTXO), the logical structure remains consistent.

The protocol ensures that **all HTLCs reference the same hash commitment** while allowing chain-specific execution semantics.

***

#### Timelock Ordering and Safety Constraints

A critical aspect of HTLC integration is **timelock ordering**.

For a two-party, two-chain swap:

* one HTLC is assigned an expiration `T₁`,
* the other is assigned `T₂`,
* where `T₁ > T₂ + Δ`.

Here, `Δ` is a safety margin accounting for:

* block production variability,
* network delays,
* transaction confirmation time,
* chain-specific finality guarantees.

This ordering ensures that:

1. A party who redeems on the shorter-timelock chain necessarily reveals `s`.
2. The counterparty has sufficient time to observe `s` and redeem on the longer-timelock chain.
3. If redemption does not occur, both parties can safely refund.

Timelock ordering is strictly enforced by the protocol and is central to cross-chain safety.

***

#### Integration Across Execution Environments

ATOMICS integrates HTLCs across fundamentally different blockchain architectures.

**EVM-Based Chains**

On EVM chains, HTLCs are implemented as smart contracts written in Solidity. These contracts:

* escrow ERC-20 tokens or native assets,
* verify hash preimages on-chain,
* enforce expiration via block timestamps.

Care is taken to:

* minimize state complexity,
* avoid reentrancy,
* ensure deterministic execution paths.

**Solana (SVM)**

On Solana, HTLC logic is implemented using programs written in Rust. Due to Solana’s account model:

* assets are held in program-controlled accounts,
* program logic enforces conditional release,
* expiration is enforced via slot or timestamp constraints.

Despite architectural differences, the same cryptographic guarantees are preserved.

**UTXO-Based Chains (Bitcoin, Dogecoin)**

On UTXO chains, HTLCs are implemented using native script primitives.

These scripts enforce:

* redemption via signature + secret revelation,
* refund via timelock-guarded signature.

This approach avoids introducing additional trust layers and preserves native asset ownership throughout the swap.\
\
Secret Revelation and Propagation

Settlement is triggered when one party redeems an HTLC by submitting the secret `s` on-chain.

Once revealed:

* `s` becomes publicly observable,
* counterparties monitor relevant chains,
* remaining HTLCs are redeemed using the same secret.

The protocol **does not require synchronous execution**. Redemption can occur asynchronously as long as timelock ordering constraints are satisfied.

This design tolerates:

* network delays,
* chain congestion,
* temporary outages.

***

#### Refund Logic and Deterministic Resolution

If settlement does not complete before expiration:

* the secret remains unrevealed,
* HTLCs transition to a refund-eligible state,
* original owners reclaim their assets.

Refund logic is:

* encoded directly in the contract or script,
* executable without counterparty cooperation,
* deterministic and time-bounded.

There is no discretionary judgment or off-chain arbitration involved.

***

#### Failure Isolation and Containment

A key design goal of HTLC integration is **failure isolation**.

Failures in one component do not cascade:

* Failure of an off-chain relayer affects coordination only.
* Failure of one chain triggers refunds without affecting others.
* Failure of a UI or bot does not compromise settlement.

HTLCs ensure that **all critical enforcement remains local to each chain**, minimizing systemic risk.

***

***

#### Auditability and Formal Reasoning

HTLC integration is intentionally minimalistic.

Each HTLC instance:

* has a small state space,
* follows a linear lifecycle,
* exposes no discretionary execution paths.

This simplicity enables:

* exhaustive state enumeration,
* formal verification efforts,
* comprehensive security auditing.

Auditors can reason about HTLC correctness independently of higher-level coordination mechanisms.\
\
**HTLC Architecture**\
\
A secret s ∈ {0,1}²⁵⁶ is sampled uniformly at random. A hash h = H(s) is computed using a preimage-resistant hash function.

The HTLC enforces:

* redemption if and only if s is revealed
* refund after expiration if s is not revealed

Timelocks are ordered across chains to ensure safe secret propagation.

This construction guarantees that no participant can extract value without revealing the secret required to unlock the corresponding contracts.<br>

```
mapping (bytes32 => Swap) public swaps; // swapID -> Swap details

// Create a new swap
function createSwap(
    bytes32 _swapID,
    address _receiver,
    uint256 _amount,
    bytes32 _hashLock,
    uint256 _expiration
) external payable {
    require(swaps[_swapID].sender == address(0), "Swap ID in use");
    // Transfer tokens or handle native coin
    // ...
    swaps[_swapID] = Swap({
        sender: msg.sender,
        receiver: _receiver,
        amount: _amount,
        hashLock: _hashLock,
        expiration: _expiration,
        isRedeemed: false,
        isRefunded: false
    });
}

// Redeem the swap by revealing the secret
function redeem(bytes32 _swapID, bytes memory _secret) external {
    Swap storage s = swaps[_swapID];
    require(!s.isRedeemed && !s.isRefunded, "Swap not active");
    require(keccak256(_secret) == s.hashLock, "Invalid secret");
    require(block.timestamp < s.expiration, "Swap expired");
    // Transfer tokens to msg.sender (should be s.receiver typically)
    // ...
    s.isRedeemed = true;
}

// Refund if timeLock is passed
function refund(bytes32 _swapID) external {
    Swap storage s = swaps[_swapID];
    require(!s.isRedeemed && !s.isRefunded, "Swap not active");
    require(block.timestamp >= s.expiration, "Not yet expired");
    // Return tokens to s.sender
    // ...
    s.isRefunded = true;
}
```

### Formal State Machine

Each HTLC follows a minimal state machine:

```
Uninitialized → Locked → Redeemed
                         → Refunded
```

States are irreversible. This minimalism reduces attack surface and simplifies auditing.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://atomics.gitbook.io/atomics/welcome-to-atomics/readme/atomic-swap-protocol/htlc-implementation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
