Skip to content

rohan911438/Inject-OS

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

50 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

InjectOS

AI-Native Execution Infrastructure for Injective

Solidity Injective TypeScript Next.js FastAPI Gemini AI Remix IDE MetaMask HackQuest

Brief: InjectOS is a secure, AI-powered execution operating system built for the Injective ecosystem. It enables natural-language blockchain execution with integrated AI transaction safety, execution previews, realtime monitoring, and ecosystem intelligence—designed for production-grade developer adoption rather than a simple hackathon demo.

Built by: Rohan Kumar
Team: BROTHERHOOD
Made for: Injective Solo AI Builder Sprint


Quick links


The Problem

Current AI-powered blockchain systems expose several fundamental risks that prevent widespread, trustable adoption:

  • Unsafe: automated execution without robust verification exposes funds and user accounts.
  • Opaque: users cannot inspect model reasoning or the transaction payload that will be signed.
  • Fragmented: DeFi state and protocol primitives are scattered across disparate UIs and RPCs.
  • Low-trust: no standard explainability or human-in-the-loop verification for AI-driven flows.
  • Risky approvals: broad token approvals and blind automation enable large-scale exploits.

InjectOS addresses this trust gap by treating execution safety and explainability as first-class primitives—combining AI convenience with deterministic previews, safety verification, and human approvals.


Why InjectOS Exists

InjectOS is not another dashboard or chatbot. It's an execution-first platform that turns human language into verifiable blockchain actions—while keeping humans in charge.

  • Vision: Make blockchain execution as intuitive as talking to an intelligent assistant, without sacrificing safety or control.
  • Mission: Provide a secure runtime and developer tooling for AI-driven execution workflows on Injective.

Core Product Philosophy

InjectOS is built around three engines that form the core runtime for every intent and execution:

  1. AI Intent Engine

    • Responsibility: Convert natural language prompts into structured, deterministic blockchain actions (calls, multicalls, swaps, delegations, etc.).
    • Role: Translation layer producing canonical intent objects with metadata (assets, chain, gas limits, caller context).
    • Why it matters: Removes ambiguity and produces auditable artifacts for downstream safety analysis.
  2. AI Transaction Safety Engine

    • Responsibility: Vet each intent and candidate transaction via multi-model checks (static analysis, symbolic simulation, heuristics, policy rules).
    • Role: Runs explainable checks, computes risk scores, recommends mitigations (split txs, limit slippage, reduce approvals).
    • Why it matters: Prevents blind signing and provides human-readable reasoning for every decision.
  3. Ecosystem Intelligence Engine

    • Responsibility: Monitor Injective network health, mempool signals, oracle freshness, liquidity, and protocol events.
    • Role: Contextualizes safety decisions (e.g., flag front-running risk, stale oracles, thin liquidity).
    • Why it matters: Adds situational awareness and allows adaptive safety policies.

Execution Workflow

flowchart LR
	A[User Prompt] --> B[AI Intent Parsing]
	B --> C[Safety Verification]
	C --> D[Transaction Preview]
	D --> E[Human Approval]
	E --> F[Injective Execution]
	F --> G[Execution Monitoring]
	G --> H[Completion Status]
	C -->|Reject / Request Edits| A
Loading

Stages explained:

  • User Prompt: Natural language input in the AI Command Center.
  • AI Intent Parsing: Deterministic parsing to typed intent objects and validation against intent schema.
  • Safety Verification: Multi-step analysis producing a safety report (risk score, mitigations, natural-language rationale).
  • Transaction Preview: Full calldata, token movements, gas estimates, and simulation traces for the user to inspect.
  • Human Approval: Signature flow via MetaMask or injected wallet after inspection.
  • Injective Execution: Signed tx submitted to Injective EVM (optionally simulated on testnet).
  • Execution Monitoring: Real-time event streaming, diffs, and alerts for anomalies.
  • Completion Status: Final success/failure receipts persisted onchain and offchain for audit.

The frontend Command Center visualizes every step and enables deep-dive inspection into model reasoning and simulation traces.


Why Injective

  • High-performance, low-latency execution—suitable for fast financial operations.
  • EVM compatibility + Cosmos interoperability for cross-chain orchestration.
  • Developer-first tooling and DeFi ecosystem make Injective ideal for execution infrastructure.
  • Predictable finality and performant RPCs support AI-native, low-latency decisioning.

InjectOS treats Injective as the primary execution fabric because it offers the primitives needed for secure, explainable, AI-driven financial execution.


Injective Integration

Integrations implemented in this repo:

  • Injective EVM Testnet — development and simulation environment.
  • MetaMask — human signature & approval flows.
  • Remix IDE — contract development and verification workflow.
  • ethers.js — contract communication, tx assembly, and parsing helpers.
  • Injective RPC — transaction submission, receipts, and mempool observation.
  • Smart contract event monitoring — backend uses events to sync UI via WebSockets.
  • Realtime tracking — optimistic UI patterns and reconciled state via onchain events.

Notes: The repository ships demo/simulated execution infrastructure for the sprint; architecture is extensible to production Injective nodes and validator-based relayers.


Smart Contract Architecture

Contracts deployed (addresses are exact):

Contract Address Responsibility
InjectOSExecution 0x3Eb27ab9B7c9a7d0B1dc02367DEA9e49f7Fd9419 Manages execution orchestration, authorized relayers, and transaction templates.
InjectOSSafety 0xd7412cB8b75A45fe5aD6bF9Ca5500811BA3B3e97 Onchain safety anchors, policy commitments, and signature gating for automated flows.
InjectOSEvents 0x33491e1b1fbD9F1d757a0ABd1a2930D189d4990E Standardized execution telemetry and event emission for backend synchronization.
InjectOSStorage 0xff0Ea64C7B7046929CAcDFeDd32D0d4208F00266 Persistence for execution receipts and tamper-evident auditor metadata.
InjectOSInterfaces 0x3Eb27ab9B7c9a7d0B1dc02367DEA9e49f7Fd9419 Shared interface/ABI layer used by the frontend and SDK (source-only interface contract).

Roles summary:

  • InjectOSExecution: Execution state machine, multicall patterns, and relayer authorization.
  • InjectOSSafety: Stores onchain policy anchors and references to offchain safety reports.
  • InjectOSEvents: Emits events consumed by the backend for realtime UI updates.
  • InjectOSStorage: Tamper-evident onchain storage for inputs/outputs; supplemented by offchain SQLite for indexing.

Verified Contracts & Explorer Links

Replace the placeholders below with your chosen Injective explorer and verification URLs. I can update these links if you paste the final explorer URLs.

Contract Address Explorer Verified Source
InjectOSExecution 0x3Eb27ab9B7c9a7d0B1dc02367DEA9e49f7Fd9419 View on Blockscout Source: Contract file
InjectOSSafety 0xd7412cB8b75A45fe5aD6bF9Ca5500811BA3B3e97 View on Blockscout Source: Contract file
InjectOSEvents 0x33491e1b1fbD9F1d757a0ABd1a2930D189d4990E View on Blockscout Source: Contract file
InjectOSStorage 0xff0Ea64C7B7046929CAcDFeDd32D0d4208F00266 View on Blockscout Source: Contract file
InjectOSInterfaces 0x3Eb27ab9B7c9a7d0B1dc02367DEA9e49f7Fd9419 View on Blockscout Source: Contract file

Tech Stack

  • Frontend: Next.js, TypeScript, Tailwind CSS, Zustand
  • Backend: FastAPI, Python, Uvicorn, WebSockets
  • Blockchain: Solidity, Injective EVM Testnet, ethers.js, Remix
  • AI Infrastructure: Gemini API (pluggable LLM layer)
  • Wallet Integration: MetaMask
  • Storage: SQLite (dev), JSON fixtures for demo
  • SDK Layer: TypeScript SDK exposing previews & event streams

Frontend Architecture

  • AI Command Center: Mission-control UI for composing intents and approving execution.
  • Workflow-driven pages: Each UI flow maps to an intent lifecycle with clear states (draft, parsed, safety_review, preview, awaiting_signature, executing, finalized).
  • Realtime sync: WebSocket-driven updates and optimistic UI with reconciliation.
  • Design goals: Low cognitive load, provenance-first, and action-focused UX.

Backend Architecture

  • FastAPI provides intent submission, preview generation, and historical queries.
  • Gemini orchestration layer calls LLMs for parsing and rationale with deterministic fallbacks.
  • Safety analysis pipeline: static heuristics, symbolic simulation, and model-guided checks.
  • Persistence: SQLite for local-first sessions and audit logs.
  • WebSockets: Push execution lifecycle events to clients.

SDK & Developer Infrastructure

The InjectOS_sdk (TypeScript) is the primary integration surface for InjectOS: a lightweight, frontend-friendly package that turns Injective EVM into an AI-native execution runtime.

Goals and design

  • Typed-first: TypeScript types for intents, safety reports, and workflow states ensure deterministic integration.
  • Modular: small entrypoints (wallet, provider, contracts, simulation, safety, events, execution) so you import only what you need.
  • UX-safe: preview-first APIs to guarantee the UX always shows deterministic previews before any signature request.

Package layout (summary)

src/lib/injective/
	constants.ts   - chain config, contract addresses, workflow enums
	provider.ts    - ethers.js provider helpers and network switching
	wallet.ts      - MetaMask / EIP-1193 connection and status detection
	contracts.ts   - InjectOS contract ABIs and typed wrappers
	execution.ts   - workflow state machine and synchronization helpers
	safety.ts      - local safety analysis and onchain safety submission helpers
	events.ts      - contract event listeners and realtime workflow updates
	simulation.ts  - deterministic preview generation (SAFE / OPTIMIZED)
	analytics.ts   - network health, activity, and ecosystem metrics helpers

Injective defaults (constants)

  • Chain name: Injective EVM Testnet
  • Chain ID: 2525
  • Default RPC: configurable via constants.ts (do not hardcode in production)
  • Explorer: Blockscout testnet (see Verified Contracts table)

Install & build

# install the SDK in another project
npm install injectos-injective-sdk

# build from repository
npm install
npm run build

Usage example (browser)

import { connectMetaMaskToInjective, getBrowserProvider, getExecutionContract, simulateSwapPreview, executionStore } from 'injectos-injective-sdk';

const wallet = await connectMetaMaskToInjective();
const provider = getBrowserProvider();
const signer = provider.getSigner();
const executionContract = getExecutionContract(signer);

const preview = await simulateSwapPreview({ amount: 1000n, mode: 'SAFE' });
console.log(preview.summary);

const state = executionStore.getState();
console.log(state.workflowState);

Key capabilities (detailed)

  • Wallet & provider helpers: Auto-detect EIP-1193 wallets, prompt chain-switch to Injective EVM Testnet, standardize ethers provider usage.
  • Contract wrappers: Typed wrappers around InjectOS contracts with helper calls for common patterns (multicall, relayer submission).
  • Simulation & previews: Deterministic simulation engine that returns calldata, token flows, gas estimates, and EVM traces that match what will be submitted.
  • Safety primitives: Local policy checks (confidence thresholds, slippage limits, ambiguity detection) and helpers to publish safety artifacts onchain via InjectOSSafety.
  • Events & sync: Robust event listeners with reconnection/backfill strategies and thin client state synchronization for mission-control UIs.
  • Analytics: Lightweight telemetry helpers to compute mempool depth, oracle age, and liquidity signals for safety alerts.

Frontend integration notes

  • Works well with React + Zustand: the executionStore is designed to be used by React components and persisted offchain for replay.
  • Use preview helpers before calling signer.sendTransaction — the SDK surfaces preview → review → sign flows.
  • Use events.ts to drive realtime badges, timeline UI, and post-execution analytics panels.

Safety behavior

  • Local safety policy (example defaults):
    • Minimum confidence: 80
    • Maximum slippage: 5%
    • Ambiguity: must be false (intent parser must be decisive)
  • Modes: SAFE (conservative, higher checks) and OPTIMIZED (higher throughput, tuned gas/fee heuristics).
  • The SDK returns a SafetyReport object with: { riskScore, issues, mitigations, simulationTrace, recommendedTx } which the UI must render before any signature.

Extensibility

  • Replace the LLM provider by implementing the IntentProvider interface.
  • Swap RPC endpoints by overriding constants.ts at build time or via runtime configuration.
  • Add enterprise policies by extending the Safety Engine with custom validators.

Why Injective (expanded)

Injective is an ideal host for InjectOS for several reasons:

  • Low-latency EVM execution — good for quick financial operations and high-frequency interactions.
  • EVM compatibility + Cosmos interoperability — enables cross-chain workflows and broader composability.
  • Developer tooling — robust RPCs, explorer infrastructure (Blockscout), and Remix compatibility accelerate developer velocity.
  • DeFi-first ecosystem — liquidity, DEXs, and derivative protocols make Injective a natural home for execution-centered tooling.

Best use cases on Injective

  • Secure DEX execution and batch swaps with deterministic previews (reduce slippage and front-running).
  • Institutional execution pipelines that require explainable AI-assisted decisioning and full audit trails.
  • Cross-protocol orchestration where EVM actions are coordinated with Cosmos-side logic.
  • Relayer services and private-execution relays that benefit from low-latency injection and validator-aware routing.
  • Simulation-driven strategies and onchain policy enforcement for marketplace operations (e.g., limit orders, auction settlement).

How To Run The Project

Prerequisites:

  • Node 18+
  • Python 3.10+
  • MetaMask
  • (Optional) Google Gemini API key
  • Git

Frontend setup (quick):

git clone <repo-url>
cd InjectOS/Frontend
npm install
npm run dev
# open http://localhost:3000

Windows PowerShell note (use call operator for Node shim):

Set-Location -Path 'C:\Users\dell\Desktop\InjectOS\Frontend'; & 'C:\nvm4w\nodejs\npm.cmd' run dev

Backend setup:

cd InjectOS/Backend
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
uvicorn main:app --reload --port 8000

Create Backend/.env with at minimum:

GEMINI_API_KEY=your_gemini_key_here
INJECTIVE_RPC_URL=https://testnet.injective.network
DATABASE_URL=sqlite:///./database/app.db
FRONTEND_ORIGIN=http://localhost:3000

Detailed Architecture

This section provides a production-oriented architecture overview: system components, data flows, deployment topology, security boundaries, and scaling considerations.

System Diagram

flowchart LR
	U["User / Operator"] --> FE["Frontend: AI Command Center"]
	FE --> API["Backend API (FastAPI)"]
	API --> AE["AI Intent Engine"]
	API --> SE["AI Transaction Safety Engine"]
	API --> EI["Ecosystem Intelligence Engine"]
	API --> SIM["Simulation & Local Testnet"]
	API --> INJ["Injective EVM RPC"]
	INJ --> EVT["InjectOSEvents & Event Bus"]
	EVT --> FE
	EVT --> DB["SQLite / Offchain Index"]
	API --> SDK["InjectOS SDK (TypeScript)"]
	FE --> WS["WebSocket Sync"]
	SDK --> WS
	LLM["Gemini / LLM Providers"] --> AE
	LLM --> SE
Loading

Component Responsibilities (expanded)

Below are expanded, implementation-focused responsibilities and interactions for each major component:

  • Frontend — AI Command Center

    • Accepts natural-language prompts, displays parsed intent objects, safety reports, and simulation traces.
    • Initiates signature flows and submits signed payloads to the backend/relay.
    • Subscribes to lifecycle events via WebSocket for realtime UI updates.
  • Backend API (FastAPI)

    • Coordinates parsing, safety analysis, simulation, and submission flows.
    • Provides typed REST endpoints and WebSocket channels for UI and SDK clients.
    • Persists audits, previews, safety reports, and receipts to offchain storage.
  • AI Intent Engine

    • Deterministic parser producing typed intent schema (JSON/TypeScript interface).
    • LLM augmentation used only for clarification, with a strict validation step before producing candidate transactions.
  • AI Transaction Safety Engine

    • Runs static analyzers, symbolic simulation (EVM traces), and heuristics to compute a risk profile and human-readable rationale.
    • Produces a safety report object: { riskScore, issues[], mitigations[], simulationTrace, recommendedTx }.
  • Ecosystem Intelligence Engine

    • Continuously samples RPC/mempool/oracle signals and produces context metadata (e.g., mempoolDepth, oracleAge, liquidityHeatmap).
    • Feeds signals into the Safety Engine to allow adaptive policies.
  • Simulation & Local Testnet

    • Deterministically replays candidate transactions to generate traces and state diffs used in previews.
    • Provides fallback previews when RPC endpoints are degraded.
  • Injective Contracts & Event Bus

    • Contracts emit standardized events consumed by the backend to reconcile onchain state with offchain previews.
    • The event bus (consumer + workers) ensures idempotent processing and replayability.
  • Storage & Indexing

    • Short-term: SQLite for local-first dev and reproducible demos.
    • Production: managed Postgres + time-series/indexing for audit queries and analytics.
  • InjectOS SDK

    • Exposes programmatic preview APIs, typed intent generation helpers, and event subscription methods for third-party integrations.

Data Flows

  • Intent lifecycle: User → Frontend → Backend → Intent Engine → Safety Engine → Preview → User Approval → Signed Tx → Injective → Events → Backend → Frontend/SDK.
  • Event sync: Onchain events emitted by contracts are consumed by the backend and forwarded via WebSocket to connected clients for real-time UI updates.
  • Audit trail: Execution inputs, previews, safety reports, and receipts are stored offchain (SQLite) and selected commitments are anchored onchain via InjectOSStorage.

Security Boundaries & Trust Model

  • Human-in-loop: high-value or policy-triggered actions require explicit wallet signatures; automated flows are gated by InjectOSSafety anchors and policy checks.
  • Least-privilege: UI recommends minimal token approvals and enforces approval-reduction patterns where possible.
  • Onchain vs offchain: critical enforcement/commitment anchors are onchain; detailed logs and model artifacts remain offchain for performance and privacy.
  • Secrets: API keys (Gemini, RPC credentials) never stored in repo — use environment variables and secret managers in production.

Scaling & Deployment Notes

  • Backend: stateless FastAPI instances behind a load balancer; attach to a managed Postgres for production (migrate from SQLite).
  • WebSockets: use a managed pub/sub (Redis, Kafka) plus sticky sessions or a WebSocket gateway for scale.
  • AI calls: LLM inference is a bottleneck—use async batching, local deterministic fallback parsers, and model caching for repeated queries.
  • Contract event processing: use a resilient worker (queue) and idempotent event handlers for replay and recovery.
  • Observability: instrument traces (OpenTelemetry), structured logs, and onchain event monitors for SLA and incident response.

Failure Modes & Mitigations

  • LLM ambiguity: deterministic intent schema + explicit validation rejects ambiguous intents and prompts for clarification.
  • Mempool front-running risk: Ecosystem Intelligence flags risky windows and suggests mitigations (split txs, gas tuning, private relay).
  • RPC outages: fallback endpoints and local simulation allow previews even if RPC degrades.
  • Event processing lag: checkpointing and replayable logs ensure eventual consistency for UI state.

Production Checklist

  • Replace SQLite with managed Postgres and configure DATABASE_URL.
  • Harden API auth and add role-based access controls for operators.
  • Configure secret management for LLM and RPC keys.
  • Add end-to-end tests for parsing → preview → simulation → signing flows.
  • Document emergency kill-switches and relayer governance policies.


Future Roadmap

  • Real Injective protocol execution & validator integrations
  • Validator-aware relayers & lower-latency finality
  • Advanced ecosystem intelligence & mempool heuristics
  • Autonomous execution agents with human-in-loop governance
  • AI governance & policy voting systems
  • Deterministic execution simulation and replay
  • Institutional-grade safety & compliance toolchains
  • Multi-agent orchestration and realtime onchain analytics

Comparison With Traditional AI Crypto Tools

The following comparison positions InjectOS relative to common tool categories. It emphasizes architectural and operational differences relevant to builders and security-conscious teams.

Capability Traditional Trading Bots DeFi Dashboards Automation Platforms InjectOS
Focus Automation / returns Visibility Task automation Safe, explainable execution infrastructure
Safety-first No Partial Varies Yes — multi-layer safety engine with human-in-loop
Explainability Minimal Minimal Varies Full rationales, audit trails, and intent artifacts
Human approval Optional Manual Optional Default for high-value actions; configurable policy
Deterministic intent model No No No Yes — typed intent objects and schema-driven flows
Onchain auditability Sometimes No Sometimes Yes — onchain commitments + offchain indexing
SDK & integrations Limited Data APIs Integrator-specific First-class TypeScript SDK, WebSocket events
Enterprise readiness Low–medium High (visualization) Medium High — design for audits, governance, and approvals

InjectOS is intentionally positioned as infrastructure rather than a single-use trading tool: it provides deterministic execution artifacts, layered safety, and clear human-in-the-loop patterns required by production teams.


Project Structure (brief)

Frontend/
	src/
Backend/
	main.py
	app/
Contract/
	contracts/
InjectOS_sdk/
README.md

Screenshots

  • image
  • image
  • image
  • image
  • image
  • image
  • image

Security Philosophy

  • Human-in-the-loop signatures for high-value flows.
  • Explainability-first safety reports for every intent.
  • Least-privilege approvals and mitigation suggestions.
  • Tamper-evident onchain commitments paired with offchain indexing.
  • Defense-in-depth: static, symbolic, and runtime checks.

Contributing

  • Issues & PRs welcome—focus on safety, reproducibility, and deterministic parsing.
  • Add tests for intent conversion and safety rules.
  • Use the demo JSON fixtures in Backend/database for reproducible scenarios.

Licensing & Attribution

This repository is licensed under the MIT License — see LICENSE for details.

Copyright (c) 2026 BROTHERHOOD (Rohan Kumar)

Respect model and provider terms of service (Gemini or other LLM providers) when using hosted APIs.


Built by Rohan Kumar
Team: BROTHERHOOD
For the Injective Solo AI Builder Sprint


About

AI-Native Execution Infrastructure for Injective

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors