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.