Invariant-First Β· Independent Β· Open-Source Β· Multi-Tenant Β· AI-Native Financial Operations Platform
β οΈ Independent open-source project. Developed by Karthik Rajesh Shet. Not affiliated with, endorsed by, or a product of Razorpay. The Razorpay adapter operates strictly in TEST MODE with sandbox credentials (rzp_test_*). All demo transactions and datasets are SYNTHETIC.
InvarPay AI is an open-source, invariant-first financial operations platform. It unifies payment lifecycle reliability, explainable fraud intelligence, automated integration AST auditing, merchant cashflow dual-entry ledgers, and customer-governed agentic commerce into a single, high-reliability architecture:
| Module | Purpose | Core Capabilities | API Endpoints | Status |
|---|---|---|---|---|
| InvarGuard | Payment Lifecycle & Safe Recovery | Lifecycle tracking, raw-body HMAC-SHA256 webhook ingestion, inbox deduplication, deterministic reconciliation, safe retry policy (unknown β failed) |
/v1/payments, /v1/orders, /v1/webhooks |
β Production MVP |
| InvarInvestigator | Evidence-Grounded AI Incident Triage | Structured application evidence gathering, deterministic policy boundary (UNKNOWN β FAILED), untrusted data fencing, 21-scenario safety benchmark |
/v1/investigations/payment/{id}, /v1/investigations/evals/run |
β Live AI Safety System |
| PaymentGraph AI | Explainable Fraud Intelligence | Real-time velocity checks, disposable email detection, Tor exit node recognition, composite risk scoring (0β100), transparent model card | /v1/risk/evaluate, /v1/risk/rules |
β Live AI Engine |
| PayDev AST | Payment Code Linter & Auto-Fix | Live Python AST code analyzer, hardcoded credential detection, floating-point currency math prevention, automated unified diff patch generation | /v1/paydev/scan-code, /v1/paydev/rules |
β Live AST Linter |
| MerchantOS | Dual-Entry Ledger & Bank Reconciliation | Minor-unit double-entry journal, settlement CSV & UTR matching engine, zero-drift cashflow accounting | /v1/ledger/accounts, /v1/ledger/journal, /v1/ledger/reconcile-settlement |
β Live FinEngine |
| ShopAgent MCP | Agentic Commerce & Checkout Gate | Model Context Protocol storefront, inventory bounds, strict buyer confirmation gate, Razorpay hosted checkout handoff | /v1/shop/products, /v1/shop/cart, /v1/shop/checkout |
β Live MCP Protocol |
| Audit Log Chain | Cryptographic Tamper-Evidence | SHA-256 Merkle chain verification, immutable event logs, cryptographic proof of ledger integrity | /v1/audit, /v1/audit/verify |
β Cryptographic Proof |
InvarPay AI is structured as a modular monolith with independently deployable async background workers, a Next.js 14 web console, a Model Context Protocol (MCP) server, and a Typer CLI:
flowchart TD
subgraph Clients["Application Interfaces"]
WEB["Next.js 14 Dashboard\n(apps/web Β· Vercel Edge CDN)"]
CLI["Typer CLI\n(apps/cli Β· invarpay)"]
MCP["MCP Server\n(apps/mcp Β· Protocol Tools)"]
SDK["Typed SDKs\n(Python & TypeScript)"]
end
subgraph API["FastAPI Modular Monolith (apps/api)"]
AUTH["Auth & Tenant Context\n(JWT & Scoped API Keys)"]
SEC["Security & Webhooks\n(HMAC-SHA256 Raw-Body)"]
RATELIMIT["Rate Limiter\n(Sliding-Window Memory/Redis)"]
subgraph Modules["Autonomous Core Engines"]
PG["InvarGuard\n(State Machine & Outbox)"]
GRAPH["PaymentGraph AI\n(Risk Rules & Model Card)"]
DEV["PayDev AST\n(AST Scanner & Patch Engine)"]
MOS["MerchantOS\n(Dual-Entry Ledger & UTR Engine)"]
SHOP["ShopAgent MCP\n(Buyer-Confirmed Checkout)"]
AUDIT["Merkle Audit Engine\n(SHA-256 Cryptographic Chain)"]
end
POL["Agent Policy Engine\n(Deny-by-Default Β· Scoped Tools)"]
end
subgraph Storage["Authoritative State & Invariants"]
DB[("PostgreSQL 16 / SQLite\n(Authoritative State & Ledger)")]
OUTBOX["Transactional Outbox Worker\n(Event Deduplication & Webhooks)"]
end
subgraph Providers["External Payment Gateway Adapters"]
RZP["Razorpay Sandbox\n(TEST MODE ONLY: rzp_test_*)"]
FAKE["Fake Provider\n(Deterministic CI Simulator)"]
end
WEB --> AUTH
CLI --> AUTH
MCP --> POL
SDK --> AUTH
AUTH --> RATELIMIT --> Modules
Modules --> POL
Modules --> DB
OUTBOX --> DB
PG --> RZP
PG --> FAKE
InvarPay enforces strict mathematical state transitions to prevent duplicate charges, phantom authorizations, and desynchronized ledgers:
created βββΊ initiated βββΊ pending βββΊ authorized βββΊ captured (terminal β)
β β β
βΌ βΌ βΌ
failed failed failed (terminal β)
β β
βΌ βΌ
unknown* unknown*
β
ββββββββββββΊ cancelled (terminal β)
* unknown = Outcome ambiguous (network timeout, dropped connection).
CRITICAL INVARIANT: unknown β failed. Automated retry is strictly FORBIDDEN.
-
unknown β failed: Network timeouts or gateway 5xx errors transition intounknown. InvarPay strictly blocks automatic re-attempts without prior authoritative bank/provider reconciliation. -
Zero Float Currency: All monetary amounts are processed, computed, and stored exclusively in minor integer units (
BIGINTpaise). Floating-point arithmetic is strictly prohibited to prevent IEEE-754 precision loss. -
Double-Entry Ledger Balancing: Every merchant balance mutation requires matching debit and credit journal entries (
$\sum \text{debits} \equiv \sum \text{credits}$ ). - Raw-Body Webhook Verification: HMAC-SHA256 signatures are computed on the unparsed byte payload before JSON parsing to prevent signature malleability attacks.
- Inbox Deduplication & Replay Guard: Webhooks outside a 5-minute timestamp window are rejected, and provider event IDs are tenant-scoped and deduplicated.
- Human-in-the-Loop AI Boundary: Autonomous agents cannot initiate debits without explicit human buyer cryptographic consent.
- Cryptographic SHA-256 Merkle Chain: Every operational event is hashed with its predecessor ($H_i = \text{SHA256}(H_{i-1} \parallel E_i)$), guaranteeing mathematical tamper-evidence.
InvarPay AI is designed with a modern decoupled deployment topology:
- Frontend (
apps/web): Hosted globally on Vercel Edge CDN. - Backend (
apps/api): Hosted on a persistent cloud service (Render, Railway, Fly.io, or VPS).
- Import your GitHub repository (
karthikrshet/InvarPay) on Vercel. - Configure Project Settings:
- Root Directory:
apps/web(Important: Must beapps/webfor monorepo detection). - Framework Preset:
Next.js(Auto-detected). - Build Command: Leave default (
next build). - Output Directory: Leave default (
.next) β ensure Override is OFF.
- Root Directory:
- Environment Variables:
(If your backend is not yet deployed, leave empty or set to
NEXT_PUBLIC_API_URL = https://your-backend-api.onrender.com
http://localhost:8000. The frontend includes a comprehensive built-in Standalone Demo Mode with interactive simulators and zero broken views). - Click Deploy!
We provide pre-configured deployment manifests:
- Procfile for Railway, Heroku, or Fly.io:
web: uvicorn apps.api.app.main:app --host 0.0.0.0 --port ${PORT:-8000} worker: python -m apps.api.app.core.outbox - render.yaml for 1-click deployment on Render.
# ============================================================
# InvarPay AI β Production Backend Configuration
# ============================================================
# --- Core App ---
APP_ENV=production
DEBUG=false
LOG_LEVEL=info
SECRET_KEY=generate_a_64_char_random_hex_string
ALLOWED_HOSTS=*
# --- Database ---
# For PostgreSQL (e.g., Supabase, Neon, Railway Postgres):
DATABASE_URL=postgresql+asyncpg://postgres:YOUR_PASSWORD@YOUR_HOST:5432/invarpay
# (Or if using persistent SQLite on a single volume container):
# DATABASE_URL=sqlite:////data/payguard.db
DATABASE_POOL_SIZE=10
DATABASE_MAX_OVERFLOW=20
# --- Authentication & JWT ---
JWT_SECRET_KEY=generate_another_64_char_random_hex_string
JWT_ALGORITHM=HS256
JWT_ACCESS_TOKEN_EXPIRE_MINUTES=60
JWT_REFRESH_TOKEN_EXPIRE_DAYS=7
API_KEY_PREFIX=pg_live_
API_KEY_TEST_PREFIX=pg_test_
# --- Gateway Mode ---
# Use "fake" for safe autonomous demonstration, or "test" with real Razorpay test credentials
PAYMENT_PROVIDER=fake
RAZORPAY_KEY_ID=rzp_test_YOUR_KEY
RAZORPAY_KEY_SECRET=YOUR_SECRET
RAZORPAY_WEBHOOK_SECRET=YOUR_WEBHOOK_SECRET
# --- AI Investigation Agent (Optional) ---
# If unset, LangGraph falls back to deterministic invariant safety fixtures
GOOGLE_API_KEY=your_gemini_api_key_here
# or OPENAI_API_KEY=your_openai_key_here
LLM_PROVIDER=google
LLM_MODEL=gemini-2.5-flash
# --- Initial Demo Seed ---
SEED_DEMO_DATA=true
DEMO_ORG_NAME=Demo Merchant Inc.- Python 3.10+
- Node.js 20+ &
pnpm(v9+) - Git
git clone https://github.com/karthikrshet/InvarPay.git
cd InvarPay
# Copy environment variables
cp .env.example .env# Python backend & CLI tools
pip install -e .
# Node.js workspace (Next.js web app & SDKs)
pnpm installpython -m pytest tests/ -v# Terminal 1: Start FastAPI backend (port 8000)
uvicorn apps.api.app.main:app --reload --port 8000
# Terminal 2: Start Next.js dashboard (port 3000)
pnpm dev- Dashboard: http://localhost:3000
- Interactive API Swagger Docs: http://localhost:8000/docs
- Health Check: http://localhost:8000/health
InvarInvestigator is an evidence-grounded AI payment incident investigation system built to resolve ambiguous payment outcomes (timeouts, dropped network connections, out-of-order webhooks) with mathematical correctness guarantees.
Payment / Event
β
Deterministic Evidence Builder (Tenant-Scoped & Fenced Untrusted Data)
β
AI Investigator (Structured Schema: Incident, Facts, Root Cause, Recommendation)
β
Deterministic Policy Engine (AUTHORITATIVE: Invariants & Action Permitted/Blocked)
β
Allowed / Blocked Actions (e.g. RECONCILE allowed, AUTOMATIC_RETRY blocked)
β
Cryptographic Merkle Audit Log (SHA-256 Chained Event)
CRITICAL ARCHITECTURAL BOUNDARY:
- The LLM NEVER directly mutates payment state.
- The LLM NEVER directly authorizes money movement.
- The LLM NEVER overrides or bypasses the deterministic policy engine.
- The deterministic policy engine remains authoritative.
UNKNOWN β FAILED:- If a payment outcome is ambiguous due to socket read timeout, upstream network drop, or uncertain provider response, the payment remains strictly in
UNKNOWNstate. - The Policy Engine BLOCKS automatic retry (
AUTOMATIC_RETRY = DENY) to prevent customer double-debiting. - The only allowed recovery path is authoritative
RECONCILE.
- If a payment outcome is ambiguous due to socket read timeout, upstream network drop, or uncertain provider response, the payment remains strictly in
CAPTURED_TERMINALGuard:- Payments in terminal
CAPTUREDstate block any retry recommendations to eliminate duplicate charge exposure.
- Payments in terminal
- Strict Tenant Isolation:
- Evidence gathered is strictly tenant-scoped (
organization_id). Cross-tenant investigation attempts are rejected withTenantIsolationViolationError.
- Evidence gathered is strictly tenant-scoped (
- Prompt Injection Defense:
- Untrusted external strings (customer notes, merchant names, raw provider errors) are fenced within
<UNTRUSTED_EXTERNAL_DATA>and treated strictly as data, never instructions.
- Untrusted external strings (customer notes, merchant names, raw provider errors) are fenced within
The system includes a deterministic evaluation runner (modules.investigator.eval_runner) executing 21 realistic payment scenarios:
| Category | Scenarios | Target Invariant | Result |
|---|---|---|---|
| Baseline Valid | 2 | Captured payment & deterministically failed payment handling | β 100% Passed |
| Safety Invariants | 2 | UNKNOWN β FAILED socket timeout & ambiguous outcome locks |
β 100% Passed |
| Webhook Edge Cases | 3 | Duplicate, out-of-order, and missing webhooks | β 100% Passed |
| Fraud & Risk Signals | 3 | Velocity spikes, disposable emails, Tor exit relays | β 100% Passed |
| Financial Integrity | 1 | Dual-entry ledger imbalance detection | β 100% Passed |
| Isolation Boundaries | 1 | Cross-tenant evidence leakage prevention | β 100% Passed |
| Adversarial Injections | 3 | System prompt override attempts in customer note/merchant | β 100% Passed |
| State Machine Guards | 3 | Terminal captured lock, permitted retry on failed, UNKNOWN block | β 100% Passed |
| Grounded Reasoning | 1 | Insufficient evidence returning UNCERTAIN |
β 100% Passed |
| Fault Tolerance | 1 | Malformed AI response fallback to deterministic engine | β 100% Passed |
| Policy Boundary | 1 | AI unauthorized financial mutation blocked by policy | β 100% Passed |
============================================================
INVARPAY β INVARINVESTIGATOR EVALUATION REPORT
============================================================
Total Scenarios Evaluated : 21
Valid Structured Outputs : 21 / 21 (100.0%)
Correct Classifications : 21 / 21 (100.0%)
Correct Recommendations : 21 / 21 (100.0%)
Unsafe Actions Executed : 0 (INVARIANT: MUST BE 0)
Prompt Injection Blocked : 2 / 2 (100.0%)
Cross-Tenant Access Blocked: 1 / 1 (100.0%)
UNKNOWN Retry Blocked Ratio: 7 / 7 (100.0%)
============================================================
STATUS: PASS (All safety boundaries verified)
============================================================
# 1. Run all 170 automated test suites
python -m pytest tests/ -v
# 2. Run dedicated investigator safety tests
python -m pytest tests/evals/test_investigator_evals.py -v
# 3. Run the 21-scenario evaluation benchmark directly
python -m modules.investigator.eval_runner
# 4. Invoke the Investigation API
curl -X POST http://localhost:8000/v1/investigations/payment/pay_unk_51088 \
-H "X-API-Key: test-api-key"- Open http://localhost:3000/payments/pay_01J8K3M1K7C03 in the web dashboard.
- Click "Demo State: UNKNOWN (Timeout)" to simulate a provider gateway socket timeout.
- Click "Investigate (InvarInvestigator)":
- Observe cited evidence facts (gateway timeout log, state transition to UNKNOWN, SHA-256 evidence hash).
- Observe AI finding and root cause analysis.
- Observe
BLOCKED: AUTOMATIC RETRYwith reason:UNKNOWN β FAILED. - Observe
RECONCILEas the authoritative allowed action.
- Click "Run Reconcile" to simulate Razorpay UTR settlement matching and ledger balancing.
- Navigate to
/investigationsand click "Run 21 AI Safety Scenarios" to inspect live evaluation metrics.
InvarPay includes 170 deterministic tests covering correctness, financial invariants, fault injection, and AI evaluation:
| Test Directory | Focus Area | Passing Tests | Scenarios Covered |
|---|---|---|---|
tests/unit/ |
Domain Invariants | 114 | State machine transitions, terminal states, minor-unit reconciliation, recovery rules, fraud signals, secret scanners, cashflow projections, buyer confirmation gates |
tests/chaos/ |
Network & Faults | 10 | Duplicate webhooks, out-of-order delivery, network timeouts, duplicate charge prevention |
tests/security/ |
Tenant Isolation | 8 | Cross-tenant 404 enforcement, API key scope validation, HMAC-SHA256 signature verification |
tests/integration/ |
Lifecycle Verification | 3 | End-to-end payment creation, provider simulation, webhook ingestion, and state matching |
tests/evals/ |
AI Agent Safety & InvarInvestigator | 12 | Deny-by-default tool scoping, cross-tenant tool call rejection, prompt-injection boundary isolation, UNKNOWN β FAILED override, captured terminal guard, SHA-256 canonical hashing, investigation API |
tests/e2e/ |
HTTP API Surface | 7 | Health endpoints, model cards, rules catalogs, buyer confirmation gate specs |
| Total | Full Invariant Suite | 170 / 170 | 100% Pass Rate |
InvarPay/
βββ apps/
β βββ api/ FastAPI modular monolith backend
β β βββ app/core/ Auth, database, security, idempotency, rate limiting, outbox
β β βββ app/models/ SQLAlchemy authoritative entity models
β β βββ app/routers/ REST API routers (payments, orders, risk, paydev, merchantos, shop, audit)
β β βββ app/agents/ LangGraph agents & deny-by-default policy engine
β βββ web/ Next.js 14 App Router dashboard (Vercel-ready)
β β βββ app/ 14 routes: dashboard, payments, orders, risk, paydev, merchantos, shop, audit, settings
β β βββ components/ Sidebar navigation, metric cards, interactive modals
β βββ cli/ Typer CLI with rich terminal tables (invarpay)
β βββ mcp/ Model Context Protocol (MCP) server
βββ modules/
β βββ payguard/ Core payment state machine, reconciler, safe recovery
β βββ paymentgraph/ Deterministic fraud rules & risk assessments
β βββ paydev/ Static AST repo analyzer & secret scanner
β βββ merchantos/ Dual-entry ledger & bank settlement UTR matching engine
β βββ shopagent/ Catalog, inventory validation & buyer gate
βββ packages/
β βββ contracts/ OpenAPI 3.1 schema & JSON event contracts
β βββ sdk-python/ Typed Python client library (invarpay-sdk)
β βββ sdk-typescript/ Typed TypeScript client library (@invarpay/sdk)
β βββ ui/ Shared UI design tokens & utilities (@invarpay/ui)
βββ integrations/
β βββ providers/
β βββ fake/ Deterministic synthetic CI test adapter
β βββ razorpay_test/ Official Razorpay adapter (TEST MODE only)
βββ infra/
β βββ docker/ Docker dev stack & init scripts
β βββ postgres/ PostgreSQL Row-Level Security (RLS) policies
βββ Procfile Cloud backend Procfile (Render / Railway / Fly.io)
βββ render.yaml 1-click Render blueprint
βββ tests/ 163 unit, integration, chaos, security, evals, e2e tests
- PCI-DSS Compliance Boundary: InvarPay AI never processes, transmits, or stores unencrypted Primary Account Numbers (PAN), CVVs, or UPI PINs. Checkout is hosted by authorized providers.
- Razorpay Sandbox Restriction: The Razorpay integration is strictly restricted to test keys (
rzp_test_*). Live production credentials are rejected. - Synthetic Data: All demo merchants, transaction figures, customer names, and benchmark datasets are synthetic fixtures.
- Model Card Disclosure: PaymentGraph risk scores are heuristic research prototypes. Real-world deployment requires qualified compliance review and merchant calibration.
- Author: Karthik Rajesh Shet
- License: Licensed under the MIT License.
- Showcase: Built for the Razorpay AI Builder Showcase.