Skip to content

FTHTrading/Global-Truth

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Global Truth Protocol

Deterministic probabilistic commitment infrastructure for event-based forecasting systems.

Field Value
Protocol Version 1.0.0
Specification 1.0.0
AI Engine 1.0.3
Contract ABI 1.0.0
Audit Status Pending
License MIT

Table of Contents

§ Section Domain
🟢 1 — Overview Protocol Summary
🔵 2 — System Architecture Layer Design
🟡 3 — AI Prediction Core Layer 1
🟣 4 — Truth Commitment Layer 2
🔴 5 — Economic Staking Layer 3
6 — Oracle Resolution Layer 4
🟤 7 — DAO Governance Layer 5
🟢 8 — Smart Contracts On-Chain
🔵 9 — API Surface Backend
🟡 10 — Security Architecture Threat Model
🟣 11 — Determinism Guarantees Reproducibility
🔴 12 — Cross-Chain Infrastructure Interoperability
13 — Testing & Verification Quality
🟤 14 — Repository Structure Navigation
🟢 15 — Quick Start Setup
🔵 16 — Technology Stack Dependencies
🟡 17 — Supplementary Documentation References

1 — Overview

GTP is a five-layer protocol that produces probabilistic forecasts for discrete events, commits those forecasts to an immutable ledger prior to resolution, and settles outcomes through a decentralized oracle with economic finality.

The system enforces three invariants:

  1. Pre-commitment — All predictions are Merkle-anchored before the event resolves. No retroactive revision is possible.
  2. Economic finality — Stakers bear financial exposure proportional to their stated confidence. Confidence without stake is excluded.
  3. Deterministic reproducibility — Given identical inputs, seed state, and model version, the protocol produces byte-identical output.

GTP does not rely on crowd sentiment, binary markets, or centralized adjudication. It produces calibrated probability distributions from a multi-model ensemble, commits them cryptographically, and resolves them through weighted oracle consensus with an on-chain dispute mechanism.


2 — System Architecture

                            ┌───────────────────────┐
                            │   External Consumers   │
                            │   (API / Dashboard)    │
                            └───────────┬───────────┘
                                        │
                            ┌───────────▼───────────┐
                            │   FastAPI Backend      │
                            │   25+ endpoints        │
                            │   CORS · Pydantic      │
                            └───────────┬───────────┘
                                        │
        ┌───────────────────────────────┼───────────────────────────────┐
        │                               │                               │
┌───────▼───────┐             ┌─────────▼─────────┐           ┌────────▼────────┐
│  Layer 5      │             │  Layer 4           │           │  Smart          │
│  DAO          │◄────────────│  Oracle            │──────────►│  Contracts      │
│  Governance   │  dispute    │  Resolution        │  settle   │  (Solidity)     │
└───────┬───────┘  escalation └─────────┬─────────┘           └────────┬────────┘
        │                               │                              │
        │                     ┌─────────▼─────────┐                    │
        │                     │  Layer 3           │◄───────────────────┘
        │                     │  Economic          │   staking / payout
        │                     │  Staking           │
        │                     └─────────┬─────────┘
        │                               │
        │                     ┌─────────▼─────────┐
        │                     │  Layer 2           │
        └────────────────────►│  Truth             │
           parameter          │  Commitment        │
           governance         └─────────┬─────────┘
                                        │
                            ┌───────────▼───────────┐
                            │  Layer 1              │
                            │  Predictive           │
                            │  Intelligence Core    │
                            └───────────────────────┘

Data flow. Events enter Layer 1 for probabilistic analysis. The ensemble output is decomposed into per-model Merkle leaves (Layer 2), committed on-chain, and made available for economic staking (Layer 3). Upon event resolution, oracles submit observations (Layer 4) and trigger settlement. Governance (Layer 5) controls protocol parameters and serves as the final dispute escalation path.


3 — AI Prediction Core

Layer 1 executes four independent probabilistic models in parallel via asyncio, then produces a weighted ensemble.

3.1 Model Inventory

Model Engine Method Key Parameters
Monte Carlo MonteCarloEngine 100,000 GBM simulations with Student's t tails seed=42, σ=0.2
Bayesian Network BayesianNetwork Beta-conjugate DAG, topological propagation prior α=2, β=2
Reinforcement Learning RLAgent Thompson sampling + UCB1, linear projection 11 actions, c=2.0
Deep Predictor DeepPredictor Pure-NumPy feedforward (64→32→1), Xavier init, BCE lr=0.001

3.2 Supporting Modules

Module Responsibility
VolatilityCalculator 4-factor composite: ensemble disagreement (35%), historical drift (25%), GARCH(1,1) (25%), implied market (15%)
FeatureEngine 12-field extraction, NaN imputation, Z-score normalization with feature-vector checksumming
DataLoader Async HTTP fetch with in-memory TTL cache and SHA-256 payload verification
CalibrationTracker Brier score, log loss, expected calibration error (ECE), reliability diagram generation

3.3 Ensemble Output Schema

truthScore      = weighted_mean(MC, Bayes, RL, DL)
volatilityIdx   = composite(disagreement, drift, garch, implied)
scenarios       = { bearCase, baseCase, bullCase }
predictionHash  = SHA-256(canonical_json(prediction))

3.4 Pipeline Flow

event_request
    │
    ▼
FeatureEngine.extract()
    │
    ├──► MonteCarloEngine.simulate()  ──┐
    ├──► BayesianNetwork.predict()     ──┤
    ├──► RLAgent.decide()              ──┤  async parallel
    └──► DeepPredictor.forward()       ──┘
                                         │
                                    weighted_mean
                                         │
                                         ▼
                               VolatilityCalculator
                                         │
                                         ▼
                               CalibrationTracker
                                         │
                                         ▼
                               prediction_output

4 — Truth Commitment

Every prediction is decomposed into per-model Merkle leaves and anchored to a tamper-proof root before the event resolves.

4.1 Components

Component Function
MerkleTree Binary hash tree with sorted-pair SHA-256, proof generation, and static verification
MerkleCommitmentEngine Converts prediction dicts into per-model leaves + ensemble leaf + volatility leaf; generates inclusion proofs; maintains audit history
BlockchainCommitment Submits (event_id, prediction_hash, truth_score, volatility_index) to chain (dry-run or live via Web3)

4.2 Commitment Flow

prediction_output
    │
    ▼
MerkleCommitmentEngine.commit()
    │
    ├──  leaf[MC]
    ├──  leaf[Bayes]
    ├──  leaf[RL]
    ├──  leaf[DL]
    ├──  leaf[ensemble]
    └──  leaf[volatility]
         │
         ▼
    MerkleTree.build()
         │
         ▼
    merkle_root (bytes32)
         │
         ▼
    BlockchainCommitment.commit_to_chain()
         │
         ▼
    on-chain tx hash

4.3 Verification

Any third party can:

  1. Obtain the Merkle root from the blockchain.
  2. Request any leaf and its inclusion proof from the API.
  3. Recompute the root locally using MerkleTree.verify_proof().

If a single model output has been altered post-commitment, the recomputed root will differ from the on-chain root.


5 — Economic Staking

5.1 Token Architecture

Token Standard Max Supply Purpose
TRUTH ERC20 + Votes + Permit 1,000,000,000 Governance, staking, fee settlement
VOL ERC20 Dynamic Synthetic volatility exposure; controller-gated mint/burn
LIQ ERC20 Dynamic Liquidity provider rewards; emission-based

5.2 TRUTH Distribution

Bucket Allocation Unlock Schedule
Community / Stakers 40% Immediate
Early Stakers 25% Immediate
DAO Treasury 20% 5% per quarter release
Team 10% 4-year linear vest
Liquidity Pools 5% Immediate

5.3 Staking Parameters

Parameter Value
Platform fee 200 bps (2%)
Accuracy bonus Up to 1.5x for >90% historical accuracy
Duration multipliers 1.0x (30d), 1.5x (90d), 2.0x (180d), 3.0x (365d)
Quarterly burn rate 1% of circulating supply

5.4 Manipulation Resistance

ManipulationSimulator validates protocol security by modeling:

  • Whale attack cost — Minimum capital required to dominate a staking pool, accounting for slashing risk.
  • Oracle bribery threshold — Cost to corrupt ≥3 of 5 oracle sources given weighted consensus rules.
  • TVL security ratio — Ensures total value locked exceeds the maximum payout of any single event.

See docs/tokenomics.md for emission projections and burn curves.


6 — Oracle Resolution

6.1 Resolution State Machine

PENDING
    │
    ▼
ORACLE_QUERIED
    │
    ▼
CONSENSUS_REACHED  (≥66% weighted agreement)
    │
    ▼
CHALLENGE_PERIOD   (72h window)
    │
    ├── no dispute ──► FINALIZED ──► payout
    │
    └── dispute filed ──► ARBITRATION
                              │
                              ▼
                         5-arbitrator panel
                              │
                              ▼
                         FINALIZED ──► payout

6.2 Oracle Sources

Source Type Weight
Chainlink Data feed 1.5
API3 First-party oracle 1.2
Validator 1 Protocol validator 1.0
Validator 2 Protocol validator 1.0
Validator 3 Protocol validator 1.0

Consensus requires ≥66% of total weighted votes to agree on the outcome.

6.3 Dispute Mechanism

Parameter Value
Minimum dispute stake 10,000 TRUTH
Arbitrator panel size 5
Arbitrator selection Reputation-weighted random draw
Decision rule Majority vote (≥3 of 5)
Losing party penalty Dispute stake forfeited

7 — DAO Governance

7.1 Proposal Tracks

Track Voting Period Quorum Approval Threshold
FAST 3 days 5% of staked supply 60%
STANDARD 7 days 10% of staked supply 60%
CONSTITUTIONAL 14 days 15% of staked supply 67%

Minimum balance to submit a proposal: 100,000 TRUTH.

7.2 Reputation Formula

Voting weight is modulated by the participant's historical performance:

$$R(u) = \frac{\text{correct predictions}}{\text{total predictions}} \cdot \log(\text{total stake}) \cdot (1 + \text{participation rate})$$

Consistently accurate participants accumulate governance influence. Inactive or inaccurate holders are down-weighted.

7.3 Emergency Controls

A 5-of-9 guardian multi-sig can invoke an emergency pause. This capability is a circuit breaker for critical vulnerabilities and does not grant parameter modification rights.


8 — Smart Contracts

Solidity ^0.8.20 with OpenZeppelin v5.

Contract Lines Key Features
TruthToken ERC20 + Votes + Permit 1B max supply, authorized minters, delegation, nonces override
VolatilityToken ERC20 Controller-gated mint/burn, auto-rebalancing supply
LiquidityToken ERC20 Dynamic emission proportional to pool activity
EventRegistry 437 Event lifecycle: create → commit → lock → resolve → dispute
StakingPool 422 Stake on outcomes, payout with accuracy bonus, slashing

All contracts inherit from audited OpenZeppelin v5 base implementations. TruthToken extends ERC20, ERC20Burnable, ERC20Votes, and ERC20Permit with a required Nonces override for Solidity v5 compatibility.


9 — API Surface

FastAPI server bound to localhost:8000. All responses are JSON. Endpoints prefixed with /api/v1.

9.1 Prediction

Method Endpoint Description
POST /predict Full ensemble prediction with Merkle root
POST /predict/batch Batch predictions for multiple events
GET /model/weights Current model weight allocation
GET /calibration Brier score, ECE, log loss

9.2 Tokenomics

Method Endpoint Description
GET /tokenomics/supply?quarter=N Circulating supply at quarter N
GET /tokenomics/schedule?quarters=N Full quarterly emission schedule
GET /tokenomics/staking-reward Projected staking yield
POST /tokenomics/payout Calculate payout for a given stake position

9.3 Oracle

Method Endpoint Description
POST /oracle/report Submit oracle observation
POST /oracle/finalize/{event_id} Finalize resolved event
GET /oracle/resolution/{event_id} Current resolution state
POST /oracle/dispute File dispute with evidence hash

9.4 Governance

Method Endpoint Description
POST /governance/proposal Submit proposal (100K TRUTH minimum)
POST /governance/vote Cast reputation-weighted vote
POST /governance/tally/{id} Evaluate quorum and approval
GET /governance/proposals List all proposals with status

9.5 Reputation & System

Method Endpoint Description
GET /reputation/{user_id} Full reputation profile
GET /reputation/leaderboard Top predictors ranked by R(u)
GET /health System health across all modules
GET /audit/merkle-history Complete Merkle commitment log
GET /audit/blockchain-log Blockchain transaction log

10 — Security Architecture

Risk Category Attack Vector Mitigation
Prediction tampering Modify model output after event resolution Merkle commitment anchored on-chain before event deadline; any alteration invalidates the root
Oracle collusion ≥3 oracle sources report false outcome Weighted consensus (Chainlink 1.5x, API3 1.2x) raises bribery cost; 72h challenge period; 5-arbitrator dispute panel
Staking pool manipulation Whale acquires dominant position in single event pool ManipulationSimulator enforces that attack cost exceeds maximum payout at current TVL; slashing penalizes failed manipulation
Governance capture Accumulate TRUTH tokens to force parameter changes Constitutional proposals require 67% approval at 15% quorum; reputation weighting reduces pure-capital influence
Validator bribery Bribe individual validators to submit false reports Cost to bribe ≥3 weighted sources exceeds event payout; reputation slashing for inconsistent reporting
Model overfitting AI ensemble memorizes training data, fails on live events 4-model ensemble with independent methodologies; CalibrationTracker monitors Brier score and ECE drift

See docs/threat-model.md for the complete threat analysis.


11 — Determinism Guarantees

The protocol guarantees that given identical inputs, the system produces byte-identical outputs.

Component Mechanism
Random seeds All stochastic models accept injected seeds via config.json. Default seed: 42.
Floating point NumPy operations use float64 throughout. No GPU non-determinism (pure CPU).
Feature hashing FeatureEngine computes SHA-256 checksums of normalized feature vectors before model dispatch.
Model versioning Each model output includes a model_version field. The ensemble hash incorporates all four version strings.
Canonical serialization Prediction dicts are serialized with json.dumps(sort_keys=True, separators=(',', ':')) before hashing.
Merkle leaves Leaf values derive from canonical JSON. Leaf ordering is deterministic (sorted-pair hashing).

See docs/determinism.md for formal specification and test vectors.


12 — Cross-Chain Infrastructure

GTP is designed for EVM-compatible deployment with a path to cross-chain operation.

Capability Status Notes
EVM L1 deployment Ready Solidity ^0.8.20, tested on Hardhat local chain
L2 rollup deployment Compatible Standard ERC20 contracts; no L1-specific opcodes
Cross-chain bridging Designed Token contracts support mint()/burn() gating for bridge integration
IPFS anchoring Supported Merkle roots and evidence hashes reference IPFS CIDs
Multi-chain oracle Planned Oracle engine is chain-agnostic; resolution messages can be relayed cross-chain

The EventRegistry contract uses bytes32 event identifiers and bytes32 proof hashes, making it compatible with any chain that supports Solidity ^0.8.20.


13 — Testing & Verification

Suite Scope Tests Status
AI Core (Phase 1) All Layer 1 models, features, calibration, Merkle 41 Pass
Full Stack Integration Cross-layer L1–L5 interaction, API endpoints 49 Pass
Smart Contracts (Hardhat) Token deployment, events, staking, resolution 12 Pass
Backend API Live endpoint validation 6 Pass
Total 108 All Pass

Test execution:

# Layer 1 — AI Core
cd ai-core && python ../tests/test_phase1.py

# Full stack — all 5 layers
python tests/test_full_stack.py

# Smart contracts
cd smart-contracts && npx hardhat test

14 — Repository Structure

GlobalTruthProtocol/
├── ai-core/
│   ├── main.py                        # PredictiveCore orchestrator
│   ├── config.json                    # Model configuration (seeds, hyperparams)
│   ├── models/
│   │   ├── monte_carlo.py             # 100K-sim GBM engine
│   │   ├── bayesian.py                # Beta-conjugate DAG
│   │   ├── reinforcement.py           # Thompson sampling + UCB1
│   │   ├── deep_learning.py           # NumPy feedforward NN
│   │   └── volatility.py              # 4-factor GARCH composite
│   ├── features/
│   │   └── feature_engine.py          # Extraction, imputation, normalization
│   ├── data/
│   │   └── data_loader.py             # Async fetch with TTL cache
│   ├── blockchain/
│   │   ├── commitment.py              # On-chain commit (dry-run / live)
│   │   └── merkle.py                  # Merkle tree + commitment engine
│   └── calibration/
│       └── calibration.py             # Brier, ECE, reliability curves
│
├── tokenomics/
│   ├── emission_model.py              # Supply schedule, burns, vesting
│   └── staking_math.py                # Payout math + ManipulationSimulator
│
├── oracle-system/
│   └── oracle_engine.py               # Multi-source consensus + disputes
│
├── dao-governance/
│   └── governance.py                  # Proposals, voting, reputation engine
│
├── smart-contracts/
│   ├── contracts/
│   │   ├── Tokens.sol                 # TRUTH + VOL + LIQ (ERC20, Votes, Permit)
│   │   ├── EventRegistry.sol          # Prediction lifecycle management
│   │   └── StakingPool.sol            # Economic staking pool
│   ├── test/
│   │   └── GTP.test.js                # 12 Hardhat tests
│   └── scripts/
│       └── deploy.js                  # Full deployment script
│
├── backend/
│   └── api_server.py                  # FastAPI (25+ endpoints)
│
├── tests/
│   ├── test_phase1.py                 # AI Core: 41 tests
│   └── test_full_stack.py             # Cross-layer L1–L5: 49 tests
│
├── docs/
│   ├── WHITEPAPER.md                  # Protocol specification (797 lines)
│   ├── architecture.md                # System flow diagrams
│   ├── threat-model.md                # Attack vectors and mitigations
│   ├── determinism.md                 # Reproducibility guarantees
│   ├── tokenomics.md                  # Emission projections and burn curves
│   └── graphs/                        # Chart generation scripts
│       ├── monte_carlo_distribution.py
│       ├── volatility_index.py
│       ├── brier_calibration.py
│       ├── supply_emission.py
│       ├── tvl_manipulation.py
│       └── reputation_distribution.py
│
└── docker-compose.yml                 # 8 services (Postgres, Redis, IPFS, etc.)

15 — Quick Start

# Clone
git clone https://github.com/FTHTrading/Global-Truth.git
cd Global-Truth

# Run AI Core tests (41 tests)
cd ai-core
python ../tests/test_phase1.py

# Run full 5-layer integration (49 tests)
cd ..
python tests/test_full_stack.py

# Run smart contract tests (12 tests)
cd smart-contracts
npm install
npx hardhat test

# Start API server
cd ../backend
python api_server.py
# → http://localhost:8000/docs (Swagger UI)
# → http://localhost:8000/api/v1/health

16 — Technology Stack

Component Technology Version
AI Core Python, NumPy, SciPy, asyncio 3.11
Smart Contracts Solidity, OpenZeppelin, Hardhat ^0.8.20 / v5
Backend API FastAPI, Pydantic, uvicorn 0.100+
Token Standards ERC20, ERC20Votes, ERC20Permit, ERC20Burnable OZ v5
Infrastructure Docker Compose, PostgreSQL, Redis, MongoDB, IPFS
Testing pytest-pattern (Python), Mocha + Chai (Solidity)

17 — Supplementary Documentation

Document Description
WHITEPAPER.md Full protocol specification (797 lines)
architecture.md Detailed system flow diagrams and layer interactions
threat-model.md Economic attack analysis, oracle collusion, governance capture
determinism.md Seed handling, floating-point reproducibility, test vectors
tokenomics.md Emission projections, burn curves, staking multiplier analysis

GTP is deterministic probabilistic commitment infrastructure. Predictions are produced by a multi-model ensemble, committed to an immutable ledger before resolution, settled through weighted oracle consensus, and governed by a merit-based DAO.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors