MicroCreate/Documentation

Product & Architecture Guide

x402 Protocol v2v1.0 API Spec
Architecture Overview

1. Overview & Philosophy

Core Concept & 3-Pillar Architecture

MicroCreate is a pay-per-capability AI operating system for media generation and post-processing. Traditional generative AI tools charge coarse flat-rate subscriptions or lock users into monolithic black boxes. MicroCreate decomposes creative production into discrete paid AI capabilities and provides three clean, separated execution paths:

Pillar 1: Single Shot Direct

Immediate, one-step FLUX.1 image synthesis with direct x402 settlement (0.01 USDC). Produces a master asset without autonomous loop overhead.

Pillar 2: Autonomous Engine

Multi-stage creative production: Creative Director planning, FLUX.1 generation, multimodal vision critique, prompt rewriting, and quality refinement.

Pillar 3: Standalone AI Enhance

Standalone AI super-resolution tool powered by Replicate nightmareai/real-esrgan. 2× (0.01 USDC) or 4× (0.02 USDC) with immutable master asset preservation.

Core Architecture Principles

  • Authoritative Server-Side Pricing: Capability prices are strictly derived on the server via getAuthoritativePaymentRequirement and getUpscalePrice.
  • Algorand TestNet Settlement: Every capability payment settles on-chain via USDC ASA 10458941 before inference execution.
  • Candidate Asset Continuity: The autonomous loop preserves candidate assets across refinement cycles rather than restarting from unrelated noise.
  • Master Asset Immutability: Original images are never overwritten by super-resolution; enhancements are recorded as derivative assets with explicit lineage (derivativeOf).

Machine-to-Machine AI Economics

MicroCreate implements the x402 Protocol for trustless HTTP 402 Payment Required negotiation. Clients can execute machine-to-machine capability requests autonomously using the official Agent Signer without interactive wallet prompts.

Core Tool

2. Single Shot Direct

Direct FLUX.1 Generation Path

Single Shot Direct is the simplest, lowest-latency path in MicroCreate. It allows a developer or user to provide a prompt and aspect ratio, immediately receive an x402 payment challenge, settle 0.01 USDC, and obtain a master image generated by Black Forest Labs FLUX.1-schnell.

Single Shot Direct deliberately excludes visual critique, prompt rewriting, autonomous refinement loops, and automatic super-resolution.

x402 Micropayment & Settlement Flow

1. Client POST /api/v1/generate/image { prompt, aspectRatio }
2. Server returns HTTP 402 with challenge (payee, 10000 base units, ASA 10458941)
3. Client signs Algorand TestNet transaction (Pera Wallet or Agent Signer)
4. Client resubmits with PAYMENT-SIGNATURE header
5. Server verifies on Algod RPC, executes FLUX.1 inference, and returns permanent image URL
Autonomous Loop

3. Autonomous Creative Workflow

The Multi-Stage Production Loop

When a user launches an Autonomous Creative Job, MicroCreate executes a deterministic orchestrator loop:

  1. Creative Planning: The AI Creative Director analyzes the goal and formulates an enriched visual prompt.
  2. Candidate Generation: Paid image.generate invokes FLUX.1 to synthesize candidate #0.
  3. Multimodal Vision Critique: Paid image.evaluate runs Groq Qwen Vision to score prompt alignment, composition, and aesthetics.
  4. Quality Decision: If score ≥ 80, the job completes immediately (ACCEPT). Otherwise, it transitions to refinement (REFINE).
  5. Prompt Refinement: Creative Director synthesizes an optimized prompt addressing the critic's feedback.
  6. Quality Refinement: Paid image.refine runs to finalize the asset.

Creative Director & Prompt Strategy

The Creative Director module uses Groq LLMs (or configured AI provider) to structure lighting, material textures, depth-of-field, and camera perspective parameters without manual prompt engineering.

Multimodal Visual Critic (Groq Vision)

The visual critic evaluates candidate images with a structured rubric: prompt fidelity, compositional balance, visual clarity, and artifacts. It returns an integer score (0–100) and actionable improvement feedback.

Quality Refinement

4. Autonomous Quality Refinement

Quality Refinement Lifecycle

When visual critique recommends refinement, the orchestrator triggers the paid image.refine capability (0.01 USDC). This executes targeted prompt refinements guided by the multimodal feedback.

Candidate Asset Continuity

MicroCreate maintains candidate continuity throughout the production session. The system evaluates and refines the active candidate asset rather than generating disconnected random imagery.

Refinement Execution & Delivery

Upon refinement completion, the resulting asset is finalized and presented with complete production telemetry, critic evaluations, and on-chain settlement receipts.

Standalone Tool

5. Standalone AI Image Enhance

Standalone Super-Resolution Tool

AI Image Enhance is an independent, user-triggered capability located at /enhance. It allows developers and users to upload any visual asset (PNG, JPEG, WEBP up to 10MB) or choose an existing creation from history, detect source dimensions dynamically, and upscale 2× or 4×.

Important: AI Image Enhance is completely decoupled from the core Single Shot and Autonomous Creative Engine workflows. It is never automatically invoked during generation.

Dynamic Dimensions & Authoritative Pricing

Target resolutions are calculated dynamically from source image dimensions. Pricing is strictly enforced server-side via getUpscalePrice:

2× AI Enhance0.01 USDC

10,000 base units · Model: RealESRGAN_x2plus
Example: 1024×1024 → 2048×2048 px (or 512×768 → 1024×1536 px)

4× Ultra High-Res0.02 USDC

20,000 base units · Model: RealESRGAN_x4plus
Example: 1024×1024 → 4096×4096 px (or 512×768 → 2048×3072 px)

AI Super-Resolution Provider Architecture (Replicate nightmareai/real-esrgan)

MicroCreate uses ReplicateSuperResolutionProvider executing the official nightmareai/real-esrgan model via the replicate SDK. The provider abstraction enables clean isolation between payment authorization, storage, and inference:

MicroCreate Backend → DefaultUpscaleService → SuperResolutionProvider → ReplicateSuperResolutionProvider (replicate) → nightmareai/real-esrgan

Master Immutability & Asset Lineage

When an upscale completes, the original master asset is never overwritten. A new derivative record is created in MongoDB with:

  • id: Unique UUID for the enhanced derivative
  • derivativeOf: Pointer to source master asset ID
  • scale: 2 or 4
  • metadata.width / height: Exact upscaled output dimensions
x402 Protocol v2

6. x402 Economics & Payment Modes

Authoritative Payment Amount Pipeline

Every capability price is derived strictly on the server:

  • image.generate: 10,000 base units (0.01 USDC)
  • image.evaluate: 10,000 base units (0.01 USDC)
  • image.refine: 10,000 base units (0.01 USDC)
  • image.upscale (2×): 10,000 base units (0.01 USDC)
  • image.upscale (4×): 20,000 base units (0.02 USDC)

Strict Exact-Payment Verification (==)

Server verification checks exact amount equality (amount === required), exact ASA ID (10458941), receiver address, and confirmed block round. Underpaid, oversized, or replayed transactions are strictly rejected.

Manual Mode (Dual Wallet: Pera & Google Embedded)

When paymentMode: "manual", execution pauses in waiting_for_approval. Users can authorize on-chain settlements using either their Pera Wallet (mobile/extension) or an instant non-custodial Google Embedded Wallet (via Web3Auth MPC). Resumption occurs only after verified on-chain confirmation.

Automatic Mode (Agent Signer)

When paymentMode: "automatic", the server Agent Signer automatically signs x402 payment requirements within safety spending quotas (agentSpendingGuard), enabling seamless machine-to-machine workflows.

PIN-Protected Runtime Mode Switch

Switching between Manual and Automatic payment modes is protected by X402_MODE_SWITCH_PIN via POST /api/v1/config/payment-mode.

Atomic Budget Ledger Accounting

Job budgets track four invariant quantities in ASA base units: totalBaseUnits = spentBaseUnits + reservedBaseUnits + availableBaseUnits.

Orchestration State Machine

7. Creative Jobs & State Machine

Deterministic State Transition Graph

Creative jobs follow strict deterministic state transitions:

PENDING → RUNNING → (WAITING_FOR_APPROVAL ↔ RUNNING) → COMPLETED / FAILED
RUNNING → AWAITING_BUDGET (if budget exhausted) → UPGRADE → RUNNING

Sequenced Event Timeline

Every transition, tool call, payment settlement, and critique decision appends an immutable, sequenced event accessible at GET /api/v1/creative-jobs/[id]/events.

Budget Top-Up & Upgrade Flow

When a job enters awaiting_budget, developers can top up budget via POST /api/v1/creative-jobs/[id]/upgrade-budget to resume production immediately.

Force-Refine Test Mode (Dev QA Override)

For development and integration test suites, setting MICROCREATE_FORCE_REFINE_TEST=true forces the visual critic to return REFINE, enabling repeatable testing of refinement loops without live AI variance.Note: This is a dev/test-only flag and must not be used in production.

Capability Registry

8. Paid Tool Capabilities

image.generate0.01 USDC

Synthesizes FLUX.1 master image assets from text prompts. Stores binary in Vercel Blob and metadata in MongoDB.

image.evaluate0.01 USDC

Multimodal visual critic evaluation (Groq Qwen Vision). Returns 0–100 score and ACCEPT / REFINE quality decision.

image.refine0.01 USDC

Executes autonomous quality refinement stage with candidate asset continuity.

image.upscale0.01 / 0.02 USDC

Standalone AI super-resolution (fal.ai Real-ESRGAN). 2× = 0.01 USDC, 4× = 0.02 USDC. Creates immutable derivative.

REST Specification

9. Complete API Reference

All endpoints return standard JSON envelopes with status codes, request IDs, and ISO-8601 timestamps.

POST/api/v1/creative-jobs

Initializes an autonomous production job with goal, totalBudgetBaseUnits, and paymentMode.

POST/api/v1/creative-jobs/[id]/approve-payment

Submits signed Algorand TestNet transaction bytes (signedTxn) to settle pending capability approval.

POST/api/v1/generate/image

Direct x402-gated single-shot FLUX.1 generation endpoint (0.01 USDC).

POST/api/v1/upscale

Direct x402-gated AI Super-Resolution endpoint (2× = 0.01 USDC, 4× = 0.02 USDC).

POST/api/v1/agent/upscale

Automatic Mode machine-to-machine super-resolution loopback endpoint via Server Agent Signer.

POST/api/v1/images/upload

Uploads a standalone source image (Multipart or Base64) to storage and returns dimensions.

Integration Code

10. Client Integration & SDKs

runManualCreativeJob.ts
typescript
import algosdk from "algosdk";
import { PeraWalletConnect } from "@perawallet/connect";

const peraWallet = new PeraWalletConnect({ chainId: 416002 });
const BASE_URL = "https://microcreate.io";

export async function runManualCreativeJob(goal: string, budgetUsdc: string = "0.04") {
  // 1. Create the autonomous creative production job
  const createRes = await fetch(`${BASE_URL}/api/v1/creative-jobs`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      goal,
      totalBudgetBaseUnits: (parseFloat(budgetUsdc) * 1_000_000).toString(),
      paymentMode: "manual",
    }),
  });
  const { data: { job } } = await createRes.json();
  console.log("Created Job:", job.id, "Initial Status:", job.status);

  // 2. Poll job status until human payment approval is required
  let currentJob = job;
  while (currentJob.status !== "completed" && currentJob.status !== "failed") {
    if (currentJob.status === "waiting_for_approval") {
      const pending = currentJob.meta.pendingApproval;
      console.log(`Payment required for '${pending.toolName}': ${pending.amountUsdc} USDC`);

      // 3. Connect Pera Wallet & construct Algorand TestNet USDC ASA transfer
      const accounts = await peraWallet.reconnectSession();
      const sender = accounts[0];

      const algodClient = new algosdk.Algodv2("", "https://testnet-api.algonode.cloud", 443);
      const suggestedParams = await algodClient.getTransactionParams().do();

      const txn = algosdk.makeAssetTransferTxnWithSuggestedParamsFromObject({
        sender,
        receiver: pending.payeeAddress,
        assetIndex: Number(pending.assetId), // 10458941 (USDC)
        amount: BigInt(pending.amountBaseUnits), // Exact match required
        suggestedParams,
      });

      // 4. Sign transaction via Pera Wallet
      const signedTxnBytes = await peraWallet.signTransaction([[{ txn }]]);
      const base64SignedTxn = Buffer.from(signedTxnBytes[0]).toString("base64");

      // 5. Submit signed transaction to server for verification & on-chain broadcast
      const approveRes = await fetch(`${BASE_URL}/api/v1/creative-jobs/${currentJob.id}/approve-payment`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          signedTxn: base64SignedTxn,
          senderAddress: sender,
        }),
      });

      const approveData = await approveRes.json();
      currentJob = approveData.data.job;
      console.log("Payment settled on-chain:", approveData.data.settlement.txId);
    } else {
      await new Promise((resolve) => setTimeout(resolve, 2000));
      const pollRes = await fetch(`${BASE_URL}/api/v1/creative-jobs/${currentJob.id}`);
      const pollData = await pollRes.json();
      currentJob = pollData.data.job;
    }
  }

  return currentJob.finalResult;
}
Storage Architecture

11. Storage & Asset Lineage Architecture

MongoDB Metadata & Vercel Blob Binary Storage

MicroCreate uses a dual-layer storage architecture in production:

  • MongoDB: Stores job documents, generation records, payment receipts, critic evaluations, and asset lineage relationships.
  • Vercel Blob Object Storage: Stores raw master and derivative image binaries with immutable URLs (/api/v1/images/[id]).
  • Local Filesystem: Development fallback storing images to .data/images/.

Original Master & Derivative Asset Model

Original master images remain immutable. Enhancements reference their parent via derivativeOf, enabling complete traceability back to the original generation prompt and settlement block.

Error System

12. Error Codes & Model

Standard Error Envelope

Standard Error Response
json
{
  "success": false,
  "error": {
    "code": "PAYMENT_AMOUNT_INSUFFICIENT",
    "message": "Payment amount mismatch: required exactly 10000 base units (0.01 USDC), received 5000 base units.",
    "details": { "required": "10000", "received": "5000" }
  },
  "meta": {
    "timestamp": "2026-08-23T04:30:00.000Z",
    "requestId": "req_8471bd72-9182-4ab8-a621-827361928371"
  }
}
Security & Config

13. Security & Environment Configuration

Cryptographic Security Invariants

  • Replay Protection: Transaction IDs and idempotency keys are enforced uniquely in MongoDB.
  • Authoritative Price Derivation: Client amounts are never trusted; verification checks server requirements.
  • Server Secret Isolation: REPLICATE_API_TOKEN, FAL_KEY, HF_TOKEN, GROQ_API_KEY, and X402_AGENT_PRIVATE_KEY are never exposed to browser bundles.

Environment Configuration Reference

VariableScopeDefault / ExampleDescription
GROQ_API_KEYSERVER-ONLYgsk_...Groq API key for Creative Director & Qwen Vision.
HF_TOKENSERVER-ONLYhf_...Hugging Face token for FLUX.1 generation.
REPLICATE_API_TOKENSERVER-ONLYr8_...Replicate API token for nightmareai/real-esrgan super-resolution.
IMAGE_UPSCALE_PROVIDERServerreplicateActive super-resolution provider ("replicate" | "fal-ai" | "mock").
IMAGE_UPSCALE_MODELServernightmareai/real-esrganSuper-resolution model identifier.
ALGORAND_USDC_ASSET_IDShared10458941Algorand TestNet USDC ASA ID.
ALGORAND_RECEIVER_ADDRESSSharedPY2IUL...Merchant payment receiver wallet address.
X402_AGENT_PRIVATE_KEYSERVER-ONLYBase64 / MnemonicServer agent wallet key for Automatic Payment mode.
X402_MODE_SWITCH_PINSERVER-ONLY6-digit PINPIN required to change runtime payment mode.
MONGODB_URISERVER-ONLYmongodb+srv://...MongoDB connection URI for jobs & metadata.
BLOB_READ_WRITE_TOKENSERVER-ONLYvercel_blob_rw_...Vercel Blob token for production image binaries.