Skip to content
Samuel1505Public

About

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

RAVEN Finance

An autonomous AI agent that underwrites, tokenizes, and manages African SME invoices as yield-bearing RWAs on Mantle — turning unpaid B2B invoices into investable on-chain assets.

Real-World Asset Financing for African SMEs, Powered by Autonomous AI on Mantle Network

RAVEN is a full-stack DeFi protocol that transforms African SME trade receivables (B2B invoices) into yield-bearing, on-chain RWA tokens. An autonomous AI agent — powered by Claude — handles the entire underwriting lifecycle: document verification, risk scoring, portfolio monitoring, and default detection. Built for the Mantle Turing Test Hackathon 2026 (AI × RWA Track).


Hackathon Submission

Question Answer
What type of real-world asset are you bringing on-chain? B2B trade receivables (SME invoices) from African emerging markets
How does AI play a role? AI autonomously underwrites each invoice, scores buyer creditworthiness, monitors repayment behavior, and rebalances investor portfolios — replacing the entire traditional credit analyst function
How is it realized on Mantle? Verified receivables are minted as yield-bearing ERC-1155 RWA tokens on Mantle; idle capital earns yield via mETH/USDY; secondary trading via Merchant Moe; every AI decision permanently recorded on-chain

Problem Statement

African SMEs generate over $1.5 trillion in legitimate invoices owed by large, creditworthy corporations every year. These invoices are real, verifiable obligations — but they sit unpaid for 60 to 120 days, destroying cash flow for small businesses that cannot afford to wait.

Traditional invoice financing is effectively out of reach:

  • Banks require hard collateral — land, vehicles, machinery — not paper receivables
  • Manual underwriting is slow and expensive — credit analysts cost money; decisions take weeks
  • No liquidity rails exist — verified invoices cannot be traded, fractionalized, or used as on-chain collateral
  • Zero transparency — every lending decision is a black box with no audit trail for regulators

The result: legitimate, credit-worthy businesses go without capital while their invoices gather dust.


Solution

RAVEN creates an end-to-end pipeline that:

  1. Tokenizes invoices as ERC-1155 RWA tokens on Mantle Network, making them fractional and tradeable
  2. Deploys an autonomous AI agent (Claude Sonnet 4.6) to verify, score, and price each invoice in under 2 minutes
  3. Opens investor pools so DeFi participants can fund invoices and earn 12–18% APR
  4. Routes idle capital to Agni Finance for additional yield while awaiting repayment
  5. Logs every AI decision immutably on-chain (with full reasoning stored on IPFS) for regulatory compliance
SME uploads invoice
        ↓
AI verifies (CAC registry, Nansen analytics, Claude reasoning)
        ↓
Invoice minted as ERC-1155 RWA token on Mantle
        ↓
Investors fund pool → SME receives liquidity
        ↓
Corporate pays invoice → Yield distributed to investors
        ↓
All decisions logged immutably on-chain

Value Propositions

Stakeholder Value
African SMEs Access liquidity in hours, not 60–120 days, without collateral
DeFi Investors Earn 12–18% APR on verified emerging-market yield with AI-managed risk
Regulators Immutable on-chain audit trail of every AI decision, verifiable forever

How It Works

For SMEs (Sellers)

An SME uploads their invoice PDF and fills in basic details (company RC number, debtor name, face value, due date). The AI agent autonomously:

  • Verifies the SME against Nigeria's Corporate Affairs Commission (CAC) registry
  • Analyzes the corporate debtor's on-chain profile via Nansen
  • Reasons over all inputs using Claude to produce a risk score (0–100), a decision (APPROVE / REJECT / MANUAL_REVIEW), and an APR-based discount rate
  • Mints an ERC-1155 token on Mantle representing the invoice as a real-world asset
  • Opens an investor funding pool for 7 days
  • Stores the complete AI reasoning report on IPFS; logs a hash on-chain

When the pool is fully funded, the SME receives the face value minus a small discount fee (the APR translated to the invoice tenor). When the corporate pays, investors are repaid with yield.

For Investors

Investors browse live invoice pools on the frontend. Each pool displays the AI risk score, discount rate (APR), funding progress, debtor details, and a link to the full on-chain reasoning. Investors deposit USDT into the EscrowVault, which immediately routes capital to Agni Finance to earn additional yield while the pool is active. When a corporate repays the invoice, investors claim their proportional share of principal plus yield.

For Compliance

Every AI action — underwriting decision, monitoring alert, default flag — is logged to the AuditLog contract on Mantle. Each entry contains the decision type, the AI agent's wallet address, a timestamp, and a SHA-256 hash of the full reasoning report on IPFS. This creates a permanent, tamper-proof audit trail any regulator can inspect.


Architecture

┌─────────────────────────────────────────────────────────────────┐
│                        RAVEN PROTOCOL                           │
│                                                                  │
│  ┌───────────────┐    ┌──────────────────┐    ┌─────────────┐  │
│  │   Next.js     │    │   AI Engine      │    │   Mantle    │  │
│  │   Frontend    │◄──►│   (FastAPI)      │◄──►│   Network   │  │
│  │   (React)     │    │   Python 3.11    │    │   (EVM)     │  │
│  └───────────────┘    └──────────────────┘    └─────────────┘  │
│         │                      │                      │         │
│    RainbowKit              Claude API           Smart Contracts │
│    Wagmi / viem            Anthropic SDK        ERC-1155 RWA   │
│    Mantle Sepolia          ───────────          ─────────────  │
│                            Underwriter          RAVENCore       │
│                            Monitor              InvoiceToken    │
│                            Rebalancer           InvoicePool     │
│                                │                EscrowVault     │
│                           ─────────────        AuditLog         │
│                           External APIs         KYCRegistry     │
│                           CAC Registry          PaymentOracle   │
│                           Nansen Analytics       ─────────────  │
│                           Pinata IPFS            Agni Finance   │
│                                                  (Yield)        │
└─────────────────────────────────────────────────────────────────┘

Component Roles

Component Role
Next.js Frontend SME submission UI, investor pool browser, real-time AI monitor feed, admin audit log
AI Engine (FastAPI) Autonomous underwriting, portfolio monitoring every 5 minutes, rebalancing signals
RAVENCore.sol Orchestrator — coordinates tokenization, pool creation, disbursement, repayment
InvoiceToken.sol ERC-1155 RWA token — mints fractional invoice tokens with on-chain metadata
InvoicePool.sol Investor pool — manages funding windows, deadlines, pool state
EscrowVault.sol Capital management — holds USDT, routes to Agni Finance, disburses yield
AuditLog.sol Immutable on-chain audit trail — every AI decision, permanent on Mantle
KYCRegistry.sol On-chain KYC/AML tracking — required before invoice tokenization
AgniYieldAdapter.sol Routes idle investor capital to Agni Finance for yield while pools are active

Smart Contracts

All contracts are deployed on Mantle Sepolia Testnet (chainId 5003), written in Solidity ^0.8.20, using OpenZeppelin v5.6.1.

RAVENCore.sol

The master orchestrator. Coordinates the full invoice lifecycle and enforces role-based access control.

Roles:

  • AI_AGENT_ROLE — underwriting and monitoring functions
  • ORACLE_ROLE — status updates and repayment confirmation
  • MANAGER_ROLE — pool disbursement to SME

Key functions:

Function Description
submitInvoice() Called by AI agent after approval; mints RWA token and creates investor pool
disburseFundedPool() When pool reaches target, disburses USDT to SME (minus discount fee)
processRepayment() Records corporate repayment and signals investor distribution
logMonitoringDecision() AI logs monitoring events on-chain
flagDefault() AI marks invoice as defaulted if overdue

InvoiceToken.sol

ERC-1155 RWA token. Each token ID represents one invoice; investors hold fractional amounts.

On-chain metadata per token:

struct InvoiceMetadata {
    address smeBeneficiary;      // SME wallet receiving liquidity
    address corporateDebtor;     // Company that owes the invoice
    uint256 faceValue;           // Invoice value in USDT (6 decimals)
    uint256 discountRate;        // APR in basis points (e.g. 1500 = 15%)
    uint256 maturityTimestamp;   // When invoice is due
    uint8   riskScore;           // AI-generated score, 0–100
    string  ipfsMetadataURI;     // Link to full AI report on IPFS
    InvoiceStatus status;        // Active | Funded | Repaid | Defaulted | Liquidated
    uint256 pooledAmount;        // Total USDT raised
    uint256 mintTimestamp;       // Block timestamp of minting
}

Key functions:

Function Description
mintInvoiceToken() Creates a new token with metadata (AI_AGENT_ROLE only)
logAIDecision() Logs underwriting or monitoring reasoning on-chain
updateStatus() Changes invoice status (ORACLE_ROLE only)
getInvoice() Reads full metadata for a token ID

InvoicePool.sol

Manages the investor fundraising pool for each invoice. Sets a 7-day funding window; if the target is not reached, the pool expires and investors can withdraw.

Pool state per invoice:

struct PoolInfo {
    uint256 fundingTarget;    // Total USDT needed
    uint256 deadline;         // Unix timestamp when pool closes
    uint256 totalFunded;      // Amount raised so far
    bool    active;           // Accepting new investments
    bool    fullyFunded;      // Reached target
}

Key functions:

Function Description
createPool() Called by RAVENCore after invoice approval
joinPool() Investor deposits USDT; funds routed to EscrowVault
expirePool() Closes pool if deadline passed without full funding

EscrowVault.sol

Holds investor USDT, routes idle capital to Agni Finance for yield, and distributes repayment.

Yield flow:

  1. Investor deposits USDT → EscrowVault holds it
  2. EscrowVault immediately deposits to Agni Finance → earns yield
  3. When pool is fully funded, EscrowVault withdraws from Agni and pays the SME (keeping yield)
  4. When corporate repays, investors claim: principal + proportional share of (discount fee + Agni yield)

Key functions:

Function Description
depositFor() Called by InvoicePool; records investor deposit and routes to Agni
disburseToSME() Withdraws from Agni, deducts discount fee, pays SME
distributeRepayment() Records corporate repayment for investor claims
claimRepayment() Investor withdraws proportional principal + yield
getInvestorPosition() Returns investor's deposit and estimated payout

AuditLog.sol

Append-only compliance log. Every AI decision is written here permanently.

Entry structure:

struct LogEntry {
    uint256 tokenId;
    string  category;    // "KYC" | "UNDERWRITE" | "MONITOR" | "COMPLIANCE"
    string  action;      // e.g. "INVOICE_TOKENIZED" | "DEFAULT_FLAGGED"
    string  dataHash;    // SHA-256 of full AI report on IPFS
    address actor;       // AI agent wallet address
    uint256 timestamp;   // block.timestamp
}

KYCRegistry.sol

On-chain KYC/AML status tracking. RAVENCore.submitInvoice() checks KYC approval before minting.

Statuses: Pending → Approved / Rejected / Revoked

AgniYieldAdapter.sol

Adapter for Agni Finance (Mantle's primary liquidity protocol). Routes USDT deposits and withdrawals; returns LP tokens that accrue yield automatically.

PaymentOracle.sol

Off-chain oracle that confirms when a corporate debtor has paid their invoice. Triggers RAVENCore.processRepayment() to begin investor distributions.


AI Engine

Located in ai-engine/. A FastAPI application running three autonomous agents concurrently.

Underwriting Agent (agents/underwriter.py)

Evaluates every new invoice submission end-to-end without human intervention.

Pipeline:

1. CAC Registry Check       → Verify SME is legitimately registered in Nigeria
2. Nansen Analytics         → Query corporate debtor's on-chain wallet profile
3. PDF Text Extraction      → Parse invoice document via PyPDF2
4. Claude API (Sonnet 4.6)  → Reason over all inputs; produce risk score + decision
5. IPFS Upload              → Store full reasoning report on Pinata
6. On-Chain Submission      → Call RAVENCore.submitInvoice() to mint ERC-1155 token

Claude outputs:

  • risk_score (0–100, where 100 is safest)
  • decision — APPROVE / REJECT / MANUAL_REVIEW
  • discount_rate_bps — APR in basis points (1000–2000 range, i.e. 10–20%)
  • risk_factors and mitigating_factors — human-readable lists
  • compliance_flags — shell company warnings, jurisdiction flags, unusual amounts
  • confidence — 0.0 to 1.0

Monitoring Agent (agents/monitor.py)

Runs every 5 minutes. Watches the entire portfolio for distress signals.

Pipeline:

1. Fetch all Active invoices from InvoiceToken contract
2. Enrich each debtor wallet via Nansen (transaction activity, labels)
3. Build portfolio snapshot JSON
4. Claude API → pattern recognition, alert generation
5. Log HIGH/CRITICAL alerts to AuditLog contract on-chain
6. Cache result for REST API polling

Alert severity levels:

Severity Trigger
CRITICAL Invoice overdue >7 days
HIGH Overdue <7 days, or maturity within 3 days
MEDIUM Maturity within 7 days + below-average risk score
LOW Near repayment, healthy status

If >30% of portfolio triggers HIGH or CRITICAL alerts, the agent sets rebalance_needed: true.

Rebalancer Agent (agents/rebalancer.py)

Responds to rebalance_needed signals. Analyzes portfolio concentration and proposes capital shifts from high-risk to lower-risk invoices. Reports recommendations to RAVENCore.

Service Clients

Client Purpose
ClaudeClient Anthropic SDK wrapper; supports demo mode with mock responses
MantleClient web3.py async client for Mantle Sepolia read/write operations
CACClient Nigerian Corporate Affairs Commission registry lookup
NansenClient On-chain analytics for debtor wallet profiling
IPFSClient Pinata API for pinning AI reasoning reports

REST API Endpoints

Method Path Description
POST /api/underwrite Submit invoice PDF + metadata; returns full RiskReport
GET /api/portfolio/status Latest portfolio monitoring snapshot
POST /api/portfolio/refresh Trigger a new monitoring cycle
GET /api/portfolio/alerts/{token_id} On-chain audit entries for a specific token
GET /api/pools List all invoice tokens with pool info
GET /api/pools/{token_id} Detailed pool info + audit trail
POST /api/portfolio/rebalance Trigger rebalancing agent
GET /api/audit Total on-chain audit log entry count
GET /api/kyc/{address} Check KYC approval status for an address
GET /health Health check

Frontend

Located in web/. A Next.js 16 app with App Router, TypeScript, Tailwind CSS 4, Wagmi, and RainbowKit.

Pages

Route Description
/ Landing page — product overview, stats, how it works
/submit SME invoice submission with PDF upload and AI result display
/dashboard SME's submitted invoices and their on-chain status
/pools Investor pool browser — all active invoice pools with risk scores and APR
/pools/[id] Pool detail page — full AI report, audit trail, investment form
/portfolio Investor's active positions, estimated yield, repayment history
/audit Admin audit log — all on-chain AI decisions, sortable and filterable

Key Components

Invoice Submission

  • InvoiceUploadForm — PDF drag-and-drop, structured form, submit to AI engine
  • RiskScoreCard — Displays risk score (color-coded 0–100), decision badge, APR, pool cap
  • AIReasoningPanel — Risk factors, mitigating factors, Claude reasoning text, confidence

Pool Browsing

  • PoolCard — Compact summary: debtor, APR, funding progress bar, risk score badge
  • PoolDetail — Full audit trail, IPFS reasoning link, investment form
  • InvestmentForm — USDT approval + deposit flow with transaction status

Portfolio

  • PortfolioStats — Total invested, estimated yield, number of positions
  • AIMonitorFeed — Live polling of monitoring agent; displays health score, alert feed, last update time

Web3 Configuration

The frontend connects exclusively to Mantle Sepolia Testnet (chainId 5003) via RainbowKit + Wagmi. Contract hooks (useInvoiceToken, useEscrowVault, useAuditLog) abstract all on-chain reads and writes. USDT approval + EscrowVault.deposit() are the primary write operations for investors.


User Flows

SME: Submitting an Invoice

1. Visit /submit → Connect wallet (MetaMask / WalletConnect)
2. Fill form: SME name, RC number, debtor name, face value, dates, industry
3. Upload invoice PDF
4. Click "Submit for AI Underwriting"
5. AI agent underwrites in <2 minutes:
   - CAC registry check
   - Nansen debtor profile (if wallet provided)
   - Claude risk scoring + reasoning
6. View results: Risk Score, Decision, Discount Rate (APR), Risk Factors
7. If APPROVED → Invoice is now tokenized on Mantle
8. Receive USDT when investor pool is fully funded (face value minus discount fee)
9. Corporate debtor pays invoice → pool lifecycle complete

Investor: Funding a Pool

1. Visit /pools → Browse active invoice pools
2. Filter by risk score, APR, industry, funding progress
3. Click a pool → Read full AI report and audit trail
4. Connect wallet → Enter USDT amount
5. Approve USDT spending (ERC-20 approve, one-time)
6. Click "Invest" → Confirm transaction
7. Capital immediately routed to Agni Finance (earning yield while waiting)
8. Monitor position at /portfolio
9. When corporate repays → claim principal + proportional yield
   e.g. $1,000 USDT invested → ~$1,036 returned (14.5% APR, 90-day tenor)

Compliance Officer: Auditing Decisions

1. Visit /audit → View full on-chain audit log
2. Filter by invoice ID, category (UNDERWRITE / MONITOR / COMPLIANCE), date
3. Click any entry → View:
   - Decision type and action
   - AI agent wallet address
   - Block timestamp
   - SHA-256 hash of full AI report
4. Click hash → Load full AI report from IPFS:
   - CAC verification result
   - Nansen on-chain profile
   - Claude reasoning text
   - Risk factors and compliance flags
   - Confidence score
5. All entries are immutable and permanently on Mantle

Continuous: AI Portfolio Monitoring

Every 5 minutes, MonitoringAgent:
1. Fetches all Active invoices from InvoiceToken contract
2. Enriches each with Nansen debtor wallet data
3. Sends portfolio snapshot to Claude
4. Claude returns: health score, alerts, rebalance signal
5. HIGH/CRITICAL alerts logged to AuditLog on-chain
6. Frontend /audit shows new monitoring entries in real time
7. Investor /portfolio shows live AIMonitorFeed widget

Tech Stack

Smart Contracts

Component Technology
Language Solidity ^0.8.20
Framework Hardhat 2.28.6
Standard Library OpenZeppelin 5.6.1
Token Standard ERC-1155
Network Mantle Sepolia (chainId 5003)
Testing Hardhat + Chai (TypeScript)

AI Engine

Component Technology
Runtime Python 3.11+
Package Manager uv
Framework FastAPI
Server uvicorn (async ASGI)
AI Model Claude Sonnet 4.6 (Anthropic API)
Web3 web3.py (async)
PDF Parsing PyPDF2
IPFS Pinata API
Scheduler APScheduler
HTTP httpx (async)
Validation Pydantic

Frontend

Component Technology
Framework Next.js 16.2.6 (App Router)
Runtime React 19.2.4
Language TypeScript 5
Styling Tailwind CSS 4
Wallet RainbowKit 2.2.11
Web3 Hooks Wagmi 2.19.5
Chain Library viem 2.49.2
State TanStack React Query
Charts Recharts 3.8.1
Icons Lucide React
File Upload react-dropzone
HTTP Client axios

Deployed Contracts

Network: Mantle Sepolia Testnet (chainId 5003)

Contract Address
USDT (Mock) 0xD6350c5757aC2196b80072F8500ebB790E12F06E
Agni Finance 0x4fe65F688602aE0014DE7988ADe000EC255516BA
AuditLog 0x14ADF21C44a4a61071D34C63D4DE4ef6467EFd56
KYCRegistry 0x7B7B074AD9E313468c33Cd583452a018Aaf96D87
InvoiceToken 0x22d9f707F3BB1F1cf000E01bBdF096cB34E0cD65
EscrowVault 0xCEA06Bf729c7FE40D6D2Ee7377A1ff3695972342
InvoicePool 0xdFC10eD57672f94e5E56A13e9f9ba1B1CB3e0170
RAVENCore 0x789A3B92fEA887fDbF476d6Bc0f1288CcD6352F2
PaymentOracle 0xCA8286c531D6d516819cAfdd7cbD6E8380B29Ab7

All contracts are verified on Mantle Sepolia Explorer.


Local Setup

Prerequisites

  • Node.js 20+
  • Python 3.11+
  • pnpm (frontend)
  • uv (AI engine — pip install uv)
  • MetaMask configured for Mantle Sepolia

1. Clone and Install

git clone https://github.com/your-org/raven.git
cd raven

2. Smart Contracts

cd smartcontract
npm install

# Run tests
npx hardhat test

# Run coverage
npx hardhat coverage

# Deploy to Mantle Sepolia (requires DEPLOYER_PRIVATE_KEY in .env)
npx hardhat run scripts/deploy.ts --network mantleTestnet

3. AI Engine

cd ai-engine
uv sync

# Copy and fill environment variables
cp ../.env.example .env

# Start the AI engine
uv run uvicorn main:app --reload --port 8000

Health check: GET http://localhost:8000/health

4. Frontend

cd web
pnpm install

# Copy and fill environment variables
cp .env.example .env.local

# Start development server
pnpm dev

App runs at http://localhost:3000.


Environment Variables

Root / AI Engine (.env)

# Blockchain
MANTLE_TESTNET_RPC=https://rpc.sepolia.mantle.xyz
DEPLOYER_PRIVATE_KEY=0x...           # AI agent wallet private key

# AI
ANTHROPIC_API_KEY=sk-ant-...         # Claude API key
CLAUDE_DEMO_MODE=false               # Set to true for mock responses (no API key needed)

# Data Providers (optional — stubbed if missing)
NANSEN_API_KEY=...                   # Nansen on-chain analytics
PINATA_JWT=...                       # IPFS pinning via Pinata
PINATA_GATEWAY=your-gateway.mypinata.cloud

Frontend (web/.env.local)

NEXT_PUBLIC_MANTLE_CHAIN_ID=5003
NEXT_PUBLIC_INVOICE_TOKEN_ADDRESS=0x22d9f707F3BB1F1cf000E01bBdF096cB34E0cD65
NEXT_PUBLIC_ESCROW_VAULT_ADDRESS=0xCEA06Bf729c7FE40D6D2Ee7377A1ff3695972342
NEXT_PUBLIC_AUDIT_LOG_ADDRESS=0x14ADF21C44a4a61071D34C63D4DE4ef6467EFd56
NEXT_PUBLIC_RAVEN_CORE_ADDRESS=0x789A3B92fEA887fDbF476d6Bc0f1288CcD6352F2
NEXT_PUBLIC_AI_ENGINE_URL=http://localhost:8000
NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID=...

Setting CLAUDE_DEMO_MODE=true runs the AI engine with realistic mock responses — useful for UI development without a Claude API key.


Project Structure

raven/
├── RAVEN_BUILD_GUIDE.md           # Detailed build specification
├── deployedAddresses.json         # Live contract addresses on Mantle Sepolia
├── render.yaml                    # Render.com deployment config for AI engine
│
├── smartcontract/                 # Solidity smart contracts
│   ├── contracts/
│   │   ├── core/
│   │   │   ├── RAVENCore.sol      # Orchestrator — invoice lifecycle
│   │   │   ├── InvoiceToken.sol   # ERC-1155 RWA token
│   │   │   ├── InvoicePool.sol    # Investor funding pool
│   │   │   └── EscrowVault.sol    # Capital management + yield routing
│   │   ├── compliance/
│   │   │   ├── KYCRegistry.sol    # On-chain KYC status
│   │   │   └── AuditLog.sol       # Immutable AI decision log
│   │   ├── integrations/
│   │   │   ├── AgniYieldAdapter.sol     # Agni Finance yield routing
│   │   │   └── MerchantMoeAdapter.sol   # Secondary market (stub)
│   │   ├── oracle/
│   │   │   └── PaymentOracle.sol  # Corporate repayment confirmation
│   │   ├── interfaces/
│   │   │   ├── IInvoiceToken.sol
│   │   │   ├── IInvoicePool.sol
│   │   │   └── IAgniFinance.sol
│   │   └── mocks/
│   │       ├── MockUSDT.sol
│   │       └── MockAgniFinance.sol
│   ├── test/                      # Hardhat + Chai test suite (67 tests)
│   │   ├── InvoiceToken.test.ts
│   │   ├── InvoicePool.test.ts
│   │   ├── EscrowVault.test.ts
│   │   ├── AuditLog.test.ts
│   │   ├── RAVENCore.test.ts
│   │   └── KYCRegistry.test.ts
│   └── scripts/
│       └── deploy.ts
│
├── ai-engine/                     # Python FastAPI autonomous agents
│   ├── main.py                    # FastAPI app + agent startup
│   ├── Dockerfile
│   ├── agents/
│   │   ├── underwriter.py         # Invoice underwriting agent
│   │   ├── monitor.py             # Portfolio monitoring agent (5-min cycles)
│   │   └── rebalancer.py          # Pool rebalancing agent
│   ├── services/
│   │   ├── claude_client.py       # Anthropic API wrapper
│   │   ├── mantle_client.py       # web3.py Mantle Sepolia client
│   │   ├── cac_client.py          # Nigerian CAC registry
│   │   ├── nansen_client.py       # On-chain analytics
│   │   ├── ipfs_client.py         # Pinata IPFS uploader
│   │   └── abis.json              # Contract ABIs
│   ├── models/
│   │   ├── invoice.py             # InvoiceSubmission + InvoiceMetadataOnChain
│   │   ├── risk_report.py         # RiskReport + PortfolioStatus + PortfolioAlert
│   │   └── decision.py            # RiskDecision enum
│   └── prompts/
│       ├── underwrite_system.txt  # Claude system prompt for underwriting
│       └── monitor_system.txt     # Claude system prompt for monitoring
│
└── web/                           # Next.js 16 frontend
    └── src/
        ├── app/
        │   ├── page.tsx            # Landing page
        │   ├── (sme)/submit/       # Invoice submission
        │   ├── (sme)/dashboard/    # SME invoice dashboard
        │   ├── (investor)/pools/   # Pool browser
        │   ├── (investor)/portfolio/ # Investor positions
        │   └── (admin)/audit/      # Audit log viewer
        ├── components/
        │   ├── invoice/            # InvoiceUploadForm, RiskScoreCard, AIReasoningPanel
        │   ├── pool/               # PoolCard, PoolDetail, InvestmentForm
        │   ├── portfolio/          # PortfolioStats, AIMonitorFeed
        │   └── web3/               # ConnectWallet
        ├── hooks/                  # useInvoiceToken, useEscrowVault, useAuditLog
        └── lib/                    # wagmi config, contract ABIs, API client

Key Design Decisions

Why ERC-1155 over ERC-721? ERC-1155 supports fractional, multi-token ownership in a single contract. Each token ID represents one invoice, and investors hold fractional amounts — which maps directly to the pool model where multiple investors co-fund a single invoice.

Why Mantle Network? Mantle offers low transaction fees (essential for logging every AI decision on-chain), native integration with Agni Finance for yield generation, and a growing DeFi ecosystem well-suited for RWA protocols.

Why Claude for underwriting? Invoice underwriting requires genuine multi-step reasoning over heterogeneous inputs: regulatory data, on-chain wallet activity, PDF documents, payment history, industry context, and jurisdiction risk. A rule-based system would need to encode thousands of edge cases. Claude reasons over all inputs in a single prompt and produces explainable, auditable decisions.

Why log every AI decision on-chain? Regulatory compliance in financial services requires that every credit decision be attributable, explainable, and permanently recorded. Logging to AuditLog on Mantle makes the AI's behavior verifiable by any regulator, auditor, or counterparty — forever — at near-zero cost per entry.


Built for the Mantle Turing Test Hackathon 2026 — AI × RWA Track

About

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages