· Documentation  · 12 min read

Payment System

Payment System

Payment System

The Architectural Blueprint: On-Chain Assets & Off-Chain Services

You will have three main components that talk to each other:

  1. The Frontend (Next.js App): This is your user interface, the Creator’s Studio. It’s what the artist interacts with. It will be responsible for connecting to the user’s Cardano wallet.
  2. The Backend (Next.js API Routes): This is your secure server. It will handle the most sensitive operations: checking token ownership and communicating with your LLM. It acts as the trusted middleware.
  3. The Cardano Blockchain: This is the decentralized ledger that holds the “Creator Pass” tokens. It is the public, verifiable database of who has permission to create.

The Fungible Token: The $CREATE Token (or “Creator Pass”)

  • Purpose: This is a standard Cardano native fungible token. Let’s call it the $CREATE token.
  • Mechanic: One unit of $CREATE is consumed to perform one significant “manipulation” or “generation” action. For example, clicking the “Generate Base” button in your studio will require and burn 1 $CREATE token.
  • Acquisition: Players purchase these tokens from your project’s official sale, or on a decentralized exchange (DEX).

The Detailed User & System Workflow

Here is the step-by-step flow from the user’s perspective, and what’s happening on the backend.

Step 1: User Connects Their Wallet (Frontend)

  • Action: The artist lands on your Creator’s Studio page and clicks a “Connect Wallet” button.
  • Frontend Logic:
    • You’ll use a JavaScript library like the Mesh SDK or Lucid for Cardano.
    • This library will prompt the user to connect their wallet (e.g., Nami, Eternl, Lace).
    • Once connected, the library gives your frontend access to the user’s public wallet address and the ability to request signatures for transactions.
    • The frontend displays their wallet address and their current $CREATE token balance, which it queries directly from the blockchain.

Step 2: User Initiates a “Paid” Action (Frontend to Backend)

  • Action: The artist has crafted their perfect prompt in the “Prompt-Crafter” and clicks the “Generate Base” button. This is a protected action.
  • Frontend Logic:
    1. The frontend does not call the LLM directly. This would expose your API keys.
    2. Instead, it makes a secure API call to your own server, to an endpoint like /api/generate-art.
    3. It sends along the user’s prompt and, most importantly, the user’s wallet address.

Step 3: Server Verifies Token Ownership (Backend)

  • Action: Your Next.js API route (/api/generate-art) receives the request.
  • Backend Logic:
    1. This is the most critical security step. The server now needs to independently verify that the wallet address sent from the frontend actually owns enough $CREATE tokens.
    2. The server uses a service like Blockfrost or Koios (or runs its own Cardano node) to query the blockchain. It asks, “What is the balance of the $CREATE token for this specific wallet address?”
    3. It checks the result. Does the user have >= 1 $CREATE token?
      • If NO: The server immediately returns an error message to the frontend: {"error": "Insufficient CREATE tokens. Please purchase more to continue."} The process stops.
      • If YES: The server proceeds to the next step.

Step 4: The “Payment” Transaction (Backend to Frontend and Back)

  • Action: The server has confirmed the user can pay. Now, it needs them to actually pay.

  • Backend Logic:

    1. The server constructs a “transaction blueprint.” This is a JSON object describing the required transaction: “Send exactly 1 $CREATE token from the user’s wallet to a pre-defined ‘burn’ address or a treasury address.”
    2. The server sends this transaction blueprint back to the frontend as the response to the initial API call.
  • Frontend Logic:

    1. The frontend receives the transaction blueprint from the server.
    2. It uses the user’s connected wallet library (Mesh/Lucid) to present this transaction to the user for their signature.
    3. A wallet pop-up appears: “This application wants you to sign a transaction to send 1 CREATE token. Do you approve?”
    4. The user signs the transaction. The wallet submits it to the Cardano blockchain.
    5. The wallet returns the transaction hash (TxID) to your frontend.
    6. The frontend now makes a second API call to the backend, to a different endpoint like /api/confirm-generation, sending the TxID and the original prompt.

Step 5: Final Confirmation and LLM Call (Backend)

  • Action: Your Next.js API route (/api/confirm-generation) receives the TxID.
  • Backend Logic:
    1. Final Verification: The server takes the TxID and uses its blockchain service (Blockfrost/Koios) to look up the transaction on-chain. It waits a few seconds for the transaction to be confirmed.
    2. It inspects the confirmed transaction. Does it match the blueprint? Did the user send exactly 1 $CREATE token to the correct address?
      • If NO: The server returns an error. The user tried to cheat the system.
      • If YES: The payment is now verifiably complete.
    3. The Payoff: The server now takes the user’s prompt and securely calls your LLM (Midjourney, Stable Diffusion API, etc.) using its own private API keys.
    4. It receives the generated images back from the LLM.
    5. It can save these images to your asset storage (like an S3 bucket or Firebase Storage).
    6. Finally, it sends the URLs of the newly generated images back to the frontend.

Step 6: Displaying the Result (Frontend)

  • Action: The frontend receives the image URLs from the server.
  • Frontend Logic: It displays the generated images in the “Idea Reel,” and the artist’s workflow continues.

Why This Architecture is Secure and Robust

  • Never Trust the Client: The server never trusts the frontend’s claim that the user has enough tokens. It always verifies directly with the blockchain, which is the immutable source of truth.
  • Private Keys Remain Private: The user’s private keys never leave their wallet. They only use them to sign the final, explicit transaction. Your server never sees them.
  • LLM API Keys are Secure: Your expensive and secret LLM API keys are only ever used on your backend server. They are never exposed to the user’s browser.
  • Atomic Transaction: The entire process is “atomic.” The user cannot get the benefit (the AI-generated art) without first making the payment (the on-chain token transaction). The server waits for cryptographic proof of payment before proceeding.

Code Snippets (Conceptual)

Frontend (using React/Next.js and a hypothetical useCardano hook):

// In your GenerateButton.js component
const { wallet, signAndSubmitTx } = useCardano();

const handleGenerateClick = async () => {
  // Step 2: Initial call to the server
  const response = await fetch('/api/generate-art', {
    method: 'POST',
    body: JSON.stringify({ prompt: '...', address: wallet.address }),
  });
  const { transactionBlueprint } = await response.json();

  // Step 4: User signs the payment transaction
  try {
    const txId = await signAndSubmitTx(transactionBlueprint);

    // Step 5: Second call to the server with proof of payment
    const finalResponse = await fetch('/api/confirm-generation', {
      method: 'POST',
      body: JSON.stringify({ prompt: '...', txId: txId }),
    });
    const { imageUrls } = await finalResponse.json();
    
    // Step 6: Display the images
    setGeneratedImages(imageUrls);
  } catch (error) {
    console.error("Transaction failed:", error);
  }
};

Backend (a Next.js API route at /api/generate-art):

// In /pages/api/generate-art.js
import { blockfrost } from '...'; // Your Cardano service

export default async function handler(req, res) {
  const { prompt, address } = req.body;

  // Step 3: Verify token balance
  const balance = await blockfrost.getBalance(address, '$CREATE_TOKEN_ASSET_ID');
  
  if (balance < 1) {
    return res.status(402).json({ error: 'Insufficient CREATE tokens.' });
  }

  // Step 4: Create and send back the transaction blueprint
  const transactionBlueprint = {
    // ... details of the transaction to send 1 $CREATE token
  };

  res.status(200).json({ transactionBlueprint });
}


Integrating credit card payments is a crucial step for reaching a mass-market audience that isn't yet comfortable with cryptocurrency. This turns your project into a true **"Web2.5" application**, offering the familiarity of traditional e-commerce with the underlying power of a blockchain.

The workflow is conceptually similar but involves swapping out the user's crypto wallet for a traditional payment processor and adding a **custodial "gas tank" wallet** that you, the business, control.

**Core Philosophy:** The user pays in a currency they understand (USD). You, the business, handle the crypto "plumbing" on their behalf. The user gets a seamless Web2 experience, while you maintain the on-chain logic of your token-based system.

---

### The Architectural Blueprint: Adding a Payment Processor and a Custodial Wallet

Your architecture now evolves:

1.  **The Frontend (Next.js App):** The user interface. Instead of a "Connect Wallet" button, it will feature a standard "Buy Credits" or "Subscribe" button.
2.  **The Backend (Next.js API Routes):** Your server's role becomes even more critical. It will now handle:
    *   Processing credit card payments via a service like **Stripe**.
    *   Managing user accounts and their `$CREATE` token balances in your own database.
    *   Controlling a secure, server-side **custodial wallet** that holds `$CREATE` tokens and a bit of ADA for transaction fees.
3.  **The Cardano Blockchain:** The blockchain's role remains the same—it is the immutable ledger for the `$CREATE` tokens. However, the *ownership* of many of these tokens will now be by your central custodial wallet.

**The Custodial Wallet (The "Gas Tank"):**
*   This is a standard Cardano wallet that your company creates and controls.
*   You will pre-load it with a large amount of `$CREATE` tokens and a healthy supply of ADA to pay for transaction fees.
*   **Crucially, the private keys for this wallet must be stored with extreme security** (e.g., using a service like AWS KMS, Azure Key Vault, or HashiCorp Vault). Never store raw private keys in your code or environment variables.

---

### The Detailed User & System Workflow (Credit Card Model)

Here is the new step-by-step flow.

**Step 1: User Purchases "Credits" (The Onboarding)**
*   **Action:** A new artist signs up for your service with a standard email and password. They go to a "Billing" or "Purchase" page. They see an offer: "10 Generation Credits for $5.00". They click "Buy."
*   **Frontend Logic:**
    *   You will use a library like `@stripe/react-stripe-js` to create a secure, PCI-compliant payment form.
    *   The user enters their credit card details directly into the Stripe element (their card info never touches your server).
    *   When they submit, the Stripe library securely sends their payment information to Stripe and returns a `paymentMethod` ID.
    *   Your frontend then sends this `paymentMethod` ID and the desired purchase amount (e.g., 10 credits) to your backend at an endpoint like `/api/billing/purchase-credits`.
*   **Backend Logic (`/api/billing/purchase-credits`):**
    1.  Your server receives the request.
    2.  It uses the **Stripe Node.js library** to create a "PaymentIntent," confirming the payment with the `paymentMethod` ID.
    3.  Stripe processes the credit card transaction.
    4.  **Upon successful payment confirmation from Stripe**, your server now updates its own internal database. It finds the user's account and updates their balance: `user.credits = user.credits + 10`.
    5.  It sends a success message back to the frontend. The user now sees "You have 10 Generation Credits" on their dashboard.

**Notice:** At this point, nothing has happened on the blockchain. The user's "credits" are just a number in your centralized database.

**Step 2: User Initiates a "Paid" Action (The Creative Loop)**
*   **Action:** The artist, who has 10 credits, crafts their perfect prompt and clicks the "Generate Base" button.
*   **Frontend Logic:**
    *   It makes a secure API call to your backend at `/api/generate-art`.
    *   It sends the prompt and the user's **authentication token (JWT)**, which proves who they are.

**Step 3: Server Deducts Credit and Spends Real Tokens (The "Web2.5" Bridge)**
*   **Action:** Your Next.js API route (`/api/generate-art`) receives the request.
*   **Backend Logic:**
    1.  **Authenticate the User:** The server verifies the user's JWT.
    2.  **Check Internal Database Balance:** It looks up the user in your database. Does `user.credits` >= 1?
        *   **If NO:** It returns an error: `{"error": "Insufficient credits. Please purchase more."}`
        *   **If YES:** It proceeds.
    3.  **Deduct the Credit:** It immediately **decrements the user's balance in the database**: `user.credits = user.credits - 1`. This is a crucial atomic step.
    4.  **THE ON-CHAIN ACTION (The Magic):** Now, your server performs the crypto transaction *on the user's behalf*.
        *   It loads its secure, server-side **custodial wallet**.
        *   It constructs a Cardano transaction to send **1 `$CREATE` token** from its own custodial wallet to a **"burn" address**.
        *   It signs this transaction using its securely stored private keys and submits it to the Cardano blockchain via a service like Blockfrost.
    5.  **This step is vital.** It ensures that every "credit" spent by a user corresponds to a real, verifiable on-chain token being consumed. This keeps your internal economy honest and transparent. You can even show users the transaction hash of the token that was burned on their behalf.

**Step 4: LLM Call and Result**
*   **Action:** The on-chain payment is now submitted. The server doesn't even need to wait for confirmation. It can proceed immediately after submitting the transaction.
*   **Backend Logic:**
    1.  The server takes the user's prompt and securely calls your LLM (Midjourney, etc.) with its private API keys.
    2.  It receives the generated images back.
    3.  It saves the images and sends the URLs back to the frontend.

**Step 5: Displaying the Result (Frontend)**
*   **Action:** The frontend receives the image URLs and displays them in the "Idea Reel."
*   **User Experience:** The entire crypto layer was completely invisible to the artist. They clicked a button, a credit was used, and they got their art. It was a seamless Web2 experience.

---

### Why This Hybrid Model is So Powerful

*   **Mass-Market Accessibility:** You remove the biggest barrier to entry for Web3. Anyone with a credit card can use your service immediately without needing to understand wallets, seed phrases, or gas fees.
*   **On-Chain Transparency and Scarcity:** You are not just selling imaginary "credits." You are selling a real, on-chain asset. The total supply of `$CREATE` tokens can be fixed and publicly auditable. Users can trust that your system is economically sound because they can see the burn transactions happening on the blockchain. This builds immense trust compared to a purely centralized "credit" system.
*   **Best of Both Worlds:** You get the smooth user experience and familiar payment model of Web2, combined with the verifiable scarcity and transparent economics of Web3.
*   **Future-Proof:** This model provides a perfect "on-ramp." You can later introduce features for advanced users to connect their own crypto wallets and use their own `$CREATE` tokens, allowing both Web2 and Web3 users to coexist in the same ecosystem.

By implementing this credit card flow with a custodial backend, you are building a sophisticated and user-friendly bridge, allowing anyone to access the power of your on-chain, token-gated creative tools.
Back to Blog

Related Posts

View All Posts »
Basic Documentation

Basic Documentation

While easy to get started, Astrowind is quite complex internally. This page provides documentation on some of the more intricate parts.

ALLIGATOR ALLEY THE BAYOU VINDICATOR

ALLIGATOR ALLEY THE BAYOU VINDICATOR

In the treacherous swamps and corrupt alleys of a world obsessed with reptilian bounty, a mysterious, gator-hide clad vigilante known only as "The Scaled Shadow" emerges to prey on those who exploit the weak – the poachers, the corrupt Guild agents, and the tyrannical Gator-Barons.

The Spiritus Continuum

The Spiritus Continuum

While easy to get started, Astrowind is quite complex internally. This page provides documentation on some of the more intricate parts.