CRE Workflows HubCRE Workflows Hub
  • Workflows
  • Chainlink repo
  • Sign in
CRE Workflows Hub
  • Workflows
  • Docs
  • Contribute workflow
  • Chainlink CRE Templates

A registry for Chainlink Runtime Environment workflows. List and share your CRE workflows without waiting for upstream approval.

Back

Created by Chainlink Labs

Prediction Market Demo

End-to-end automated, AI-powered prediction market using CRE with Gemini AI and Firebase. Create binary markets on-chain, stake USDC, and CRE settles outcomes with AI fact-checking.

View on GitHub
TypeScript

This demo showcases an end-to-end automated, AI-powered prediction market using the Chainlink Runtime Environment (CRE) integrated with Google's Gemini AI and Firebase. Users create binary (Yes/No) prediction markets on-chain, stake USDC tokens, and CRE automatically settles outcomes using AI-powered fact-checking.

What This Demo Does

This project showcases how to build a fully automated prediction market system where:

  • Users create markets by asking binary (Yes/No) questions on-chain
  • Users stake ERC-20 tokens (USDC) to make predictions
  • After the market closes, anyone can request settlement
  • CRE automatically triggers when it detects the settlement request
  • Gemini AI determines the factual outcome using Google search grounding
  • CRE submits a cryptographically signed settlement report back on-chain
  • Settlement data is stored in Firestore for audit and display
  • Winners claim their proportional share of the total pool

Key Technologies

  • Smart Contracts: Solidity prediction market with CRE receiver integration
  • CRE: Event-driven workflow orchestration
  • Gemini AI: Automated fact-checking and outcome determination
  • Firebase/Firestore: Audit trail and data persistence
  • Next.js Frontend: User interface for viewing settlement history

Security Considerations

caution Important Notes

  • This is a demo project — Not audited or production-ready.
  • Never commit secrets — Keep .env out of version control.
  • Test with small amounts — Use testnet tokens only.
  • Verify AI responses — Gemini responses may be incorrect or biased.
  • Monitor gas usage — Settlement transactions consume gas from your account.

Repository Structure

This repository contains three main components:

.
├── contracts/              # Foundry project: SimpleMarket.sol and deployment scripts
├── cre-workflow/           # CRE TypeScript workflow for AI-powered settlement
├── frontend/               # Next.js app for viewing settlement data from Firestore
├── firebase-setup.md       # Firebase/Firestore configuration guide
└── README.md

CRE Workflow Directory

A Chainlink Runtime Environment project containing:

  • TypeScript workflow orchestration
  • Gemini AI integration
  • EVM settlement logic
  • Firestore database integration
  • Configuration and secrets management

Contracts Directory

A Foundry project containing:

  • SimpleMarket.sol - Binary prediction market smart contract
  • Comprehensive test suite
  • Deployment and interaction scripts
  • CRE receiver template integration

Frontend Directory

A Next.js application that:

  • Connects to Firestore database
  • Displays recent market settlements
  • Shows AI responses, confidence scores, and transaction hashes
  • Provides a simple UI for monitoring the system

Prerequisites

To run this demo, you'll need:

  • Git
  • Node.js v20+
  • Bun (JavaScript runtime and package manager)
  • Foundry/Forge (forge, cast, anvil)
  • Chainlink Runtime Environment CLI
  • Gemini API Key
  • Firebase Project with Firestore enabled
  • ETH Sepolia funds for gas
  • USDC on Sepolia for market participation

Quick Start

Option 1: Test CRE Workflow Only (Fastest)

This repo ships with the address of a pre-deployed contract and transaction for immediate testing.

1. Test the CRE workflow

Install the workflow dependencies:

cd cre-workflow/prediction-market-demo
bun install

Configure the RPC endpoint by editing cre-workflow/project.yaml and setting your Sepolia RPC URL for local-simulation.

2. Set environment variables

Navigate back to the cre-workflow directory and create your .env file:

cd ..  # Back to cre-workflow directory
cp .env.example .env

Populate the .env file with the following values:

CRE_ETH_PRIVATE_KEY=0x...       # Private key with Sepolia ETH
CRE_TARGET=local-simulation
GEMINI_API_KEY_VAR=...          # From https://aistudio.google.com/api-keys
FIREBASE_API_KEY_VAR=...        # From Firebase console
FIREBASE_PROJECT_ID_VAR=...     # From Firebase console

See the prerequisites section for information on obtaining your Gemini and Firebase keys.

3. Run the simulation

Run the CRE workflow simulation:

cre workflow simulate prediction-market-demo --target local-simulation

When prompted, use this pre-deployed transaction:

  • Transaction hash: 0x24f3ccee54786d754ee07e4b8578ff6916c3cfca6e0f6fd71675aaad0039bc19
  • Event index: 0

Option 2: Full End-to-End Test

1. Clone the repository

git clone https://github.com/smartcontractkit/cre-gcp-prediction-market-demo.git
cd cre-gcp-prediction-market-demo

2. Deploy the smart contract

Install contract dependencies and set environment variables:

cd contracts
forge install
export PRIVATE_KEY=...
export RPC_URL=...

Deploy a new SimpleMarket contract. The constructor arguments are: (1) the payment token address (USDC on ETH Sepolia) and (2) the CRE forwarder address (ETH Sepolia CRE Simulation Forwarder).

forge create src/SimpleMarket.sol:SimpleMarket \
  --broadcast \
  --rpc-url $RPC_URL \
  --private-key $PRIVATE_KEY \
  --constructor-args 0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238 0x15fC6ae953E024d975e77382eEeC56A9101f9F88

Note down the new contract address and export it:

export MARKET_ADDRESS=...

caution Access Control: The provided ReceiverTemplate.sol includes setter functions to enable access control of the onReport function which are not used in this end-to-end test. See the CRE docs for best practices.

3. Create a prediction market

Get the next available market ID:

cast call $MARKET_ADDRESS \
  "nextMarketId()" \
  --rpc-url $RPC_URL

Convert from hex to decimal:

cast to-dec 0x000000000000000000000000000000000000000000000000000000000000001c
# Example output: 28
# The first market ID for a new contract will be 0.

Create a new market:

cast send $MARKET_ADDRESS \
  "newMarket(string)" \
  "Will the buffalo bills win the 2025 superbowl?" \
  --rpc-url $RPC_URL \
  --private-key $PRIVATE_KEY

note Market Duration: Markets close after 3 minutes. Complete the next steps before the market closes.

4. (Optional) Place a prediction

Approve USDC spending:

cast send 0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238 \
  "approve(address,uint256)" \
  $MARKET_ADDRESS \
  1000000 \
  --rpc-url $RPC_URL \
  --private-key $PRIVATE_KEY

Place your prediction (Outcome: 1 = No, 2 = Yes):

cast send $MARKET_ADDRESS \
  "makePrediction(uint256,uint8,uint256)" \
  0 \
  2 \
  1000000 \
  --rpc-url $RPC_URL \
  --private-key $PRIVATE_KEY

5. Configure and run the CRE workflow

Install workflow dependencies:

cd ../cre-workflow/prediction-market-demo
bun install

Add your market address to cre-workflow/prediction-market-demo/config.json:

{
  "geminiModel": "gemini-2.5-flash",
  "evms": [
    {
      "marketAddress": "<YOUR_MARKET_ADDRESS>",
      "chainSelectorName": "ethereum-testnet-sepolia",
      "gasLimit": "1000000"
    }
  ]
}

Add ETH Sepolia RPC URL to cre-workflow/project.yaml:

local-simulation:
  rpcs:
    - chain-name: ethereum-testnet-sepolia
      url: <your_rpc_url>

Set up environment variables:

cd ..
cp .env.example .env

Populate .env with your keys:

CRE_ETH_PRIVATE_KEY=
CRE_TARGET=local-simulation
GEMINI_API_KEY_VAR=
FIREBASE_API_KEY_VAR=
FIREBASE_PROJECT_ID_VAR=

6. Request settlement and execute

note Market Closure: The market must be closed before settlement can be requested. Markets close after 3 minutes by default.

Request settlement:

cast send $MARKET_ADDRESS \
  "requestSettlement(uint256)" \
  0 \
  --rpc-url $RPC_URL \
  --private-key $PRIVATE_KEY

Note the transaction hash. Then simulate the workflow:

cre workflow simulate prediction-market-demo --target local-simulation

When prompted, enter the transaction hash and log index 0.

To broadcast and write results on-chain:

cre workflow simulate prediction-market-demo --target local-simulation --broadcast

7. (Optional) Claim winnings and run frontend

Claim your prediction if you won:

cast send $MARKET_ADDRESS \
  "claimPrediction(uint256)" \
  0 \
  --rpc-url $RPC_URL \
  --private-key $PRIVATE_KEY

To run the frontend:

cd ../frontend
bun install
cp .env.local.example .env.local

Add your Firebase credentials to .env.local:

NEXT_PUBLIC_FIREBASE_API_KEY="your-api-key"
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN="your-auth-domain"
NEXT_PUBLIC_FIREBASE_PROJECT_ID="your-project-id"

Start the development server:

bun run dev

The frontend will be available at http://localhost:3000.

Install the CRE CLI to use this template

You can use the command below or download the latest CLI release on GitHub.

curl -sSL https://cre.chain.link/install.sh | bash
Author
Chainlink Labs
LicenseMIT

Disclaimer

This template represents an educational example to use a Chainlink system, product, or service and is provided to demonstrate how to interact with Chainlink's systems, products, and services to integrate them into your own. This template is provided "AS IS" and "AS AVAILABLE" without warranties of any kind, it has not been audited, and it may be missing key checks or error handling to make the usage of the system, product or service more clear. Do not use this example in a production environment without completing your own audits and application of best practices. Neither Chainlink Labs, the Chainlink Foundation, nor Chainlink node operators are responsible for unintended outputs that are generated due to errors in code.