Marketplace API

Download text guide

LIMONATA MARKETPLACE — ACCOUNTS, RENTALS, MODEL API AND SETTLEMENT
=======================================
2026-10-31. Target mainnet date: 2026-11-11.

Implemented behavior
--------------------
Real accounts, verified payout-wallet ownership, provider-created listings,
search/filters, private provider endpoint records, API key creation/revocation,
provider agent heartbeats, exact LIMO quotes and provider dashboards.
There are no demo providers, synthetic GPU counts, fabricated deposit credits or invented payouts.
An empty inventory means no resources have been listed yet.

An already linked Windows GPU PC can run a separate owner-only private AI test:
https://limonata.xyz/assets/limonata-windows-ai-test-1.zip . GPU test v4 must have
cached its verified small model first. Start-Limonata-AI.cmd keeps that model
loaded and prints a private workspace link for the same account on a laptop.
The free10-minute session supports chat and a session-bound API key without
orders, reservations, funding or changes to the existing offline server listing.
It does not qualify Windows Linux-VM hosting. See the provider guide for limits.
Private keys use /api/marketplace/owner-ai/v1/models and /chat/completions only.
The regular paid model API, checkout and provisioning gates remain independent.

The rental pipeline is implemented: confirmed funding, signed booking, provider
provisioning, private service access, model inference, metered settlement,
refunds and provider withdrawals. A provider agent makes outbound authenticated
requests, runs only its locally installed profiles, and returns bounded results.
It supports model connectors, explicit trusted-container profiles and a CPU Kata
VM driver with no container fallback, and a dedicated Linux CPU QEMU/SSH driver; see the provider guide. GPU VM passthrough
is not enabled by this driver and still requires dedicated hardware qualification.

Production payments require a verified operator configuration for the actual
chain, escrow bytecode, finality, funded relay, metering key and acquisition
provider. They remain closed while this configuration is absent. No test provider,
local EVM credit or local fixture is presented as production LIMO.

Gas and payment boundary
------------------------
The intended product model remains: users pay LIMO for compute, never gas.
GET /api/marketplace/config exposes explicit sponsor, escrow, chain and finality
readiness, verified from the configured network. Without valid configuration, checkout
fails before requesting a transaction or moving money. Readiness is not a public
Boolean switch: chain ID, genesis, deployed code, confirmations and relay funds
are checked against operator-owned pins. See marketplace/settlement-config.mjs. There is no fallback
to user-paid gas when sponsor balance/budget is unavailable.

The new marketplace settlement contract is distinct from the old AI escrow: the old contract documentation does not establish mainnet finality, validated deployment,
marketplace provisioning or a never-user-paid gas funding rail. A signed payout
wallet proves ownership only; it never creates a balance or permission to spend.
Provider earnings are derived from confirmed service settlements; withdrawable
credit is read from the finalized escrow state. It remains unknown if the chain
cannot be verified. A personal ownership signature never creates funds.

Backend integration
-------------------
  import { createMarketplaceHandler } from './marketplace/api.mjs';
  const handleMarketplace = createMarketplaceHandler();

Inside the existing HTTP server, before other API routes:
  if (await handleMarketplace(req, res, u, ipOf(req))) return;

Options: dataFile, publicOrigin, secureCookies, now (for tests), store (for tests).
Default origin: MARKETPLACE_PUBLIC_ORIGIN or https://limonata.xyz.
All cookie-authenticated mutations require exactly that Origin, JSON bodies
when data is needed and X-CSRF-Token from /session or sign-in response.
Canonicalize www/alternate frontend origins to the configured origin.
No forwarded host is trusted. HTTPS origins use Secure cookies. Local test
servers must explicitly select an HTTP publicOrigin; never disable Secure on
the deployed HTTPS site.

Data persistence and operations
-------------------------------
Default file: .data/marketplace/state.json, mode 0600 in mode 0700 directory.
This ignored runtime file contains account email addresses, salted scrypt
password hashes, hashed session/API tokens, CSRF tokens, verified wallets and
listing records. Back it up as private application data, never as source code.
No plaintext passwords, raw API secrets, blockchain private keys or model
provider credentials are stored. API secrets are shown once at creation.

Mutations reload state under an exclusive .lock file; writes fsync a unique
temporary file, rename it atomically and fsync its directory. Concurrent
processes serialize. Corrupt or unsupported state fails closed; it is never
silently replaced with an empty database. A failed mutation does not commit.
A process crash may leave a .lock file; inspect its recorded PID and confirm
no writer exists before removing the lock. Do not remove locks from a live
service. Full filesystem or lock failure returns unavailable and never starts
payment. Initial absence of the file is valid; initial public reads do not
create application state.

This storage is suitable for the first single-host release. A multi-host
production release needs a transactional database plus shared rate limits,
backup/restore drills, and reviewed retention/account recovery procedures.
Current rate limits are per process (240 requests/minute/IP,600/account,300/API
key,12 auth attempts per email and IP per15minutes). Password hashing, body
deadlines, active HTTP requests and synchronous model waiters are also bounded.
Keep one public application instance or add
a centralized rate limiter before scaling. Each account is limited to 100
listings, 20 active API keys, 10 sessions and 50 unexpired quotes. Quotes expire
after 10 minutes and are purged when creating another quote or a session.

Account limitations requiring follow-up
---------------------------------------
Email delivery/verification, password reset, account deletion/export and MFA
are not implemented. API explicitly reports emailVerified:false. Do not imply
ownership of an email address was verified. Passwords require 12-256 characters
and use scrypt N=16384,r=8,p=1 with random salt. Sessions last 7 days, rotate
on sign-in, are stored hashed, and can be revoked through sign-out.
EVM personal-message signatures bind payout wallets to the canonical domain,
account ID, unique nonce and five-minute expiry. Wallets cannot be shared
across marketplace accounts. Changing wallet after creating listings is blocked
pending a safe reviewed migration; API keys cannot link/change wallets.

API reference
--------------
Base path: /api/marketplace. All timestamps are Unix milliseconds.
Money is a decimal string; wei uses 18 decimals and BigInt, never float math.
All responses JSON, no-store. Errors: {error,code,message}.

GET /config
  {launchDate,types,paymentsEnabled,payments,gasless:true,
   modelGatewayEnabled,provisioningEnabled,apiKeyScopes,...}

GET /session
  {user:null} or {user:{id,name,email,walletAddress,emailVerified:false},csrfToken}
POST /auth/register {name,email,password} -> 201 {user,csrfToken} + cookie
POST /auth/login {email,password} -> {user,csrfToken} + cookie
POST /auth/logout -> {ok:true}, revokes current session and clears cookie

POST /wallet/challenge {address} -> {challenge:{id,message,expiresAt}}
  User signs challenge.message using personal_sign / signMessage, no transaction.
POST /wallet/verify {challengeId,signature} -> {user}
  Consumes a one-use challenge and verifies recovered wallet address.

GET /listings?type=gpu|server|model&q=...&region=...&minVram=...&sort=price_asc
  Optional sort=price_desc|newest|vram_desc, limit 1..100, offset.
  Filtering and sorting happen before pagination. Returns {listings,total}.
  Public listing fields: id,type,title,description,region,gpuModel,gpu,vramGb,
  gpuCount,cpuCores,cpu,ramGb,storageGb,priceLimoPerHour,payoutAddress,modelName,
  status,verified:false,availability,provider:{id,name},timestamps.
  Listings have availability offline or reported_online. Public responses never
  expose endpointUrl or account email. Paused listings are hidden from search.

POST /listings
  {type,title,description,region,gpuModel,vramGb,gpuCount,cpuCores,ramGb,
   storageGb,priceLimoPerHour,payoutAddress,modelName,endpointUrl}
  Fields depend on type. Prices positive, at most 8 fractional decimals;
  hours/bytes/hardware counts integer. Payout must match verified account wallet.
  GPU requires model/count/VRAM; server requires CPU/RAM/storage; model requires
  modelName and HTTPS endpointUrl. Endpoint stored privately, never fetched.
  -> 201 {listing}. New listing status listed, offline and unverified.

PATCH /listings/:id
  Own listings only. Allowed fields: title,description,region,priceLimoPerHour,
  status (listed|paused). Resource identity/payout cannot be silently switched.

POST /providers/heartbeat {listingId,ready:boolean}
  Bearer API key with providers:write required, listing ownership enforced.
  Report every 30-60 seconds; presence expires after 120 seconds. No probe or
  attestation is implied. Session cookies are insufficient for this agent route.

GET /dashboard -> {dashboard:{listings,orders,earnings,payoutAddress,payments}}
  Owner listing responses include private endpointUrl. Session or dashboard:read.
POST /quotes {listingId,hours:1..720} -> {quote,payments}
  Own resource rentals rejected. Quote freezes exact rate, duration, payout and
  totalWei/totalLimo; expiry 10 minutes; checkoutEnabled reflects verified settlement, userGasLimo:'0'.
POST /orders {orderId,signature} -> funded booking; see preparation flow below
GET /orders -> {orders,payments}; session or orders:read key

GET /keys -> {keys,scopes}, browser session only
POST /keys {name,scopes?,expiresInDays?,listingIds?} -> 201 {key,secret}, browser session + CSRF only
  Default scopes ['listings:read']; permitted scopes include listings:read,
  listings:write,orders:read,orders:write,compute:write,providers:write,dashboard:read.
  New keys expire after90days by default; expiresInDays accepts1..365.
  Optional listingIds binds the key to1..100 selected owned listings. Provider
  keys default to a snapshot of the current owned listings if omitted, and cannot
  control future listings automatically. The browser asks for the listings on the
  provider machine. Expiry and listingIds appear in the safe key metadata.
  Bound keys cannot read account-wide dashboard/balance aggregates. Other reads,
  mutations and inference results remain restricted even with mixed scopes.
  Legacy unbound/non-expiring keys remain compatible; rotate before production.
DELETE /keys/:id -> {ok:true}, owner browser session + CSRF only
  Bearer keys cannot create/revoke other keys. Revocation is immediate.

Provider/API requests use Authorization: Bearer limo_mk_<secret>.
Cookie mutations require CSRF; Bearer actions require matching scopes and
ownership and reject a hostile Origin when one is present.

Rental, funding and withdrawal API
---------------------------------
GET /payments/status -> verified readiness, network, acquisition, sponsor, escrow
GET /payments/balance -> {balance:{creditWei,creditLimo,...},payments}
POST /payments/funding/verify {transactionHash,fundingId?}
  Imports a confirmed native-value funding event from an allowlisted acquisition
  provider/sponsor, matching the linked owner. Does not credit a caller's amount.
POST /orders/prepare {quoteId} -> {order,authorization:{typedData,...}}
  Requires existing confirmed LIMO credit and available provider capacity.
  The customer signs typedData with eth_signTypedData_v4, never a transaction.
POST /orders {orderId,signature} -> confirmed escrow + provisioning state
GET /orders/:id/access -> private access mode for the customer
POST /orders/:id/cancel -> immediately revokes access and queues provider teardown
POST /payments/withdraw/prepare {amountWei} -> {withdrawalId,authorization}
POST /payments/withdraw/submit {withdrawalId,signature} -> confirmed native payout
  An owner signs typedData; a relay pays gas. The recipient is the linked wallet.
  Signed transactions are journaled before broadcast and reconciled after restart.

Automatic Windows/Linux provider setup
--------------------------------------
The Windows/Linux assistant detects hardware, pairs through a browser code and creates
private configuration automatically. No manual hardware specifications or API
key copy is needed. Run the verified installer from:
https://limonata.xyz/provider/install.sh
Windows: https://limonata.xyz/provider/install.ps1
ZIP: https://limonata.xyz/assets/limonata-provider-agent-1.3.0.zip

POST /providers/enrollment/start {devicePublicKey,inventory,offers}
POST /providers/enrollment/poll {deviceToken}
POST /providers/enrollment/cancel {deviceToken}
GET /providers/enrollment/:userCode (browser session)
POST /providers/enrollment/approve {userCode,offers,publish?} (session+CSRF+wallet)
The device receives an X25519/HKDF/AES-GCM encrypted provider key; the browser
never receives its plaintext. Codes expire after ten minutes and polling is
limited. Approval respects recommended hardware budgets and creates resources
offline/unverified. Services require local preparation before readiness.

Provider transport
------------------
POST /providers/jobs/claim {workerId,listingIds?} -> {job?}
POST /providers/jobs/:id/renew {leaseToken}
POST /providers/jobs/:id/complete {leaseToken,result}
POST /providers/jobs/:id/fail {leaseToken,reason?}
  Requires providers:write key and ownership. Leases expire; retries are bounded.
  The server never requests a provider-supplied URL. Host connector URLs and
  credentials stay on the provider machine. Workloads cannot supply images,
  Docker switches, shell commands or private host paths.

Model and server access
-----------------------
POST /orders/:id/inference {request:{messages,max_tokens?,temperature?,stream:false},idempotencyKey}
POST /orders/:id/requests {request:{method:'GET'|'POST',path,body?},idempotencyKey}
GET /inference/:requestId -> pending, succeeded with response, or failed
  Requires the active funded rental owner. Bearer access needs compute:write.
GET /v1/models -> only the caller's active rented models, IDs limo:<orderId>
POST /v1/chat/completions {model:'limo:<orderId>',messages,max_tokens?,tools?,stream?}
  Bounded OpenAI-compatible text and function-call subset. JSON or SSE response;
  SSE chunks are emitted after the provider finishes (not live token streaming).
  The call waits up to95seconds, then returns a timeout instead of an async202.
  Optional Idempotency-Key prevents duplicate inference on a repeated HTTP call.
  Tools are structured data for the customer's client; the provider never executes
  their commands. Endpoints, credentials and the installed model remain fixed.
GET /orders/:id/workspace
POST /orders/:id/workspace/keys
POST /orders/:id/workspace/chats
GET|DELETE /orders/:id/workspace/chats/:chatId
POST /orders/:id/workspace/chats/:chatId/messages
  Cookie-authenticated rental owner only. Histories persist until rental end.
  Access keys are bound to one order, hashed and expire with the rental.
  Expiry/cancellation removes chat/input/output content from canonical state and
  revokes rental keys. New deployment backups omit rental text. Financial/order
  records remain. External client/provider copies cannot be remotely erased.
WSS /api/marketplace/ssh-relay
  First-message authentication, no secrets in URLs. Both provider and renter must
  match the active SSH VM rental. Only encrypted guest SSH is forwarded, no public
  process command execution or arbitrary TCP destination. End-of-rental revocation
  closes connections. The client ZIP contains Windows/Linux/macOS instructions.
  Booking a QEMU listing requires sshPublicKey (Ed25519 or RSA>=2048) on the quote.
  Customer private SSH keys never leave the client. CPU Linux host only; no GPU
  passthrough or Windows VM host qualification. Dedicated hardware acceptance remains.

Public endpoint metadata remains private and is never used as an egress target.
A provider declaration is not a hardware attestation. The provider is responsible
for installing its real model and approved Docker image/profile. The platform's
meter, explicitly authorized in the signed booking, settles delivered duration;
customers can end service and receive unused credit. See settlement-design.txt
for this trust model, finality and operator configuration requirements.

Provider guide: https://limonata.xyz/marketplace/provider-guide
Provider download: https://limonata.xyz/assets/limonata-provider-agent-1.3.0.tar.gz
Security architecture and remaining production boundaries:
https://limonata.xyz/marketplace/security

Verification
-------------
  node --test marketplace/api.test.mjs marketplace/compute.test.mjs marketplace/settlement.test.mjs marketplace/commerce-recovery.test.mjs marketplace/lifecycle.test.mjs

Tests cover account hashing/cookies, origin+CSRF, wallet signature/replay/expiry,
listing/heartbeat ownership, key hashing/scopes/revocation, private endpoints,
filters, dangerous endpoint metadata, exact LIMO math, blocked checkout,
stale/changed quotes, zero unverified earnings, durable writes, concurrent
writers, transaction failure, lock refusal and corrupt-state fail-closed.
Tests use temporary application state, randomly generated test wallets and
local loopback HTTP only. They do not contact a chain or move any funds.