Skip to content

/api/image/generate - In Process#9

Merged
sweetmantech merged 3 commits into
mainfrom
sweetmantech/myc-3552-apiimagegenerate-in-process
Nov 29, 2025
Merged

/api/image/generate - In Process#9
sweetmantech merged 3 commits into
mainfrom
sweetmantech/myc-3552-apiimagegenerate-in-process

Conversation

@sweetmantech
Copy link
Copy Markdown
Contributor

@sweetmantech sweetmantech commented Nov 29, 2025

Summary by CodeRabbit

  • New Features

    • Generated images are uploaded to decentralized storage and provided as fetchable image URLs.
    • Generated images now create on-chain-style "moments" with metadata; responses include image URL, storage upload result, and moment details.
  • Chores

    • Request-driven buyer account extraction and new upload/metadata helpers added to support the end-to-end image + moment flow.

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link
Copy Markdown
Contributor

vercel Bot commented Nov 29, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Updated (UTC)
recoup-api Ready Ready Preview Nov 29, 2025 2:16pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 29, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

Adds Arweave client and upload utilities, JSON/image upload helpers, buyer-account extraction, and In Process moment creation; the x402 image generation route now uploads generated images to Arweave, creates a moment, and returns upload and moment details in the response.

Changes

Cohort / File(s) Summary
Arweave client
lib/arweave/client.ts
New module that initializes and exports a configured arweave client and a decoded ARWEAVE_KEY from env with validation and detailed error messages.
Arweave upload core
lib/arweave/uploadToArweave.ts
Refactor: named export uploadToArweave(data: Buffer, contentType, getProgress?) using shared client/ARWEAVE_KEY, creates transaction from Buffer, adds optional progress callback and loop.
Arweave upload helpers
lib/arweave/uploadImageToArweave.ts, lib/arweave/uploadJsonToArweave.ts
New helpers: uploadImageToArweave decodes base64 image and delegates to uploadToArweave; uploadJsonToArweave serializes JSON and uploads.
Arweave util
lib/arweave/isCID.ts
Catch block simplified: removed error logging and returns false on parse failure (behavior unchanged).
Moment creation API
lib/inprocess/createMoment.ts
New createMoment with typed request/response that POSTs to In Process API and surfaces non-OK responses with status and response text.
Image moment orchestration
lib/inprocess/createImageMoment.ts
New createImageMoment that builds contract metadata from prompt/account/arweaveUri, uploads metadata to Arweave, calls createMoment, and returns the moment or null on error.
Buyer account extraction
lib/x402/getBuyerAccount.ts
New getBuyerAccount(request) that base64-decodes X-PAYMENT header JSON and returns paymentPayload.payload.authorization.from (no guards).
API route integration
app/api/x402/image/generate/route.ts
GET handler now extracts buyer account, uses uploadImageToArweave to upload generated image, computes arweaveUri/imageUrl, calls createImageMoment, and extends response with imageUrl, arweaveResult, and moment.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Image Client
    participant API as /api/x402/image/generate
    participant ArwClient as Arweave Network
    participant InProc as In Process API

    Client->>API: GET (includes X-PAYMENT header)
    API->>API: getBuyerAccount(request)
    API->>API: generate image (existing)
    API->>ArwClient: uploadImageToArweave(base64 image)
    ArwClient-->>API: arweave transaction (arweaveUri)
    API->>ArwClient: uploadJsonToArweave(contract metadata)
    ArwClient-->>API: contractMetadataUri
    API->>InProc: createMoment(contract+token metadata + account)
    InProc-->>API: moment creation response (contractAddress, tokenId, hash)
    API-->>Client: 200 OK { result, imageUrl, arweaveResult, moment }
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Review lib/arweave/client.ts for correct ARWEAVE_KEY decoding and error messages.
  • Validate uploadToArweave transaction construction, tags, and progress loop correctness.
  • Confirm createImageMoment error handling and how route treats null moment returns.
  • Check getBuyerAccount assumptions and consider missing/malformed header handling in the route.

Possibly related PRs

Poem

🐰 I nibble code and stash each little byte,

Images hop to Arweave under moonlight,
Metadata stitched and a moment takes flight,
Buyer tracked, a tiny web3 delight,
Hooray — a rabbit's hop in every byte! ✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title '/api/image/generate - In Process' directly references the main API endpoint being modified and indicates the integration of In Process functionality, which aligns with the core objective of the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4a5c001 and a6605df.

📒 Files selected for processing (1)
  • lib/x402/getBuyerAccount.ts (1 hunks)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (6)
lib/x402/getBuyerAccount.ts (1)

9-21: Consider adding type validation for the extracted account value.

The function uses optional chaining to safely navigate the payload structure, but doesn't verify that the final value is actually a string. If the payload contains an unexpected type at authorization.from (e.g., a number or object), it would be returned as-is, potentially causing issues downstream.

Consider adding a type check:

 export function getBuyerAccount(request: NextRequest): string | null {
   const xPaymentHeader = request.headers.get("X-PAYMENT");
   if (!xPaymentHeader) return null;

   try {
     const decoded = Buffer.from(xPaymentHeader, "base64").toString("utf-8");
     const paymentPayload = JSON.parse(decoded);
-    return paymentPayload.payload?.authorization?.from || null;
+    const account = paymentPayload.payload?.authorization?.from;
+    return typeof account === "string" ? account : null;
   } catch (error) {
     console.error("Error parsing X-PAYMENT header:", error);
     return null;
   }
 }
app/api/x402/image/generate/route.ts (2)

62-67: Handle moment creation failure gracefully.

The createImageMoment function returns null on failure, but this isn't handled before including it in the response. While the API might tolerate a null moment field, it would be better to either log the failure or handle it explicitly.

Consider adding logging when moment creation fails:

   const momentResult = await createImageMoment({
     prompt,
     account,
     arweaveUri,
     mediaType: result.images[0].mediaType,
   });
+
+  if (!momentResult) {
+    console.warn("Failed to create moment, but image was generated successfully");
+  }

Alternatively, if moment creation is critical, fail the entire request if it returns null.


54-60: Consider handling Arweave upload failures separately from image generation.

If the Arweave upload fails (line 54), the entire request fails even though the image was successfully generated. Depending on requirements, you might want to return the generated image to the user even if storage fails, or at least provide a more specific error message.

Consider wrapping the Arweave operations in a try-catch:

   const result = await generateImage(prompt);

   if (!result) {
     return NextResponse.json(
       { error: "Failed to generate image" },
       {
         status: 500,
         headers: getCorsHeaders(),
       },
     );
   }
+
+  try {
     const arweaveResult = await uploadImageToArweave({
       base64Data: result.images[0].base64,
       mimeType: result.images[0].mediaType,
     });

     const arweaveUri = `ar://${arweaveResult.id}`;
     const imageUrl = getFetchableUrl(arweaveUri);

     const momentResult = await createImageMoment({
       prompt,
       account,
       arweaveUri,
       mediaType: result.images[0].mediaType,
     });
+  } catch (storageError) {
+    console.error("Failed to store image or create moment:", storageError);
+    return NextResponse.json(
+      { error: "Image generated but failed to store", result },
+      {
+        status: 500,
+        headers: getCorsHeaders(),
+      },
+    );
+  }
lib/arweave/uploadImageToArweave.ts (1)

2-2: Consider removing the alias for clarity.

The import alias uploadDataToArweave isn't necessary and slightly reduces code clarity. The original name uploadToArweave is already clear.

-import { uploadToArweave as uploadDataToArweave } from "./uploadToArweave";
+import { uploadToArweave } from "./uploadToArweave";

And update line 18:

-  return uploadDataToArweave(buffer, imageData.mimeType, getProgress);
+  return uploadToArweave(buffer, imageData.mimeType, getProgress);
lib/inprocess/createImageMoment.ts (1)

61-64: Improve error handling to aid debugging.

The catch block returns null without propagating the error or providing context to the caller. This makes it difficult to debug failures in production.

Consider one of these approaches:

Option 1: Throw the error with context (preferred for critical operations):

   } catch (error) {
     console.error("Error creating image moment:", error);
-    return null;
+    throw new Error(`Failed to create image moment: ${error instanceof Error ? error.message : error}`);
   }
 }

Option 2: Return detailed error information:

-export async function createImageMoment(
-  params: CreateImageMomentParams,
-): Promise<CreateMomentResponse | null> {
+export async function createImageMoment(
+  params: CreateImageMomentParams,
+): Promise<{ success: true; data: CreateMomentResponse } | { success: false; error: string }> {

This allows the caller to handle failures appropriately.

lib/arweave/uploadToArweave.ts (1)

28-30: Consider using a logging framework instead of console.log.

The console.log statement will run in production. While upload progress logging can be useful for debugging, consider using a structured logging framework that allows for log level configuration.

Example refactor (if using a logger like winston or pino):

-    console.log(
-      `${uploader.pctComplete}% complete, ${uploader.uploadedChunks}/${uploader.totalChunks}`,
-    );
+    logger.debug(
+      `Upload progress: ${uploader.pctComplete}% complete, ${uploader.uploadedChunks}/${uploader.totalChunks}`,
+    );
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8d04648 and 82393c2.

📒 Files selected for processing (9)
  • app/api/x402/image/generate/route.ts (3 hunks)
  • lib/arweave/client.ts (1 hunks)
  • lib/arweave/isCID.ts (1 hunks)
  • lib/arweave/uploadImageToArweave.ts (1 hunks)
  • lib/arweave/uploadJsonToArweave.ts (1 hunks)
  • lib/arweave/uploadToArweave.ts (2 hunks)
  • lib/inprocess/createImageMoment.ts (1 hunks)
  • lib/inprocess/createMoment.ts (1 hunks)
  • lib/x402/getBuyerAccount.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (4)
app/api/x402/image/generate/route.ts (3)
lib/x402/getBuyerAccount.ts (1)
  • getBuyerAccount (9-21)
lib/arweave/getFetchableUrl.ts (1)
  • getFetchableUrl (12-37)
lib/inprocess/createImageMoment.ts (1)
  • createImageMoment (18-65)
lib/arweave/uploadJsonToArweave.ts (1)
lib/arweave/uploadToArweave.ts (1)
  • uploadToArweave (12-36)
lib/inprocess/createImageMoment.ts (1)
lib/inprocess/createMoment.ts (2)
  • CreateMomentResponse (31-35)
  • createMoment (43-60)
lib/arweave/uploadToArweave.ts (1)
lib/arweave/client.ts (2)
  • arweave (25-31)
  • ARWEAVE_KEY (33-33)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Vercel Agent Review
🔇 Additional comments (10)
lib/arweave/isCID.ts (1)

15-17: LGTM! Clean error handling.

Removing the unused error parameter and console.error logging simplifies the catch block. The function correctly returns false on any parsing error.

lib/arweave/uploadJsonToArweave.ts (1)

10-14: LGTM! Clean abstraction.

The function provides a clean abstraction for uploading JSON data to Arweave. The implementation correctly serializes the data and delegates to the shared uploadToArweave helper.

lib/arweave/uploadImageToArweave.ts (1)

13-19: LGTM! Clean image upload abstraction.

The function correctly decodes base64 image data to a buffer and delegates to the shared upload helper with appropriate content type and progress callback.

lib/arweave/client.ts (2)

4-23: LGTM! Robust client initialization with good error handling.

The Arweave client initialization includes comprehensive error handling for missing or invalid credentials. The error messages are clear and actionable.

Security note: Ensure that ARWEAVE_KEY is properly secured in your deployment environment and never committed to version control. Consider documenting this requirement in your README or deployment docs.


25-31: Verify timeout value is appropriate for your use case.

The 20-second timeout may need adjustment based on the size of uploads and network conditions. For large images or slow networks, this might be too short.

Consider testing with various image sizes to ensure the timeout is sufficient. You can also make this configurable via environment variable:

timeout: parseInt(process.env.ARWEAVE_TIMEOUT || "20000", 10),
lib/inprocess/createImageMoment.ts (1)

40-58: Based on my investigation, I have gathered sufficient information to rewrite the review comment. Let me provide the final output:


Confirm the intent of free image-generated moments with zero price and no time window.

The moment is created with pricePerToken: "0", saleStart: 0, and saleEnd: 0, representing a free mint with no temporal restrictions. The implementation uses a simple REST API wrapper to https://inprocess.fun/api/moment/create, which performs server-side validation. Confirm this is the intended behavior for image-generated moments and that the inprocess.fun API accepts these values without issues.

lib/arweave/uploadToArweave.ts (4)

1-2: LGTM! Good refactor to centralize Arweave client.

Importing the Arweave client and key from a centralized module reduces duplication and makes configuration management cleaner.


4-11: LGTM! Clear documentation.

The JSDoc documentation clearly describes the function's purpose, parameters, and return value.


17-23: LGTM! Transaction creation is correct.

The transaction is properly created with the data Buffer, tagged with the content type, and signed with the centralized key.


12-16: Perfect! The verification is complete. Based on the search results, I can now provide the rewritten review comment:


All imports correctly use the named export syntax.

The change from default export to named export has been properly implemented across the codebase. Both dependent files (uploadJsonToArweave.ts and uploadImageToArweave.ts) correctly import using the named export syntax:

  • import { uploadToArweave } in uploadJsonToArweave.ts
  • import { uploadToArweave as uploadDataToArweave } in uploadImageToArweave.ts

No default imports remain, confirming the breaking change has been fully propagated.

Comment thread app/api/x402/image/generate/route.ts
Comment thread lib/inprocess/createMoment.ts
Comment thread lib/inprocess/createImageMoment.ts
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 82393c2 and 4a5c001.

📒 Files selected for processing (1)
  • lib/x402/getBuyerAccount.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Vercel Agent Review

Comment thread lib/x402/getBuyerAccount.ts
Comment thread lib/x402/getBuyerAccount.ts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant