description
A non‑custodial exchange and payments network that delivers instant, low‑fee onramp/offramp and cross‑asset settlement via generalized state channels in a hub‑and‑spoke topology, built on Rootstock/RIF for settlement and powered by Fetch.ai uAgents for autonomous orchestration.
Problem it solves
- Fiat↔crypto friction: Slow, expensive, and opaque conversions.
- Retail payments on L1: High latency/cost, poor UX for merchants and users.
- Cross‑asset fragmentation: Custodial bridges/centralized providers dominate today’s flows.
- Operational load: Manual risk, compliance, and routing processes don’t scale.
Core idea
- Generalized state channels: Move most activity off‑chain; only open/close/disputes hit L1.
- Hub‑and‑spoke: A capitalized hub provides quotes, routing, and risk; users/merchants connect as spokes.
- AI‑driven operations: Fetch.ai uAgents automate quoting, risk, compliance, and rebalancing.
- Rootstock/RIF rails: Bitcoin‑secured EVM finality with RIF tooling for payments and liquidity.
Architecture
On‑chain (Rootstock / RIF)
- ChannelFactory: Deploys/upgrades bilateral channel contracts.
- Adjudicator: Enforces latest co‑signed state, resolves disputes, pays out.
- Token escrows: Collateral vaults for stablecoins/native tokens on Rootstock.
- RIF integrations: RIF Payments and Lumino‑style patterns for channel semantics and fee policies.
Off‑chain (Agents, services, data plane)
- Hub Node (uAgent):
- Quoting & RFQ: Firm/time‑boxed prices for swaps, on/off‑ramp, and payments.
- Routing: Single‑hop via hub; multi‑hub federation is supported later.
- Risk engine: Credit limits, exposure tracking, pre‑trade/post‑trade checks.
- Rebalancing: Executes DEX/CEX trades or cross‑chain moves to maintain inventory.
- Fiat orchestration: Connects PSPs/banks; handles payouts and receipts.
- Spoke Clients (uAgents):
- Wallets, merchants, marketplaces, PSPs running lightweight agents.
- Handle channel lifecycle, sign updates, request quotes, emit receipts.
- Watchers (optional):
- Monitor channels; auto‑respond in disputes; provide liveness guarantees.
- Oracles & providers:
- Price feeds, KYT/KYC vendors, sanctions screening, bank/PSP webhooks.
Control vs data planes
- Control plane: Agent‑to‑agent messages (quotes, intents, authorizations, risk decisions).
- Data plane: Co‑signed channel state updates; optional Merkle‑batched receipts for audits.
State channel lifecycle
- Open: Parties lock collateral into a channel on Rootstock via the
ChannelFactory.
- Update: Off‑chain, co‑signed state transitions (balances, assets, conditions, fees).
- Conditional transfers:
- HTLCs: Hashlocks/timelocks for atomic multi‑party or cross‑asset flows.
- Generalized conditions: Oracle attestations (e.g., fiat cleared) or policy predicates.
- Checkpoint (optional): Post compressed state to reduce dispute windows and costs.
- Dispute/Close: Either side can submit latest signed state to the
Adjudicator; contract enforces payout.
Core flows
Onramp (fiat → crypto/stablecoin)
- Intent: User requests amount/asset; hub returns firm quote.
- Authorization: PSP/bank pre‑auth is obtained; uAgents record proof.
- Credit & deliver: Hub grants conditional credit in the user↔hub channel and delivers the crypto off‑chain (state update).
- Settle fiat: Hub settles with PSP; oracle/uAgent attestation lifts condition; balances finalized.
Offramp (crypto/stablecoin → fiat)
- Intent: User requests fiat payout; hub quotes rate/fee.
- Value transfer: User moves crypto to hub via channel update (or on‑chain deposit).
- Payout: Hub executes fiat transfer to user’s bank/card; attestation finalizes off‑chain state.
Payments (merchant checkout)
- Quote: Buyer agent requests merchant price; hub provides guaranteed total including FX/fees.
- Auth: Buyer and hub co‑sign a conditional update; merchant receives instant authorization.
- Capture: Upon fulfillment or time‑based event, condition clears; merchant’s balance finalizes.
- Settlement preference: Merchant auto‑settles to fiat (offramp) or stablecoin (stay on‑chain).
Cross‑asset / cross‑chain swaps
- Atomicity: HTLCs/conditions across two channels (user↔hub, hub↔liquidity venue).
- Inventory mgmt: Hub rebalances via Rootstock DEXs, external CEXs, or additional channels on other chains.
Economics and fees
- Routing fee: Basis‑points per executed payment.
- FX spread: Transparent spread in quoted price.
- Lifecycle gas: Users pay open/close; routine transfers are gasless (off‑chain).
- Tiering: Volume‑based discounts; merchant programs for predictable cost.
Security, trust, and risk
- Non‑custodial: Latest signed state is user‑recoverable via adjudicator; force‑close always available.
- Hub collateralization: Posted collateral plus dynamic credit limits per counterparty.
- Watchers: Third‑party services ensure timely dispute responses.
- Compliance: KYC/KYB for fiat endpoints, KYT, sanctions checks, travel‑rule‑ready messaging.
- Audits and proofs: Merkle‑batched receipts; periodic checkpoints for verifiable accounting.
AI orchestration with Fetch.ai and uAgents
- Autonomous workflows:
- Quoting: Solicit multi‑venue quotes; pick best execution; issue firm, time‑boxed quotes.
- Risk: Real‑time exposure checks, per‑user/merchant limits, anomaly detection.
- Rebalancing: Trigger swaps/transfers when thresholds breached; schedule low‑cost windows.
- Compliance ops: Automate KYC refresh, travel‑rule data exchange, and screening.
- Fiat events: React to PSP webhooks; clear conditions; reconcile ledgers.
- Agent roles:
- HubAgent: Price, route, risk, and settlement control.
- MerchantAgent: Pricing, refunds, payouts, settlement preference policy.
- BuyerAgent: Funding, payment approvals, receipt management.
- WatcherAgent: Channel monitoring and dispute response.
- Benefits: Lower ops toil, faster response, safer limits, and better liquidity utilization.
Technology stack
- Settlement layer: Rootstock (RSK) EVM secured by Bitcoin; RIF Payments and Lumino‑style channel semantics.
- Smart contracts: Solidity channel factory/adjudicator, token escrows, fee policies, checkpointing.
- Agents: Python uAgents (Fetch.ai) for hub, buyers, merchants, watchers.
- Integrations: PSPs/banks (ACH/SEPA/cards), price oracles, KYT/KYC providers, analytics.
- Frontend: Wallet/merchant UIs, SDKs for web/mobile and server integrations.
- Observability: Metrics, traces, balance and latency dashboards; anomaly alerts.
Developer experience
- SDKs/APIs:
- Open/attach to channel, send payments, request quotes, subscribe to receipts.
- Idempotent webhooks for fiat events; sandbox keys and simulators.
- Operational tooling:
- Risk policy editor, limit management, partial freeze/unfreeze, instant refunds.
- Exportable audit trails and receipts; dispute assistant.
Performance targets
- p95 latency: < 500 ms for authorizations and off‑chain transfers.
- All‑in cost: Single‑digit bps typical; zero gas for routine messages.
- Reliability: Auto‑failover watchers; SLOs on quote validity and payout times.
Roadmap
- MVP: Single‑hub Rootstock deployment, stablecoin rails, card/ACH onramp, merchant checkout, force‑close, basic watcher.
- Phase 2: Cross‑chain swaps, multi‑hub routing/federation, automated rebalancing, enhanced analytics.
- Phase 3: Advanced risk engine (ML‑assisted), dynamic fee markets, privacy upgrades (payment privacy sets), broader fiat corridors.
Differentiation
- Latency/cost: State channels outperform rollups/bridges for real‑time retail.
- Capital efficiency: Hub reuses collateral across many users; users avoid repeated L1 gas.
- Safety: Non‑custodial with adjudicator‑enforced exits and watcher redundancy.
- AI‑native ops: Fetch.ai uAgents continuously optimize quotes, risk, and liquidity.
In short: this system makes moving value between fiat and crypto feel instant and inexpensive, while preserving the safety of on‑chain finality (Rootstock/RIF) and leveraging autonomous uAgents (Fetch.ai) to run the complex routing, risk, and compliance workflows behind the scenes.
- Added a complete end‑to‑end description incorporating Rootstock/RIF settlement and Fetch.ai uAgents roles, detailing architecture, flows, security, economics, and roadmap.
- Frontend: Next.js 15 + React 19, Tailwind 4, Radix UI, Recharts.
- Wallet/Chains: RainbowKit + wagmi + viem with custom Rootstock chains.
- Agents/Backend: Python FastAPI + uvicorn + Web3.py + Fetch.ai uAgents and Agent Chat Protocol.
- Messaging: HTTP endpoints with optional WebSocket patterns on the frontend.
- Payments: Rootstock rUSDT ERC-20 transfers with on-chain verification.
How pieces fit together
- Wallet and networks: The app exposes wallets via
RainbowKitProvider and configures EVM networks, including Rootstock, in wagmi. Custom Rootstock chains are added because they’re not bundled by default:
// Custom Rootstock chains (not included in wagmi/chains by default)
export const rootstock = {
id: 30,
name: 'Rootstock Mainnet',
network: 'rootstock',
nativeCurrency: {
decimals: 18,
name: 'Rootstock Bitcoin',
symbol: 'RBTC',
},
}
export const config = createConfig({
chains: [
// Ethereum, L2s, others...
// Rootstock networks
rootstock,
rootstockTestnet,
],
connectors,
transports: {
// ...
[rootstock.id]: http(RPC_CONFIGS.rootstock_mainnet.rpcUrl),
[rootstockTestnet.id]: http(RPC_CONFIGS.rootstock_testnet.rpcUrl),
},
ssr: true,
})
- RPC configuration: A single source of truth for endpoints across chains, including Rootstock:
// Rootstock Networks
rootstock_mainnet: {
name: 'Rootstock Mainnet',
chainId: 30,
rpcUrl: 'https://public-node.rsk.co',
explorerUrl: 'https://explorer.rsk.co',
nativeCurrency: { name: 'Rootstock Bitcoin', symbol: 'RBTC', decimals: 18 },
},
- Providers: React Query + wagmi + RainbowKit are composed in one place for easy client hydration:
return (
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient}>
<RainbowKitProvider appInfo={{ appName: 'AgentChat', learnMoreUrl: 'https://rainbowkit.com' }} modalSize="compact">
{children}
</RainbowKitProvider>
</QueryClientProvider>
</WagmiProvider>
)
- Frontend ↔ Agent bridge: The UI talks to local uAgents via an HTTP abstraction. When Agentverse is unavailable, it falls back to a local registry and uses HTTP for localhost agents:
// Load available agents from Agentverse or local registry
const response = await axios.get(`${FETCHAI_CONFIG.AGENTVERSE_BASE_URL}/agents`)
this.agents = response.data.agents || []
// Fallback to local agents
this.agents = this.getLocalAgents()
// For local agents, use HTTP endpoints directly
const response = await axios.post(
`http://${agent.endpoint}:${agent.port}/api/chat`,
{ message, user_id: 'blockchain_user', timestamp: new Date().toISOString() },
{ timeout: 10000 }
)
return response.data.response || response.data.message || 'No response received'
- WebSocket ergonomics (UI): The hook centralizes event subscriptions and cleans up listeners to avoid stale closures:
useEffect(() => {
if (typeof window === 'undefined') return
wsService.connect(userId)
if (onMessageReceived) {
wsService.onMessageReceived((message) => {
callbacksRef.current.onMessageReceived?.(message)
})
}
// ...
Agents, chat protocol, and payments
- Merchant Agent: A uAgents-powered merchant that speaks the Agent Chat Protocol and exposes FastAPI endpoints in the same process.
# Create uagents merchant agent using private key
MERCHANT_PRIVATE_KEY = os.getenv("MERCHANT_PRIVATE_KEY")
merchant_agent = Agent(name="merchant", seed=MERCHANT_PRIVATE_KEY, port=8003, endpoint=["http://localhost:8003/submit"], publish_agent_details=True)
@chat_proto.on_message(ChatMessage)
async def handle_chat_message(ctx: Context, sender: str, msg: ChatMessage):
# ... ack incoming message ...
response_text = await process_merchant_message(item.text)
response = ChatMessage(timestamp=datetime.utcnow(), msg_id=uuid4(), content=[TextContent(type="text", text=response_text)])
await ctx.send(sender, response)
- HTTP API co-hosted with the agent: We run the uAgent in a background thread and FastAPI in the main thread so the same port can serve both message-based and REST flows.
def run_merchant_and_api():
agent_thread = threading.Thread(target=lambda: merchant_agent.run())
agent_thread.daemon = True
agent_thread.start()
uvicorn.run(app, host="127.0.0.1", port=8003, log_level="info")
- Payment verification on Rootstock: Minimal ABI, event-based verification of rUSDT
Transfer to merchant address. This keeps the footprint tiny and avoids full contract bindings.
ERC20_ABI = [{
"anonymous": False,
"inputs": [
{"indexed": True, "name": "from", "type": "address"},
{"indexed": True, "name": "to", "type": "address"},
{"indexed": False, "name": "value", "type": "uint256"},
],
"name": "Transfer",
"type": "event",
}]
token = w3.eth.contract(address=RUSDT_CONTRACT, abi=ERC20_ABI)
def verify_payment(tx_hash: str, expected_to: str, expected_amount: int) -> bool:
receipt = w3.eth.get_transaction_receipt(tx_hash)
logs = token.events.Transfer().process_receipt(receipt)
for log in logs:
if log["args"]["to"].lower() == expected_to.lower() and log["args"]["value"] == expected_amount:
return True
return False
- Purchase flow endpoints:
POST /purchase quotes payment details; POST /retry_purchase verifies the on-chain transfer and finalizes.
@app.post("/purchase")
def purchase(request: dict):
# ...
return {
"status": "402 Payment Required",
"token_address": RUSDT_CONTRACT,
"recipient_address": MERCHANT_ADDRESS,
"amount": amount * 10**18,
"currency": "rUSDT",
"chain": "rootstock_testnet",
}
Partner technologies and their benefits
- Rootstock (RSK) + RIF: Bitcoin‑secured EVM with stable tooling and predictable costs; straightforward ERC‑20 event verification; easy wallet support via wagmi/RainbowKit once custom chains are registered.
- Fetch.ai + uAgents: A structured agent framework and chat protocol that makes autonomous workflows (quotes, verifications, receipts) simple to model and extend; local Agentverse fallback keeps the app usable offline.
What’s hacky (in a good way)
- Co-hosting agent and API: A single Python process runs both the uAgent and HTTP server using a background thread—fast to iterate and easy to deploy on one port.
- Tiny ABI: Event‑only ERC‑20 ABI to keep verification lightweight and robust.
- Local-first agent discovery: If Agentverse is unreachable, the frontend falls back to a local agent registry and uses HTTP instead of WS for
localhost.
- Custom chain shims: Rootstock networks are injected manually into wagmi to unlock wallet UX across RBTC/rUSDT without forking libraries.
What we didn’t ship yet (roadmap realism)
- The design targets generalized state channels; the current MVP uses on-chain Rootstock transfers plus off‑chain chat/receipts. Channel factory/adjudicator contracts and conditional transfers are planned next.
GitHub repositories
- Monorepo:
aidefi (this repo)
src/ — Next.js app, wallet integration, Fetch.ai client service, analytics UI
python/ — uAgents (uagents), FastAPI, payment verification utilities
- If you want a “Repos” section in your submission, list:
- Frontend:
aidefi-frontend — Next.js + wagmi + RainbowKit
- Agents/Backend:
aidefi-agents — uAgents + FastAPI + Web3.py
- Shared:
aidefi-protocol — contracts/specs (future)
Tooling versions
# Fetch.ai Agent Requirements
uagents>=0.5.0
fastapi>=0.100.0
uvicorn>=0.23.0
pydantic>=2.0.0
websockets>=11.0.0
"dependencies": {
"@rainbow-me/rainbowkit": "^2.2.8",
"@tanstack/react-query": "^5.90.2",
"next": "15.5.4",
"react": "19.1.0",
"viem": "^2.37.8",
"wagmi": "^2.17.5"
}
- Drafted an accurate “How it’s made” grounded in your code: Next.js + wagmi/RainbowKit with custom Rootstock chains; Python uAgents + FastAPI co-hosted service; Rootstock rUSDT verification via Web3.py; Agentverse fallback and HTTP-first local integration; plus partner benefits and practical hacks.