# Harbor Docs
> Harbor - A Uniswap V4 bond trading protocol
import { Card } from '../components/Card'
import { CardGrid } from '../components/CardGrid'
import { Coins, TrendingUp, Shield, Code } from 'lucide-react'
## Get started
Learn how on bond trading infrastructure with our comprehensive integration tools.
} href="/developers/trading-api" moreText="More" />
} href="/developers/bond-issuance" moreText="More" />
} href="/developers/escrow-integration" moreText="More" />
} href="/developers/sdk" moreText="More" />
#### Escrow Contract
The Escrow Contract manages the tokenized representations of both collateral and bonds. It ensures proper collateralization of `hTokens` through a combination of open wrapping/unwrapping functions and access-controlled minting and burning. It also facilitates settlement and redemption workflows through integration with the Harbor market contract (hook).
#### Key Responsibilities
* Token Wrapping: Convert underlying collateral into wrapped forms (e.g., UNI → hUNI) and back
* Bond Collateralization: Lock and release bond NFTs as collateral
* Access Control: Only `market` contracts can deposit and withdraw bond NFTs
* (Planned): Manage redemption and settlement of matured bond positions
#### Core Functions
```solidity
interface IEscrow is ERC20 {
// Corresponding token
address public immutable underlying;
// Public: wrapping/unwrapping collateral
function wrapToken(uint256 amount) external;
function unwrapToken(uint256 amount) external;
// Role-restricted: bond management
function depositBond(address issuer, uint256 tokenId, address from) external;
function withdrawBond(address issuer, uint256 tokenId, address to) external;
// TODO:
function redeemBond(address issuer, uint256 tokenId) internal;
}
```
## Overview
```mermaid
graph TB
Registry[Registry Contract]
Issuers[Bond Issuers]
Registry -->|market 1| Escrow
Registry -->|market 2| Escrow2
Issuers -->|added to whitelist| Registry
subgraph "Harbor Market"
Escrow[Escrow Contract]
Pool[Uniswap Pool]
Escrow <-->|hook callback| Pool
end
subgraph "Harbor Market2"
Escrow2[Escrow Contract]
Pool2[Uniswap Pool]
Escrow2 <-->|hook callback| Pool2
end
subgraph "External"
Users1[Users]
Users2[Liquidity Providers]
Users2 -->|deposit Tokens| Escrow
Users2 -->|add Liquidity| Pool
Users1 -->|buy/sell bonds| Escrow
Users1 -->|swap tokens| Pool
end
```
#### Registry Contract
The Registry serves as the **central coordinator** and **factory** for the Harbor ecosystem.
It maintains:
* Market metadata and configuration
* Authorized issuers and participants
* Fee structures and governance parameters
#### Key Responsibilities
* **Market Creation**: Atomically creates markets with escrow tokens, hooks, and pools
* **Issuer Management**: Maintains registry of supported bond issuers
* **Infrastructure Coordination**: Manages relationships between components
* **Access Control**: Provides issuer validation for escrow contracts
#### Core Functions
```solidity
interface IRegistry {
function createMarket(...) external returns (MarketKey, Currency, address, PoolId);
function isIssuerSupported(address issuer) external view returns (bool);
function addSupportedIssuer(address issuer) external;
}
```
## Bonds
Harbor considers a bond to be any [Non-Fungible Token](https://en.wikipedia.org/wiki/ERC-721) that represents ownership of locked tokens that will become unlocked in the future (also called a vesting NTF, etc). Bonds are only accepted from whitelisted issuers to ensure that all bonds in the system will work correctly. All bonds must either implement the `IHarbor.sol` interface, or utilize an adapter which presents the required information in the correct format.
```solidity
interface IHarbor is IERC721Enumerable {
/**
* @notice Reference data postion needed to calculate offers.
*
* @param underlying Address of the underlying token
* @param faceValue Face value of the bond
* @param duration Total duration of the lock in seconds
* @param created Timestamp of when the lock was created
* @param maturity Timestamp of when the lock matures
* @param redeemed Flag indicating whether the locked tokens have been redeemed
*/
struct ReferenceData {
address underlying;
uint256 faceValue;
uint256 duration;
uint256 created;
uint256 maturity;
bool redeemed;
}
}
```
## Escrow
The Harbor system is centered around an escrow contract which holds collateral (liquid tokens and bonds) for a single underlying ERC20 asset (hereafter called the `Token`).
When the escrow contract receives a collateral asset, it issues Harbor tokens (`hToken`) representing the value of the collateral at a 1:1 ratio. Harbor tokens use the same ticker as the underlying asset, with the prefix `h` (e.g. `UNI` -> `hUNI`).
* Users can **wrap** liquid tokens into the escrow contract to receive `hTokens`, and **unwrap** `hTokens` for `Tokens` at any time.
* Harbor [markets](/components/markets) can receive NFT bonds, backed by a whitelisted issuer, in which case the escrow contract will issue a number of `hTokens` equal to the minimum guaranteed redemption value (face value) of the bond.
* `hTokens` are used to purchase immature bonds from the market.
:::info
The escrow contract guarantees that every `hToken` is backed 1:1 by a `Token` held in escrow, either directly as liquid tokens or indirectly via bonds.
:::
#### Uniswap Pool
Each escrow contract is paired with a Uniswap V4 pool, which allows users to swap `hTokens` for `Tokens`. The pool is connected to the escrow contract using Uniswap V4 Hooks.
```mermaid
graph TB
Deployer[Harbor Deployer]
Escrow[Escrow Contract]
Pool[Uniswap Token / hToken Pool]
Escrow <--> |Uniswap Hooks| Pool
Deployer --> Escrow
```
The pool is intended to always trend towards a **1:1 price ratio**, which is maintained by market arbitrage forces:
* If the price of the pool becomes unbalanced with insufficient `Tokens`, the escrow contract can use any liquid `Tokens` it holds to buy back `hTokens` from the pool.
* If the price of the pool becomes unbalanced with insufficient `hTokens`, any user can deposit `Tokens` into the escrow contract to receive `hTokens`, which they can then sell into the pool to take advantage of the arbitrage opportunity.
#### Adding Liquidity
If a user holds `Tokens` and would like to add liquidity to the pool (assuming the price is currenlty at 1:1), they can deposit half of their tokens into the escrow contract to receive `hTokens`, and then add both `Tokens` and `hTokens` to the pool.
**Assuming the user has 100 `Tokens`:**
```mermaid
sequenceDiagram
participant User as User Wallet
participant Escrow as Escrow Contract
participant Pool as Uniswap Pool
User->>Escrow: deposit 50 Tokens
Escrow-->>User: receive 50 hTokens
User->>Pool: addLiquidity(50 Tokens, 50 hTokens)
Pool-->>User: receive LP tokens
```
## Markets
The [Escrow](/components/escrow) contract, is paired with a `Harbor market` (A Uniswap v4 Hook) which provides an interface for end users to buy/sell bond NFTs from/into the escrow.
The *market* makes use of an on-chain pricing algorithm to dynamically set the price at which it will buy and sell bonds, based on their attributes.
The *market* keeps track of which bonds it has bought from users and the price paid, and utilizes its own logic to resell bonds to generate profit on behalf of liquidity providers.
### Example Flow
Imagine a user wants to sell a bond that contains 100 locked `Tokens`. Based on the remaining time to maturity, the pricing algorithm determines the market should be willing to buy the bond for 90 `Tokens` and sell the bond for 95 `Tokens`.
**A user sells the bond into the market:**
```mermaid
sequenceDiagram
participant User as User Wallet
participant Market as Market Contract
participant Pricing as Pricing Algorithm
participant Escrow as Escrow Contract
Market-->>Pricing: Request buy price of bond
Pricing-->>Market: Current price is 90 Tokens
User->>Market: Transfer bond worth 100 Tokens
Market->>Escrow: Transfer bond
Escrow->>Market: Transfer 100 hTokens
Market->>User: Transfer 90 tokens
```
At this point, the user has sold their bond for 90 `hTokens`. The NFT and its underlying 100 `Tokens` is now in escrow, with 10 `hTokens` held by the market.
**Another user buys the bond from the market:**
```mermaid
sequenceDiagram
participant User as User Wallet
participant Market as Market Contract
participant Pricing as Pricing Algorithm
participant Escrow as Escrow Contract
Market-->>Pricing: Request sell price of bond
Pricing-->>Market: Current price is 95 Tokens
User->>Market: Transfer 95 hTokens
Market-->>Market: Add 5 from own hTokens
Market->>Escrow: Transfer 100 hTokens
Escrow->>Market: Transfer bond worth 100 Tokens
Market->>User: Transfer bond
```
At this point, the user has purchase the bond for 95 `hTokens`. The market has added 5 of its 10 tokens to the user's 95 to redeem the bond from the escrow. The user now owns the bond, and the market has generated 5 `hTokens` in profit.
The profit generated can be paid out to liquidity providers, who can use it to redeem liquid tokens from the escrow contract.
## Pricing
When a `Harbor market` is presented with a bond to buy or sell, it makes use of an on-chain pricing algorithm which generates a quote based on the attributes of the bond, such as the amount of tokens locked up in the bond, the time to maturity, the issuer, and/or other attributes.
Let:
* $$P\_b(t)$$: the buy price of the bond at time $$t$$
* $$P\_s(t)$$: the sell price at time $$t$$
* $$V$$: the face value (redemption value) of the bond at maturity $$T$$
* $$P(t)$$: the market price function returned by the pricing algorithm
Then, to guarantee profitability and arbitrage safety, the pricing algorithm should satisfy:
```math
P_b(t) < P_s(t) < V \quad \forall t < T
```
Additionally, prices must not decrease over time:
$$
\frac{dP(t)}{dt} \geq 0
$$
If a bond is purchased but not resold, the maximum profit is realized at redemption:
$$
\Pi(t) = V - P\_b(t)
$$
> where $$\Pi(t)$$ is the profit if the bond is held to maturity.
Consider the following Linear strategy.
Example Linear pricing strategy demonstrating how bond prices increase linearly from purchase price to face value over time
### Guardrails
guard against common risks.
#### JIT Profit Extraction
1. Attacker sees profitable bond incoming via mempool
2. Front-runs by wrapping large amount OP → vOP
3. Bond purchase happens, profit distributed across all vOP holders
4. Attacker immediately unwraps vOP → OP, capturing profit
5. LP who provided long-term liquidity gets diluted returns
:::warning
#### Liquidity Drain
Syntetic token is trading below 1:1 parity on external markets
1. Arbitrageur buys cheap vTKN (e.g., 0.95 vTKN each)
2. Unwraps vTKN for full 1:1 TKN value
3. 5% instant profit extracted from LP reserves
4. Repeat until pool drained
:::
:::warning
#### Fee Structure for Non-LP Operations
```
If allowing public wrap/unwrap:
- Wrap fee: 0.5% (discourages profit extraction)
- Unwrap fee: 1% (protects against arbitrage)
- Fees go to LP rewards pool
```
:::
:::warning
#### Time Delays
```
- Wrap to unwrap delay: 24 hours minimum
- Prevents MEV sandwich attacks
- Forces commitment to LP position
```
External market scenario:
* vOP trades at $1.40 on vOP/USDC (below $1.50 fair value)
* Attacker buys 50k vOP for $70k
* Unwraps internally for 50k OP = $150k
* $80k profit extracted from pool
:::
### Overview
```mermaid
graph TB
subgraph "Harbor Protocol"
Registry[Registry Contract]
Escrow[Escrow Contract]
Market[Market Contract]
Registry -->|escrow factory| Escrow
Registry -->|market factory| Market
Escrow <-->|transfer bonds| Market
end
subgraph "Uniswap V4"
Pool[Uniswap Pool]
Escrow <-->|hook callback| Pool
end
subgraph "External Entities"
Issuers[Bond Issuers]
Users1[Users]
Users2[Liquidity Providers]
Issuers -->|added to whitelist| Registry
Users2 -->|deposit Tokens| Escrow
Users2 -->|add Liquidity| Pool
Users1 -->|buy/sell bonds| Market
Users1 -->|swap tokens| Pool
end
```
### Data Flow
#### Market Creation Flow
```mermaid
sequenceDiagram
participant User
participant Registry
participant Escrow
participant Hook
participant PoolManager
User->>Registry: createMarket(params)
Registry->>Escrow: new Escrow(name, symbol, currency, admin, registry)
Registry->>Hook: Deploy Harbor Hook
Registry->>Escrow: grantRole(CAN_MINT_BURN, hook)
Registry->>PoolManager: initialize(poolKey, price)
Registry->>User: return (marketKey, escrowToken, hook, poolId)
```
#### Bond Trading Flow
```mermaid
sequenceDiagram
participant Trader
participant Hook
participant Escrow
participant Registry
participant Pool
Trader->>Hook: Swap bonds
Hook->>Registry: isIssuerSupported(issuer)
Registry-->>Hook: true/false
Hook->>Escrow: mint/burn tokens
Hook->>Pool: Execute swap
Pool-->>Hook: Swap result
Hook-->>Trader: Bonds/tokens
```
### Security Model
#### Access Control Hierarchy
```
Registry (Admin)
├── Market Creation
├── Issuer Management
└── Infrastructure Coordination
Escrow (Role-Based)
├── CAN_DEPOSIT_WITHDRAW → Harbor Hook
├── CAN_MINT_BURN → Harbor Hook
└── DEFAULT_ADMIN_ROLE → Registry
Harbor Hook
├── Bond Trading (Public)
├── Liquidity Management (Public)
└── Token Operations → Escrow
```
#### Trust Assumptions
1. **Registry Admin**: Trusted to manage issuers and system parameters
2. **Bond Issuers**: Must be validated and added to registry before use
3. **Harbor Hook**: Granted specific roles for token operations
4. **Uniswap V4**: Underlying AMM infrastructure assumed secure
### Integration Points
#### With Uniswap V4
* Uses Pool Manager for pool initialization and management
* Hook integrates with swap, liquidity, and initialization flows
* Dynamic fee structure based on trading patterns
#### With Bond Issuers
* Standardized `IBondIssuer` interface for compatibility
* Bond validation through `BondAdapter` utility
* Registry-managed whitelist for supported issuers
#### With External Systems
* ERC20 compatibility for wrapped tokens
* OpenZeppelin AccessControl for role management
* Upgradeable patterns for future enhancements
### Design Principles
1. **Modularity**: Clear separation between Registry, Escrow, and Hook
2. **Security**: Role-based access control and validation at every level
3. **Composability**: Standard interfaces for integration with other protocols
4. **Efficiency**: Atomic operations and gas-optimized implementations
5. **Extensibility**: Plugin architecture for new bond types and pricing models
### Next Steps
* [Registry System](/architecture/registry) - Deep dive into market management
* [Escrow Contract](/architecture/escrow) - Token and bond operations
* [Harbor Hook](#TODO) - Trading implementation
### Security Model
#### Access Control Hierarchy
```
Registry (Admin)
├── Market Creation
├── Issuer Management
└── Infrastructure Coordination
Escrow (Role-Based)
├── CAN_DEPOSIT_WITHDRAW → Harbor Hook
├── CAN_MINT_BURN → Harbor Hook
└── DEFAULT_ADMIN_ROLE → Registry
Harbor Hook
├── Bond Trading (Public)
├── Liquidity Management (Public)
└── Token Operations → Escrow
```
#### Trust Assumptions
1. **Registry Admin**: Trusted to manage issuers and system parameters
2. **Bond Issuers**: Must be validated and added to registry before use
3. **Harbor Hook**: Granted specific roles for token operations
4. **Uniswap V4**: Underlying AMM infrastructure assumed secure
### Integration Points
#### With Uniswap V4
* Uses Pool Manager for pool initialization and management
* Hook integrates with swap, liquidity, and initialization flows
* Dynamic fee structure based on trading patterns
#### With Bond Issuers
* Standardized `IBondIssuer` interface for compatibility
* Bond validation through `BondAdapter` utility
* Registry-managed whitelist for supported issuers
#### With External Systems
* ERC20 compatibility for wrapped tokens
* OpenZeppelin AccessControl for role management
* Upgradeable patterns for future enhancements
### Design Principles
1. **Modularity**: Clear separation between Registry, Escrow, and Hook
2. **Security**: Role-based access control and validation at every level
3. **Composability**: Standard interfaces for integration with other protocols
4. **Efficiency**: Atomic operations and gas-optimized implementations
5. **Extensibility**: Plugin architecture for new bond types and pricing models