System objective
AutoLayer is an execution plane between applications or agents and Stellar, Soroban, and paid HTTPS services. It removes RPC, XDR construction, transaction simulation, fee sponsorship, payment negotiation, and service discovery from the caller-facing interface while preserving wallet authorization and non-custodial fund ownership.RFP delivery boundary and Stellar integration
This architecture directly addresses the X402 Facilitator with Bazaar (Discovery) Support RFP. The grant boundary is the x402 facilitator, Stellar-native Bazaar, MCP agent interface, Stellarupto contribution, SDKs, examples, conformance, security hardening, and production operation. AutoLayer’s broader automation runtime remains available to the product but is not used to inflate the RFP scope or budget.
The working MVP is deliberately separated from grant acceptance:
Selected building blocks
The runtime dependency graph excludes the AGPL OpenZeppelin Relayer, its x402 plugin, and its SDK. The repository is Apache-2.0 and the dependency gate inventories reachable production packages before release.
Repository layout
Web application
apps/web is a Vite-built React single-page application. The same artifact supports the public site and console deployment:
autolayer.fiserves product pages and/playground.console.autolayer.firedirects/to/console.VITE_API_URLselects the API origin at build time.
@stellar/stellar-sdk, request signatures through Stellar Wallets Kit, reconstruct signed envelopes, and submit to Horizon.
Wallet integration uses the v2 static API from @creit-tech/stellar-wallets-kit. The kit is initialized once with defaultModules(), connection uses authModal(), reload restoration uses getAddress(), and signing uses signTransaction() or signAuthEntry(). Before each signature AutoLayer calls setNetwork() with the explicitly selected testnet or pubnet passphrase. Wallets without SEP-43 auth-entry support may connect and sign Classic transactions but cannot complete x402 Soroban authorization signing.
API process
apps/api/src/index.ts configures the process in this order:
- Security headers with Helmet.
- Configurable CORS origins.
- A 256 KB JSON body limit.
- Structured Pino request logs.
- Canonical x402 middleware for the paid example.
- Automation, facilitator, discovery, skills, and MCP routers.
- A centralized non-leaking error handler.
- PostgreSQL connectivity, Agenda handler registration, and scheduler startup.
- Graceful SIGINT/SIGTERM shutdown of Agenda and PostgreSQL.
x402 facilitator
The facilitator is composed withx402Facilitator from @x402/core and ExactStellarScheme from @x402/stellar/exact/facilitator. AutoLayer does not maintain a private fork of exact verification.
Two explicit registrations are created:
extra.areFeesSponsored: true. A configurable maximum transaction fee is a safety ceiling. The payment relayer signs and submits the facilitator-built invocation; the buyer signs Soroban authorization entries rather than a prebuilt settlement transaction.
Standard endpoints
The body is the canonical object:
Exact authorization and settlement flow
The buyer signs a Soroban authorization entry, not a pre-signed transaction. The canonical base64PaymentPayload carries the upstream Stellar payload: { transaction } form verbatim. Verification binds the signature to the declared invocation tree, CAIP-2 network, SEP-41 token contract, integer amount, recipient and ledger expiration. Classic G... accounts use native signatures; custom contract accounts execute their __check_auth policy.
maxTimeoutSeconds is converted to a bounded signatureExpirationLedger using current ledger cadence. Values use SEP-41 integer base units: seven decimal places means one unit is 0.0000001 token and no floating-point arithmetic is permitted. Seller onboarding checks that Classic recipients have the required trustline before advertising an issued asset.
Settlement repeats all security-critical verification after simulation, enforces the configured resource-fee ceiling, submits through a dedicated fee-paying signer, waits for a final transaction result and returns its hash. Tampering changes the authorized invocation and fails signature validation. Expired authorizations fail closed. Production replay protection records authorization/transaction identities and confirmed outcomes; a timeout is reconciled against Stellar before any resubmission so an indeterminate result cannot become a double charge.
Network behavior
Testnet uses the upstream default Soroban RPC. Pubnet usesSTELLAR_MAINNET_RPC_URL. Stellar identifiers are never inferred from the API environment. A payment explicitly selects one CAIP-2 network.
The facilitator account requires XLM for inclusion and resource fees. Buyers require the payment asset but do not require XLM when fees are sponsored. Recipients of issued Classic assets must establish the relevant trustline; SEP-41 contract-account behavior depends on the token implementation.
Stellar upto settlement
Metered services cannot know the final price when authorization is created. AutoLayer therefore proposes a Soroban contract-backed Stellar upto scheme rather than relying only on SEP-41 approve and transfer_from, which cannot independently guarantee recipient binding and single settlement.
The current draft is in specs/schemes/upto/scheme_upto_stellar.md, with a testnet contract in contracts/upto-settlement. The payer authorizes a tuple containing the domain, CAIP-2 network, contract address, payer, token, fixed recipient, maximum amount, nonce, expiration ledger and facilitator. The actual amount is supplied at capture time, must be non-negative and no greater than the maximum, and is transferred directly from payer to recipient. The contract never takes custody.
The consumed (payer, nonce) key prevents replay and is retained with a TTL beyond the authorization’s validity window. The contract records no balance and adds no registry write to exact payments. Soroban simulation, instruction/memory/read/write ceilings and state-rent monitoring are required release checks. Smart accounts can add daily caps, token allowlists, approved facilitator/recipient sets and per-call limits inside __check_auth while preserving the protocol tuple.
Grant-period integration includes finalizing the network specification with the x402 Technical Steering Committee, contributing client/facilitator adapters and fixtures to the upstream package, resolving review feedback, publishing deployments and settled hashes on testnet and pubnet, and completing contract/off-chain security review. AutoLayer will not advertise production upto support until those gates pass. Batch settlement and auth-capture remain explicitly compatible phase-two extensions and are outside this grant.
Bazaar discovery
Discovery metadata is declared by resource servers withdeclareDiscoveryExtension and transported in the x402 v2 extension block. AutoLayer uses extractDiscoveryInfo(..., true) from @x402/extensions/bazaar for schema and protocol validation.
Cataloging occurs only after successful settlement. A verify-only request cannot write to the catalog. The result is returned in a base64-encoded EXTENSION-RESPONSES header so sellers can distinguish successful cataloging from a soft drop.
HTTP resources are keyed by URL. MCP resources are keyed by the tuple resource URL + tool name. The PostgreSQL row stores:
- Resource key, URL, and
httpormcptype - MCP tool name when applicable
- x402 version
- Description, MIME type, service name, and tags
- Accepted payment requirements as JSONB
- Echoed extension data and validated discovery information as JSONB
- Last update timestamp
- A generated weighted full-text search vector
GET /discovery/resources supports type, payTo, scheme, network, extension, limit, and offset. GET /discovery/search uses websearch_to_tsquery and ts_rank_cd, orders equal scores by freshness, fetches one additional row to calculate partialResults, and returns an opaque base64url cursor.
Catalog integrity
Discovery processing is a soft-drop side effect: invalid metadata never changes payment settlement, but it is rejected from the catalog and its machine-readable outcome is returned throughEXTENSION-RESPONSES. Validation checks the schema advertised by the extension, rejects unsupported external references, binds catalog payment terms to the successfully settled requirements, and never trusts client-echoed pricing independently.
routeTemplate is percent-decoded before traversal and normalization checks, so encoded .., separators and ambiguous paths cannot bypass validation. HTTP identity is the normalized resource URL; MCP identity is the required tuple of resource URL and input.toolName. The production origin-control layer will use an HTTPS challenge or signed well-known document, with renewal and conflict rules, before allowing a listing to claim a public origin.
Search quality and evaluation
The MVP uses PostgreSQL weighted full-text retrieval: service name and tags receive greater weight than descriptions and parameter text, ranking usests_rank_cd, and freshness is only a deterministic tie-breaker. Cursor pagination fetches one extra result to set partialResults accurately.
A checked-in relevance set currently exercises ten natural-language queries over twelve representative resources. The recorded local baseline is nDCG@10 0.9983, MRR 1.0000, recall@10 1.0000, with p95 query latency reported separately from ranking quality. During the grant this becomes a versioned, larger and adversarial corpus covering HTTP and MCP resources, misspellings, intent synonyms, network/asset filters and zero-result queries. CI will fail on agreed regression thresholds; production dashboards will track p50/p95 latency, zero-result rate and clicked/paid outcomes. Hybrid lexical/vector retrieval may be introduced only when measured results justify its operational cost.
Conformance upkeep and interoperability
AutoLayer stores Bazaar data in the canonical x402 resource shape instead of a Stellar-only projection. Seller helpers emit per-parameter descriptions and the standard extension; buyer helpers consume the same pagination and resource fields used by other facilitators. The team will monitor x402 Foundation specification changes and Technical Steering Committee decisions, pin reviewed package versions, run scheduled compatibility tests against upstream main, and update fixtures when endpoint shapes, filters or cataloging rules evolve. Each release will include a wire-level diff review and cross-facilitator fixture run. This maintenance commitment continues through the grant period and the production handoff; the awarded implementation will not freeze discovery behavior at the award-date draft.Agent and skills interface
POST /mcp implements JSON-RPC initialization, tools/list, and tools/call. The current tools are:
search_services: natural-language Bazaar search with network and limit inputs.paid_call: forwards a caller-provided x402 payment signature to an HTTPS resource already present in the catalog.
data.reason. Paid calls accept HTTPS only, require an exact catalog match, apply a 30-second timeout, and return the upstream status, response body, and PAYMENT-RESPONSE receipt.
GET /v1/skills supports intent, protocol, network, and action filters. GET /v1/skills/:slug/spec returns a versioned contract with authentication mode, action input/output schemas, safety requirements, and deterministic retry semantics so an agent does not need Stellar CLI, RPC, XDR, or SDK knowledge.
Automation runtime
Automation proposals are persisted in PostgreSQL and scheduled through Agenda’s PostgreSQL backend. The domain supports generic typed Soroban contract calls, DCA, rebalancing, and disbursement policy proposals. A proposal creates a fresh delegate keypair, derives a deterministic policy identifier, encrypts delegate material with AES-GCM and contextual additional authenticated data, prices the requested finite run count, and returns wallet session-creation material. Generic calls bind the wallet session to the exact contract and function; the contract must enforce argument-sensitive financial invariants. Lifecycle states distinguish proposal, payment, activation, active execution, pause, completion, cancellation, failure, and expiration. Jobs are registered before Agenda starts. Run limits and wallet session authorization limits are stored separately because one scheduled disbursement can consume multiple transfer authorizations. The Soroban convention is:xWrapper gateway
xWrapper is a first-class AutoLayer Gateway feature, not another name for the facilitator. Its target request path is:Implementation
Wrapper and vault records are owner-scoped in PostgreSQL. Operator keys are compared as SHA-256 digests with constant-time equality; the derived owner identifier is stored instead of the key. Vault values use AES-256-GCM with a unique nonce, authenticated context containing the secret ID, and key-version enforcement. The public proxy emits canonical x402 v2PAYMENT-REQUIRED, decodes PAYMENT-SIGNATURE, verifies and settles through @x402/stellar, then returns PAYMENT-RESPONSE. Enabled wrappers are upserted into the off-chain Bazaar and removed on disable or deletion.
Outbound targets must use HTTPS. Userinfo, loopback, link-local, private, reserved, .local, and .internal targets are rejected. Every resolved address must be public, the chosen address is pinned into the TLS connection, redirects are rejected, sensitive and hop-by-hop headers are stripped, and request/response size and time limits are enforced.
Rate and monthly quota counters use atomic PostgreSQL upserts so limits hold across multiple API replicas. Request logs and settlement records power the Console analytics view.
Remaining launch gates
External KMS custody forKEY_ENCRYPTION_MASTER_KEY, secret rotation UI, retention jobs for quota/audit tables, circuit breaking, penetration testing, external security review, and live mainnet conformance evidence remain operational release gates.
Data protection and keys
Automation delegate keys are encrypted at rest using a 32-byte master key and versioned encryption metadata. The payment relayer and automation paymaster must be separate funded accounts. Environment validation rejects reuse of the same secret. Production should replace static environment secrets with workload identity and KMS-backed secret retrieval. Key rotation must retain decryption support for prior ciphertext versions until data is rewrapped. Logs must redact payment signatures, authorization XDR, secrets, and authorization headers.Deployment topology
Run migrations as a single pre-deploy job. API replicas may scale horizontally. Agenda locking and PostgreSQL advisory locks coordinate scheduled work. Settlement throughput should use multiple channel signers or fee-bump separation to avoid a single account sequence bottleneck. The upstream Stellar facilitator supports signer selection and a separate fee-bump signer; production configuration should use those facilities rather than sharing one sequence source under burst load.Availability and degraded modes
- If PostgreSQL is unavailable, readiness fails and mutating endpoints stop.
- If a Stellar RPC is degraded, the corresponding network is unavailable; the other network must remain independently observable.
- Verify failure never falls through to resource delivery.
- Settlement timeout is indeterminate, not a safe retry signal. Reconciliation must query transaction state before resubmission.
- Bazaar search can remain read-only during settlement degradation.
- Scheduler jobs use bounded retries and record the last error; terminal financial errors require operator review.
Observability
Production instrumentation should expose request latency and error rate by route, verification rejection reason, settlement duration and outcome by network, RPC simulation/send latency, signer sequence utilization, Agenda queue depth and lock age, automation run outcome, Bazaar indexing soft-drop reasons, search latency and zero-result rate, and paid-call upstream latency. Alerts should cover elevated invalid-reason rates, settlement confirmation timeout, low paymaster XLM balance, signer sequence contention, database saturation, scheduler lag, and catalog write failures.Security threat and control map
The grant-period threat model will enumerate assets, actors, entry points and abuse cases for
/verify, /settle, discovery ingestion, MCP forwarding, operator APIs and the upto contract. It is delivered with the on-chain monitoring plan before mainnet. Audit Bank review covers the settlement path, authorization validation, discovery trust boundary and the upto contract; all critical/high findings block the production tag.
Wire conformance and acceptance matrix
Acceptance is based on observable wire behavior, not internal implementation claims. Current reproducible evidence is recorded in the dated RFP proof report. It includes the canonical exact testnet transactioned9fa12…b2e34, the upto testnet contract deployment and partial settlement, search metrics, package versions and the verification transcript.
Published evidence must include immutable CI links, exact dependency/package versions, transaction hashes linked to a Stellar explorer, test date and network. A local mock, build-only result or manually constructed noncanonical client does not satisfy a network acceptance item.
Grant delivery plan to mainnet
Milestone 1 — Public testnet and Bazaar foundation
- Harden the hosted/self-hosted exact facilitator and self-facilitation package around upstream
@x402/stellar. - Complete native HTTP/MCP automatic cataloging, origin control, canonical filters, headers and seller/buyer SDK helpers.
- Publish free testnet service, role-based seller/buyer/operator guides and the first paid/discoverable integration.
- Run the canonical-client testnet suite and publish its settlement hash, CI transcript and wire fixtures.
Milestone 2 — Metered settlement, agents and production controls
- Finalize the Stellar
uptoprofile with the TSC and contribute implementation, contract, tests and fixtures upstream. - Expand MCP discover/pay/retry support and publish the second agent-driven integration with no pre-baked service integration.
- Deliver the versioned relevance set, quality/latency report, load tests, on-chain monitoring plan and corresponding threat model.
- Add channel signer management, KMS integration, reconciliation, backup/restore testing and operational dashboards.
Milestone 3 — Audit remediation and mainnet launch
- Complete Audit Bank review and resolve all launch-blocking findings; audit funding is not included in the development budget.
- Pass upstream and AutoLayer e2e/conformance suites for exact and
uptoonstellar:testnetandstellar:pubnet. - Publish one confirmed transaction hash per network per scheme, the conformance report, SBOM/license result and resolved security report.
- Launch the permissively licensed managed service and reproducible self-hosted release, with at least 99% availability target, alerts, runbook and community maintenance handoff.
Maintenance commitment
During the grant, upstream x402 spec and package changes are reviewed at least weekly and compatibility CI runs on every dependency update plus a scheduled cadence. After launch, AutoLayer will maintain supported release branches, publish migration notes for wire changes, triage conformance regressions as release blockers and provide a documented handoff path so the Stellar community can operate or fork the service under Apache-2.0.Implementation status
This table is the source of truth for product claims. A successful TypeScript build is not equivalent to a mainnet conformance run or security review.