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.
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.
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.
β 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.
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.
Get a local demo running in minutes.
Node.js (v18+)
An Arbitrum Ethereum wallet with Sepolia testnet ETH
A Gemini API key
git clone https://github.com/daviddprtma/flow-state.git
cd flow-state
npm run install:allcp .env.example .env# Now edit .env with your keys and contract addressesnpm run devThe dashboard will be live at http://localhost:5173, allowing you to interact with the streaming protocol.
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"npx hardhat run scripts/deploy.js --network sepolianpm test # Run all tests
npm run test:contracts # Smart contract tests only
npm run test:sdk # SDK tests only
| 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 |
| 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! |
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 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
| Contract | Sepolia Address |
| MockMNEE Token | 0x96B1FE54Ee89811f46ecE4a347950E0D682D3896 |
| FlowStateStream | 0x155A00fBE3D290a8935ca4Bf5244283685Bb0035 |
Smart Contracts: Solidity, Hardhat
Backend SDK: TypeScript
Frontend: Vite, React, JavaScript, Tailwind CSS
AI Agent Logic: Gemini API
Network: Ethereum, Arbitrum
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());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' });
});// 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' }// 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 depositWhen 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.
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!`);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);Watch two AI agents transact autonomously:
Agent Alice (Consumer) needs weather data
Agent Bob (Provider) offers weather API at $0.0001/call
Alice opens a FlowState stream to Bob
Alice makes 1,000 API calls over 10 minutes
Bob's balance increases in real-time: $0.00 β $0.10
Bob withdraws earnings anytime
Alice cancels stream when done, gets unused deposit back
All payments happen automatically, no human intervention!
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
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
SDK Reference β Integrate FlowState into your agents.
Live Demo: flow-state-arbitrum.netlify.app
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
Contributions are what make the open-source community amazing. Any contributions you make are greatly appreciated.
Fork the Project
Create your Feature Branch (git checkout -b feature/AmazingFeature)
Commit your Changes (git commit -m 'Add some AmazingFeature')
Push to the Branch (git push origin feature/AmazingFeature)
Open a Pull Request
Distributed under the MIT License. See LICENSE file for more information.
π 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