Product & Architecture Guide
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:
Immediate, one-step FLUX.1 image synthesis with direct x402 settlement (0.01 USDC). Produces a master asset without autonomous loop overhead.
Multi-stage creative production: Creative Director planning, FLUX.1 generation, multimodal vision critique, prompt rewriting, and quality refinement.
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
getAuthoritativePaymentRequirementandgetUpscalePrice. - 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.
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
3. Autonomous Creative Workflow
The Multi-Stage Production Loop
When a user launches an Autonomous Creative Job, MicroCreate executes a deterministic orchestrator loop:
- Creative Planning: The AI Creative Director analyzes the goal and formulates an enriched visual prompt.
- Candidate Generation: Paid
image.generateinvokes FLUX.1 to synthesize candidate #0. - Multimodal Vision Critique: Paid
image.evaluateruns Groq Qwen Vision to score prompt alignment, composition, and aesthetics. - Quality Decision: If score ≥ 80, the job completes immediately (
ACCEPT). Otherwise, it transitions to refinement (REFINE). - Prompt Refinement: Creative Director synthesizes an optimized prompt addressing the critic's feedback.
- Quality Refinement: Paid
image.refineruns 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.
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.
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:
10,000 base units · Model: RealESRGAN_x2plus
Example: 1024×1024 → 2048×2048 px (or 512×768 → 1024×1536 px)
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:
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 derivativederivativeOf: Pointer to source master asset IDscale: 2 or 4metadata.width / height: Exact upscaled output dimensions
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.
7. Creative Jobs & State Machine
Deterministic State Transition Graph
Creative jobs follow strict deterministic state transitions:
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.
8. Paid Tool Capabilities
Synthesizes FLUX.1 master image assets from text prompts. Stores binary in Vercel Blob and metadata in MongoDB.
Multimodal visual critic evaluation (Groq Qwen Vision). Returns 0–100 score and ACCEPT / REFINE quality decision.
Executes autonomous quality refinement stage with candidate asset continuity.
Standalone AI super-resolution (fal.ai Real-ESRGAN). 2× = 0.01 USDC, 4× = 0.02 USDC. Creates immutable derivative.
9. Complete API Reference
All endpoints return standard JSON envelopes with status codes, request IDs, and ISO-8601 timestamps.
Initializes an autonomous production job with goal, totalBudgetBaseUnits, and paymentMode.
Submits signed Algorand TestNet transaction bytes (signedTxn) to settle pending capability approval.
Direct x402-gated single-shot FLUX.1 generation endpoint (0.01 USDC).
Direct x402-gated AI Super-Resolution endpoint (2× = 0.01 USDC, 4× = 0.02 USDC).
Automatic Mode machine-to-machine super-resolution loopback endpoint via Server Agent Signer.
Uploads a standalone source image (Multipart or Base64) to storage and returns dimensions.
10. Client Integration & SDKs
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;
}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.
12. Error Codes & Model
Standard Error Envelope
{
"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"
}
}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, andX402_AGENT_PRIVATE_KEYare never exposed to browser bundles.
Environment Configuration Reference
| Variable | Scope | Default / Example | Description |
|---|---|---|---|
| GROQ_API_KEY | SERVER-ONLY | gsk_... | Groq API key for Creative Director & Qwen Vision. |
| HF_TOKEN | SERVER-ONLY | hf_... | Hugging Face token for FLUX.1 generation. |
| REPLICATE_API_TOKEN | SERVER-ONLY | r8_... | Replicate API token for nightmareai/real-esrgan super-resolution. |
| IMAGE_UPSCALE_PROVIDER | Server | replicate | Active super-resolution provider ("replicate" | "fal-ai" | "mock"). |
| IMAGE_UPSCALE_MODEL | Server | nightmareai/real-esrgan | Super-resolution model identifier. |
| ALGORAND_USDC_ASSET_ID | Shared | 10458941 | Algorand TestNet USDC ASA ID. |
| ALGORAND_RECEIVER_ADDRESS | Shared | PY2IUL... | Merchant payment receiver wallet address. |
| X402_AGENT_PRIVATE_KEY | SERVER-ONLY | Base64 / Mnemonic | Server agent wallet key for Automatic Payment mode. |
| X402_MODE_SWITCH_PIN | SERVER-ONLY | 6-digit PIN | PIN required to change runtime payment mode. |
| MONGODB_URI | SERVER-ONLY | mongodb+srv://... | MongoDB connection URI for jobs & metadata. |
| BLOB_READ_WRITE_TOKEN | SERVER-ONLY | vercel_blob_rw_... | Vercel Blob token for production image binaries. |