Skip to content

ebenbaruk/FendForItself

Repository files navigation

  _____               _ _____          ___ _       _  __
 |  ___|__ _ __   __| |  ___|__  _ __|_ _| |_ ___| |/ _|
 | |_ / _ \ '_ \ / _` | |_ / _ \| '__|| || __/ __| | |_
 |  _|  __/ | | | (_| |  _| (_) | |   | || |_\__ \ |  _|
 |_|  \___|_| |_|\__,_|_|  \___/|_|  |___|\__|___/_|_|

The supply-side primitive of the agentic economy.

Spawn a 100%-autonomous AI-run company on Arc in 30 seconds. Identity, wallet, pricing, and a live x402 endpoint — all from one human sentence.

→ Live demo: fendforitself.up.railway.app

Live Demo Arc Testnet USDC x402 Gemini 3 Flash Next.js 15 License: MIT

Built for Agentic Economy on Arc — Circle + Arc + Lablab.ai, April 2026.


The thesis — why FendForItself exists

Every existing x402 and agentic-commerce demo you've seen is demand-side: an AI agent that pays humans, APIs, or other services. That's half the economy.

The other half — the missing primitive — is supply-side: the ability to spawn new agentic companies that other agents then buy from. Not chatbots. Not wrappers. Autonomous businesses, each with its own on-chain identity, its own treasury, its own priced endpoint, and its own revenue — all owned and operated by AI end-to-end.

FendForItself is the first demonstrable instance of that primitive. A human types one sentence. A Gemini-powered CEO agent plans a roadmap, generates an Arc wallet, funds it, designs a product, sets a sub-cent price, and publishes a live x402-protected endpoint. Within 30 seconds, a new agentic company is alive, reachable, and earning — and another 60 buyer agents can transact with it immediately, each purchase settled on-chain in USDC.

"By 2026, at least one small business will be revealed to have been completely run by AI — from owner to marketing to accounting." — World Ethical Data Foundation, 2026 Predictions

We didn't wait for that reveal. We built the factory that makes it happen on demand.


The market

The agentic economy is not a future trend. It's happening now, at scale, and it's massive.

Signal Source
$3–5 trillion of global commerce mediated by AI agents by 2030 McKinsey, Oct 2025
40%+ of enterprise apps will embed AI agents by end of 2026 Gartner
75% of businesses plan to deploy AI agents by end of 2026 Gartner
69,000 agents already transacting on x402, $50M+ in micropayments processed x402 Foundation
Only 11% of orgs have agentic systems in production today Industry surveys

The gap between "exploring agents" (89% of orgs) and "shipping agents in production" (11%) is the biggest infrastructure opportunity in software since the early cloud days. Payment rails, identity, and programmatic company creation are the missing plumbing. We're building the last one.


What it does — in 30 seconds of demo

 ┌────────────────────────────────────────────────────────────────┐
 │ $ a company that sells stablecoin-rebalancing signals to DAO   │
 │   treasury bots                                                │
 │                                                                │
 │ [CEO]      booting agent...                                    │
 │ [CEO]      roadmap: 8 tasks (5 to execute)                     │
 │ [CEO]      "PegGuard" — Defending DAO reserves with real-time  │
 │            stability intel.                                    │
 │ [WALLET]   0x2B9F…73Bd                                         │
 │ [ARC]      funding tx 0x1c6ade…9b52 confirmed ✓                │
 │ [PRODUCT]  Stability Signal 1.0  @ $0.0080 / call              │
 │ [SYSTEM]   company is live.                                    │
 │                                                                │
 │ ┌─ ROADMAP ──────────────────────────────────────────┐         │
 │ │ ✓  establish identity                    0.9s      │         │
 │ │ ✓  generate wallet                       0.5s      │         │
 │ │ ✓  seed treasury                         1.2s      │         │
 │ │ ✓  design product                        0.8s      │         │
 │ │ ✓  launch company                        0.1s      │         │
 │ │ ·  discover yield aggregator agents   (planned)   │         │
 │ │ ·  index liquidity health metrics     (planned)   │         │
 │ │ ·  publish gas-optimized signal feed  (planned)   │         │
 │ └────────────────────────────────────────────────────┘         │
 │                                                                │
 │ PegGuard                                  $0.0500 USDC ● live │
 │ ┌─ LIVE X402 ENDPOINT · ARC-TESTNET ─────────[copy curl]┐     │
 │ │ POST /api/buy/c_7okvp1r5sn                             │     │
 │ │ returns 402 · settles USDC on Arc via EIP-3009        │     │
 │ └────────────────────────────────────────────────────────┘     │
 │                                                                │
 │              [ run demo traffic (60 buyers) ]                  │
 └────────────────────────────────────────────────────────────────┘

One click on run demo traffic → 60 buyer wallets each sign EIP-3009 and pay the company in USDC on Arc testnet. The live tx feed fills up. Every hash is clickable through to testnet.arcscan.app.

The CEO's outputs are 100% live Gemini calls. Name, tagline, mission, product system prompt, and per-purchase responses are each generated by gemini-3-flash-preview at runtime. Nothing is hardcoded.


How it works

 ┌──────────────┐     SSE      ┌─────────────────────────┐
 │ Terminal UI  │ ───────────► │ /api/create-company     │
 │ (Next.js)    │              │  runCeoAgent()          │
 └──────┬───────┘              │   └─ Gemini 3 Flash     │
        │                      │     (function calling)   │
        │                      └──────────┬──────────────┘
        │                                 ▼
        │      CEO tools (in strict order, with live task tracking)
        │      ┌─────────────────────────────────────────┐
        │      │  plan_tasks — roadmap of 8 tasks        │
        │      │  generate_company_identity              │
        │      │  generate_wallet — viem random EOA      │
        │      │  fund_wallet — master → new wallet USDC │
        │      │  register_product — name, price, prompt │
        │      │  launch_company — status: live          │
        │      └─────────────────────────────────────────┘
        │
        │ "run demo traffic"
        ▼
 ┌───────────────────────────┐     ┌──────────────────────────┐
 │ /api/demo-loop/[id]       │────►│ /api/buy/[companyId]     │
 │  60× spawn buyer wallet   │     │  x402 server             │
 │     fund from master      │     │  - 402 challenge JSON    │
 │     payFor() (x402-client │     │  - EIP-3009 verify       │
 │       signs EIP-3009)     │     │  - transferWithAuth      │ ─► Arc USDC
 └───────────────────────────┘     │  - Gemini product reply  │    contract
                                   └──────────────────────────┘

Settlement is real. When a buyer sends X-Payment, our server decodes the base64 JSON, extracts the EIP-3009 authorization + signature, and calls USDC.transferWithAuthorization(...) on Arc (contract 0x3600000000000000000000000000000000000000). The master wallet relays the tx and pays the sub-cent Arc gas in USDC. The buyer never pays gas — this is the whole point of EIP-3009.

We became our own x402 facilitator for Arc because no hosted one exists yet (see Circle Product Feedback, below). The wire format matches the x402 spec exactly — any future Arc-aware x402 client will be able to pay our endpoints with zero changes on our side.


Why this is revolutionary

  1. Supply-side primitive for agentic commerce — a frontier nobody else addresses. Existing x402 demos showcase agents buying. We showcase agents being businesses. The spawned company is not a wrapper around a human service; it is the service.

  2. Every spawned company is a real monetized endpoint. Not a mock. POST /api/buy/[companyId] returns a live 402 Payment Required per the x402 spec. Any x402-aware client on Arc can pay it and receive a Gemini-generated response. You can curl it yourself.

  3. Sub-cent unit economics — only possible on Arc. At $0.005/call:

    • Ethereum L1 (~$0.50 gas): −10 000% margin (100× loss per sale)
    • Base L2 (~$0.003 gas): 40% margin (marginal after inference cost)
    • Arc + USDC native gas (~$0.0001): 98% margin
    • This IS the business model. Without Arc, an agentic company selling sub-cent services cannot exist.
  4. Provably live on-chain. 59 of 60 buyer purchases settled in our reference demo. Sample confirmed tx:

  5. The CEO actually thinks. The Gemini system instruction forces the agent to reason about target customer, problem, pricing rationale, and output format before writing a single tool call. The product system_prompt it emits is prescriptive enough that every purchase delivers a cohesive, formatted answer — not a generic completion.


Hackathon track alignment

Track How we hit it
🪙 Per-API Monetization Engine (primary) Every spawned company is a per-request monetized API. Real 402 challenge, real USDC settlement per call.
🤖 Agent-to-Agent Payment Loop 60 buyer agents each independently sign EIP-3009 and pay the company agent. Machine-to-machine, no custodial batching.
🛒 Real-Time Micro-Commerce Flow Settlement is per-interaction, not per-subscription. The TxFeed shows commerce happening in real time.

Submission proof

Requirement Status
Per-action pricing ≤ $0.01 ✅ Pricing range $0.005 – $0.01, enforced in register_product
50+ on-chain tx in demo 60 buyer tx per run, 59 confirmed in reference run (1.7% transient failure)
Margin story (why this fails with traditional gas) ✅ Static margin panel in UI + section above
Circle Developer Console tx ✅ Initial master funding done via faucet.circle.com — visible in Circle Developer Account
Arc Block Explorer verification ✅ Every tx hash deep-links to testnet.arcscan.app directly from the UI

Circle Product Feedback

This section is our consolidated response for the Product Feedback Incentive ($500 USDC). Honest, technical, and built on the specific pain points we hit in 48 hours of building.

Products used

  • Arc Testnet — settlement layer. Chain 5042002, RPC rpc.testnet.arc.network, explorer testnet.arcscan.app.
  • USDC on Arc — ERC-20 interface at 0x3600000000000000000000000000000000000000 (6 decimals), native 18-decimals gas balance.
  • Circle Faucet (faucet.circle.com) — initial master wallet funding (~$72 testnet USDC).
  • x402 protocol — Circle-supported open standard. We wrote a spec-compliant implementation from scratch because the x402 npm package does not yet support Arc (see Challenges #1).
  • Consciously NOT used (with reason): Circle Wallets (Dev-Controlled), Circle Gateway, CCTP / Bridge Kit. Every spawned company wallet in FendForItself is a viem.generatePrivateKey() EOA. We would have used Circle Wallets if the hackathon-hour onboarding had been lower (see Challenge #7).

Use case — why this exact stack

The thesis of FendForItself is sub-cent per-action pricing. A $0.005/call product does not survive Ethereum L1 gas ($0.50 per tx = −10 000% margin — one sale loses 100× its revenue) and barely breaks even on Base L2 ($0.003 per tx = 40% margin, fully erased by inference cost). Arc is the only production-grade L1 where USDC is the native gas token denominated in dollars. Our model stays above 98% margin on Arc and cannot exist on any other chain.

  • USDC was the natural quote currency: every AI agent already holds it, its $1 peg removes FX logic from pricing, and it's the only asset where a price quoted at $0.005 means $0.005 to the customer one second later.
  • x402 was chosen because it's the only HTTP-native payment standard. It turns every endpoint into a monetizable resource without API keys, sessions, or accounts. Agents discover, pay, and consume in a single round trip.

We picked the stack because it was the only combination that made the business model possible — not because it was easy.

Successes during development

  • Arc RPC stability under load. A 60-buyer demo run = 119 sequential transactions (60 funding + 59 settlement) in under 90 seconds. Sub-second finality verified on every hash.
  • USDC faucet frictionless. Master wallet funded in ~45 seconds on first try. No captcha, no queue, no waitlist.
  • EVM compatibility is real. viem.defineChain, writeContract, waitForTransactionReceipt — all worked out of the box. We didn't debug a single chain config issue.
  • Block explorer quality. testnet.arcscan.app is fast, readable, and every hackathon-required proof (tx lookup, wallet balance, contract interactions) was one click.
  • Gas predictability. USDC-denominated gas means we could quote user-facing costs in dollars with no FX logic anywhere in the codebase. This is a meaningful accounting simplification.
  • EIP-3009 as the x402 primitive. Once the EIP-712 domain was correct, signatures validated on first attempt. transferWithAuthorization is the right abstraction — gas-free for the signer, atomic verification + settlement in one call.

Challenges we actually encountered

These are the exact issues we hit. Each would have saved us hours if documented or shipped.

1. x402 npm package v1.2.0 does not support Arc. The Network Zod enum in src/types/shared/network.ts hardcodes only: abstract, abstract-testnet, base-sepolia, base, avalanche-fuji, avalanche, iotex, sei, sei-testnet, polygon, polygon-amoy, peaq, story, educhain, skale-base-sepolia, plus Solana. Neither arc nor arc-testnet is present. This means x402-next (Next.js middleware), x402-fetch (client wrapper), and x402-express all reject Arc at schema-validation time. We reimplemented the full x402 wire format from spec (lib/x402-server.ts, lib/x402-client.ts) using only viem for signing and on-chain submission. Works perfectly, but represents several hours of unexpected protocol re-derivation for what should be a single line of enum addition.

2. Arc USDC's EIP-712 domain name is "USDC", not "USD Coin". Every other Circle-issued USDC contract (Base, Polygon, Arbitrum, Avalanche, etc.) uses "USD Coin". On Arc, name() returns "USDC". This is not surfaced anywhere in docs.arc.network. We burned roughly two hours debugging FiatTokenV2: invalid signature reverts and only cracked it by calling name() directly on the contract and diffing our EIP-712 domain.

3. Arc USDC cannot be drained to exactly zero. transferWithAuthorization that would leave from at balance 0 reverts with Cannot clear balance of empty account. This is Arc-specific — because USDC is the native gas token, fully-zeroing also deactivates the account slot. It is currently undocumented. We hit it when our per-buyer funding was exactly equal to the purchase price. Our workaround in app/api/demo-loop/[companyId]/route.ts is to over-fund by price × 2 + $0.005. Stranded dust in throwaway wallets is accepted cost.

4. Dual-decimal representation of USDC is a footgun. Native gas balance is 18 decimals (via publicClient.getBalance()); ERC-20 interface balance is 6 decimals (via balanceOf()). Both return the same underlying value, just scaled differently. The contract addresses doc mentions this briefly, but once deep in code it is very easy to call the wrong one and quietly pass the wrong atomic amount to transferWithAuthorization. Two near-bugs in our codebase were averted only by defensive asserts.

5. x402 facilitator coverage on Arc is zero. Coinbase's hosted x402 facilitator does not support Arc. Circle Nanopayments does not expose a public testnet facilitator URL accessible without enterprise onboarding. For a "x402-on-Arc-first" hackathon, this meant either (a) wait for facilitator ecosystem to catch up, or (b) write your own. We took option (b) — our master wallet submits transferWithAuthorization calls itself. Works, but significantly increases code and security burden for every project that wants to sell x402-protected content on Arc.

6. RPC read-your-writes lag. transfer() confirms (receipt returned by waitForTransactionReceipt with ≥1 block), yet ~1.7% of the time, the immediately-following transferWithAuthorization for that same account reverts with ERC20: transfer amount exceeds balance. Observed 1 failure out of 60 in our reference demo run. State propagation is not quite "read-your-writes" from the RPC endpoint we used. No client-side retry is shipped in our code — we accepted the failure rate for demo purposes.

7. Circle Dev-Controlled Wallets onboarding exceeded our hackathon time budget. Entity Secret Ciphertext generation, 2FA enrollment, wallet set creation — each legitimate for production, collectively ~45–60 minutes for a team that has 48 hours total. We chose viem.generatePrivateKey() and a master-wallet EOA setup. This means we lost the "Circle Wallets–native" positioning points for the jury despite using every other Circle primitive. A "testnet fast-lane" mode would have flipped this decision.

8. Arc-specific docs are scattered. docs.arc.network has the RPC + chain ID. docs.arc.network/arc/references/contract-addresses.md has the USDC address and decimals note. But there is no single "Arc vs. stock USDC — what's different" page listing the three Arc-specific deviations (domain name, empty-clear revert, dual decimals). A single cheat-sheet page would 3× the pace of any new Arc build.

Recommendations, prioritized by impact

1. 🔥 Ship arc and arc-testnet in the x402 npm Network enum immediately. This is the single highest-leverage change in the entire ecosystem. Two files to edit (src/types/shared/network.ts and the EvmNetworkToChainId map); probably 20 lines of code total. Until this ships, every Arc hackathon team in the world either silently fails on x402-next/x402-fetch/x402-express, or reimplements the protocol from scratch as we did. Please do not let this be a 6-month PR.

2. Document Arc USDC's EIP-712 domain explicitly. Add to docs.arc.network/arc/references/contract-addresses.md, right under the USDC row, a copy-pasteable code block:

const domain = {
  name: "USDC",          // NOT "USD Coin"
  version: "2",
  chainId: 5042002,
  verifyingContract: "0x3600000000000000000000000000000000000000",
};

Each developer who Googles "FiatTokenV2: invalid signature" on Arc will arrive at this line and save two hours.

3. Document the empty-balance revert behavior. Create a new "Arc vs. stock USDC — behavioral deviations" page. List: (a) native gas token semantics, (b) can't drain to zero in one tx, (c) dual-decimal representation gotcha, (d) any future Arc-specific USDC quirks. Silent deviations from stock Circle USDC behavior are the #1 cause of 2h debugging sessions.

4. Ship an official hosted x402 facilitator for Arc. A public Cloudflare Worker or Circle-hosted service at e.g. x402-facilitator.arc.network that accepts /verify + /settle POSTs per the x402 spec and relays transferWithAuthorization onto Arc. This is the single biggest Arc x402 ecosystem gap. Once this exists, every x402 SDK in every language works on Arc with a single URL override. Without it, every project reinvents the relayer — which means every project has its own security bugs.

5. Publish a @circle/agent-sdk meta-package that bundles:

  • Circle Wallets Developer SDK
  • x402 client/server helpers pre-configured for Arc
  • Arc chain config (defineChain for viem)
  • EIP-3009 signer + EIP-712 domain helper for Arc USDC
  • Permit2 integration One npm install @circle/agent-sdk should be enough to be Circle-native on Arc in 2 minutes, not 2 days. Right now it's a scavenger hunt across @circle-fin/developer-controlled-wallets, x402, chain-specific contract addresses, and three different blog posts.

6. Add a "testnet fast-lane" to Circle Dev-Controlled Wallets. A mode that auto-provisions an Entity Secret behind the scenes and skips the 2FA prompt for testnet-only wallets. Reserve the full onboarding for mainnet. This would turn Circle Wallets into the default choice for hackathons; today we use viem because we cannot afford the setup.

7. Expose faucet.circle.com as an HTTP API (not just a web UI). Keep rate limits. But let CI, scripted demos, and CLI tools top up without a human click.

8. Publish canonical circlefin/-hosted reference implementations of an x402 seller on Arc and an x402 buyer on Arc. Not blog posts. Actual GitHub repos that are kept current. Each has a single entrypoint (npm install && npm start), working .env.example, and zero-config demo mode. When I searched for these, I did not find them.


Tech stack

  • Blockchain: Arc Testnet (chain 5042002)
  • Settlement currency: USDC (ERC-20 at 0x3600000000000000000000000000000000000000)
  • Payment protocol: x402 (spec-compliant Arc-native implementation, see lib/x402-server.ts and lib/x402-client.ts)
  • Settlement primitive: EIP-3009 transferWithAuthorization
  • LLM: Gemini 3 Flash (gemini-3-flash-preview) via @google/genai, with function calling
  • Framework: Next.js 15 (App Router, SSE route handlers)
  • Wallet / crypto: viem (EOA generation, EIP-712 signing, contract interaction)
  • Language: TypeScript end-to-end
  • Host: single Node.js process (state in-memory + JSON snapshot, no DB)

See CLAUDE.md for the deep-internals map — which file does what, the exact Arc gotchas we live with in code, and the dev discipline (one-task-one-commit loop) we followed throughout.


Getting started

Prerequisites

  • Node.js ≥ 20
  • A Gemini API key (free tier works)
  • A funded master wallet on Arc testnet

Setup

git clone https://github.com/ebenbaruk/FendForItself.git
cd FendForItself
npm install
cp .env.example .env.local

Edit .env.local:

GEMINI_API_KEY=your_gemini_key_here
MASTER_PRIVATE_KEY=0x_your_64char_hex_key   # 0x prefix optional

Fund the master wallet

  1. Derive the address from your MASTER_PRIVATE_KEY (any EVM wallet tool, or import into MetaMask).
  2. Go to faucet.circle.com, connect the wallet, select Arc network, claim testnet USDC.
  3. Verify balance at https://testnet.arcscan.app/address/YOUR_ADDRESS.

~$5 USDC is enough for ~10 full demo runs (60 buyers each).

Run

npm run dev
# open http://localhost:3000
  1. Type a one-line company brief (e.g. "sports-betting signals for trading bots").
  2. Watch the CEO roadmap populate, the wallet fund itself, and the product go live.
  3. Click run demo traffic — 60 buyer agents purchase from the company on-chain.
  4. Click any tx hash to verify on testnet.arcscan.app.

Deploy

The app is stateless enough to deploy to any Node.js host. We recommend Railway or Fly.io (single long-running process preserves the in-memory company registry across requests — Vercel's serverless cold starts will reset state between invocations). Paste GEMINI_API_KEY + MASTER_PRIVATE_KEY + PORT=3000 into the platform's env vars and push.


Roadmap (not in demo — clearly marked as "planned" in the UI)

These were in scope for the v2 but cut to preserve demo reliability. They're the natural next steps:

  • Real email marketing via AgentMail Bearer API. The CEO would draft 2–3 marketing emails and send them to hardcoded agent + human recipients. Honored tasks 6–8 in the current UI. Deferred because AgentMail's x402 integration lives on Base, not Arc, so paying it on-chain from Arc requires a bridge hop we didn't want to add mid-hackathon.
  • ERC-8004 on-chain identity. Each spawned company gets a real on-chain identity NFT + reputation registry entry. Aligns with the growing AI-agent trust-layer standard.
  • Multi-company marketplace. Spawned companies discovering and purchasing from each other on Arc — a truly closed agentic economy. The infra is ready; the orchestration logic and UI are not.
  • Circle Dev-Controlled Wallets. Swap viem random EOAs for real Circle Wallets when the testnet onboarding friction is reduced.
  • Bridge Arc → Base (CCTP). Let companies on Arc pay for real mainnet services (AgentMail, etc.) by briding revenue cross-chain.

Credits

Built by Eli Ben Baruk (@ebenbaruk) for Agentic Economy on Arc, April 2026.

Special thanks to Circle, Arc, and the Lablab.ai team for putting up the infrastructure that made this possible, and to the x402 Foundation for turning a 30-year-dormant HTTP status code into the plumbing of the agentic economy.


License

MIT — per hackathon rules. Reuse freely. If you build on this, let me know.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages