# Technical Overview

Tharwa's technical infrastructure establishes a new standard for institutional DeFi deployment: **audited smart contracts** managing diversified real-world asset portfolios with enterprise-grade security, transparency, and operational efficiency. This architecture enables trillion-dollar capital compatibility while maintaining the composability and innovation advantages of decentralized finance.

**Design Objective:** Bridge the gap between traditional institutional asset management and on-chain financial infrastructure through proven, scalable, and professionally audited smart contract systems.

## **Design Philosophy: Security Meets Innovation**

Traditional DeFi protocols often sacrifice security for innovation, or innovation for security. Tharwa's architecture is built on three core principles:

{% tabs %}
{% tab title="Security First" %}
**Every contract audited before deployment**

* PrismSec audits with 0 critical findings
* Role-based access control throughout
* Emergency pause mechanisms
* Comprehensive test coverage

**Result**: Institutional-grade security standards
{% endtab %}

{% tab title="Real-World Integration" %}
**Built for actual asset management**

* ERC standards for composability
* Transparent on-chain accounting
* Real yield from real assets
* Professional treasury operations

**Result**: Bridge between TradFi and DeFi
{% endtab %}

{% tab title="Developer Friendly" %}
**Standard interfaces with custom optimizations**

* ERC-4626 for yield vaults
* ERC-1155 for bond products
* LayerZero for cross-chain
* Gas-optimized implementations

**Result**: Easy integration with existing DeFi
{% endtab %}
{% endtabs %}

## **Smart Contract Ecosystem**

Tharwa's protocol consists of five interconnected smart contracts, each designed for a specific purpose:

| Contract      | Address (Mainnet)                            | Purpose                    | Standard      |
| ------------- | -------------------------------------------- | -------------------------- | ------------- |
| **thUSD**     | `0x76972F054aB43829064d31fF5f3AcC5Fabe57FE8` | RWA-backed stablecoin      | LayerZero OFT |
| **sthUSD**    | `0xf7Af0A8079F12F19533B0DF69ce7ee6718b0C46f` | Yield-bearing staked token | ERC-4626      |
| **thBonds**   | `0xAc02FF90bC709A134cD4Ad0b50BaB8be9e0f504e` | Fixed-term bond vaults     | ERC-1155      |
| **TRWA**      | `0x7b10d50b5885bE4c7985A88408265c109bd1EeC8` | Governance token           | LayerZero OFT |
| **thUSDSwap** | `0x7b930eaD88e7DAD023af9eaDb5D2AC817096c2Bc` | Stableswap liquidity pool  | AMM           |

### **How the Contracts Work Together**

Understanding Tharwa requires seeing how each contract serves the ecosystem:

{% hint style="info" %}
**The Flow**: User deposits USDC → mints thUSD → stakes to sthUSD for yield OR locks in thBonds for fixed returns → governed by TRWA holders → traded via thUSDSwap
{% endhint %}

**Contract Interactions:**

1. [**thUSD**](https://tharwa.gitbook.io/tharwa/core-products/thusd-the-stablecoin-built-differently) **(The Foundation)**
   * Users mint [thUSD](https://tharwa.gitbook.io/tharwa/core-products/thusd-the-stablecoin-built-differently) by depositing USDC/USDT/DAI
   * Backed 1:1 by diversified RWA portfolio
   * Can be held, staked, or locked in bonds
2. [**sthUSD**](https://tharwa.gitbook.io/tharwa/yield-products/sthusd-yield-distribution) **(The Yield Layer)**
   * Users stake [thUSD](https://tharwa.gitbook.io/tharwa/core-products/thusd-the-stablecoin-built-differently) to earn dynamic yield
   * Share value grows as RWA portfolio generates returns
   * Instant liquidity with optional cooldown security
3. [**thBonds**](https://tharwa.gitbook.io/tharwa/yield-products/tharwa-bonds) **(The Fixed Income Layer)**
   * Users lock [thUSD](https://tharwa.gitbook.io/tharwa/core-products/thusd-the-stablecoin-built-differently) for guaranteed fixed returns
   * ERC-1155 NFTs allow secondary market trading
   * Predictable yields from structured asset allocation
4. [**TRWA**](https://tharwa.gitbook.io/tharwa/core-products/tokenomics) **(The Governance Layer)**
   * Controls protocol parameters and treasury decisions
   * Earned through [Genesis Points](https://tharwa.gitbook.io/tharwa/incentives-and-community/season-1-genesis), not purchased
   * Enables decentralized management of RWA portfolio
5. **thUSDSwap (The Liquidity Layer)**
   * Provides deep liquidity for [thUSD](https://tharwa.gitbook.io/tharwa/core-products/thusd-the-stablecoin-built-differently) trading
   * Maintains [peg stability](https://tharwa.gitbook.io/tharwa/core-products/thusd-the-stablecoin-built-differently/peg-defense-and-liquidity) through arbitrage
   * Enables composability with broader DeFi

### **Architecture Principles**

* **Security First**: All contracts audited by PrismSec with 0 critical findings
* **Gas Optimized**: ERC-1155 bonds cost <$1 to mint on Ethereum mainnet
* **Composable**: Standard interfaces (ERC-4626, ERC-1155) for DeFi integration
* **Omnichain Ready**: LayerZero integration for multi-chain deployment
* **Institutional Grade**: Role-based access control and emergency pause mechanisms

***

## **Deep Dive: Contract Specifications**

### **thUSD: The Foundation Layer**

thUSD isn't just another stablecoin but a **programmable treasury unit** that represents ownership in a diversified RWA portfolio.

#### **What Makes thUSD Different**

{% tabs %}
{% tab title="Traditional Stablecoins" %}
**USDC/USDT Model:**

* Backed by bank deposits
* Centralized control
* No yield for holders
* Limited transparency

**Problems:**

* Users earn nothing
* Opaque reserves
* Regulatory risk
* No DeFi composability
  {% endtab %}

{% tab title="thUSD Innovation" %}
**RWA-Backed Model:**

* Backed by diversified real assets
* Decentralized governance
* Yield flows to ecosystem
* Full transparency

**Advantages:**

* Real yield generation
* On-chain verification
* Regulatory compliance
* DeFi composability
  {% endtab %}
  {% endtabs %}

#### **Technical Implementation**

thUSD is built on **LayerZero's OFT (Omnichain Fungible Token)** standard, enabling seamless cross-chain transfers:

```solidity
// Core minting function (access controlled)
function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
    _mint(to, amount);
    emit Minted(to, amount);
}

// Cross-chain transfers via LayerZero
function sendFrom(
    address from, 
    uint16 dstChainId, 
    bytes32 toAddress, 
    uint256 amount, 
    LzCallParams calldata callParams
) external payable {
    _debitFrom(from, dstChainId, toAddress, amount);
    _lzSend(dstChainId, payload, callParams.refundAddress, callParams.zroPaymentAddress, callParams.adapterParams, msg.value);
}
```

**Why These Functions Matter:**

* **Controlled Minting**: Only authorized addresses can mint thUSD, ensuring proper RWA backing
* **Cross-Chain Native**: thUSD can move between chains without bridges or wrapping
* **Gas Efficient**: LayerZero optimizes cross-chain transfer costs
* **Institutional Ready**: Access controls meet compliance requirements

### **sthUSD - ERC-4626 Yield Vault**

**Technical Implementation:**

* **Standard**: ERC-4626 with Tharwa-specific optimizations
* **Yield Vesting**: Linear vesting over 30-day periods to prevent donation attacks
* **Cooldown System**: Optional staged withdrawal with configurable periods
* **Fee Structure**: Optional entry/exit fees (capped at 10%)

**Core Accounting Model:**

```solidity
function totalAssets() public view returns (uint256) {
    return _pooledAssets - _unvestedAmount();
}

// Donation-attack resistant accounting
function _unvestedAmount() internal view returns (uint256) {
    if (block.timestamp >= _vestingEnd) return 0;
    return _yieldAmount * (_vestingEnd - block.timestamp) / _vestingPeriod;
}
```

**Key Parameters:**

* **Vesting Period**: 30 days (configurable)
* **Cooldown Period**: 0, 3, or 7 days (configurable)
* **Entry/Exit Fees**: 0-1000 bps (currently 0)

### **thBonds - ERC-1155 Bond System**

**Bond Structure:**

* **Token ID**: UTC midnight timestamp of maturity date
* **Fixed Terms**: 90, 180, 360 days
* **Discounted Pricing**: Bonds sold at discount, redeemable 1:1 at maturity
* **Early Exit**: Linear penalty decay from 20% to 0%

**Current Bond Parameters:**

| Duration | Token ID Calculation                               | Discount Price | APY   | Cap      |
| -------- | -------------------------------------------------- | -------------- | ----- | -------- |
| 90 days  | `block.timestamp + 90 days` truncated to midnight  | \~0.96 thUSD   | 3.94% | 1M thUSD |
| 180 days | `block.timestamp + 180 days` truncated to midnight | \~0.93 thUSD   | 5.91% | 2M thUSD |
| 360 days | `block.timestamp + 360 days` truncated to midnight | \~0.88 thUSD   | 8.00% | 4M thUSD |

**Bond Metadata Structure:**

```solidity
struct BondMetadata {
    uint256 principal;        // Original deposit amount
    uint256 maturityAmount;   // Amount redeemable at maturity
    uint256 maturityDate;     // Maturity timestamp
    uint256 purchaseDate;     // Purchase timestamp
    bool claimed;             // Redemption status
    uint256 earlyExitPenalty; // Current penalty for early exit
}
```

***

## **Security Architecture**

### **Multi-Layered Security Model**

1. **Smart Contract Security**
   * Comprehensive audit by PrismSec
   * Role-based access control (OpenZeppelin AccessControl)
   * Emergency pause mechanisms
   * Reentrancy protection
2. **Operational Security**
   * Multi-signature wallet governance
   * Timelocked administrative functions
   * Circuit breakers for extreme scenarios
   * Blacklist functionality for compliance
3. **Economic Security**
   * Over-collateralization of stablecoin backing
   * Diversified asset portfolio to minimize correlation risk
   * CVaR optimization for tail risk management

### **Audit Results Summary**

| Contract     | Auditor  | Critical | High | Medium | Low | Status  |
| ------------ | -------- | -------- | ---- | ------ | --- | ------- |
| thUSD & TRWA | PrismSec | 0        | 0    | 1      | 2   | ✅ Fixed |
| sthUSD       | PrismSec | 0        | 0    | 1      | 1   | ✅ Fixed |
| thBonds      | PrismSec | 0        | 0    | 1      | 1   | ✅ Fixed |

**Audit Reports:**

* [thUSD & TRWA Audit](https://github.com/tharwa-finance/contracts-v0/blob/main/audits/prismsec_thUSD_TRWA_audit.pdf)
* [sthUSD Audit](https://github.com/tharwa-finance/contracts-v0/blob/main/audits/prismsec_tharwa_sthUSD_audit.pdf)
* [thBonds Audit](https://github.com/tharwa-finance/contracts-v0/blob/main/audits/prismsec_tharwa_bonds_audit.pdf)

***

## **Integration Guide**

### **Developer Resources**

**Repository**: <https://github.com/tharwa-finance/contracts-v0>

**Network Deployments:**

* **Ethereum Mainnet**: All contracts live and operational
* **Sepolia Testnet**: Full testing environment available

**Development Setup:**

```bash
# Clone repository
git clone https://github.com/tharwa-finance/contracts-v0.git

# Install dependencies (Foundry required)
forge install

# Run tests
forge test

# Generate coverage report
forge coverage
```

### **Standard Interfaces**

**ERC-4626 Integration (sthUSD):**

```solidity
// Standard ERC-4626 functions
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
function totalAssets() external view returns (uint256);
function convertToShares(uint256 assets) external view returns (uint256);
```

**ERC-1155 Integration (thBonds):**

```solidity
// Standard ERC-1155 functions for bond trading
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes memory data) external;
function balanceOf(address account, uint256 id) external view returns (uint256);
function uri(uint256 id) external view returns (string memory);
```

***

## **Performance Metrics**

### **Gas Efficiency**

* **thBonds Minting**: <$1 on Ethereum mainnet
* **sthUSD Deposits**: \~50,000 gas
* **Cross-chain thUSD**: LayerZero optimized

### **Scalability**

* **Multi-chain Ready**: LayerZero OFT standard
* **Batch Operations**: ERC-1155 batch transfers
* **Efficient Storage**: Packed structs and optimized mappings

***

{% hint style="info" %}
**Developer Support**

* **GitHub**: [tharwa-finance/contracts-v0](https://github.com/tharwa-finance/contracts-v0)
* **Discord**: [Developer Channel](https://discord.gg/gn9htPaF9v)
* **Documentation**: Comprehensive inline code comments
  {% endhint %}
