> ## Documentation Index
> Fetch the complete documentation index at: https://docs.garden.finance/llms.txt
> Use this file to discover all available pages before exploring further.

# Starknet

> Implement atomic swaps on Starknet using Cairo contracts and SNIP-12 signatures

## Contract architecture

Garden uses Hashed Time Lock Contracts (HTLCs) to implement atomic swap functionality on Starknet. The contract manages the lifecycle of a swap through four main operations with enhanced signature support and flexible initiation methods:

<CardGroup cols={4}>
  <Card title="Initiate" icon="play" href="#initiate" />

  <Card title="Redeem" icon="check" href="#redeem" />

  <Card title="Refund" icon="rotate-left" href="#refund" />

  <Card title="Instant refund" icon="bolt" href="#instant-refund" />
</CardGroup>

## Core functions

### Initiate

The initiate function creates a new HTLC by locking ERC20 tokens in the contract. Starknet provides three flexible initiation methods:

#### Basic initiation

```rust theme={null}
fn initiate(
    ref self: ContractState,
    redeemer: ContractAddress,
    timelock: u128,
    amount: u256,
    secret_hash: [u32; 8],
)
```

#### Initiation on behalf

```rust theme={null}
fn initiate_on_behalf(
    ref self: ContractState,
    initiator: ContractAddress,
    redeemer: ContractAddress,
    timelock: u128,
    amount: u256,
    secret_hash: [u32; 8],
)
```

#### Signature-based initiation

```rust theme={null}
fn initiate_with_signature(
    ref self: ContractState,
    initiator: ContractAddress,
    redeemer: ContractAddress,
    timelock: u128,
    amount: u256,
    secret_hash: [u32; 8],
    signature: Array<felt252>,
)
```

<Note>
  Uses SNIP-12 signatures for off-chain authorization, enabling gasless transactions where authorized third parties can initiate swaps on behalf of users.
</Note>

### Redeem

The redeem function allows the redeemer to claim the locked tokens by providing the secret that hashes to the stored secret hash.

```rust theme={null}
fn redeem(
    ref self: ContractState, 
    order_id: felt252, 
    secret: Array<u32>
) -> Result<()>
```

<Info>
  The secret must hash to the exact value stored during initiation using SHA256. Once revealed, this secret enables the counterparty to claim funds on the other chain. No signature required — anyone can execute if they know the secret.
</Info>

### Refund

The refund function allows the initiator to reclaim their tokens after the timelock has expired and the redeemer has not claimed the funds.

```rust theme={null}
fn refund(
    ref self: ContractState,
    order_id: felt252
)
```

<Note>
  Starknet uses block number-based timing similar to Ethereum, providing predictable settlement windows based on Starknet's consistent block production.
</Note>

### Instant refund

The instant refund function provides a way for the redeemer to consent to canceling the swap before the timelock expires using SNIP-12 signatures.

```rust theme={null}
fn instant_refund(
    ref self: ContractState,
    order_id: felt252,
    signature: Array<felt252>
)
```

<Note>
  This requires the redeemer's SNIP-12 signature to prevent unauthorized instant refunds. This ensures mutual consent before the settlement window expires.
</Note>

## Starknet-specific features

### Order state management

The contract uses a Cairo struct to store swap state with efficient storage patterns:

```rust theme={null}
#[derive(Drop, Serde, starknet::Store, Debug)]
pub struct Order {
    is_fulfilled: bool,
    initiator: ContractAddress,
    redeemer: ContractAddress,
    initiated_at: u128,
    timelock: u128,
    amount: u256,
}
```

### Poseidon-based order IDs

Starknet uses the Poseidon hash function for generating unique order identifiers:

```rust theme={null}
fn generate_order_id(
    self: @ContractState,
    chain_id: felt252,
    secret_hash: [u32; 8],
    initiator_address: felt252,
) -> felt252 {
    let mut state = PoseidonTrait::new();
    state = state.update(chain_id);
    state = state.update_with(secret_hash);
    state = state.update(initiator_address);
    state.finalize()
}
```

<Tip>
  Poseidon hashing is optimized for zero-knowledge proofs and provides efficient computation on Starknet while ensuring order uniqueness.
</Tip>

### SNIP-12 signature validation

The contract implements SNIP-12 (Starknet Improvement Proposal 12) for secure off-chain message signing:

```rust theme={null}
let is_valid = ISRC6Dispatcher { contract_address: initiator }
    .is_valid_signature(message_hash, signature);
let is_valid_signature = is_valid == starknet::VALIDATED || is_valid == 1;
assert!(is_valid_signature, "HTLC: invalid initiator signature");
```

### Event logging

The contract emits events for each state transition to enable efficient off-chain monitoring:

```rust theme={null}
#[event]
#[derive(Drop, starknet::Event)]
pub enum Event {
    Initiated: Initiated,
    Redeemed: Redeemed,
    Refunded: Refunded,
}

#[derive(Drop, starknet::Event)]
pub struct Initiated {
    order_id: felt252,
    secret_hash: [u32; 8],
    amount: u256,
}
```

### ERC20 token integration

Unlike native currency swaps, Starknet HTLC works with ERC20 tokens:

```rust theme={null}
#[storage]
struct Storage {
    pub token: IERC20Dispatcher,
    pub orders: Map::<felt252, Order>,
}
```

<Check>
  The contract uses OpenZeppelin's ERC20 interface for secure token transfers with proper allowance and balance checks.
</Check>

### Gas optimization

Starknet's unique fee model enables several optimizations:

```rust theme={null}
fn safe_params(
    self: @ContractState, 
    redeemer: ContractAddress, 
    timelock: u128, 
    amount: u256,
) {
    assert!(redeemer.is_non_zero(), "HTLC: zero address redeemer");
    assert!(timelock > 0, "HTLC: zero timelock");
    assert!(amount > 0, "HTLC: zero amount");
}
```

<Info>
  Parameter validation is grouped into a single function to optimize for Starknet's execution model while maintaining security.
</Info>
