MAFIA AI
  • Intro
  • Getting Started
    • How it Works
    • Features
    • $MAFIA Token
    • Tokenomics
  • Technical
    • System Architecture
    • Roadmap
Powered by GitBook
On this page
  • High Level Components
  • How It Works
  • Internal Components
  • State Management
  • Conversation Flow Examples
  • Workflow Execution
  • User Layer Components
  • Components
  1. Technical

System Architecture

PreviousTokenomicsNextRoadmap

Last updated 18 hours ago

MAFIA (Modular Autonomous Financial Intelligence Agent) is a multi-agent system orchestrated by the AgentController, which delegates tasks to specialized subagents.

High Level Components

Agent Controller (Orchestrator): Classifies intent and routes control of flow to to specific subagent for processing.

SubAgents: Each subagent is a specialist in a a given domain, typically a DeFi protocol, web search or knowledge base lookup using RAG. Subagents are equipped with tools that enable them to execute actions, like creating transaction call data, creating user-operations to send to the user's smart wallet, and executing transactions.

Agent Service: This serves as the quality control mechanism. Multiple decisions are made by the system between user input and system output. The Agent Service ensures the output aligns with the user's intention.

How It Works

🔄 Multi-Turn Conversations

  • Maintains context across multiple user messages

  • Persistent transaction state in Session Manager

  • Conversation history tracking

🎯 Intelligent Intent Classification

  • Confidence scoring for routing decisions

  • Multiple classification methods (keyword, LLM, fallback)

  • Context-aware transaction state detection

🔐 Transaction Safety

  • Always requires user confirmation before generating transactions

  • Clear transaction summaries before confirmation

  • Cancel/abort capabilities at any step

⚡ Flexible Architecture

  • Modular node design for easy extension

  • Tool integration (Tavily, ChromaDB, web3.py)

📊 Comprehensive Monitoring

  • Routing confidence scores

  • Processing time tracking

  • Error handling and reporting

  • LangSmith integration support

Internal Components

Internally, MAFIA is powered by a sophisticated LangGraph workflow that provides intent classification, state management and action execution and multi-step transaction creation. The graph orchestrates multiple nodes to handle web search, knowledge base queries, and multi-step transaction creation.

🔀 Conversational Router

Entry Point - Sophisticated intent classification with confidence scoring

Features:

  • Keyword-based routing (high confidence ≥ 0.8)

  • LLM-assisted routing (medium confidence 0.4-0.8)

  • Fallback routing (low confidence < 0.4)

  • Transaction state awareness - Detects ongoing transactions

  • Multi-turn conversation support

Intent Classifications:

  • web_search - Market data, DeFi news, current prices

  • knowledge_base - Protocol documentation queries

  • transaction_inquiry - "What can I do?" type questions

  • transaction_request - Incomplete transaction requests

  • transaction_confirmation - Yes/No confirmation responses

  • transaction_complete - Complete transaction ready for execution

  • general - DeFi education and general conversation

🔍 Web Search Node

Purpose: Real-time DeFi market data and news retrieval

Tool: Tavily Web Search API Use Cases:

  • Current token prices

  • DeFi protocol news

  • Market trends and analysis

  • Yield farming opportunities

📚 Knowledge Base Node

Purpose: RAG-powered queries about Chedda Finance & MAFIA AI

Tool: File Knowledge Base (ChromaDB) Content Sources:

  • Gitbook documentation

  • Protocol specifications

  • FAQ documents

  • User guides

❓ Transaction Inquiry Node

Purpose: List available DeFi operations and capabilities

Responses:

  • Available transaction types (supply, withdraw, borrow, repay)

  • Supported assets (USDC, ETH, etc.)

  • Pool information (CB Assets, Memecoin pools)

  • Example commands

📝 Transaction Request Node

Purpose: Parse transaction details and gather missing information

Features:

  • Component extraction from natural language

  • Missing information detection

  • Session state persistence via Session Manager

  • Multi-turn information gathering

Parsed Components:

  • Action: supply, withdraw, borrow, repay, balance check

  • Amount: numerical value, "max", "all"

  • Currency: USDC, ETH, other supported tokens

  • Pool: cbassets, memecoin (auto-detected)

✅ Transaction Confirmation Node

Purpose: Process user confirmation responses

Features:

  • Confirmation pattern recognition (yes, no, confirm, cancel)

  • Transaction state transition (confirming → confirmed)

  • Security confirmation - Always requires explicit user approval

🚀 Transaction Complete Node

Purpose: Generate blockchain transaction calldata

Tool: Blockchain Tool (web3.py) Features:

  • Smart contract interaction with DeFi protocols

  • Multi-step transaction sequencing (approve → supply)

  • Base mainnet calldata generation

  • ABI encoding for contract methods

💬 General Conversation Node

Purpose: DeFi education and general assistance

Features:

  • LLM-powered responses for DeFi concepts

  • Educational content about lending, borrowing, yield farming

  • Fallback responses when LLM unavailable

📤 Response Formatter Node

Final Step - Formats all responses for client consumption

Output Format:

{
  "response_text": "Human-readable response",
  "transactions": [{"to": "0x...", "data": "0x..."}],
  "metadata": {"intent": "...", "confidence": "high"},
  "error": null
}

State Management

AgentState Structure

{
  "message": "User input",
  "session_id": "unique_session",
  "user_address": "0x...",
  "user_name": "User",
  "intent": "transaction_request",
  "confidence": "high",
  "transaction_state": TransactionState,
  "response_text": "Generated response",
  "transaction_data": [...]
}

TransactionState Model

{
  "action": "supply",           # supply, borrow, withdraw, repay
  "amount": "100",             # "100", "max", "50.5"
  "currency": "USDC",          # "USDC", "ETH"
  "pool": "cbassets",          # "cbassets", "memecoin"
  "step": "confirming",        # gathering, confirming, confirmed
  "user_confirmed": false
}

Session Manager

  • Persistent state across conversation turns

  • Transaction state storage in memory

  • Session cleanup for inactive users

  • Multi-user support with isolated sessions


Conversation Flow Examples

Example 1: Complete Transaction

User: "I want to supply 100 USDC"
Router: transaction_request → Request Node → "Confirm supplying 100 USDC to CB Assets pool?"
User: "Yes"
Router: transaction_confirmation → Confirmation Node → Complete Node → Calldata generated

Example 2: Incomplete Transaction

User: "I want to supply USDC"
Router: transaction_request → Request Node → "How much USDC would you like to supply?"
User: "100 USDC"
Router: transaction_request → Request Node → "Confirm supplying 100 USDC?"
User: "Yes"
Router: transaction_confirmation → Complete Node → Transaction created

Example 3: Web Search

User: "Current DeFi news"
Router: web_search → WebSearch Node → Tavily API → Latest DeFi articles

Workflow Execution

LangGraph Setup

from langgraph.graph import StateGraph, END, START

workflow = StateGraph(AgentState)

# Add all nodes
workflow.add_node("conversational_router", self.conversational_router_node)
workflow.add_node("web_search", self.web_search_node)
# ... other nodes

# Set entry point
workflow.set_entry_point("conversational_router")

# Define conditional edges
workflow.add_conditional_edges(
    "conversational_router",
    self.route_decision,
    {
        "web_search": "web_search",
        "transaction_request": "transaction_request",
        # ... other routes
    }
)

# All paths lead to response formatter
workflow.add_edge("web_search", "response_formatter")
workflow.add_edge("response_formatter", END)

return workflow.compile()

Agent Invocation

result = self.graph.invoke(initial_state)

User Layer Components

From the user's standpoint, the flow of execution is fairly simple and follows this process:

Components

User

  • External app user interacts with the application through a chat interface on the MAFIA web app.

  • MAFIA exposes API endpoints, thus, could be called by other applications or AI agents.

Smart Contract Wallet

  • ERC-4337 compatible account abstraction wallet

  • Stores user assets and executes validated UserOperations

  • Implements signature validation for:

    • ECDSA signatures (user-approved)

    • Session keys (AI-delegated)

    • Multi-sig requirements (high-value tx)

MAFIA

  • Brains behnd the operation.

  • Receives user intent from a chat messages.

  • Classifies this intent and creates an action that is returned to the users.

  • Can submit user operations to user's smart wallet for execution.

External Vaults

  • User operations created by MAFIA are submitted on chain to the respective DeFi protocol smart contracts for execution.

The end-user interacts with MAFIA through a chat interface and an smart contract wallet.

ERC-4337
Internal State Graph