Skip to main content

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.
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.

Core Guarantees

Provably Fair

Commit-reveal scheme with cryptographic randomness prevents prediction or manipulation

Permissionless Verification

Any participant can verify the winner selection process on-chain

Censorship Resistant

Distributed randomness sampling prevents single-party manipulation

Immutable Records

All transactions and winner selection recorded on-chain

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.
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

Data Model

{
  assetId: number,
  status: "ACTIVE" | "SOLD_OUT" | "COMPLETED",
  numberOfTokens: number,
  tokenCost: number (in lamports),
  tokensSold: number,
  assetOwner: PublicKey,
  proceeds: bigint,
  winner?: PublicKey
}

Transaction Flow

Phase 1: Platform Initialization

1

create_tradmatrix

Admin initializes global program state. One-time operation.

Phase 2: Asset & Randomness Setup

1

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.

Phase 3: Token Sales

1

User 1: init_user + buy_token (Batched)

First participant creates account and purchases token. Operations batched for efficiency.
2

User N: buy_token (Sequential)

Subsequent participants submit separate transactions to avoid write conflicts on tokensSold counter.
3

Auto-Status Transition

When final token sells, asset status automatically transitions to SOLD_OUT.

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

// 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

InstructionsReason
create_asset + open_varRandomness must be initialized with asset
init_user + buy_tokenUser → immediate participation

❌ Never Batch

InstructionsReasonSolution
Multiple buy_tokenBoth mutate tokensSoldSubmit separate sequential TXs
update_end_at + sample_varMust wait for target slot~5 second delay between
sample_var + reveal_varCensorship resistancePermissionless separation
pick_winner + settle_winnerEvent-driven asyncBackend 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:
EventPurpose
tradmatrixCreatedPlatform initialized
assetCreatedAsset created
userInitializedParticipant onboarded
tokenPurchasedToken acquired
assetSoldOutTriggers randomness automation
varOpenedRandomness account created
varEndAtUpdatedTriggers sampling automation
varSampledTriggers reveal automation
varRevealedTriggers winner selection
varNextSeed chaining for backup
samplesIncreasedIterations added
varClosedRandomness cleanup
winnerSelectedWinner determined, funds distributed
winnerSettledWinner 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

Entropy Protocol Details

Deep dive into the cryptographic commit-reveal scheme and provably fair randomness