DEV Community

Cover image for I Put Carbon Pledges on the Solana Blockchain for Earth Day (And Built the AI to Back It Up)
Arya Koste
Arya Koste

Posted on

I Put Carbon Pledges on the Solana Blockchain for Earth Day (And Built the AI to Back It Up)

DEV Weekend Challenge: Earth Day

This is a submission for Weekend Challenge: Earth Day Edition

Did you know that a single cheeseburger emits roughly 3.5 kg of CO₂? That's equivalent to driving 14 km in a petrol car — from a sandwich.

Most of us have no idea what our daily choices actually cost the planet. And even when we do, knowing isn't enough. What if you could prove you're changing — publicly, permanently, on the blockchain?

EcoLens is an AI-powered carbon footprint analyzer that goes beyond awareness. It identifies your impact, proposes greener alternatives, and lets you pledge your commitment on the Solana blockchain — a public, immutable record that your word is real.


The Problem

Carbon footprint calculators exist, but they're tedious. You fill out a form, pick from dropdowns, hit calculate, and get a vague yearly number that means nothing to your Tuesday lunch decision.

The real gap isn't information — it's accountability. People know beef is carbon-heavy. They still order it. What changes behavior is a commitment with skin in the game.

That's the loop I wanted to close: identify → understand → pledge → act.


What EcoLens Does

📸 Vision Analysis

Upload any image — your meal, a shopping receipt, your car, a product — and Gemini 2.0 Flash analyzes it using real lifecycle emissions data. You don't describe anything; just point your camera.

✍️ Text & Voice Analysis

Type or speak a description:

"I flew economy class from Mumbai to London"
1,850 kg CO₂ · Very High Impact · Equivalent to driving 7,400 km

⚖️ Compare Mode

Can't decide? Compare two options side by side — "beef burger vs. black bean burger" — and see exactly how many kg CO₂ you save by choosing the greener option, with a winner crown.

🌿 Structured Results

Every analysis returns:

  • CO₂ in kg, severity rating, animated breakdown by source
  • 3 specific, actionable alternatives with estimated savings
  • A relatable real-world equivalent

◎ Solana On-Chain Pledges ← the key differentiator

After every analysis, you can sign a pledge with your Phantom wallet. The commitment is written as a Memo transaction on Solana — permanent, public, tied to your wallet address.

🤖 Streaming AI Agent

A persistent chat powered by Gemini that streams responses token-by-token, secured behind Auth0.

📊 Carbon Budget + History

Set a weekly CO₂ budget. Every analysis is saved to localStorage, tracked against your goal, and visualised in a circular progress meter.


The Tech Stack

Layer Choice Why
Framework Next.js 15 (App Router) Server components + API routes in one repo
AI Google Gemini 2.0 Flash Vision + text + streaming, accurate emissions data
Auth Auth0 for Agents Protects AI endpoints, user identity scoping
Blockchain Solana (Devnet) On-chain pledge via Phantom + Memo Program
Animation Framer Motion Smooth result reveals, animated CO₂ bars
Styling Tailwind CSS Custom dark earth-tone design system

How I Used Google Gemini

Gemini is the brain of EcoLens — it handles both image analysis and chat via gemini-2.0-flash.

The key insight was engineering a structured output contract. The model always returns valid JSON so the UI can render rich cards without parsing gymnastics:

const ANALYSIS_PROMPT = `You are EcoLens AI, an expert environmental scientist.
Analyze the input and return ONLY valid JSON:
{
  "carbonKg": number,
  "category": "food" | "transport" | "energy" | "shopping" | "waste" | "other",
  "title": string,
  "summary": string,
  "breakdown": [{"label": string, "kg": number, "percentage": number}],
  "alternatives": [{"action": string, "impact": string, "reduction": string}],
  "equivalent": string,
  "severity": "low" | "medium" | "high" | "very_high",
  "rating": number
}`;
Enter fullscreen mode Exit fullscreen mode

For image analysis, the image and prompt go in a single multimodal API call:

const parts: Part[] = [
  { inlineData: { data: imageBase64, mimeType: file.type } },
  { text: "Analyze the carbon footprint of everything in this image." },
];
const result = await model.generateContent({
  contents: [{ role: "user", parts }],
  generationConfig: { temperature: 0.3 }, // low temp = consistent scientific estimates
});
Enter fullscreen mode Exit fullscreen mode

The AI chat uses streaming via sendMessageStream — responses type out token-by-token with a blinking cursor, making it feel alive:

export async function* streamChatWithEcoAgent(message, history) {
  const result = await chat.sendMessageStream(message);
  for await (const chunk of result.stream) {
    if (chunk.text()) yield chunk.text();
  }
}
Enter fullscreen mode Exit fullscreen mode

The API route pipes this directly into a ReadableStream response — no buffering, no delay.


How I Used Auth0 for Agents

Every call that touches the Gemini AI is gated by Auth0 before the agent acts. This is the "Auth0 for Agents" pattern: the AI doesn't act anonymously, it acts on behalf of a verified identity.

// app/api/analyze/route.ts
export async function POST(req: NextRequest) {
  const session = await getSession();

  if (!session?.user) {
    return NextResponse.json({ error: "Authentication required" }, { status: 401 });
  }

  // Agent acts on behalf of session.user.sub — traceable, auditable
  const analysis = await analyzeCarbon(text, imageBase64, imageMimeType);
  return NextResponse.json({ analysis, analyzedBy: session.user.sub });
}
Enter fullscreen mode Exit fullscreen mode

The same gate protects /api/chat and /api/compare. No anonymous AI calls — every analysis is tied to a real, verified person.


How I Used Solana — The Heart of the Accountability Loop

This is the part I'm most excited about, and the piece that makes EcoLens more than just another carbon calculator.

The idea: awareness without commitment changes nothing. Solana lets us make commitments permanent and public.

The Flow

  1. Gemini analyzes your activity and suggests a greener alternative
  2. You click "Sign pledge with Phantom"
  3. EcoLens constructs a Memo transaction encoding your pledge, the CO₂ saved, and a timestamp
  4. Phantom signs and broadcasts it to Solana Devnet
  5. The transaction is confirmed on-chain — your pledge is now permanent
import {
  Connection, PublicKey, Transaction,
  TransactionInstruction, clusterApiUrl,
} from "@solana/web3.js";

const MEMO_PROGRAM_ID = new PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr");

const memoData = JSON.stringify({
  app: "EcoLens",
  pledge: "I pledge to: cycle instead of drive this week",
  carbonKg: 2.4,
  ts: new Date().toISOString(),
});

const tx = new Transaction().add(
  new TransactionInstruction({
    keys: [{ pubkey: publicKey, isSigner: true, isWritable: false }],
    programId: MEMO_PROGRAM_ID,
    data: Buffer.from(memoData, "utf-8"),
  })
);

const { signature } = await window.solana.signAndSendTransaction(tx);
await connection.confirmTransaction({ signature, blockhash, lastValidBlockHeight });
Enter fullscreen mode Exit fullscreen mode

The pledge is verifiable on Solana Explorer. Anyone can look up your wallet and see your carbon commitments, timestamped and immutable.

Why the Memo Program?

The Solana Memo Program (MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr) is the simplest, cheapest way to write arbitrary data on-chain. A pledge transaction costs a fraction of a cent in SOL and is confirmed in ~400ms. It's perfect for this use case — lightweight, auditable, and human-readable.

Why This Matters Beyond the Demo

Carbon pledges have a trust problem. Corporate net-zero commitments get announced and quietly abandoned. There's no receipt. Solana changes that: your pledge is a transaction hash. It can't be edited, deleted, or denied. Future versions of EcoLens could build a public leaderboard of wallets with the most on-chain green commitments — turning individual accountability into social proof.


A Real Example: From Analysis to On-Chain Pledge

Here's the full EcoLens loop in action:

1. User uploads photo of beef steak dinner
   → Gemini Vision: 6.8 kg CO₂ · High Impact

2. Breakdown:
   Beef (production)    ████████  5.2 kg (76%)
   Cooking energy       ██        0.9 kg (13%)
   Transport/packaging  ▌         0.7 kg (11%)

3. Equivalent to: Driving 27 km in a petrol car

4. Top alternative: "Choose chicken instead — Save ~4.1 kg CO₂"

5. User clicks "Sign pledge with Phantom"
   → Phantom signs memo transaction
   → Confirmed on Solana Devnet in 412ms
   → TX: 3xK7...mNpQ (verifiable on Explorer)
Enter fullscreen mode Exit fullscreen mode

That's the full loop — from a photo to an on-chain commitment in under 30 seconds.


What I Learned

Structured outputs unlock rich UIs. Getting Gemini to reliably return JSON meant the frontend could be fully reactive — no parsing edge cases, no streaming text parsing hacks.

Temperature matters for science. At 0.7, CO₂ estimates drift between calls. At 0.3, they're reproducible and match published lifecycle data.

Solana's Memo Program is criminally underused. It's the simplest on-chain data primitive — 0.000005 SOL per transaction, confirmed in milliseconds, human-readable on Explorer. For any app that needs verifiable records, it's a better solution than most people realize.

Auth-gating AI is a pattern, not an afterthought. Making the AI agent require Auth0 session means every analysis is tied to a real identity — which is the foundation for future per-user carbon portfolios and wallet-linked pledge histories.


Try It Yourself

🌍 EcoLens

AI Carbon Footprint Analyzer with On-Chain Pledges

Next.js Gemini Auth0 Solana TypeScript

Snap a photo of your lunch, describe your commute, or upload a receipt — EcoLens uses Google Gemini Vision to instantly reveal the hidden CO₂ cost of your daily choices. Then pledge to do better on the Solana blockchain — a permanent, public, verifiable commitment.


✨ Features

Feature Description
📸 Vision Analysis Upload any photo — Gemini Vision identifies items and calculates CO₂
✍️ Text Analysis Describe any activity and get an accurate, sourced emission estimate
🎙️ Voice Input Speak your description using the browser's Speech API
⚖️ Compare Mode Race two options side by side — see the greener choice with a winner crown
Solana Pledges Sign an on-chain pledge with Phantom — permanent, immutable, verifiable
🤖 Streaming AI Chat Gemini-powered eco-agent that streams responses token-by-token
📊 Carbon Budget Set a weekly CO₂ goal and track it against a

git clone https://github.com/aryakoste/ecolens
cd ecolens
cp .env.local.example .env.local
# Add GEMINI_API_KEY, Auth0 credentials
npm install
npm run dev
Enter fullscreen mode Exit fullscreen mode

To test the Solana pledge feature, install Phantom wallet and switch it to Devnet in settings.


What's Next

  • [ ] Mainnet pledges — real SOL-backed carbon commitments with token rewards for follow-through
  • [ ] Public pledge leaderboard — on-chain wallet rankings for green commitments
  • [ ] NFT certificates — mint a Solana NFT when you hit a weekly carbon goal
  • [ ] Snowflake analytics — aggregate anonymized emissions data across all users for community insights

Prize Categories

Prize Technology How it's used
Best use of Solana @solana/web3.js + Phantom On-chain carbon pledges via the Memo Program
Best use of Google Gemini Gemini 2.0 Flash Vision analysis, structured JSON output, streaming chat
Best use of Auth0 for Agents @auth0/nextjs-auth0 v3 Auth-gates every AI endpoint — the agent acts on behalf of a verified identity

Every gram of CO₂ you avoid is a gift to the planet. And now, you can prove it. Happy Earth Day 🌍

Built with Google Gemini 2.0 Flash, Auth0 for Agents, and Solana for the DEV.to Earth Day Challenge 2025.

Top comments (0)