Logo
Learn
  • Explore Course
Build
  • Explore Buildathon
  • Project Archive
Hack
Hack Coming Soon
  • Explore IRL Hackhouse
  • How to Qualify
  • Past Events

FlowState

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.

Videos

Description

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.

πŸ’‘ 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

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

➑️ 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 contractsSEPOLIA_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 proofconst 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 modeconst 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 paymentconst 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 automaticallyawait 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 streamconst 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 spendingconst decision = await agent.optimizeSpending();console.log(`AI Decision: ${decision.action}`);console.log(`Reasoning: ${decision.reasoning}`);

// Natural language queriesconst 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

  • SDK Reference – Integrate FlowState into your agents.

  • Live Demo: flow-state-arbitrum.netlify.app


πŸ—ΊοΈ 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.

Progress During Hackathon

πŸ“‹ FlowState Progress Build Plan Phase 1: Foundation & Environment Setup (Day 1-2) βœ… Prerequisites Check Install Node.js (v18+) Create an Arbitrum Sepolia testnet wallet (e.g., MetaMask) Obtain Sepolia testnet ETH from a faucet Get a Gemini API key from Google AI Studio βœ… Project Installation bash # Clone repository git clone https://github.com/daviddprtma/flow-state.git cd flow-state # Install all dependencies (contracts, SDK, frontend) npm run install:all βœ… Environment Configuration bash # Create environment file cp .env.example .env # Edit .env with your values: # - SEPOLIA_RPC_URL (get from Alchemy/Infura) # - PRIVATE_KEY (your wallet's private key) # - GEMINI_API_KEY (optional, for AI features) Phase 2: Smart Contract Deployment (Day 2-3) βœ… Test Deployment on Sepolia bash # Deploy contracts to Sepolia testnet npx hardhat run scripts/deploy.js --network sepolia Expected Output: MockMNEE Token contract address FlowStateStream contract address βœ… Contract Verification Verify contracts on Sepolia Etherscan Update vite-project/src/contactInfo.js with deployed addresses Test token minting (for MockMNEE) Phase 3: Run Core Tests (Day 3) βœ… Test Suite Execution bash npm test # Run all tests npm run test:contracts # Smart contract tests only npm run test:sdk # SDK tests only Key Tests to Verify: Stream creation and cancellation MNEE token transfers x402 payment negotiation Spending limits enforcement Phase 4: Launch Demo Environment (Day 4) βœ… Start Development Server bash npm run dev Access Points: Dashboard: http://localhost:5173 Provider demo: Ready for API testing Consumer demo: Ready for agent testing βœ… Run Demo Scripts bash # Terminal 1 - Start provider npm run demo:provider # Terminal 2 - Run consumer agent npm run demo:consumer Expected Demo Flow: Agent Alice requests weather data Agent Bob responds with payment requirements (x402) AI decides optimal payment mode MNEE payment stream opens 1000 API calls processed automatically Real-time balance updates visible in dashboard Phase 5: Explore Key Features (Day 5-6) βœ… Feature Deep Dive 1. x402 Service Discovery javascript // Test basic agent functionality import { FlowStateAgent } from 'flowstate-sdk'; const agent = new FlowStateAgent({ privateKey: process.env.AGENT_PRIVATE_KEY, geminiApiKey: process.env.GEMINI_API_KEY }); // Make automated payment-enabled request const response = await agent.fetch('https://api.weather-agent.com/forecast'); 2. AI-Powered Payment Decisions javascript // Let Gemini decide optimal payment mode const recommendation = await agent.recommendPaymentMode({ service: 'weather-api', expectedCalls: 1000, duration: '1 hour' }); console.log(recommendation); // { mode: 'streaming', reason: '...' } 3. Provider Setup with Middleware javascript // Test Express middleware implementation import express from 'express'; import { flowStateMiddleware } from 'flowstate-sdk'; const app = express(); app.use(flowStateMiddleware({ endpoints: { "GET /api/weather": { price: "0.0001", mode: "streaming", minDeposit: "1.00" } } })); Phase 6: Dashboard & Monitoring (Day 6) βœ… Dashboard Features to Test Connect wallet (MetaMask) View active payment streams Monitor balance changes in real-time Set spending limits Test emergency stop mechanism Withdraw earnings (as provider) βœ… Real-time Analytics Track gas savings (~95% expected) Monitor stream rates (MNEE/second) View AI decision logs Phase 7: Advanced Customization (Day 7-8) βœ… Modify for Your Use Case Option A: Custom Payment Rates solidity // Edit contracts/FlowPayStream.sol // Modify rate calculation or add new token support Option B: New AI Provider Integration javascript // Edit sdk/src/GeminiPaymentBrain.ts // Replace Gemini with OpenAI/Claude Option C: Additional Endpoints javascript // Edit server/middleware/flowPayMiddleware.js // Add new API endpoints with custom pricing βœ… Deploy to Production (Optional) bash # Build frontend for production npm run build:web # Deploy to Netlify (configured in vite-project/netlify.toml) # Or deploy contracts to mainnet with real MNEE Phase 8: Documentation & Extension (Day 9-10) βœ… Create Your Own Documentation Document custom configurations Record demo video of your setup Note any issues encountered and solutions βœ… Extension Ideas to Try Multi-agent mesh: Run multiple consumer agents Custom safety rules: Implement rate limiting per agent Alternative stablecoins: Add USDC/DAI support Webhook notifications: Alert on stream events Analytics dashboard: Track spending patterns 🎯 Success Metrics By completing this build, you should achieve: βœ… 95% gas savings vs per-request payments βœ… < 1 second stream initialization time βœ… Real-time balance updates (second-by-second) βœ… Autonomous AI-powered payment decisions 🚨 Troubleshooting Tips Issue Solution Contract deployment fails Check Sepolia RPC URL and private key in .env Dashboard not loading Run npm run build:web then npm run dev AI decisions not working Verify Gemini API key and network connectivity Stream creation reverts Ensure MockMNEE tokens are minted first πŸ“š Learning Resources x402 Protocol Documentation MNEE Stablecoin Info Hardhat Deployment Guide πŸŽ‰ Completion Checklist All tests pass Demo runs successfully with two agents Dashboard shows active streams AI selects optimal payment mode Custom endpoints work with payments Emergency stop functions properly Documentation updated for your setup

Tech Stack

SolidityTypescriptReactViteJavascriptTailwind CSSGemini APIArbitrum Ethereum
Team Leader
DDavid Pratama
GitHub Link
github

GitHub

https://github.com/daviddprtma/flow-state
Product Category
AINFTDeFi