WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

Commit 1a14f24

Browse files
committed
add example to store ai generated images on shelby
1 parent 6929e27 commit 1a14f24

30 files changed

+2827
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ This Turborepo includes the following example applications:
2828

2929
| Name | Description | Path & Links |
3030
| --- | --- | --- |
31+
| `@shelby-protocol/ai-image-generation` | Shelby AI image generation example | [`apps/ai-image-generation`](./apps/ai-image-generation) |
3132
| `@shelby-protocol/cross-chain-accounts` | Shelby cross chain accounts example | [`apps/cross-chain-accounts`](./apps/cross-chain-accounts) |
3233
| `@shelby-protocol/download-example` | An example app to demonstrate downloading blobs using the Shelby SDK | [`apps/download-blob`](./apps/download-blob) |
3334
| `@shelby-protocol/upload-example` | An example app to demonstrate uploading blobs using the Shelby SDK | [`apps/upload-blob`](./apps/upload-blob) |
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Shelby Protocol Configuration
2+
NEXT_PUBLIC_SHELBY_API_URL=https://api.shelbynet.shelby.xyz
3+
4+
# AI Service API Keys
5+
OPENAI_API_KEY=your_openai_api_key_here
6+
7+
# Shelby API Key for enhanced rate limits
8+
NEXT_PUBLIC_SHELBY_API_KEY=your_shelby_api_key_here
9+
10+
# Aptos API Key for enhanced rate limits
11+
NEXT_PUBLIC_APTOS_API_KEY=your_aptos_api_key_here
12+
13+
14+
NEXT_PUBLIC_SPONSOR_ACCOUNT_ADDRESS=0x...
15+
NEXT_PUBLIC_SPONSOR_PRIVATE_KEY=ed25519-priv-0x...

apps/ai-image-generation/README.md

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
# Shelby AI Image Generation - Decentralized AI Artifact Registry
2+
3+
This demo demonstrates how **Shelby can serve as the data and provenance layer for AI systems**. Every AI inference run produces verifiable, on-chain artifacts that are immutable, attributable, and accessible via Shelby's decentralized network.
4+
5+
Unlike traditional cloud storage solutions, this application showcases Shelby as a **"Web3 S3" specifically designed for AI workloads** - where AI-generated content lives permanently on-chain with cryptographic provenance, not trapped in centralized systems.
6+
7+
## 🧠 What Makes This AI-Focused
8+
9+
This isn't just file storage - it's an **AI artifact registry** that demonstrates:
10+
11+
### **AI Provenance & Authenticity**
12+
13+
- Every generated image is cryptographically tied to your Aptos wallet address
14+
- Immutable storage ensures AI outputs can't be tampered with after creation
15+
- Full traceability from prompt → model → output → storage
16+
17+
### **Decentralized AI Infrastructure**
18+
19+
- **Compute Layer**: OpenAI DALL-E 3 (external AI service)
20+
- **Storage Layer**: Shelby protocol (decentralized, incentivized network)
21+
- **Provenance Layer**: Aptos blockchain (immutable ownership records)
22+
23+
### **AI-Specific Metadata**
24+
25+
Each generated image includes structured metadata stored alongside:
26+
27+
```json
28+
{
29+
"prompt": "A futuristic city at sunset",
30+
"engine": "openai",
31+
"model": "dall-e-3",
32+
"createdAt": 1698765432000,
33+
"creator": "0x1234...abcd",
34+
"image": {
35+
"url": "https://api.shelbynet.shelby.xyz/shelby/v1/blobs/0x745...123/images/...."
36+
},
37+
"blobName": "images/A futuristic city at sunset_82p.png"
38+
}
39+
```
40+
41+
## 🏗️ Architecture: Modular Compute-Storage Separation
42+
43+
```
44+
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────────┐
45+
│ AI Compute │ │ Shelby Storage │ │ Aptos Blockchain │
46+
│ (DALL-E 3) │───▶│ (Artifacts) │───▶│ (Provenance) │
47+
│ │ │ │ │ │
48+
│ • Image Gen │ │ • Immutable │ │ • Ownership │
49+
│ • Model Runs │ │ • Decentralized │ │ • Commitments │
50+
│ • Stateless │ │ • Auditable │ │ • Expiration │
51+
└─────────────────┘ └──────────────────┘ └─────────────────────┘
52+
```
53+
54+
This architecture proves that **AI models can run anywhere, but their data, artifacts, and provenance should live in a decentralized, verifiable layer**.
55+
56+
## 🔥 Why This Matters for AI
57+
58+
### **Verifiable AI Outputs**
59+
60+
- Prove ownership of AI-generated content
61+
- Combat deepfakes with cryptographic authenticity
62+
- Enable model output traceability and reproducibility
63+
64+
### **Open AI Infrastructure**
65+
66+
- AI artifacts aren't locked in vendor silos (AWS, Google Cloud)
67+
- Decentralized storage with incentivized uptime guarantees
68+
- Permissionless access to AI-generated data
69+
70+
### **Future-Ready for Verifiable Compute**
71+
72+
- Today: External AI + Shelby storage
73+
- Tomorrow: Shelby-native AI compute in TEEs with zero-knowledge proofs
74+
- Same artifact storage pattern scales to fully decentralized AI pipelines
75+
76+
## Getting Started
77+
78+
### Prerequisites
79+
80+
- `node` and `pnpm`
81+
- Shelby and Aptos API keys. For best performance, you are encouraged to generate an API key so your app will not hit the rate limit.
82+
- Head to [Geomi](https://geomi.dev/)
83+
- Generate an API key for `shelbynet` and add it to the `.env` file as `NEXT_PUBLIC_SHELBY_API_KEY=<my-api-key>`
84+
- Generate an API key for `devnet` and add it to the `.env` file as `NEXT_PUBLIC_APTOS_API_KEY=<my-api-key>`
85+
- OpenAI API Key. Head to [OpenAI Platform](https://platform.openai.com/api-keys) to generate an API Key and add it to the `.env` file as `OPENAI_API_KEY=<my-api-key>`
86+
87+
Create an `.env` file by copying the `.env.example` file and fill out the required variables.
88+
89+
```bash
90+
cp .env.example .env
91+
```
92+
93+
Then install dependencies and run the dapp locally
94+
95+
```bash
96+
pnpm install
97+
pnpm run dev
98+
```
99+
100+
Open [http://localhost:3001](http://localhost:3001) with your browser to see the result.
101+
102+
## 🛠️ Technical Implementation
103+
104+
### **AI Generation Pipeline**
105+
106+
```typescript
107+
// 1. Generate image via OpenAI API
108+
const imageBuffer = await generateImage(prompt);
109+
110+
// 2. Create cryptographic commitments
111+
const commitments = await generateCommitments(provider, imageBuffer);
112+
113+
// 3. Register blob on Aptos blockchain
114+
const payload = ShelbyBlobClient.createRegisterBlobPayload({
115+
account: account.address,
116+
blobName: `images/${blobName}.png`,
117+
blobMerkleRoot: commitments.blob_merkle_root,
118+
// ... other metadata
119+
});
120+
121+
// 4. Upload to Shelby's decentralized network
122+
await shelbyClient.rpc.putBlob({
123+
account: account.address,
124+
blobName: imageName,
125+
blobData: new Uint8Array(imageBuffer),
126+
});
127+
```
128+
129+
### **Key Features**
130+
131+
- **Cross-chain wallet support** (Aptos native + Solana + EVM wallets via sponsored transactions)
132+
- **Metadata co-location** (JSON metadata stored alongside each image)
133+
- **Gallery view** (All your AI artifacts in one place)
134+
- **Explorer integration** (Direct links to Shelby blob explorer)
135+
136+
### **What You'll Experience:**
137+
138+
1. **Connect Wallet** - Your Aptos address becomes your AI identity
139+
2. **Generate Image** - AI creates content using your prompt
140+
3. **Store on Shelby** - Image + metadata uploaded to decentralized storage
141+
4. **Verify Provenance** - View your artifacts in Shelby Explorer with full ownership proof
142+
143+
## 🔮 What This Proves About Shelby
144+
145+
| **Capability** | **Demonstrated** |
146+
| ------------------------------ | ------------------------------------------------------ |
147+
| **AI Artifact Storage** | ✅ Images stored & served decentralized |
148+
| **Replaces S3/IPFS for AI** | ✅ Fast reads, permanent storage, verifiable ownership |
149+
| **Compute-Storage Separation** | ✅ Model runs anywhere, results live on Shelby |
150+
| **Provenance & Authenticity** | ✅ Each blob cryptographically tied to creator |
151+
| **Future-Ready Architecture** | ✅ Same pattern works for Shelby-native compute |
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import { type NextRequest, NextResponse } from "next/server";
2+
3+
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
4+
5+
interface OpenAIImageResponse {
6+
data?: { b64_json?: string; url?: string }[];
7+
}
8+
9+
async function genWithOpenAI(prompt: string): Promise<Buffer> {
10+
if (!OPENAI_API_KEY) throw new Error("Set OPENAI_API_KEY");
11+
12+
const resp = await fetch("https://api.openai.com/v1/images/generations", {
13+
method: "POST",
14+
headers: {
15+
"Content-Type": "application/json",
16+
Authorization: `Bearer ${OPENAI_API_KEY}`,
17+
},
18+
body: JSON.stringify({ model: "dall-e-3", prompt, size: "1024x1024" }),
19+
});
20+
21+
const json = (await resp.json()) as OpenAIImageResponse;
22+
const data = json.data?.[0];
23+
24+
if (data?.b64_json) {
25+
return Buffer.from(data.b64_json, "base64");
26+
}
27+
28+
if (data?.url) {
29+
const img = await fetch(data.url);
30+
if (!img.ok)
31+
throw new Error(`Failed to fetch image from OpenAI URL: ${img.status}`);
32+
return Buffer.from(await img.arrayBuffer());
33+
}
34+
35+
throw new Error(`Unexpected OpenAI image response: ${JSON.stringify(json)}`);
36+
}
37+
38+
export async function POST(request: NextRequest) {
39+
try {
40+
const body = await request.json();
41+
const prompt = String(body?.prompt || "");
42+
43+
if (!prompt) {
44+
return NextResponse.json({ error: "prompt required" }, { status: 400 });
45+
}
46+
47+
const imageBuffer = await genWithOpenAI(prompt);
48+
49+
return new NextResponse(new Uint8Array(imageBuffer), {
50+
headers: {
51+
"Content-Type": "image/png",
52+
"Content-Length": imageBuffer.length.toString(),
53+
},
54+
});
55+
} catch (e: any) {
56+
console.error(e);
57+
return NextResponse.json(
58+
{ error: e?.message || "generation failed" },
59+
{ status: 500 },
60+
);
61+
}
62+
}
25.3 KB
Binary file not shown.
66.3 KB
Binary file not shown.
64.7 KB
Binary file not shown.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
@import "@shelby-protocol/ui/globals.css";
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { Toaster } from "@shelby-protocol/ui/components";
2+
import localFont from "next/font/local";
3+
import { WalletProvider } from "@/components/WalletProvider";
4+
import "./globals.css";
5+
import type { Metadata } from "next";
6+
7+
const geistSans = localFont({
8+
src: "./fonts/GeistVF.woff",
9+
variable: "--font-geist-sans",
10+
});
11+
const geistMono = localFont({
12+
src: "./fonts/GeistMonoVF.woff",
13+
variable: "--font-geist-mono",
14+
});
15+
16+
export const metadata: Metadata = {
17+
title: "Shelby AI Image Generation Example",
18+
description: "An AI image generation example using Shelby protocol",
19+
};
20+
21+
export default function RootLayout({
22+
children,
23+
}: Readonly<{
24+
children: React.ReactNode;
25+
}>) {
26+
return (
27+
<html lang="en">
28+
<body className={`${geistSans.variable} ${geistMono.variable}`}>
29+
<WalletProvider>
30+
{children}
31+
<Toaster />
32+
</WalletProvider>
33+
</body>
34+
</html>
35+
);
36+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"use client";
2+
3+
import { useState } from "react";
4+
import { GeneratedImages } from "@/components/GeneratedImages";
5+
import { Header } from "@/components/Header";
6+
import { ImageGenerator } from "@/components/ImageGenerator";
7+
8+
export default function Home() {
9+
const [_, setRefreshTrigger] = useState(0);
10+
11+
const handleImageGenerated = () => {
12+
setRefreshTrigger((prev) => prev + 1);
13+
};
14+
15+
return (
16+
<div className="min-h-screen p-5">
17+
<Header />
18+
19+
{/* Main Content */}
20+
<main className="flex-1">
21+
<div className="max-w-4xl mx-auto space-y-6">
22+
<div className="text-center">
23+
<h1 className="text-4xl font-bold mb-4">AI Image Generation</h1>
24+
<p className="text-lg text-muted-foreground">
25+
Generate images using AI and store them on the Shelby protocol
26+
</p>
27+
</div>
28+
29+
<ImageGenerator onImageGenerated={handleImageGenerated} />
30+
<GeneratedImages />
31+
</div>
32+
</main>
33+
</div>
34+
);
35+
}

0 commit comments

Comments
 (0)