Skip to content

About

Build on genlayer

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

ClaimBot

ClaimBot CI GenLayer Next.js PostgreSQL

ClaimBot is a parametric insurance application built on GenLayer. Policyholders purchase coverage, submit evidence from trusted public sources, and receive an AI-assisted claim decision from GenLayer validators. Approved claims trigger an on-chain payout, subject to evidence and treasury-solvency rules.

The repository contains the intelligent contract, a Next.js dashboard, an Express API, PostgreSQL persistence, Docker configuration, deployment scripts, and automated tests.

Current Deployment

Item Value
Network GenLayer Testnet Bradbury
RPC https://rpc-bradbury.genlayer.com
Contract 0x9a37443046001F2563a625f861BC712a8A46F35d
Main contract contracts/claimbot_main.py

This is a testnet deployment. Do not treat testnet balances or decisions as production insurance coverage.

What ClaimBot Does

  • Offers flood, crop-failure, flight-delay, and port-strike policy templates.
  • Separates risk-premium income from underwriting capital in the treasury.
  • Requires two to six evidence URLs when a claim is filed.
  • Scores distinct trusted evidence sources before AI evaluation.
  • Uses GenLayer validators to fetch evidence and evaluate the policy trigger.
  • Automatically pays approved claims when treasury checks pass.
  • Supports cooling-off cancellation and rejected-claim appeals.
  • Exposes treasury solvency, loss-ratio, policy, and claim analytics.
  • Supports a mock-data demo mode for UI development without a chain or database.
  • Uses the connected browser wallet for live purchases, claims, cancellations, and appeals.

How It Works

  1. The treasury receives underwriting capital through fund_treasury.
  2. A user connects an EVM-compatible browser wallet.
  3. The user selects a policy template, coverage area, amount, and expiry.
  4. The wallet signs purchase_policy and pays the exact calculated premium.
  5. The contract accepts the policy only when its full coverage amount passes the current liquidity, concentration, and post-payout reserve checks.
  6. The frontend records the submitted transaction in PostgreSQL for dashboard queries.
  7. After the cooling-off period, the policyholder files a claim with trusted evidence URLs.
  8. Validators fetch the evidence, run an LLM assessment, and compare results through GenLayer's Equivalence Principle.
  9. The contract approves a payout only when the event is confirmed, confidence is sufficient, no red flags are returned, the evidence score is at least 70, and the treasury remains solvent.
flowchart LR
    U[User wallet] --> F[Next.js frontend]
    F -->|Signed writes| C[ClaimBot contract]
    F -->|Record and query data| A[Express API]
    A --> D[(PostgreSQL)]
    A -->|Contract views| C
    C -->|Fetch evidence| W[Trusted web sources]
    C --> V[GenLayer validators and LLMs]
    C -->|Approved payout| U
Loading

Policy Products

Template ID Product Base premium Expected evidence
flood-ng Nigeria flood insurance 2.0% Government, weather, news
crop-failure Crop failure insurance 3.0% Satellite, weather, government
flight-delay Flight delay insurance 1.5% Logistics, news
port-strike Cargo and port-strike insurance 2.5% Logistics, news, government

Premium And Capital Model

The seeded percentages are risk premiums, not full collateral deposits. Policy premiums are split into the payout pool, emergency reserve, and DAO fee, while fund_treasury records separate underwriting capital in capital_in.

Before a policy is stored, the contract simulates paying its full coverage amount. Issuance is rejected unless:

  • The payout pool contains the full coverage amount.
  • The coverage is no more than 10% of the payout pool.
  • The pool remaining after payout covers 20% of the remaining active exposure.
  • The policy's exposure can be released without an accounting underflow.

Initial claims and appeals use this same check and the same settlement helper. An appeal approved by validators remains rejected if the treasury cannot safely pay it.

Evidence Scoring

Only trusted domains are scored. Repeated URLs from the same domain do not increase the score.

Source type Points
Government 35
Satellite 25
Logistics 25
Weather 20
News 20

The minimum score for a payout decision is 70. The contract, not the frontend preview, is authoritative.

Architecture

Intelligent Contract

contracts/claimbot_main.py is the deployable GenLayer contract. It stores policies, claims, wallet indexes, treasury state, and governance proposals as schema-compatible contract storage.

Public write methods:

  • fund_treasury
  • purchase_policy
  • file_claim
  • appeal_claim
  • cancel_policy
  • submit_governance_proposal
  • vote_proposal
  • execute_proposal

Public view methods:

  • get_policy
  • get_claim
  • get_wallet_policies
  • get_wallet_claims
  • get_treasury
  • get_global_stats
  • list_templates
  • is_claimable
  • get_proposal
  • list_proposals
  • get_governance_config

The contract pins its py-genlayer runner dependency in the source header.

Frontend

The frontend is a Next.js 15 and React 19 application. It provides:

  • Landing page and dashboard routes.
  • Browser-wallet connection and Bradbury network switching.
  • Policy purchase and cancellation.
  • Claim submission, status polling, and appeals.
  • Treasury and protocol analytics views.

Live writes go directly from the browser wallet to GenLayer. No private key is stored in the frontend.

Backend

The Express API:

  • Serves demo data when DEMO_MODE=true.
  • Reads contract state in live mode.
  • Stores client-signed policy and claim transaction metadata.
  • Serves PostgreSQL-backed dashboard queries.
  • Exposes health and Bradbury configuration status.

PostgreSQL is optional in demo mode. It is required for the complete live-mode recording flow.

Repository Layout

.
|-- contracts/
|   |-- claimbot_main.py          # deployable GenLayer contract
|   |-- claim_manager.py          # supporting domain module
|   |-- policy_manager.py
|   `-- treasury_manager.py
|-- frontend/
|   |-- src/app/                  # Next.js routes
|   |-- src/components/           # landing page and dashboard UI
|   |-- src/hooks/                # wallet, data loading, and polling
|   `-- src/services/             # REST and browser-wallet clients
|-- backend/
|   |-- src/routes/               # Express REST endpoints
|   |-- src/services/             # demo and Bradbury clients
|   |-- src/db/                   # PostgreSQL pool and migration runner
|   `-- schema.sql
|-- scripts/
|   |-- check_genlayer_schema.py  # static Studio/schema guard
|   `-- deploy_bradbury.mjs       # deploy and smoke-test script
|-- deployment/deploy.py          # alternative Python deploy helper
|-- tests/                        # contract and schema tests
|-- .github/workflows/ci.yml
`-- docker-compose.yml

Tech Stack

Layer Technology
Intelligent contract Python, GenLayer
Frontend Next.js 15, React 19, TypeScript, Tailwind CSS
Wallet integration genlayer-js, browser EIP-1193 provider
Backend Node.js 20, Express
Database PostgreSQL 16
Charts and UI Recharts, Framer Motion, Lucide React
Tests Pytest, static schema checks, GitHub Actions
Deployment GenLayer Bradbury, Vercel, Render, Docker

Quick Start

Prerequisites

  • Git
  • Node.js 20 and npm
  • Python 3.12 for contract tests
  • Docker, only if using the included PostgreSQL/full-stack setup
  • MetaMask or another EIP-1193 wallet for live Bradbury transactions

1. Clone the repository

git clone https://github.com/Jerry-Tekh/claimBotApp.git
cd claimBotApp

2. Install application dependencies

npm run install:all

This installs the root development tools and the separate frontend and backend packages.

3. Configure local environment files

cp backend/.env.example backend/.env
cp frontend/.env.example frontend/.env.local

The examples default to DEMO_MODE=true, the local API at port 4000, and the existing Bradbury contract address.

4. Start the application

npm run dev
Service URL
Frontend http://localhost:3000
Dashboard http://localhost:3000/dashboard
Backend http://localhost:4000
Health check http://localhost:4000/health

Runtime Modes

Capability Demo mode Live mode
DEMO_MODE true false
Deployed contract required No Yes
PostgreSQL required No Yes for complete recording
Browser wallet required Optional Required for writes
Policy and claim decisions Mocked GenLayer validators
Suitable for production No Testnet testing only

In live mode, the legacy backend write routes return HTTP 409. The frontend must sign the transaction in the user's wallet and then call the matching record-* endpoint.

Environment Variables

Backend: backend/.env

Variable Required Description
PORT No Express port, default 4000
NODE_ENV Production Use production on hosted deployments
FRONTEND_URL Production Allowed frontend origin for CORS
RUN_MIGRATIONS Docker deploys Runs schema.sql before the server starts
DATABASE_URL Live mode PostgreSQL connection string
GENLAYER_ENDPOINT Live mode Bradbury RPC endpoint
CONTRACT_ADDRESS Live mode Deployed ClaimBot address
DEMO_MODE Yes true for mocks, false for Bradbury
GENLAYER_PRIVATE_KEY No Maintenance/deployment scripts only

PRIVATE_KEY is accepted by some maintenance scripts as a compatibility alias, but GENLAYER_PRIVATE_KEY is the preferred ClaimBot name. Normal user transactions do not require either variable on the backend.

For a hosted PostgreSQL database:

DATABASE_URL=postgresql://USER:PASSWORD@HOST/DATABASE?sslmode=verify-full

Frontend: frontend/.env.local

Variable Required Description
NEXT_PUBLIC_API_URL Yes Express API origin
NEXT_PUBLIC_API_BASE_URL No Supported alias for the API origin
NEXT_PUBLIC_GENLAYER_ENDPOINT Live mode Bradbury RPC endpoint
NEXT_PUBLIC_CONTRACT_ADDRESS Live mode Deployed ClaimBot address

NEXT_PUBLIC_* values are exposed to the browser and baked into a production build. Never place a private key in a frontend environment variable.

Database

Start only PostgreSQL:

docker compose up -d postgres
npm run db:setup

Start the complete Docker stack:

docker compose up --build

The schema creates policy, claim, evidence, payout, treasury, governance, fraud, and monitoring tables plus dashboard views and indexes. Migration statements are idempotent.

API Reference

Public reads

Method Endpoint Description
GET / API metadata
GET /health Runtime and Bradbury configuration status
GET /api/templates Policy templates
GET /api/policies/:wallet Policies owned by a wallet
GET /api/policies/:policyId/detail One policy
GET /api/claims/wallet/:wallet Claims filed by a wallet
GET /api/claims/:claimId One claim
GET /api/claims/:claimId/status Refresh claim status
GET /api/treasury Treasury and solvency data
GET /api/stats Protocol analytics

Demo writes

These routes execute mock/demo-compatible writes and are rejected in live mode:

Method Endpoint
POST /api/policies/purchase
POST /api/policies/cancel
POST /api/claims/submit
POST /api/claims/appeal

Live transaction recording

The browser first submits the signed contract transaction, then records its transaction hash and UI metadata through:

Method Endpoint
POST /api/policies/record-purchase
POST /api/policies/record-cancel
POST /api/claims/record-submit
POST /api/claims/record-appeal

API routes are rate-limited to 100 requests per minute per IP.

Contract Deployment

Bradbury deployment and smoke test

Create an ignored deployment file:

touch contracts/.env.local

Add:

GENLAYER_PRIVATE_KEY=0xYOUR_DEPLOYER_PRIVATE_KEY
GENLAYER_ENDPOINT=https://rpc-bradbury.genlayer.com

Then run:

npm run contract:check-schema
npm run contract:deploy-bradbury

The deployment script:

  • Loads contracts/claimbot_main.py.
  • Validates the generated contract schema.
  • Deploys with no constructor arguments.
  • Writes public deployment values to .env.bradbury.
  • Funds the underwriting pool for the smoke-test coverage amount.
  • Purchases a small test policy and exercises contract views.
  • Waits for the cooling-off interval, files a test claim, and verifies stats.

The deployer wallet needs Bradbury GEN. The smoke test performs real testnet transactions.

To test an existing deployment instead of creating a new one, add:

CONTRACT_ADDRESS=0xEXISTING_CONTRACT_ADDRESS

GenLayer Studio

Paste the complete contents of contracts/claimbot_main.py into Studio. The constructor takes no arguments, so leave constructor input empty. Run the local schema guard before pasting:

npm run contract:check-schema

Testing

Contract and schema tests:

python -m pytest tests/ -v --tb=short

The suite covers evidence scoring, trusted domains, premiums, solvency, claim decisions, lifecycle rules, abuse controls, appeals, schema compatibility, and migration idempotency. Direct contract tests use all four real policy-template rates and maximum coverage values, successful initial and appeal payouts, insolvent appeals, and duplicate claim IDs.

Additional checks:

npm run contract:check-schema
cd frontend && npm run type-check && npm run build
cd ../backend && npm run check:bradbury

GitHub Actions runs the contract suite, frontend type/build checks, and backend syntax/module checks on pushes and pull requests.

Production Deployment

Frontend on Vercel

  1. Import this repository.
  2. Set the root directory to frontend.
  3. Use the Next.js framework preset.
  4. Add the frontend environment variables.
  5. Redeploy after changing any NEXT_PUBLIC_* value.

Backend on Render

  1. Create a web service from this repository.
  2. Set the root directory to backend.
  3. Deploy with backend/Dockerfile.
  4. Add the backend environment variables.
  5. Set FRONTEND_URL to the exact Vercel origin.
  6. Point DATABASE_URL to PostgreSQL, such as Neon.
  7. Set RUN_MIGRATIONS=true for the initial schema application.

Verify:

GET https://YOUR-BACKEND/health

For live mode, the response should report mode: "live" and contractConfigured: true. signerConfigured: false is expected when no maintenance key is installed.

Security Notes

  • Never commit .env, .env.local, .env.bradbury, or wallet private keys.
  • User-facing live writes must be signed in the user's browser wallet.
  • The backend private key is optional and must be reserved for intentional maintenance tooling.
  • Evidence URLs are untrusted input. The contract limits source count, uses a trusted-domain allowlist, caps fetched content, and instructs validators to ignore embedded instructions.
  • Treasury checks limit liquidity risk, concentration risk, reserve-ratio breaches, and accounting underflow before initial and appeal payouts.
  • Claim IDs are globally unique and rejected before validator execution when a duplicate is submitted.
  • Governance methods exist at contract level, but the current dashboard does not expose a governance interface.

Known Limitations

  • The configured deployment is a public testnet deployment.
  • Claim decisions depend on external web availability and validator consensus.
  • PostgreSQL stores application indexes and submitted transaction metadata; it is not a replacement for contract settlement state.
  • The dashboard polls pending claim status and may take several minutes to reflect validator completion.
  • Dynamic policy-template governance is reserved for a future contract upgrade.

Documentation

About

Build on genlayer

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages