Skip to content

daviddprtma/flow-state

Repository files navigation

🌊 FlowState

The Streaming Extension for x402

A hybrid payment protocol that solves the N+1 Signature Problem for AI agent payments.
Combining x402's HTTP-native service discovery with continuous MNEE token streams on Ethereum.

Arbitrum x402 MNEE License Status


💡 The Problem & Our Solution

Traditional AI agent payments require a new transaction for every single API request, leading to high costs and friction. FlowState introduces streaming payments, making interactions efficient and scalable.

Traditional Approach FlowState Approach
100 Requests = 100 Signatures 100 Requests = 2 Signatures
High & unpredictable gas costs ~95% Gas Savings
Slow, blocking transactions Fast, non-blocking streams

Key Innovation: Just 2 on-chain transactions (Open + Close) are needed, regardless of how many requests are made.


🚀 Core Features

  • ✅ x402 Protocol Support – Utilizes a standard HTTP-based payment negotiation flow.
  • ✅ MNEE Token Streams – Enables continuous, second-by-second payment flows using the MNEE stablecoin.
  • ✅ AI-Powered Payment Decisions – An onboard AI (Gemini) dynamically chooses the most efficient payment mode.
  • ✅ Multi-Agent Collaboration – Supports a mesh network for agents to discover and pay each other.
  • ✅ Built-in Safety – Includes programmable spending limits and emergency stop mechanisms.
  • ✅ Real-Time Dashboard – A visual interface to monitor active streams, balances, and analytics.

🏗️ Architecture

A high-level look at how the system connects:

graph TD
    A[AI Agent / Client] -->|"1. HTTP Request (x402)"| B[API Service Provider]
    B -->|"2. Payment Required (x402)"| A
    A -->|3. Open Stream TX| C[Ethereum / Arbitrum]
    C -->|4. Streams MNEE/sec| D[FlowStateStream Contract]
    D -->|5. Authorize & Serve| B
    A -->|6. Close Stream TX| C

Loading

➡️ For a deeper dive, read the full Architecture Documentation.


⚡ Quick Start

Get a local demo running in minutes.

Prerequisites

  • Node.js (v18+)
  • An Arbitrum Ethereum wallet with Sepolia testnet ETH
  • A Gemini API key

1. Clone & Install

git clone https://github.com/daviddprtma/flow-state.git
cd flow-state
npm run install:all

2. Configure Environment

cp .env.example .env
# Now edit .env with your keys and contract addresses

3. Launch the Project

npm run dev

The dashboard will be live at http://localhost:5173, allowing you to interact with the streaming protocol.

� Advanced Setup

Environment Variables (Optional)

Copy .env.example to .env and fill in your values:

cp .env.example .env
# Only needed if deploying your own contracts
SEPOLIA_RPC_URL="https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY"
PRIVATE_KEY="YOUR_DEPLOYER_PRIVATE_KEY"

# AI Features (Optional)
GEMINI_API_KEY="your_gemini_api_key"

Deploy Your Own Contracts

npx hardhat run scripts/deploy.js --network sepolia

Run Tests

npm test                    # Run all tests
npm run test:contracts      # Smart contract tests only
npm run test:sdk           # SDK tests only

Available Scripts

Command Description
npm run dev Start frontend dev server
npm run build:web Build for production
npm run test Run all tests
npm run deploy:sepolia Deploy contracts to Sepolia
npm run demo:provider Run provider demo
npm run demo:consumer Run consumer demo

🔄 The Hybrid Approach: x402 Discovery + MNEE Streaming

Why Both?

Approach Best For Limitation
x402 Per-Request Few API calls Payment overhead per request
Streaming High-volume usage Requires upfront deposit
FlowState Hybrid Any usage pattern None - best of both!

How It Works

1. Agent makes HTTP request to API
2. Server returns HTTP 402 with x402-compatible payment requirements
3. FlowState SDK parses requirements, uses Gemini AI to decide:
   - Few requests expected? → Use x402 per-request mode
   - Many requests expected? → Create MNEE payment stream
4. Agent pays and accesses service
5. AI continuously optimizes payment mode based on actual usage

🤖 The AI Agent Payment Problem

The Challenge: AI agents need to make thousands of micropayments per second for:

  • API calls ($0.0001 per call)
  • Compute resources ($0.01/second)
  • Data feeds ($0.001/second)
  • Content consumption (per-token pricing)

Traditional Solutions Fail:

  • ❌ Discrete transactions: Too expensive (gas fees exceed payment value)
  • ❌ Batching: Creates settlement delays (30+ seconds)
  • ❌ Off-chain solutions: Requires trusted intermediaries

FlowState Solution:

  • ✅ x402 discovery: Standard HTTP 402 for universal agent interoperability
  • ✅ Streaming payments: Efficient for high-volume usage
  • ✅ MNEE stablecoin: Sub-cent fees + instant settlement
  • ✅ AI-powered: Gemini decides optimal payment mode

🧪 Sepolia Testnet Contracts

Contract Sepolia Address
MockMNEE Token 0x96B1FE54Ee89811f46ecE4a347950E0D682D3896
FlowStateStream 0x155A00fBE3D290a8935ca4Bf5244283685Bb0035

🧩 Tech Stack

  • Smart Contracts: Solidity, Hardhat
  • Backend SDK: TypeScript
  • Frontend: Vite, React, JavaScript, Tailwind CSS
  • AI Agent Logic: Gemini API
  • Network: Ethereum, Arbitrum

🎯 Use Cases

1. x402 Service Discovery + Streaming

import { FlowStateAgent } from 'flowstate-sdk';

const agent = new FlowStateAgent({
  privateKey: process.env.AGENT_PRIVATE_KEY,
  geminiApiKey: process.env.GEMINI_API_KEY
});

// SDK automatically handles x402 flow:
// 1. Makes request → receives HTTP 402
// 2. Parses payment requirements
// 3. AI decides: streaming (high volume) or per-request (low volume)
// 4. Creates MNEE stream if streaming mode
// 5. Retries request with payment proof
const weather = await agent.fetch('https://api.weather-agent.com/forecast');
console.log(await weather.json());

2. Provider with x402 Middleware

import express from 'express';
import { flowStateMiddleware } from 'flowstate-sdk';

const app = express();

// One line to add payment requirements!
app.use(flowStateMiddleware({
    endpoints: {
        "GET /api/weather": {
            price: "0.0001",
            mode: "streaming",
            minDeposit: "1.00",
            description: "Weather data API"
        },
        "POST /api/translate": {
            price: "0.001",
            mode: "per-request",
            description: "Translation service"
        }
    },
    mneeAddress: process.env.MNEE_ADDRESS,
    flowStateContract: process.env.FLOWSTATE_CONTRACT
}));

app.get('/api/weather', (req, res) => {
    // Only reached if payment verified!
    res.json({ temp: 28, city: 'Lagos' });
});

3. AI-Powered Payment Mode Selection

// Gemini analyzes usage and recommends optimal mode
const agent = new FlowStateAgent({
  geminiApiKey: process.env.GEMINI_API_KEY,
  dailyBudget: '50.00'
});

// First request: AI analyzes expected usage
// "I expect to make 1000 API calls" → Streaming mode (more efficient)
// "I need just one translation" → Per-request mode (simpler)

const recommendation = await agent.recommendPaymentMode({
  service: 'weather-api',
  expectedCalls: 1000,
  duration: '1 hour'
});

console.log(recommendation);
// { mode: 'streaming', reason: 'High volume usage - streaming saves 90% on gas' }

4. GPU Compute with Streaming

// Rent GPU resources with real-time payment
const computeStream = await agent.createStream({
  recipient: gpuProviderAddress,
  ratePerSecond: '0.01', // $36/hour
  deposit: '36.00',      // 1 hour prepaid
  metadata: { purpose: 'ML training' }
});

// Cancel early? Get unused funds back automatically
await computeStream.cancel(); // Refunds remaining deposit

🔄 Mainnet Migration

When ready for production with real MNEE:

Feature Testnet (Sepolia) Mainnet
Token MockMNEE (free mint) Real MNEE
Network Sepolia (11155111) Ethereum (1)
Gas Free testnet ETH Real ETH

MNEE Mainnet Contract: 0x8ccedbAe4916b79da7F3F612EfB2EB93A2bFD6cF

Update vite-project/src/contactInfo.js with mainnet addresses and deploy FlowStateStream to mainnet.


🤖 Agent SDK Usage

Basic Stream Creation

import { FlowStateAgent } from 'flowstate-sdk';

const agent = new FlowStateAgent({
  privateKey: process.env.AGENT_PRIVATE_KEY,
  network: 'sepolia'
});

// Create a payment stream
const stream = await agent.createStream({
  recipient: '0x1234...5678',
  ratePerSecond: '0.0001',
  deposit: '10.00',
  metadata: {
    agentId: 'weather_bot_01',
    purpose: 'API Metering'
  }
});

console.log(`Stream #${stream.id} created!`);

AI-Powered Agent

import { FlowStateAgent } from 'flowstate-sdk';

const agent = new FlowStateAgent({
  privateKey: process.env.AGENT_PRIVATE_KEY,
  geminiApiKey: process.env.GEMINI_API_KEY,
  dailyBudget: '50.00'
});

// Let AI optimize your spending
const decision = await agent.optimizeSpending();
console.log(`AI Decision: ${decision.action}`);
console.log(`Reasoning: ${decision.reasoning}`);

// Natural language queries
const response = await agent.ask("Should I subscribe to the translation API?");
console.log(response);

📊 Demo Scenario

Watch two AI agents transact autonomously:

  1. Agent Alice (Consumer) needs weather data
  2. Agent Bob (Provider) offers weather API at $0.0001/call
  3. Alice opens a FlowState stream to Bob
  4. Alice makes 1,000 API calls over 10 minutes
  5. Bob's balance increases in real-time: $0.00 → $0.10
  6. Bob withdraws earnings anytime
  7. Alice cancels stream when done, gets unused deposit back

All payments happen automatically, no human intervention!


🔒 Security Features

  • Spending Limits: Daily and per-stream caps
  • Emergency Pause: Instantly stop all agent activity
  • Auto-cancellation: Streams cancel when services fail
  • Suspicious Activity Detection: AI monitors for anomalies
  • Human Override: Dashboard controls for manual intervention

📁 Project Structure

flowpay/
├── contracts/
│   ├── FlowPayStream.sol      # MNEE streaming contract
│   └── MockMNEE.sol           # Test token for Sepolia
├── scripts/
│   └── deploy.js              # Deployment script
├── sdk/
│   └── src/
│       ├── FlowPaySDK.ts      # Agent SDK with x402 handling
│       ├── GeminiPaymentBrain.ts  # AI payment decisions
│       └── SpendingMonitor.ts # Budget management
├── server/
│   └── middleware/
│       └── flowPayMiddleware.js  # x402 Express middleware
├── demo/
│   ├── consumer.ts            # AI agent demo (consumer)
│   └── provider.ts            # API provider demo
├── vite-project/
│   ├── src/
│   │   ├── components/        # React components
│   │   ├── pages/             # Dashboard, Streams, Docs
│   │   ├── context/           # Wallet context
│   │   └── contactInfo.js     # Contract addresses
│   └── netlify.toml           # Deployment config
├── test/
│   └── FlowPayStream.test.js  # Contract tests
├── hardhat.config.js
├── package.json
├── LICENSE                    # MIT License
└── README.md

📖 Documentation & Links


🗺️ Roadmap

  • Mainnet launch
  • Multi-token stream support (USDC, DAI)
  • Client SDKs for Python and Go
  • Formal audit with a leading firm
  • Integration examples with popular AI agent frameworks

🤝 Contributing

Contributions are what make the open-source community amazing. Any contributions you make are greatly appreciated.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📝 License

Distributed under the MIT License. See LICENSE file for more information.


Video Demo Presentation

Here's the demo video for FlowState 👇

IMAGE ALT TEXT HERE

Built with ❤️ by David Pratama

About

FlowState combines x402's HTTP-native service discovery with continuous payment streaming for AI agents using MNEE stablecoin. The best of both worlds: standardized discovery + efficient streaming.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors