Reader Guide
Normal reader
Focus on Overview, How It Works, and Deployment.
Judge
Read Stacks Alignment, Security, and Judging Criteria first.
Builder
Inspect API Reference, Deployment, and Truthful Status.
Lend402 Overview
The Stacks-native payment and credit rail for agentic APIs.
Lend402 is the closest thing to Stripe for agentic API calls on Stacks. A provider wraps an endpoint behind x402, an agent receives an HTTP 402 challenge, and the request is financed and settled on Stacks with sBTC-backed USDCx before the origin response is returned.
One-Sentence Pitch
Lend402 lets an AI agent pay for a request the moment it needs it, using Stacks as the settlement layer and sBTC-backed credit instead of API keys and monthly billing.
Product
x402 Payment + JIT Credit
Paid agent calls wrapped around Stacks-native settlement.
Core Assets
sBTC + USDCx
sBTC secures the credit path and USDCx handles priced API settlement.
Deployment
Vercel + Railway
Next.js on Vercel, Postgres and Redis on Railway, settlement on Stacks.
Target Network
MAINNET
CAIP-2 network id stacks:1.
End-to-End Flow
How a paid request moves through the system
01
Provider registers an API vault
The provider submits an origin URL, a per-call USDCx price, rate limits, and optional webhook details. Lend402 stores that vault in Postgres and exposes a wrapped payment-aware endpoint.
02
Agent hits the wrapped endpoint
The gateway returns HTTP 402 with an x402 V2 challenge that specifies the Stacks network, the asset, the price, the payee, and the request resource.
03
Agent finances and signs the call
The agent SDK runs a read-only collateral preview, falls back to a live DIA quote if the vault cache is cold, builds the Clarity borrow-and-pay transaction, attaches strict post-conditions, signs the transaction, and retries with the official x402 payment-signature header.
04
Gateway validates and settles
Lend402 parses the payment payload, guards against replays and rate abuse, broadcasts the signed Stacks transaction, waits for confirmation, and records the call.
05
Origin response is released
Once settlement confirms, the gateway forwards the request to the provider origin and returns the upstream response with an official x402 payment-response receipt header.
06
Provider dashboard reflects revenue
Vault owners can review call counts, wrapped URLs, earnings, and recent payment activity from the dashboard surfaces inside the app.
Payment Sequence
GET /v/{vault_id}/path
checkGlobalRateLimit() · checkAndIncrRateLimit(challenge)
402 Payment Required · payment-required header (x402Version: 2)
GET /v/{vault_id}/path · payment-signature header
parsePaymentSignatureHeader() · verifyXPayment() · validateBorrowAndPayTransaction()
getSettled(txid) — replay check · checkAndIncrRateLimit(rate)
broadcastTransaction(signedTx)
borrow-and-pay(amount, merchant, collateral)
fetch-live-sbtc-price() · 150% collateral ratio check · transfer sBTC in · transfer USDCx out to merchant
setSettled(txid, { blockHeight, payer })
Forward request (payment headers stripped) + x-lend402-* injected
200 OK + response body
200 OK + payment-response header · { success, txid, blockHeight }
Stacks Alignment
Why this product belongs on Stacks
Lend402 is not a generic API paywall lightly renamed for a Bitcoin hackathon. The core value proposition depends on Stacks-specific primitives.
The borrow-and-pay path is written in Clarity. The settlement asset path is framed around sBTC collateral and USDCx-denominated pricing. The agent and gateway speak Stacks network identifiers, build Stacks transactions, and rely on Stacks tooling for signing, verification, and broadcast.
That means the system is aligned with the exact judging language around Clarity, sBTC, USDCx, stacks.js, and broader Stacks dev tooling. The idea is not just that the UI mentions those primitives; the runtime flow depends on them.
Clarity Vault
The core contract is SP31DP8F8CF2GXSZBHHHK5J6Y061744E1TNFGYWYV.lend402-vault-v7. It handles borrow-and-pay, liquidity accounting, collateral checks, cached DIA-backed quote paths, and provider-directed settlement.
Stacks Agent SDK
The agent client intercepts 402 responses, computes borrowing requirements, builds the Stacks transaction, signs it, and retries the request with a valid x402 payload.
Gateway and Proxy
The Next.js gateway is both the x402 boundary and the payment-aware reverse proxy. It enforces payment, persists call metadata, and safely forwards the origin request.
Postgres and Redis
Postgres stores vaults and settled calls. Redis is used for rate limiting, replay protection, and settlement idempotency where low-latency lookups matter.
Cache Warmer Route
An authenticated internal route can submit refresh-price-cache on-chain from a dedicated relayer wallet so the contract's cached DIA quote stays warm for read-only paths.
Security Model
Controls already in the codebase
Deployment
How the product is currently meant to run
Recommended Topology
Vercel hosts the Next.js frontend and API routes.
Railway Postgres stores vault registrations, calls, and dashboard data.
Railway Redis handles rate limiting, replay protection, and settlement idempotency.
Stacks mainnet is the intended settlement layer.
Operational Notes
The schema now lives under database/migrations.
Environment variables use DATABASE_URL and REDIS_URL.
Railway service references follow the ${ServiceName.VAR_NAME} pattern.
Mainnet is the default stance; testnet is only for explicit validation work.
Repository Map
contracts/lend402-vault-v5.clar
The deployed lending and settlement contract.
packages/agent-sdk/src/
The standalone npm SDK — interceptor, types, network helpers, and x402 utils.
src/app/api/v/[vault_id]/[[...path]]/route.ts
The payment gateway, settlement boundary, and origin proxy.
src/app/(app)/vault/*
Provider registration and dashboard pages.
database/migrations/*
Postgres schema and migration history.
API Reference
Gateway and management endpoints
/v/{vault_id}/{path}402 / 200Payment gateway. Returns 402 challenge without payment-signature; forwards to origin and returns 200 with payment-response header after settlement.
/api/vaults201Register a new API vault. Requires authenticated wallet signature. Returns vault_id and wrapped gateway URL.
/api/vaults200List vaults for the authenticated wallet address. Returns vault metadata and per-vault call counts.
/api/internal/refresh-price-cache200Authenticated internal route. Submits a refresh-price-cache transaction to warm the on-chain DIA oracle cache.
x402 Headers
payment-required← Response
Base64 JSON challenge. Contains x402Version, resource, and accepts[].
payment-signature→ Request
Base64 JSON payment. Contains signed transaction hex and accepted option.
payment-response← Response
Base64 JSON receipt. Contains txid, blockHeight, payer, and success flag.
Agent SDK
npm install @winsznx/lend402
The payment interceptor is published as a standalone npm package so any AI agent can integrate JIT micro-lending without depending on the full Lend402 repo. Install it, spread mainnetConfig(), add your private key and vault address, and every HTTP 402 your agent hits is automatically financed and retried in a single await.
On a failed borrow or signing error the interceptor throws — the vault's PostConditionMode.Deny guarantee means no funds move. The agent's treasury is unchanged on any error path.
withPaymentInterceptor(config, axiosConfig?)Returns an Axios instance with the 402 interceptor attached. Runs simulate-borrow, signs borrow-and-pay with PostConditionMode.Deny, and retries the original request transparently.
mainnetConfig()Partial AgentClientConfig for Stacks mainnet (stacks:1). Includes StacksMainnet network object and canonical sBTC and USDCx contract addresses. Spread with your privateKey, agentAddress, and vault contract details.
testnetConfig()Same as mainnetConfig() but targeting stacks:2147483648 with the corresponding testnet contract addresses.
AgentClientConfigTypeScript interface for the full interceptor configuration — privateKey, agentAddress, network, caip2Network, vault and token contract details, plus optional timeoutMs, maxPaymentRetries, and onEvent callback.
AgentEventStructured event emitted at each stage: REQUEST_SENT · PAYMENT_REQUIRED_RECEIVED · SIMULATE_BORROW_OK · TX_BUILT · TX_SIGNED · PAYMENT_HEADER_ATTACHED · REQUEST_RETRIED · PAYMENT_CONFIRMED · DATA_RETRIEVED · ERROR.
Judging Criteria
How the current codebase aligns, truthfully
Innovation
Strong
The differentiator is not only x402 paywalls. Lend402 adds just-in-time credit, so an agent does not need to pre-hold the full payment asset for every call.
Technical Implementation
Strong, with remaining hardening work
The flow spans Clarity, signed Stacks transactions, typed x402 payloads, DIA-backed pricing, settlement polling, Postgres persistence, Redis controls, and provider-facing operational tooling.
Stacks Alignment
Very strong
The product depends on Stacks-specific primitives: Clarity, sBTC, USDCx, stacks.js tooling, Stacks network identifiers, and Stacks transaction semantics.
User Experience
Good and improving
Providers get a registration path and dashboard, while agents interact with a single payment-aware endpoint. The next UX frontier is embedded wallets and lower-friction production onboarding.
Impact Potential
Strong
This is infrastructure for agentic commerce on Stacks, not just a single end-user app. It can be reused across paid data APIs, inference endpoints, and autonomous tools.
Truthful Status