Complete Documentation

Comprehensive guide to Incrypt Oracle - Everything you need to know about our decentralized oracle infrastructure, prediction markets, smart contracts, and ecosystem.

🚧 Private beta as of November 18, 2025 — metrics, integrations, and partnerships shown here are testnet simulations and internal targets. No third-party firms have formally audited or endorsed the protocol yet.

📖 Introduction

Incrypt Oracle is a sophisticated, production-grade decentralized oracle infrastructure built on Binance Smart Chain (BSC) specifically architected for prediction markets. The platform leverages a multi-validator consensus mechanism with reputation-weighted validation, optimistic resolution with rapid dispute windows (4 hours vs industry standard 24-48 hours), and a comprehensive revenue model through subscription services and premium market features. The entire system is powered by the native $IO token, which serves dual purposes as both a governance mechanism and a staking/validation requirement for network participants.

What Makes Incrypt Oracle Different?

⚡ Industry-Leading Resolution Speed

4-Hour Optimistic Resolution: Markets resolve in 1-4 hours with a 4-hour dispute window, compared to industry standards of 24-48 hours (UMA) or 12+ hours (Polymarket).

Requires only ≥50% validator agreement vs 100% for full consensus. Result: 6-12x faster than traditional oracle systems.

🤖 Revolutionary AI Validator Network

Automatic API Discovery: AI validators automatically discover 10+ relevant APIs for any prediction market question without manual curation.

Uses Hugging Face models (Meta-Llama-3-8B-Instruct) for intelligent analysis. 24/7 availability with transparent on-chain reasoning.

✅ Production-Ready Deployment

BSC Testnet Deployment: All core contracts deployed and verified on Binance Smart Chain Testnet.

All smart contracts verified on BSCScan. Active validators, data feeds, and markets running on testnet. Mainnet ready.

💰 Sustainable Revenue Model

Multiple Revenue Streams: Trading fees (2%), API subscriptions (tiered pricing), and market creation fees.

50/50 revenue split between token holders (stakers) and treasury for long-term sustainability.

🎯 Additional Key Features

Reputation-Weighted Consensus - Validators build reputation over time, with more accurate validators having higher weight in consensus calculations
Advanced Security - Division-by-zero protection, input validation, slashing mechanism, reentrancy guards, and comprehensive test coverage (88%+)

Supported Data Types

Crypto Prices
Sports Events
🗳️
Elections
🌤️
Weather Data

✨ Features

🎯 Oracle Infrastructure

  • Decentralized Validation - Multiple validator nodes ensure data integrity
  • Real-time Data Feeds - Sub-second oracle updates with minimal gas fees
  • High Confidence Scoring - Reputation-weighted consensus mechanism
  • Prediction Market Optimized - Purpose-built for outcome resolution

🎲 IncryptPredict Demo

  • Create Markets - Launch prediction markets on any event
  • AMM Trading - Automated market maker for outcome shares
  • Real-time Odds - Live price discovery and liquidity management
  • Instant Settlement - Oracle-powered automatic resolution

🏛️ DAO Governance

  • Proposal System - Submit and vote on platform improvements
  • Treasury Management - Community-controlled fund allocation
  • Revenue Distribution - 50/50 split between holders and treasury
  • Validator Governance - Stake-weighted voting on oracle parameters

🛠️ Developer Tools

  • JavaScript SDK - Easy integration with comprehensive documentation
  • React Hooks - Ready-to-use hooks for React applications
  • TypeScript Support - Full type definitions for better DX
  • Multi-chain Ready - BSC Mainnet, Testnet, and local development

🏗️ Technical Architecture

System Architecture Overview

Incrypt Oracle consists of several interconnected components working together to provide decentralized oracle services:

Core Smart Contracts

Oracle, Market, DAO, Token, Revenue contracts

Validator Nodes

Off-chain services that fetch and submit data

Frontend Application

Next.js web interface for users

JavaScript SDK

Developer library for easy integration

Consensus Mechanism

Incrypt Oracle uses a reputation-weighted consensus algorithm where validators submit data values and the final consensus is calculated as:

consensusValue = Σ(values[i] × reputations[i]) / Σ(reputations[i])

This ensures that more accurate validators (with higher reputation) have greater influence on the final consensus value.

Data Flow

1. Event occurs (e.g., Bitcoin reaches $100k)
   ↓
2. Validators fetch data from multiple sources
   ↓
3. Each validator submits their validation on-chain
   ↓
4. Smart contract aggregates submissions
   ↓
5. Consensus algorithm calculates final value
   ↓
6. Confidence score computed from variance
   ↓
7. Data feed updated with new value
   ↓
8. Prediction markets automatically resolved

🤖 AI Validator

Overview

Incrypt Oracle features a revolutionary AI-powered validator that combines artificial intelligence with automatic API discovery to provide faster, more accurate oracle resolutions. Inspired by Sora Oracle's agentic approach, our AI validator uses Hugging Face models to analyze prediction market questions, automatically discover relevant data sources, and provide intelligent reasoning for each validation.

Key Features

🔍

Automatic API Discovery

AI automatically discovers 10+ relevant APIs for any prediction market question without pre-registration. Searches RapidAPI, APIs.guru, and known sources.

🧠

Hugging Face Integration

Uses state-of-the-art language models (Meta-Llama-3-8B-Instruct) to analyze questions, synthesize data, and provide detailed reasoning.

📊

Multi-Source Validation

Fetches data from multiple discovered APIs and calculates consensus using median values and variance analysis for robust results.

💡

Intelligent Reasoning

Provides detailed reasoning and metadata for each validation, including confidence scores, data sources used, and model information.

Higher Starting Reputation

AI validators start with 1200 reputation (vs 1000 for human validators) and maintain reputation through accurate validations.

🤝

Hybrid Consensus

Works seamlessly with human validators in reputation-weighted consensus, combining AI speed with human intuition.

How AI Validator Works

1. Question Analysis

When a prediction market question is created, the AI validator analyzes the question text, description, and category to understand what data is needed.

2. API Discovery (Inspired by Sora Oracle)

The AI agent automatically searches for relevant APIs:

  • Searches RapidAPI marketplace for relevant endpoints
  • Queries APIs.guru public API directory
  • Uses known reliable sources based on category (crypto, sports, elections, weather)
  • Returns top 10 most relevant APIs with authentication methods

3. Data Fetching

Fetches data from the top 5 discovered APIs, handling authentication, rate limiting, and errors gracefully.

4. AI Synthesis

Uses Hugging Face inference API to:

  • Analyze the question and fetched data
  • Extract the most likely numeric value
  • Provide detailed reasoning for the validation
  • Calculate confidence based on data agreement

5. Validation Submission

Submits validation to the oracle contract with:

  • Extracted value (scaled to 4 decimal places)
  • AI metadata JSON containing confidence, sources, reasoning, and model info
  • Data source identifier

Smart Contract Integration

The AI validator is fully integrated into the IncryptOracle smart contract:

ValidatorType Enum

enum ValidatorType {
    Human,
    AI
}

Key Functions

  • registerAIValidator(address, uint256) - Owner-only function to register AI validators
  • submitAIValidation(bytes32, uint256, string, string) - Submit validation with AI metadata
  • getValidationSubmission(bytes32, address) - Get validation details including AI metadata
  • getAIValidatorCount() - Get count of active AI validators

AI Validator Node Setup

The AI validator runs as a separate Node.js service. See the ai-validator/ directory for full implementation.

Quick Start

cd ai-validator
npm install
cp .env.example .env
# Configure .env with your settings
npm run build
npm start

Required Environment Variables

  • AI_VALIDATOR_PRIVATE_KEY - Private key for validator wallet
  • HUGGINGFACE_API_TOKEN - Your Hugging Face API token
  • ORACLE_ADDRESS - IncryptOracle contract address
  • RAPIDAPI_KEY - (Optional) RapidAPI key for enhanced discovery

SDK Integration

The JavaScript SDK includes full support for AI validators:

Get AI Validator Count

const oracle = new IncryptOracle({ network: 'bsc-testnet' });
const aiCount = await oracle.getAIValidatorCount();
console.log(`Active AI validators: ${aiCount}`);

Get Validation Submission with AI Metadata

const submission = await oracle.getValidationSubmission(feedId, validatorAddress);
if (submission.validatorType === ValidatorType.AI && submission.aiMetadata) {
  console.log('AI Confidence:', submission.aiMetadata.confidence);
  console.log('Sources:', submission.aiMetadata.sources);
  console.log('Reasoning:', submission.aiMetadata.reasoning);
}

Benefits of AI Validators

Faster Resolutions

AI can process and validate data much faster than manual validators, enabling near-instant resolutions for time-sensitive markets.

Automatic Expansion

No manual API curation needed. AI automatically discovers new data sources as prediction markets expand to new categories.

Transparent Reasoning

Every AI validation includes detailed reasoning, making the decision process transparent and auditable.

Cost Efficiency

AI validators reduce operational costs while maintaining high accuracy through multi-source validation.

24/7 Availability

AI validators operate continuously without downtime, ensuring consistent oracle service.

Hybrid Security

Combines AI speed with human validators for defense-in-depth security through diverse validation approaches.

Specialized Oracle Templates

Dedicated oracle wrappers for high-value market categories. Each template is deployed, verified on BscScan, and wired into the core `IncryptOracle` contract to provide category-specific data models, rate limits, and validation heuristics.

CryptoPriceOracle.sol

60-second crypto price feeds with automatic validator rotation and exchange failover.

Contract Address (BSC Testnet):
0x7c7A94F460d13004db170fd11cC11Ec01f14108fView on BSCScan →
Tracks BTC/USD, ETH/USD, BNB/USD pairs with 4-hour optimistic resolution
Ensures minimum update interval enforcement per feed
AI validator metadata embedded for each submission
Seamless feed creation APIs for new pairs

SportsOracle.sol

Sports event oracle optimized for instant post-game resolution.

Contract Address (BSC Testnet):
0x151c35c569605C752B1F765d9f12fc209c9026a8View on BSCScan →
Supports leagues like NFL, NBA, UEFA with automated question formatting
Encodes scores for both teams in a single uint256 for fast settlement
Event lifecycle states (Scheduled → Live → Completed)
Validator gating to prevent stale submissions

WeatherOracle.sol

Weather metrics oracle powering insurance and catastrophe prediction markets.

Contract Address (BSC Testnet):
0x5bE075Cd0EF40B83B6F45caCC5A3fE548F571970View on BSCScan →
Tracks Temperature, Rainfall, Wind, Humidity, Extreme Events
Location-scoped feeds with rate-limited updates
Numeric encoding (value * 100) to avoid floating point
On-chain helper utilities for string/metric conversions

ElectionOracle.sol

Election results oracle aligned with official election authority announcements.

Contract Address (BSC Testnet):
0x1516901e599F2E5cE03869473272eFa98638c2d0View on BSCScan →
Supports multi-candidate races with winner index encoding
High-threshold validation requirements for sensitive feeds
Tracks official result timestamps and audit trail
Future-proofed for run-offs and recount workflows

📜 Smart Contracts

Comprehensive overview of all Incrypt Oracle smart contracts, their functions, security features, and deployment addresses.

Core Contracts

IncryptOracle.sol

Core oracle contract managing validators and data feeds with reputation-weighted consensus

Contract Address (BSC Testnet):
0x35f86a92C903873dFB33fE7EF04CA0e4f93Ba0a7View on BSCScan →
Key Features
Reputation-weighted consensus mechanism
Optimistic resolution with 4-hour dispute window
Dynamic validator management (3-21 validators)
Automatic slashing for poor performance
Division-by-zero protection
Gas-optimized validator updates
Key Functions
createDataFeed(string name, string description, uint256 threshold)

Create a new data feed for oracle validation

registerValidator(uint256 stakeAmount)

Register as a validator with minimum 1,000 IO token stake

submitValidation(bytes32 feedId, uint256 value, string dataSource)

Submit validation data for a feed (validator only)

🛡️ Security

ReentrancyGuard, Pausable, Ownable, division-by-zero protection, input validation

PredictionMarket.sol

AMM-based prediction market with oracle integration and private market support

Contract Address (BSC Testnet):
0x4448dE2d0Aab5129c92198fCbc55502dAEaA5096View on BSCScan →
Key Features
Constant Product Market Maker (CPMM) model
Oracle-powered automatic resolution
Optimistic resolution support (50% threshold)
Private markets with access control
Market creation fees (50 IO public, 100 IO private)
Comprehensive input validation
Key Functions
createMarket(string question, string desc, string category, uint256 duration, bytes32 oracleFeedId, uint256 liquidity, bool isPrivate, address[] allowed)

Create a new prediction market

buyShares(uint256 marketId, uint8 outcome, uint256 amount)

Buy shares for a specific outcome

sellShares(uint256 marketId, uint8 outcome, uint256 shares)

Sell shares back to the pool

🛡️ Security

ReentrancyGuard, input validation, division-by-zero protection, oracle staleness checks

IOToken.sol

ERC20 governance token with ERC20Votes extension for DAO voting

Contract Address (BSC Testnet):
0x40147E5600b107Dd48001Ec6034A8385aE3747E7View on BSCScan →
Key Features
ERC20Votes extension for delegation
Governance voting capabilities
Validator staking requirement
Market currency and subscription payments
Key Functions
transfer(address to, uint256 amount)

Transfer tokens to another address

approve(address spender, uint256 amount)

Approve spender to transfer tokens

delegate(address delegatee)

Delegate voting power to another address

🛡️ Security

OpenZeppelin ERC20, ERC20Votes standard implementation

RevenueDistributor.sol

Automated fee distribution with 50/50 split to stakers and treasury

Contract Address (BSC Testnet):
0x5e69123b5591C16e236Ec1d508dc338168e80De6View on BSCScan →
Key Features
50/50 revenue split (holders/treasury)
Round-based reward system
Gas-optimized claiming (lastProcessedRound tracking)
Paginated reward claiming (100 rounds max)
Minimum 7-day staking period
Key Functions
stakeTokens(uint256 amount)

Stake IO tokens to receive rewards

unstakeTokens(uint256 amount)

Unstake tokens after minimum period

claimRewards(void)

Claim pending rewards

🛡️ Security

ReentrancyGuard, Pausable, SafeERC20, round limit checks

IncryptDAO.sol

OpenZeppelin Governor for community governance with timelock integration

Contract Address (BSC Testnet):
0xa900e5f7074cf9C002217AbfE97c289dB1526825View on BSCScan →
Key Features
Proposal submission and voting
Timelock integration for delayed execution
Stake-weighted voting
Proposal queuing and execution
Key Functions
propose(address[] targets, uint256[] values, bytes[] calldatas, string description)

Submit a governance proposal

castVote(uint256 proposalId, uint8 support)

Cast vote on a proposal

🛡️ Security

OpenZeppelin Governor, TimelockController integration

OracleSubscription.sol

Tiered subscription service for oracle API access with rate limiting

Contract Address (BSC Testnet):
0xfAA6F894ce67c1e6f101341E4330e648b649c676View on BSCScan →
Key Features
Three subscription tiers (Free, Basic, Premium)
Rate limiting per tier
Monthly billing with renewal
Per-request overflow pricing
Key Functions
subscribe(SubscriptionTier tier, uint256 months)

Subscribe to oracle API access

freeSubscribe(void)

Subscribe to free tier (1,000 requests/month)

🛡️ Security

Access control, rate limiting, input validation

📂 View Source Code

All contracts are open-source and available on GitHub for review and auditing.

View Contracts on GitHub →

🛡️ Security & Audits

Security is paramount in oracle design. Incrypt Oracle implements multiple layers of protection against common attack vectors and manipulation attempts.

Security Features

Division-by-Zero Protection

Comprehensive safety checks prevent consensus calculation failures when all validators have zero reputation or when consensus values are zero.

  • Consensus calculation checks totalWeight > 0 before division
  • Special handling for zero consensus values with variance-based confidence
  • Pool liquidity checks before AMM calculations
  • Share count validation before division operations

Input Validation

All external inputs are validated with explicit require statements and range checks.

  • Range checks for amounts, durations, thresholds
  • String length validation for market questions/descriptions
  • Oracle data freshness checks (24-hour max for full, 4-hour for optimistic)
  • Confidence threshold enforcement (≥70% for full, ≥50% for optimistic)

Slashing Mechanism

Automatic slashing for validators with poor performance (<50% accuracy) with cooldown periods and stake preservation.

  • 1-hour cooldown period prevents rapid successive slashes
  • Minimum stake preservation (never slashes below MIN_STAKE)
  • Maximum 3 slashes before automatic validator removal
  • False dispute penalties (1% stake slash)

Reentrancy Protection

All state-changing functions protected with OpenZeppelin ReentrancyGuard.

  • Checks-Effects-Interactions pattern followed throughout
  • SafeERC20 for token transfers
  • Comprehensive protection on all critical functions

Access Control

Role-based access control with Ownable pattern and validator-only modifiers.

  • Validator-only modifiers for validation submission
  • Creator-only functions for private market participant management
  • Emergency pause functionality on all critical contracts
  • Timelock integration for governance updates

Integer Safety

Solidity 0.8.x automatic overflow checking plus explicit underflow checks.

  • Automatic overflow protection via Solidity 0.8.x
  • Explicit underflow checks before subtractions
  • SafeMath patterns for critical calculations

Security Audit Report

🟡 Preliminary Review

Audit Details

Audit Firm:AI Smart Contract Auditor (Free Audit from beta project)
Audit Date:November 2025
Security Score:Pending formal audit
Status:Preliminary automated + manual review

Issues Found

Critical:Pending
High:Pending
Medium:Pending
Low:Pending
Informational:Pending

We completed a free beta assessment with AI Smart Contract Auditor and are packaging the documentation, tests, and contracts to submit for a proper third-party audit from firms such as CertiK or Halborn as soon as they accept the engagement. We are ready to hand off the codebase, but Incrypt Oracle has not been audited or endorsed by CertiK, Halborn, or any other external firm yet.

Planned Audit Coverage

Oracle core logic
Validator management
Data aggregation
Economic incentives
Prediction market resolution
Revenue distribution
Slashing mechanism

⚠️ Integration Best Practices

  • Always check confidence levels (≥70% for critical, ≥50% for optimistic)
  • Validate freshness - check timestamp to ensure data is recent (≤24 hours for full, ≤4 hours for optimistic)
  • Handle staleness - implement fallback mechanisms if oracle data is too old
  • Monitor validators - track validator reputations and stake amounts
  • Use multiple oracles - for critical applications, consider multiple oracle sources

🎯 Development Roadmap

Our comprehensive development roadmap outlines the evolution of Incrypt Oracle from foundation to global scale, with clear milestones and deliverables.

Phase 1: Foundation

COMPLETE

Core infrastructure and initial deployment

Core smart contracts development (Oracle, Market, DAO, Token, Revenue)
BSC testnet deployment and verification
Basic frontend interface with wallet connection
JavaScript SDK v1.0 with React hooks
Validator node service implementation
Security fixes and optimizations
Integration and edge case test suites
Documentation (SDK, Validator Guide, Deployment)
🚀

Phase 2: Launch

IN PROGRESS

Production launch and mainnet deployment

Optimistic resolution mechanism
Domain-specific oracle templates
Revenue features (subscription service, premium markets)
Frontend blockchain integration (real-time updates)
Final security audit (CertiK/Halborn)
BSC mainnet deployment
$IO token launch
IncryptPredict production launch
Validator onboarding program
📈

Phase 3: Growth

PLANNED

Expansion and ecosystem development

Mobile app (React Native/iOS/Android)
Additional data sources (stock prices, forex, commodities)
Third-party protocol integrations (DeFi lending, derivatives)
Cross-chain expansion (Polygon, Arbitrum, Optimism)
Advanced analytics dashboard
API rate limiting and tier management UI
🌍

Phase 4: Scale

FUTURE

Global scale and advanced features

Multi-outcome markets (beyond binary)
Conditional markets and market dependencies
Institutional oracle services (enterprise tier)
Automated market making algorithms
Historical data APIs
GraphQL endpoint for complex queries
WebSocket connections for real-time data streaming

Overall Progress

100%
Foundation
44%
Launch
0%
Growth
0%
Scale

💰 Tokenomics & Revenue

$IO Token Utility

Token Utility

  • Governance: ERC20Votes extension enables delegation and voting on DAO proposals
  • Validator Staking: Minimum 1,000 IO tokens required to register as validator
  • Prediction Market Currency: Primary medium of exchange for market participation
  • Subscription Payments: Required for API access tiers (Basic: 100 IO/month, Premium: 1,000 IO/month)
  • Market Creation Fees: 50 IO for public markets, 100 IO for private markets

Economic Security Model

Minimum Validator Stake:1,000 IO tokens (~$100-1,000 at various IO prices)
Slashing:10% of stake per poor validation (<50% accuracy)
Maximum Slashes:3 before automatic removal
Cooldown:1 hour between slashes (prevents rapid depletion)
Reputation System:Builds over time, affects consensus weighting

Revenue Model

1. Prediction Market Trading Fees

  • • Default fee: 2% (200 basis points) on all buy/sell transactions
  • • Configurable per market (up to 10% maximum)
  • • Collected in IO tokens and routed to RevenueDistributor

2. Oracle API Subscriptions

Free Tier:
1,000 requests/month (no revenue, network growth)
Basic Tier:
100 IO/month for 10,000 requests, 1 IO per additional request
Premium Tier:
1,000 IO/month for unlimited requests
Estimated revenue potential: $5,000-50,000/month at scale

3. Market Creation Fees

  • • Public market: 50 IO tokens (~$5-50 depending on IO price)
  • • Private market: 100 IO tokens (~$10-100)
  • • Collected immediately on market creation

4. Premium Market Features

  • • Private market access control (100 IO creation fee)
  • • Future premium features: custom fee structures
  • • Extended resolution times
  • • Custom oracle feeds

Revenue Distribution

The RevenueDistributor contract implements an automated 50/50 revenue split:

50% to Token Holders

  • • Distributed proportionally to stakers based on stake size
  • • Staking minimum: No minimum (but must stake to receive rewards)
  • • Distribution interval: 7 days (configurable)
  • • Reward calculation: userReward = (userStake / totalStaked) × holderShare
  • • Gas-optimized claiming with round-based accounting

50% to Treasury

Controlled by DAO for:
  • • Development funding
  • • Security audits
  • • Marketing and partnerships
  • • Validator incentives
  • • Emergency reserves

Staking Mechanism

For Token Holders

  • Stake IO tokens to receive proportional share of holder rewards
  • Minimum staking period: 7 days (prevents gaming)
  • Unstake anytime after minimum period
  • Rewards claimable anytime (gas-optimized pagination for users with many rounds)

For Validators

  • Minimum stake: 1,000 IO tokens required
  • Stake can be slashed for poor performance (<50% accuracy)
  • Reputation system builds over time with accurate validations
  • Higher reputation = higher weight in consensus calculation

Market Economics

Liquidity Requirements

  • • Minimum liquidity: 1,000 IO tokens per market
  • • Ensures market viability and prevents manipulation

Fee Structure

  • • Default fee: 2% (200 basis points)
  • • Market creator sets fee (up to 10% max)
  • • Collected on all buy/sell transactions

AMM Slippage

  • • Automatic based on pool ratios
  • • No slippage protection needed for small trades
  • • Larger trades experience natural slippage

📊 Analytics Dashboard

Real-time insights into the Incrypt Oracle ecosystem. Monitor oracle uptime, market performance, user growth, and platform metrics.

📊 Demo data for now - Real live platform launch TBA

12.5%

2,500,000

Total Volume (USD)

8.2%

5,247

Active Users

0.1%

99.97

Oracle Uptime

15.3%

23

Active Markets

5%

3

Active Validators

18.7%

850,000

Total Staked (IO)

Daily Trading Volume

Markets by Category

Crypto45%
Sports25%
Politics15%
Economics10%
Technology5%

User Growth

Oracle Performance (24h)

Uptime (%)
Latency (s)

Top Markets by Volume

Last 7 days
1

Will Bitcoin close above $90k before November 30, 2025?

$450,000 volume1247 traders
$450k
1247 traders
2

Will ETH staking deposits reach 32M ETH by November 18, 2025?

$320,000 volume892 traders
$320k
892 traders
3

Will BNB Chain gas fees average below 3 gwei during November 2025?

$280,000 volume743 traders
$280k
743 traders
4

Will the Fed announce an additional rate cut in November 2025?

$190,000 volume567 traders
$190k
567 traders
5

Will Solana daily TPS average stay above 2,500 this November?

$150,000 volume445 traders
$150k
445 traders

Real-time Network Status

Oracle Status
Online
Avg Response
1.1s
Data Feeds
47 Active
Validators
3 Online

📋 Testnet Reports

Comprehensive testing results, deployment reports, and security audits for the Incrypt Oracle smart contracts on BSC Testnet.

Deployment Overview

121
Total Tests
All Passed
92%
Code Coverage
High Coverage
Beta
Security Status
AI Smart Contract Auditor review

Contract Testing Results

ContractCoverageTestsIntegrationEdge Cases
IOToken95%1853
IncryptOracle88%23812
PredictionMarket92%3165
IncryptDAO90%2742
RevenueDistributor94%2232
OracleSubscription85%1521

Total: 121+ tests, 88%+ coverage across all contracts

📋 Deployment Summary

  • • Network: BSC Testnet (Chain ID: 97)
  • • Total Gas Used: 12,567,890
  • • Total Cost: 0.0628 BNB
  • • All contracts verified on BSCScan

Performance Analysis

15%
Gas Reduction
95K
Avg Function Cost
2.5M
Total Deploy Cost
FunctionGas UsedUSD Cost*Frequency
Token Transfer21,000$0.52High
Buy Shares95,000$2.38High
Submit Validation85,000$2.13Medium
Create Proposal145,000$3.63Low
Create Market180,000$4.50Low

* Based on 5 GWEI gas price and $400 BNB price

📡 API Reference

IncryptOracle Contract Methods

createDataFeed(string name, string description, uint256 threshold)bytes32

Create a new data feed for oracle validation

registerValidator(uint256 stakeAmount)void

Register as a validator with minimum 1,000 IO token stake

submitValidation(bytes32 feedId, uint256 value, string dataSource)void

Submit validation data for a feed (validator only)

getDataFeed(bytes32 feedId)(name, description, value, timestamp, confidence, isActive)

Retrieve complete data feed information

getActiveFeedIds(void)bytes32[]

Get array of all active data feed IDs

raiseDispute(bytes32 feedId, uint256 proposedValue)void

Raise a dispute during optimistic resolution window

isDisputeWindowOpen(bytes32 feedId)bool

Check if dispute window is open for a feed

PredictionMarket Contract Methods

createMarket(string question, string desc, string category, uint256 duration, bytes32 oracleFeedId, uint256 liquidity, bool isPrivate, address[] allowed)uint256

Create a new prediction market

buyShares(uint256 marketId, uint8 outcome, uint256 amount)uint256

Buy shares for a specific outcome

sellShares(uint256 marketId, uint8 outcome, uint256 shares)uint256

Sell shares back to the pool

resolveMarket(uint256 marketId)void

Resolve market based on oracle data

claimWinnings(uint256 marketId)uint256

Claim winnings from resolved market

calculateCost(uint256 marketId, uint8 outcome, uint256 amount)uint256

Calculate cost to buy shares before purchase

getOdds(uint256 marketId)(noOdds, yesOdds)

Get current odds for market outcomes

OracleSubscription Contract Methods

subscribe(SubscriptionTier tier, uint256 months)void

Subscribe to oracle API access

freeSubscribe(void)void

Subscribe to free tier (1,000 requests/month)

recordRequest(address subscriber, bytes32 feedId)bool

Record API request (owner only)

canMakeRequest(address subscriber)bool

Check if subscriber can make request

getSubscription(address subscriber)(tier, startTime, endTime, requestsUsed, requestsLimit, isActive)

Get subscription details

💡 Integration Examples

import { IncryptOracle } from 'incrypt-oracle-sdk';

// Initialize the oracle
const oracle = new IncryptOracle({
  network: 'bsc-mainnet', // or 'bsc-testnet'
  rpcUrl: 'https://bsc-dataseed1.binance.org/',
});

// Get latest price data
const btcPrice = await oracle.getPrice('BTC/USD');
console.log('BTC Price:', btcPrice.value, 'USD');

// Subscribe to price updates
oracle.subscribe('BTC/USD', (data) => {
  console.log('New BTC price:', data.value);
  console.log('Confidence:', data.confidence);
  console.log('Timestamp:', data.timestamp);
});

React Application Example

import React from 'react';
import { useIncryptOracle, usePriceData } from 'incrypt-oracle-sdk/react';

function CryptoPriceTracker() {
  const { oracle, isConnected, error } = useIncryptOracle({
    network: 'bsc-mainnet'
  });
  
  const { data: btcPrice, loading: btcLoading } = usePriceData(oracle, 'BTC/USD');
  const { data: ethPrice, loading: ethLoading } = usePriceData(oracle, 'ETH/USD');
  
  if (!isConnected) return <div>Connecting to oracle...</div>;
  if (error) return <div>Error: {error.message}</div>;
  
  return (
    <div>
      <h2>Live Crypto Prices</h2>
      
      <div>
        <h3>Bitcoin</h3>
        {btcLoading ? (
          <p>Loading BTC price...</p>
        ) : (
          <div>
            <p>Price: ${btcPrice?.value.toFixed(2)}</p>
            <p>Confidence: {btcPrice?.confidence}%</p>
          </div>
        )}
      </div>
      
      <div>
        <h3>Ethereum</h3>
        {ethLoading ? (
          <p>Loading ETH price...</p>
        ) : (
          <div>
            <p>Price: ${ethPrice?.value.toFixed(2)}</p>
            <p>Confidence: {ethPrice?.confidence}%</p>
          </div>
        )}
      </div>
    </div>
  );
}

Prediction Market Integration

import { ethers } from 'ethers';
import { IncryptOracle } from 'incrypt-oracle-sdk';

// Initialize with signer for write operations
const provider = new ethers.BrowserProvider(window.ethereum);
const signer = await provider.getSigner();

const oracle = new IncryptOracle({
  network: 'bsc-mainnet',
  signer: signer
});

// Create a prediction market
async function createPredictionMarket() {
  // First, create an oracle data feed
  const feedId = await oracle.createDataFeed(
    'ELECTION_2025',
    'US Special Election 2025 Winner',
    5 // Validation threshold
  );
  
  console.log('Data feed created:', feedId);
  
  // Then create market using that feed
  // (requires PredictionMarket contract interaction)
}

🔬 Technical Specifications

Consensus Algorithm Details

Reputation-Weighted Consensus Formula

Given:
- values[]: Array of submitted values from validators
- reputations[]: Corresponding reputation scores
- count: Number of validations submitted
Step 1: Calculate Weighted Sum
weightedSum = Σ(i=0 to count-1) values[i] × reputations[i]
totalWeight = Σ(i=0 to count-1) reputations[i]
Step 2: Calculate Consensus Value
require(totalWeight > 0, "Total weight must be greater than 0")
consensusValue = weightedSum / totalWeight
Step 3: Calculate Variance
variance = Σ(i=0 to count-1) ((values[i] - consensusValue)² × reputations[i]) / totalWeight
Step 4: Derive Confidence Score
if consensusValue == 0:
allZero = check if all values are zero
confidence = allZero ? MAX_CONFIDENCE : MAX_CONFIDENCE / 2
else:
confidence = variance == 0 ? MAX_CONFIDENCE : MAX_CONFIDENCE - (variance × MAX_CONFIDENCE / consensusValue)
confidence = min(confidence, MAX_CONFIDENCE)

Optimistic Resolution Logic

submittedCount = number of validators who submitted
totalValidators = activeValidators.length
threshold = feed.validationThreshold
if submittedCount >= threshold:
resolve with full confidence
else if submittedCount >= (totalValidators × 50 / 100):
resolve with optimistic flag
set optimisticResolutionTime = block.timestamp
open 4-hour dispute window
else:
wait for more validations
continue waiting

AMM (Automated Market Maker) Mathematics

Constant Product Formula

For a market with:
- S_yes: Total YES shares
- S_no: Total NO shares
- L_yes: YES pool liquidity
- L_no: NO pool liquidity
Invariant: L_yes × S_yes = k (constant product)
Buying ΔS_yes shares costs:
Cost = (L_yes × ΔS_yes) / (S_yes - ΔS_yes)
Selling ΔS_yes shares yields:
Payout = (L_yes × ΔS_yes) / (S_yes + ΔS_yes)
Odds:
Yes_Odds = L_yes / (L_yes + L_no)
No_Odds = L_no / (L_yes + L_no)
Fee Calculation:
Fee = Cost × feeBasisPoints / 10000
NetCost = Cost - Fee
NetPayout = Payout - (Payout × feeBasisPoints / 10000)

Network Parameters & Constants

IncryptOracle.sol

MIN_VALIDATORS: 3
MAX_VALIDATORS: 21
MIN_STAKE: 1,000 × 10^18 IO tokens
VALIDATION_WINDOW: 1 hour
MAX_CONFIDENCE: 10,000 (100.00%)
SLASH_THRESHOLD: 5,000 (50%)
SLASH_PERCENTAGE: 10%
MAX_SLASHES: 3
DISPUTE_WINDOW: 4 hours
OPTIMISTIC_RESOLUTION_THRESHOLD: 50%

PredictionMarket.sol

BASE_FEE: 200 (2% in basis points)
MAX_FEE: 1,000 (10% maximum)
MIN_LIQUIDITY: 1,000 × 10^18 IO tokens
RESOLUTION_BUFFER: 1 hour
MARKET_CREATION_FEE: 50 × 10^18 IO (public)
PRIVATE_MARKET_FEE: 100 × 10^18 IO (private)

RevenueDistributor.sol

HOLDER_SHARE_PERCENTAGE: 5,000 (50%)
TREASURY_SHARE_PERCENTAGE: 5,000 (50%)
MIN_STAKING_PERIOD: 7 days
DISTRIBUTION_INTERVAL: 7 days

Gas Optimizations

• Validator reputation updates: ~15,000 gas saved per resolution
• Round-based reward claiming: ~50,000+ gas saved
• Loop iteration reduction: 20-30% overall savings
• Storage packing for efficient slot usage
• Early termination checks in consensus

✅ Testing & Coverage

Comprehensive Test Suite Architecture

The test suite is organized into multiple layers covering unit tests, integration tests, edge cases, and gas optimization verification:

Test Structure

test/
├── IncryptOracle.test.js # Unit tests for oracle core
├── IOToken.test.js # Token functionality tests
├── integration/
│ ├── oracleFlow.test.js # End-to-end oracle validation flow
│ └── predictionMarket.test.js # Full market lifecycle testing
└── edgeCases/
└── oracle.test.js # Edge cases, zero values, max validators, etc.

Integration Test Coverage

  • • Full Oracle Flow: Validator registration → Feed creation → Validation submission → Consensus calculation → Resolution
  • • Reputation Updates: Verifies validator reputation adjustments based on accuracy
  • • Slashing Mechanism: Tests slashing triggers, cooldown periods, and stake preservation
  • • Market Lifecycle: Create → Trade → Resolve → Claim complete flow
  • • Optimistic Resolution: Tests 50% threshold resolution and dispute window

Edge Case Coverage

  • • Zero validator scenarios
  • • Maximum validator count enforcement (21 validators)
  • • Oracle data staleness detection
  • • Division-by-zero prevention in consensus calculation
  • • Very large and very small value handling
  • • Validation window expiration
  • • Empty reputation scenarios

Test Coverage Metrics

ContractCoverageTestsIntegrationEdge CasesGas Usage
IOToken95%18531.2M
IncryptOracle88%238122.4M
PredictionMarket92%31653.4M
IncryptDAO90%27422.7M
RevenueDistributor94%22321.8M
OracleSubscription85%15211.5M

Total: 121+ tests, 88%+ coverage across all contracts

Live Metrics & Performance

Network Performance

Oracle Uptime:99.97%
Average Resolution Latency:1.1s
Optimistic Resolution:4-hour dispute window
Gas Efficiency:20-30% reduction vs initial

Network Status

Active Validators:3+ (expandable to 21)
Data Feeds:47+ active
Total Volume:$5,800+ (BSC Testnet)
Total Staked:3,000+ IO tokens

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Workflow

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for new functionality
  5. Run the test suite (npm test)
  6. Commit your changes (git commit -m 'Add amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

Code Style

Solidity

Follow the Solidity Style Guide

TypeScript/JavaScript

ESLint + Prettier configuration included

React

Functional components with hooks

Testing

Comprehensive test coverage required

🔗 Links

This project is licensed under the MIT License - see the LICENSE file for details.