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

# System Architecture

> Complete technical architecture of Tradmatrix platform

# Tradmatrix System Architecture

## Overview

Tradmatrix is a provably-fair asset ownership distribution platform built on Solana. The system enables fractional asset participation through token-based distribution with cryptographically verified winner selection using the Entropy protocol's commit-reveal scheme.

<Note>
  **Key Innovation**: The Entropy commit-reveal scheme, combined with Solana's slot hashing, ensures that no single party can predict or manipulate the winner selection outcome.
</Note>

## Core Guarantees

<CardGroup cols={2}>
  <Card title="Provably Fair" icon="shield-check">
    Commit-reveal scheme with cryptographic randomness prevents prediction or manipulation
  </Card>

  <Card title="Permissionless Verification" icon="unlock">
    Any participant can verify the winner selection process on-chain
  </Card>

  <Card title="Censorship Resistant" icon="lock-open">
    Distributed randomness sampling prevents single-party manipulation
  </Card>

  <Card title="Immutable Records" icon="bookmark">
    All transactions and winner selection recorded on-chain
  </Card>
</CardGroup>

## System Layers

### Layer 1: On-Chain Smart Contracts (Solana)

The Solana program manages all critical operations including asset creation, token distribution, and provably-fair winner selection.

<Tabs>
  <Tab title="Core Instructions">
    **6 Primary Instructions**

    * `create_tradmatrix` - Initialize platform (admin-only, one-time)
    * `create_asset` - Create participation event with tokens and pricing
    * `init_user` - Onboard participant
    * `buy_token` - Purchase participation token
    * `pick_winner` - Select winner using provably fair algorithm, distribute proceeds
    * `settle_winner` - Record winner's wallet address
  </Tab>

  <Tab title="Entropy Instructions">
    **7 Randomness Instructions**

    * `open_var` - Initialize randomness account with commit hash
    * `update_end_at` - Set target slot for randomness sampling
    * `sample_var` - **PERMISSIONLESS** - Capture Solana slot hash
    * `reveal_var` - Reveal pre-committed seed, compute final random value
    * `next_var` - Enable backup winner selection (seed chaining)
    * `increase_samples` - Add iterations for multiple selections
    * `close_var` - Cleanup randomness state, reclaim rent
  </Tab>
</Tabs>

## Data Model

<Tabs>
  <Tab title="Asset">
    ```typescript theme={null}
    {
      assetId: number,
      status: "ACTIVE" | "SOLD_OUT" | "COMPLETED",
      numberOfTokens: number,
      tokenCost: number (in lamports),
      tokensSold: number,
      assetOwner: PublicKey,
      proceeds: bigint,
      winner?: PublicKey
    }
    ```
  </Tab>

  <Tab title="Token">
    ```typescript theme={null}
    {
      tokenNumber: number, // 1-indexed: 1 to numberOfTokens
      assetId: number,
      owner: PublicKey,
      isPurchased: boolean,
      isWon?: boolean,
      purchasedAt: Date
    }
    ```
  </Tab>

  <Tab title="User">
    ```typescript theme={null}
    {
      wallet: PublicKey,
      username: string,
      createdAt: Date,
      totalTokens: number
    }
    ```
  </Tab>

  <Tab title="Entropy Secret">
    ```typescript theme={null}
    {
      assetId: number,
      commit: Buffer,    // 32 bytes (keccak256 hash)
      seed: Buffer,      // 32 bytes (encrypted with AES-256-GCM)
      iteration: number,
      createdAt: Date,
      revealedAt?: Date
    }
    ```
  </Tab>
</Tabs>

## Transaction Flow

### Phase 1: Platform Initialization

<Steps>
  <Step title="create_tradmatrix">
    Admin initializes global program state. One-time operation.
  </Step>
</Steps>

### Phase 2: Asset & Randomness Setup

<Steps>
  <Step title="create_asset + open_var (Batched)">
    Admin creates participation event and initializes randomness account with cryptographic commitment.

    **Batching Benefit**: Atomic initialization ensures randomness account exists before any operations.
  </Step>
</Steps>

### Phase 3: Token Sales

<Steps>
  <Step title="User 1: init_user + buy_token (Batched)">
    First participant creates account and purchases token. Operations batched for efficiency.
  </Step>

  <Step title="User N: buy_token (Sequential)">
    Subsequent participants submit separate transactions to avoid write conflicts on `tokensSold` counter.
  </Step>

  <Step title="Auto-Status Transition">
    When final token sells, asset status automatically transitions to `SOLD_OUT`.
  </Step>
</Steps>

### Phase 4-8: Cryptographic Winner Selection

The Entropy protocol ensures fair selection through a commit-reveal scheme:

```
[Asset Sold Out]
        ↓
[5s Safety Buffer]
        ↓
TX4: update_end_at (set target slot)
        ↓
[~5 seconds for slot progression]
        ↓
TX5: sample_var (PERMISSIONLESS - capture slot hash)
        ↓
TX6: reveal_var (reveal pre-committed seed)
        ↓
TX7: pick_winner (compute winner from random value)
        ↓
TX8: settle_winner (record winner address)
```

**Timeline**: 15-20 seconds from sold out to winner settled

## Provably Fair Algorithm

### Commit-Reveal Scheme

The system prevents any party from predicting the winner:

**Commitment Phase** (Asset Creation):

1. Entropy provider generates random 32-byte seed
2. Compute commit = keccak256(seed)
3. Pass commit hash to `open_var` instruction

**Reveal Phase** (After Randomness Available):

1. Entropy provider reveals the pre-committed seed
2. Verify: keccak256(revealed\_seed) == original\_commit
3. Compute final random value: keccak256(slot\_hash || seed || iterations)

**Security Properties**:

* ✅ Entropy provider cannot predict slot\_hash at commit time (300+ validators control)
* ✅ Solana validators cannot predict seed (locked in commitment hash)
* ✅ Each party controls independent randomness source
* ✅ Final value combines both sources unpredictably

### Seed Encryption

Seeds are encrypted at rest using AES-256-GCM:

```
Encrypted = IV (16 bytes) || AuthTag (16 bytes) || Ciphertext
```

**Purpose**: Protects against premature revelation if database is compromised

## Token Numbering

Tokens use 1-based indexing for user-friendly display:

### Implementation

```
Asset Creation:
  └─ tokensSold = 0

First Purchase:
  ├─ nextTokenNumber = tokensSold + 1 = 1
  ├─ PDA seed: ["token", assetId, 1]
  ├─ Increment: tokensSold = 1
  └─ User sees: "Token #1"

Final Purchase (100 tokens):
  ├─ nextTokenNumber = tokensSold + 1 = 100
  ├─ PDA seed: ["token", assetId, 100]
  ├─ Increment: tokensSold = 100
  └─ User sees: "Token #100"
```

### Winner Selection Formula

```rust theme={null}
// On-chain computation
let winning_token_number = (random_u64 % tokensSold) + 1;

// Result: 1-based token number matching user's perception
```

The `+1` is critical: modulo produces 0 to (N-1), the +1 converts to 1-based range (1 to N).

## Timing Constraints

### SlotHashes Sysvar Availability

* **Window**: 150 slots (\~75 seconds) after target slot
* **Fallback**: Deterministic hash if outside window
* **Mitigation**: Event-driven automation ensures sampling within 10-15 seconds

### Slot Progression Requirements

```
update_end_at(current_slot + 10)
        ↓ [Must wait until current_slot >= target]
sample_var (capture SlotHash)
        ↓ [Immediate]
reveal_var (derive final random value)
        ↓ [Immediate]
pick_winner (select winner)
```

## Transaction Batching Rules

### ✅ Always Batch

| Instructions              | Reason                                    |
| ------------------------- | ----------------------------------------- |
| `create_asset + open_var` | Randomness must be initialized with asset |
| `init_user + buy_token`   | User → immediate participation            |

### ❌ Never Batch

| Instructions                  | Reason                    | Solution                           |
| ----------------------------- | ------------------------- | ---------------------------------- |
| Multiple `buy_token`          | Both mutate `tokensSold`  | Submit separate sequential TXs     |
| `update_end_at + sample_var`  | Must wait for target slot | \~5 second delay between           |
| `sample_var + reveal_var`     | Censorship resistance     | Permissionless separation          |
| `pick_winner + settle_winner` | Event-driven async        | Backend reads WinnerSelected event |

**Why separate sample\_var + reveal\_var?**

* sample\_var is permissionless; batching breaks this principle
* Maintains audit trail with separate on-chain entries
* Prevents timing violations if slots progress unexpectedly

**Why separate pick\_winner + settle\_winner?**

* pick\_winner emits winning token number on-chain
* Backend listens for WinnerSelected event
* Backend then submits settle\_winner with event data
* Eliminates backend winner calculation; uses on-chain value

## Performance Characteristics

### Transaction Throughput

* **Token Purchases**: Sequential per asset (tokensSold conflicts)
* **Users**: Parallel (independent wallets)
* **Assets**: Parallel (independent asset accounts)
* **Randomness Flow**: Sequential (inter-instruction dependencies)

### Latency

```
Single Token Purchase: 0.5-2 seconds
Sold Out → Winner: 15-20 seconds (automated)
Total per Event: 15-25 seconds from final token
```

### Database Operations

* **Event Processing**: \~100 writes per event cycle
* **Entropy Storage**: 1 record per asset (32 bytes seed + overhead)
* **Activity Logging**: \~15 entries per event cycle

## Event Processing

The backend subscribes to 13 blockchain events:

| Event               | Purpose                              |
| ------------------- | ------------------------------------ |
| `tradmatrixCreated` | Platform initialized                 |
| `assetCreated`      | Asset created                        |
| `userInitialized`   | Participant onboarded                |
| `tokenPurchased`    | Token acquired                       |
| `assetSoldOut`      | Triggers randomness automation       |
| `varOpened`         | Randomness account created           |
| `varEndAtUpdated`   | Triggers sampling automation         |
| `varSampled`        | Triggers reveal automation           |
| `varRevealed`       | Triggers winner selection            |
| `varNext`           | Seed chaining for backup             |
| `samplesIncreased`  | Iterations added                     |
| `varClosed`         | Randomness cleanup                   |
| `winnerSelected`    | Winner determined, funds distributed |
| `winnerSettled`     | Winner confirmed                     |

## Error Handling & Recovery

### Transaction Retry Strategy

```
Attempt 1: Immediate
Attempt 2: Wait 1 second
Attempt 3: Wait 2 seconds  
Attempt 4: Wait 4 seconds
Maximum: 4 total attempts
```

### Timing Violations

If SlotHashes window exceeded:

* Program uses fallback deterministic hash
* Alert triggers in monitoring
* Randomness still valid but reduced entropy
* Retry with `next_var` for better randomness

### Backup: Blockchain Polling

Event listener failures trigger polling-based backup:

* Runs every 60 seconds
* Syncs all ACTIVE/SOLD\_OUT assets
* Catches events missed by real-time listener

## Architecture Diagram

```
┌─────────────────────────────────────────────────────┐
│             TRADMATRIX SYSTEM OVERVIEW              │
├─────────────────────────────────────────────────────┤
│                                                     │
│  Frontend (React)    Blockchain (Solana)           │
│  ├─ Wallet Auth      ├─ Tradmatrix Program         │
│  ├─ Sign TX          ├─ 13 Instructions            │
│  └─ Monitor Status   └─ 13 Events                  │
│         │                    ▲                      │
│         │                    │                      │
│         └────────────────────┼──────────────────┐  │
│                              │                  │  │
│  Backend Services (Node.js)  │                  │  │
│  ├─ Event Listener ◄────────┘                  │  │
│  ├─ Transaction Builder                        │  │
│  ├─ Entropy Service (Seeds & Commits)          │  │
│  ├─ Transaction Submitter ────────────────────►│  │
│  └─ Automation Handlers                        │  │
│         │                                       │  │
│         ▼                                       │  │
│  MongoDB (Persistent State)                    │  │
│  ├─ Assets & Tokens                           │  │
│  ├─ Users & Activity                           │  │
│  └─ Encrypted Entropy Seeds                    │  │
│                                                 │  │
└─────────────────────────────────────────────────────┘
```

## Deployment Checklist

### Pre-Mainnet Verification

* [ ] Entropy service tested with 10+ cycles
* [ ] Transaction submitter retry logic operational
* [ ] Event automation handlers integrated
* [ ] Seed encryption key secured in environment
* [ ] Monitoring and alerting configured
* [ ] Admin key security reviewed

### Post-Mainnet Monitoring

* [ ] Randomness timing validation on live network
* [ ] Failed transaction alerts
* [ ] Pending automation dashboard
* [ ] Weekly audit log reviews

## Next Steps

<Card title="Entropy Protocol Details" icon="sparkles" href="/technical/entropy-protocol">
  Deep dive into the cryptographic commit-reveal scheme and provably fair randomness
</Card>
