# Project export: AgentZero

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: TreeHacks 2025
- Tagline: Our autonomous and verifiable AI agent removes human inconsistency in making trading decisions, enabling data-driven trades with real-time analysis, customization, and safety.
- Devpost: https://devpost.com/software/agentzero
- GitHub: https://github.com/2pir2/TreeHack2025
- Result: winner (Web3 Prize: Best AI Agents ($8k Cash + 8k EIGEN [1st] & $7k Cash + 7k EIGEN [2nd]))
- Team: 3 GitHub contributor(s) — Andy Han (17 commits), Weixin Yu (14 commits), Hayley Zhang (1 commits)

## Devpost submission (written by the team)

### Inspiration

As a stock-market investor, I deeply understand emotions are one of the greatest obstacles to success in financial markets. Humans have all felt the fear of uncertainty and loss, the temptation of impulsive choices, and the long period to react and make decisions. But what if we could remove human fragility and the reaction time from the equation? By using a fully automated, verifiable AI agent, we utilize technology to make precise, unstoppable, and data-driven decisions. Our fully autonomous agent is more than just a tool—it is a revolution in investing. With real-time analysis, user-defined customization, and adaptive intelligence, it ensures that trades are executed efficiently, rationally, strategically, and safely. The future of finance is not dictated by emotions, but by innovation. It is time to embrace the next generation of investment intelligence.

### What it does

Our system consists of two specialized machine learning models: Price Model: This model is trained on historical Ethereum (ETH) price data, identifying patterns, trends, and volatility to make accurate price predictions. News Model: This model processes real-time news from Eigenlayer and other sources, analyzing sentiment, keywords, and market-moving narratives to gauge the impact of external events on ETH prices using the finBERT large language model. We combine these models by allowing users to assign custom weightings to each—giving them control over how much influence price trends versus news sentiment have on the agent’s final decision-making. Once the weighted predictions are generated, our fully automated AI agent can execute trades and market reactions in real-time, ensuring optimal strategies based on user preferences and live data. This level of customization and automation ensures a strategic, data-driven approach that removes emotional bias and maximizes efficiency in ETH trading.

### How we built it

We built our system by integrating EigenLayer for fetching real-time news data and Dune for pulling Ethereum price data. News Processing: The news data is retrieved via EigenLayer and analyzed using an LLM (finBERT), which assigns a sentiment score from -1 to 1 continuously to each news event, where score 1 indicates most positive, -1 indicates most negative, and 0 represents neutral. We then computed the average score for all of related the news. Price Prediction: The price model is trained using a Random Forest Regression model on historical price data from Dune, identifying market trends and fluctuations. User Interaction & Agent Customization: Users can set custom weightings for the influence of news sentiment versus price prediction on decision-making. Users also define the execution frequency, determining how often the automated agent executes actions based on the weighted results. By combining these elements, our AI-driven system provides a fully customizable and verifiable trading agent, allowing users to optimize their strategies with real-time, data-driven decisions while eliminating emotional bias.

### Challenges we ran into

At the beginning, we had limited knowledge of blockchain technology, making it challenging to deploy our agent on-chain. However, by learning from online resources and extensive research through Google, we gradually gained the coding skills needed to integrate agent. Another major challenge was designing a verification process to ensure that the model was trained on the intended dataset. Verifying the authenticity of training data in a decentralized environment is inherently complex. We addressed this by reducing the model's size, making it more efficient while maintaining transparency in the training process. Through persistence and problem-solving, we overcame these obstacles to build a trustworthy, on-chain AI trading agent that is both verifiable and efficient.

### Accomplishments we're proud of

We started from scratch and converted our innovative and crazy idea into an applicable real-world project. Through effective collaboration, extensive problem-solving, and actively seeking help from sponsors, our team built an impactful and inspiring AI agent that can own and manage on-chain data (current price), integrate verifiable off-chain services and Web3 APIs (Dune and Infura testnet faucet), and enforce policies or rules that guarantee safety, trust, and transparency.

### What we learned

New knowledge in web3 and blockchain: We learned new knowledge in web3 and blockchain, which is a hot and intriguing area but brand new to all 3 of our team members, including the fundamental concepts like zero-knowledge proof and zkTLS, and TestNet. The fact that the agent can automatically generate proofs that provide users with an easy and efficient way of verification is intriguing to us. We also learned about the impactful companies in this area like EigenLayer with its Verifiable Agents and Taisu Venture, which helped us verify the source of the data we retrieved from OpenAI. As we developed our verification of machine learning datasets, we also came up with an interesting algorithm for proofing the dataset used. New knowledge in web3 and blockchain: We learned new knowledge in web3 and blockchain, which is a hot and intriguing area but brand new to all 3 of our team members, including the fundamental concepts like zero-knowledge proof and zkTLS, and TestNet. The fact that the agent can automatically generate proofs that provide users with an easy and efficient way of verification is intriguing to us. We also learned about the impactful companies in this area like EigenLayer with its Verifiable Agents and Taisu Venture, which helped us verify the source of the data we retrieved from OpenAI. As we developed our verification of machine learning datasets, we also came up with an interesting algorithm for proofing the dataset used. Technical skills: We also developed our coding skills by building up machine learning and LLM models and atomizing the whole process, and tested experiments with APIs. Technical skills: We also developed our coding skills by building up machine learning and LLM models and atomizing the whole process, and tested experiments with APIs. Soft and interpersonal skills: Moreover, as John Hennessy mentioned in the workshop, we should be humble and authentic and always do something new. We kept these values in mind through the whole process of TreeHacks, and always asking questions, sharing our thoughts, and thinking outside of the box to be innovative. Our team worked together from not knowing each other to close teammates and friends. Our interpersonal skills like teamwork and communication improved, and we knew how to work with people from different backgrounds and skillsets. Soft and interpersonal skills: Moreover, as John Hennessy mentioned in the workshop, we should be humble and authentic and always do something new. We kept these values in mind through the whole process of TreeHacks, and always asking questions, sharing our thoughts, and thinking outside of the box to be innovative. Our team worked together from not knowing each other to close teammates and friends. Our interpersonal skills like teamwork and communication improved, and we knew how to work with people from different backgrounds and skillsets.

### What's next

Although we have successfully deployed AgentZero on-chain, there is still room for improvement to enhance its performance and accuracy. Improved News Analysis: We aim to refine the news analysis logistics to better interpret and categorize news events with greater contextual understanding. Enhancing sentiment detection and incorporating entity recognition could improve decision-making accuracy. Higher-Resolution Data: Currently, due to the lack of a pro version, we are limited to hourly data rather than minute-by-minute or second-level updates. Upgrading our data pipeline to process more granular real-time data would enable faster, more responsive trading actions. AgentZero is also applicable to other coins in the future. Exploring Advanced Deep Learning Models: While Random Forest Regression has served us well, we plan to experiment with more advanced deep learning architectures such as LSTMs, Transformers, or Reinforcement Learning to improve price prediction accuracy. By implementing these improvements, AgentZero will continue evolving into a smarter, faster, and more precise AI-powered trading agent.

## README (from the GitHub repository)

# TreeHack2025 Repository
## This project wins the first place in the Web3 track for The Best AI Agent. WoW!!
Welcome to the TreeHack2025 Team1 project on web3! This repository contains various tools and models developed during TreeHack 2025 to analyze and predict Ethereum (ETH) prices using machine learning.

## Introduction
We are deploying an automated unstoppble verifiable ai agent that helps you manage your asset on blockchain. This project specifically targeted Ethereum(ETH)

## How to run this project
**Clone the repository:**
   ```bash
   git clone https://github.com/2pir2/TreeHack2025.git
   cd TreeHack2025
  cd Eigenlayer
  pnpm install
   ```

* inside the .env file in the folder, change the open-ai key to your open-ai key and the opacity key to your wallet's private key *
```bash
pnpm run dev
cd ../TestETH
python3 main.py
```


## Detected evidence (automated analysis)

Indexed codebase: 28 recognized source files, 141 KB.
- Express (technology) — detected in the code
- Go (language) — detected in the code
- Python (language) — detected in the code
- TypeScript (language) — detected in the code

## Codebase structure (from repository index)

### Files (49 of 49)

```
.DS_Store
.gitignore
BlockSimulation/action.txt
BlockSimulation/test.py
Eigenlayer/.env.example
Eigenlayer/Formfile
Eigenlayer/Output.json
Eigenlayer/package.json
Eigenlayer/README.md
Eigenlayer/src/agent/createAgent.ts
Eigenlayer/src/index.ts
Eigenlayer/src/server.ts
Eigenlayer/src/witness.ts
Eigenlayer/test.py
Eigenlayer/tsconfig.json
ETH_filtered.csv
eth_price_xgboost_model_performance.csv
eth_price_xgboost_model.pkl
ETH.csv
model_hash.txt
NewsAnalyzer/analyze.py
NewsAnalyzer/output_with_sentiment.csv
Output.csv
README.md
test
TestETH/analyze.py
TestETH/ccxtread.py
TestETH/main.py
TestETH/newsread.py
TestETH/read.py
TestETH/scheduler.py
TestETH/test.py
TestETH/TrainingModels/gru.py
TestETH/TrainingModels/LR/train.py
TestETH/TrainingModels/LSTM.py
TestETH/TrainingModels/RandomForest/eth_price_predictions.csv
TestETH/TrainingModels/RandomForest/trainRandomForest.py
TestETH/TrainingModels/train.py
TestETH/TrainingModels/trainxgboost.py
TestETH/trainRandomForest.py
TestETH/utils/__init__.py
WeightsVerification/eth_price_model_performance.csv
WeightsVerification/eth_price_model.pkl
WeightsVerification/ETHHash.py
WeightsVerification/go.mod
WeightsVerification/go.sum
WeightsVerification/main.go
WeightsVerification/model_hash.txt
WeightsVerification/test.py
```

### Dependencies

- Eigenlayer/package.json: @layr-labs/agentkit@latest, @layr-labs/agentkit-eigenda@latest, @layr-labs/agentkit-opacity@latest, @layr-labs/agentkit-witnesschain@latest, @types/cors@^2.8.17, @types/express@^4.17.21, @types/node@^20.11.24, @typescript-eslint/eslint-plugin@^7.1.0, @typescript-eslint/parser@^7.1.0, axios@^1.7.9, cors@^2.8.5, dotenv@^16.4.5, eigenda-sdk@latest, eslint@^8.57.0, express@^4.18.3, prettier@^3.2.5, tsx@^4.19.2, typescript@^5.3.3
- WeightsVerification/go.mod: github.com/bits-and-blooms/bitset@v1.8.0, github.com/blang/semver/v4@v4.0.0, github.com/consensys/bavard@v0.1.13, github.com/consensys/gnark@v0.10.0, github.com/consensys/gnark-crypto@v0.12.2-0.20240215234832-d72fcb379d3e, github.com/davecgh/go-spew@v1.1.1, github.com/fxamacker/cbor/v2@v2.5.0, github.com/google/pprof@v0.0.0-20230817174616-7a8ec2ada47b, github.com/ingonyama-zk/icicle@v0.0.0-20230928131117-97f0079e5c71, github.com/ingonyama-zk/iciclegnark@v0.1.0, github.com/mattn/go-colorable@v0.1.13, github.com/mattn/go-isatty@v0.0.19, github.com/mmcloughlin/addchain@v0.4.0, github.com/pmezard/go-difflib@v1.0.0, github.com/rs/zerolog@v1.30.0, github.com/stretchr/testify@v1.8.4, github.com/x448/float16@v0.8.4, golang.org/x/sys@v0.15.0, gopkg.in/yaml.v3@v3.0.1, rsc.io/tmplfunc@v0.0.3

### Recent commits (newest first)

- Update README.md
- Update README.md
- Fix bug: timestamp filtering
- Integrate news prediction, fix response parsing
- Clean
- Merge branch 'main' of github.com:2pir2/TreeHack2025
- Implement data retrieval from news
- Create README.md
- Merge branch 'main' of github.com:2pir2/TreeHack2025
- Update file path
- Add newsread
- added
- Merge branch 'main' of https://github.com/2pir2/TreeHack2025
- added
- Merge branch 'main' of github.com:2pir2/TreeHack2025
- Integrate deployment
- changes
- Merge branch 'main' of github.com:2pir2/TreeHack2025
- Integrate the data retrieval into the main flow
- addded

## Key source files (fetched from GitHub, selected and truncated for size)

### WeightsVerification/go.mod

```
module Hack

go 1.21

toolchain go1.23.0

require (
	github.com/consensys/gnark v0.10.0
	github.com/consensys/gnark-crypto v0.12.2-0.20240215234832-d72fcb379d3e
)

require (
	github.com/bits-and-blooms/bitset v1.8.0 // indirect
	github.com/blang/semver/v4 v4.0.0 // indirect
	github.com/consensys/bavard v0.1.13 // indirect
	github.com/davecgh/go-spew v1.1.1 // indirect
	github.com/fxamacker/cbor/v2 v2.5.0 // indirect
	github.com/google/pprof v0.0.0-20230817174616-7a8ec2ada47b // indirect
	github.com/ingonyama-zk/icicle v0.0.0-20230928131117-97f0079e5c71 // indirect
	github.com/ingonyama-zk/iciclegnark v0.1.0 // indirect
	github.com/mattn/go-colorable v0.1.13 // indirect
	github.com/mattn/go-isatty v0.0.19 // indirect
	github.com/mmcloughlin/addchain v0.4.0 // indirect
	github.com/pmezard/go-difflib v1.0.0 // indirect
	github.com/rs/zerolog v1.30.0 // indirect
	github.com/stretchr/testify v1.8.4 // indirect
	github.com/x448/float16 v0.8.4 // indirect
	golang.org/x/sys v0.15.0 // indirect
	gopkg.in/yaml.v3 v3.0.1 // indirect
	rsc.io/tmplfunc v0.0.3 // indirect
)

```

### Eigenlayer/package.json

```
{
  "name": "eigenai-quickstart",
  "version": "1.0.0",
  "description": "A ready-to-use scaffold for building verifiable AI agents using Layr Labs' AgentKit adapters",
  "main": "dist/index.js",
  "type": "module",
  "scripts": {
    "dev": "tsx watch src/server.ts",
    "build": "tsc",
    "start": "node dist/index.js",
    "example": "ts-node src/index.ts",
    "lint": "eslint . --ext .ts",
    "format": "prettier --write \"src/**/*.ts\""
  },
  "keywords": [
    "ai",
    "agentkit",
    "opacity",
    "eigenda",
    "witnesschain",
    "verifiable-ai"
  ],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@layr-labs/agentkit": "latest",
    "@layr-labs/agentkit-eigenda": "latest",
    "@layr-labs/agentkit-opacity": "latest",
    "@layr-labs/agentkit-witnesschain": "latest",
    "cors": "^2.8.5",
    "dotenv": "^16.4.5",
    "eigenda-sdk": "latest",
    "express": "^4.18.3"
  },
  "devDependencies": {
    "@types/cors": "^2.8.17",
    "@types/express": "^4.17.21",
    "@types/node": "^20.11.24",
    "@typescript-eslint/eslint-plugin": "^7.1.0",
    "@typescript-eslint/parser": "^7.1.0",
    "axios": "^1.7.9",
    "eslint": "^8.57.0",
    "prettier": "^3.2.5",
    "tsx": "^4.19.2",
    "typescript": "^5.3.3"
  },
  "pnpm": {
    "onlyBuiltDependencies": [
      "esbuild"
    ]
  }
}
```

### TestETH/main.py

```python
from ccxtread import data_retrieval_price # data retrieval for price data
from newsread import data_retrieval_news # data retrieval for news
from test import send_eth, w3connect # deployment
from trainRandomForest import fun_process_price
from analyze import fun_process_news

import pandas as pd
import numpy as np
from datetime import datetime

# time = "2023-10-01 03:40:00"  # timestamp format

# data retrieval function (time) => data format in csv format
def fun_data_price(time):
    start_time = pd.to_datetime(time) - pd.Timedelta(days=10)
    date = time.split(" ")[0]
    start_time = start_time.strftime("%Y-%m-%d %H:%M:%S")
    start_date = start_time.split(" ")[0]
    start_time = start_time.split(" ")[1]
    df = data_retrieval_price(start_date, date, start_time)
    return df

def fun_data_news(time):
    start_time = pd.to_datetime(time) - pd.Timedelta(days=1)
    start_time = start_time.strftime("%Y-%m-%d %H:%M:%S")
    df = data_retrieval_news(start_time, time)
    return df

weight_price = 0.9
weight_news = 1 - weight_price

# prediction function (time) => predicted value (float)
def predict(time, w1, w2):
    price_predicted = fun_process_price(fun_data_price(time))[0]
    # return price_predicted
    news_average = fun_process_news(fun_data_news(time))
    return (weight_news * news_average + 1) * price_predicted

def current_price(time):
    # get the data for the current day
    start_date = time.split(" ")[0]
    end_time = pd.to_datetime(time) + pd.Timedelta(days=1)
    end_time = end_time.strftime("%Y-%m-%d %H:%M:%S")
    end_date = end_time.split(" ")[0]
    return data_retrieval_price(start_date, end_date, "00:00:00")

# current value (time) => current price (float)
def current(time):
    df = current_price(time)
    target_time = pd.to_datetime(time)
    df["timestamp"] = pd.to_datetime(df["timestamp"])
    closest_index = (df["timestamp"] - target_time).abs().idxmin()
    value = df.loc[closest_index, "close"]
    print(f"@@@ Recent Price for time {time}: {value} @@@")
    return value

def decision(time):
    predicted = predict(time, weight_price, weight_news)
    current_price = current(time)
    print(f"@@@ Final Predicted Price for time {time} (weighted): {predicted} @@@")
    if abs(predicted - current_price) <= 0.01 * current_price:
        return 0
    elif predicted > current_price:
        return 1
    else:
        return -1

def do_trx(action):
    if action is not None:
        if action == 1:
            print("🟢 Buying ETH...")
        elif action == -1:
            print("🔴 Selling ETH...")
        try:
            w3connect()
            send_eth(action)
        except Exception as e:
            print(f"❌ Error sending ETH: {e}")

def check_do_trx():
    current_time = datetime.now()
    current_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
    time = "2023-09-28 20:15:00"  # buying
    time = "2023-09-28 18:00:00"  # selling
    time = "2023-09-30 04:00:00" # no action
    action = decision(time)
    do_trx(action)

check_do_trx()

```

### WeightsVerification/main.go

```go
// package main

// import (
// 	"fmt"

// 	"github.com/consensys/gnark-crypto/ecc"
// 	"github.com/consensys/gnark/backend/groth16"
// 	"github.com/consensys/gnark/frontend"
// 	"github.com/consensys/gnark/frontend/cs/r1cs"
// )

// // Sigmoid function approximation using a polynomial
// func sigmoid(api frontend.API, x frontend.Variable) frontend.Variable {
// 	one := frontend.Variable(1)
// 	// Approximate sigmoid using 1 / (1 + exp(-x)) ≈ 1 / (1 + (1 - x + x^2/2))
// 	approxExpNegX := api.Add(one, api.Sub(x, api.Div(api.Mul(x, x), frontend.Variable(2))))
// 	return api.Div(one, approxExpNegX)
// }

// // LogisticRegressionCircuit defines a simple logistic regression model

// func (circuit *ProveModelCircuit) Define(api frontend.API) error {
// 	nFeatures := len(circuit.FeatureValues)
// 	sum := circuit.Bias

// 	// Compute linear combination: sum = w1*x1 + w2*x2 + ... + wn*xn + bias
// 	for i := 0; i < nFeatures; i++ {
// 		weightedFeature := api.Mul(circuit.FeatureValues[i], circuit.Weights[i])
// 		sum = api.Add(sum, weightedFeature)
// 	}

// 	// Apply sigmoid function approximation
// 	probability := sigmoid(api, sum)

// 	// Threshold at 0.5 for classification (0 or 1)
// 	threshold := frontend.Variable(5)
// 	classPrediction := api.Cmp(probability, threshold)
// 	api.AssertIsEqual(classPrediction, circuit.Prediction)

// 	return nil
// }

// type ProveModelCircuit struct {
// 	FeatureValues [2]frontend.Variable `gnark:",private"`
// 	Weights       [2]frontend.Variable `gnark:",private"`
// 	Bias          frontend.Variable    `gnark:",private"`
// 	Prediction    frontend.Variable    `gnark:",private"`
// }

// func main() {
// 	// Compile the logistic regression circuit
// 	var logRegCircuit ProveModelCircuit
// 	r1cs, err := frontend.Compile(ecc.BN254.ScalarField(), r1cs.NewBuilder, &logRegCircuit)
// 	if err != nil {
// 		fmt.Println("Error compiling circuit:", err)
// 		return
// 	}

// 	// Generate zk-SNARK proving and verification keys
// 	pk, vk, err := groth16.Setup(r1cs)
// 	if err != nil {
// 		fmt.Println("Error during setup:", err)
// 		return
// 	}

// 	// Example feature values, weights, bias, and expected prediction
// 	assignment := &ProveModelCircuit{}
// 	assignment.FeatureValues[0] = 20
// 	assignment.FeatureValues[1] = 30
// 	assignment.Weights[0] = 5
// 	assignment.Weights[1] = -2
// 	assignment.Bias = 1
// 	assignment.Prediction = 1
// 	// Generate proof
// 	fmt.Print(assignment)
// 	witness, err := frontend.NewWitness(assignment, ecc.BN254.ScalarField())
// 	if err != nil {
// 		fmt.Println("Error creating witness:", err)
// 		return
// 	}

// 	proof, err := groth16.Prove(r1cs, pk, witness)
// 	if err != nil {
// 		fmt.Println("Error proving:", err)
// 		return
// 	}

// 	// Verify proof
// 	publicWitness, err := witness.Public()
// 	if err != nil {
// 		fmt.Println("Error getting public witness:", err)
// 		return
// 	}

//		err = groth16.Verify(proof, vk, publicWitness)
//		if err != nil {
//			fmt.Println("Verification failed")
//		} else {
//			fmt.Println("Verification succeeded")
//		}
//	}

// package main

// import (
// 	"fmt"

// 	"github.com/consensys/gnark-crypto/ecc"
// 	"github.com/consensys/gnark/backend/groth16"
// 	"github.com/consensys/gnark/frontend"
// 	"github.com/consensys/gnark/frontend/cs/r1cs"
// )

// // Decision Tree Node - Approximating a Decision Tree in zk-SNARKs
// func decisionTree(api frontend.API, feature1, feature2 frontend.Variable) frontend.Variable {
// 	threshold1 := frontend.Variable(15)
// 	threshold2 := frontend.Variable(25)

// 	// First split: if feature1 > 15
// 	leftBranch := api.Cmp(feature1, threshold1)

// 	// Second split: if feature2 > 25
// 	rightBranch := api.Cmp(feature2, threshold2)

// 	// Decision: If leftBranch == 1 and rightBranch == 1 → Class 1, else Class 0
// 	prediction := api.Mul(leftBranch, rightBranch) // This ensures both conditions are met
// 	return prediction
// }

// // RandomForestCircuit - An approximation of a 3-tree Random Forest
// type RandomForestCircuit struct {
// 	FeatureValues [2]frontend.Variable `gnark:",private"`
// 	Prediction    frontend.Variable    `gnark:",public"`
// }

// func (circuit *RandomForestCircuit) Define(api frontend.API) error {
// 	// Define three decision trees (simplified)
// 	tree1 := decisionTree(api, circuit.FeatureValues[0], circuit.FeatureValues[1])
// 	tree2 := decisionTree(api, circuit.FeatureValues[0], api.Add(circuit.FeatureValues[1], frontend.Variable(5)))
// 	tree3 := decisionTree(api, api.Add(circuit.FeatureValues[0], frontend.Variable(-3)), circuit.FeatureValues[1])

// 	// Majority Voting: Sum of tree outputs should be >= 2 for class 1, else class 0
// 	sumPredictions := api.Add(api.Add(tree1, tree2), tree3)
// 	finalPrediction := api.Cmp(sumPredictions, frontend.Variable(2)) // If at least 2 trees vote "1", final class is 1
// 	api.Println("This is the final predictinp", finalPrediction)
// 	// Ensure that the computed prediction matches the expected prediction
// 	api.AssertIsEqual(finalPrediction, circuit.Prediction)

// 	return nil
// }

// func main() {
// 	// Compile the Random Forest circuit
// 	var rfCircuit RandomForestCircuit
// 	r1cs, err := frontend.Compile(ecc.BN254.ScalarField(), r1cs.NewBuilder, &rfCircuit)
// 	if err != nil {
// 		fmt.Println("Error compiling circuit:", err)
// 		return
// 	}

// 	// Generate zk-SNARK proving and verification keys
// 	pk, vk, err := groth16.Setup(r1cs)
// 	if err != nil {
// 		fmt.Println("Error during setup:", err)
// 		return
// 	}

// 	// Example feature values and expected prediction
// 	assignment := &RandomForestCircuit{}
// 	assignment.FeatureValues[0] = 20 // Example feature 1
// 	assignment.FeatureValues[1] = 30 // Example feature 2
// 	assignment.Prediction = 1        // Expected majority class

// 	// Generate witness
// 	witness, err := frontend.NewWitness(assignment, ecc.BN254.ScalarField())
// 	if err != nil {
// 		fmt.Println("Error creating witness:", err)
// 		return
// 	}

[truncated — 4518 more characters]
```

### Eigenlayer/src/index.ts

```typescript
import { createAgent } from './agent/createAgent.ts';

async function main() {
  try {
    console.log('🤖 Initializing AI Agent...');
    const agent = await createAgent();

    // Example 1: Generate verifiable text
    console.log('\n📝 Generating verifiable text...');
    const prompt = 'What is the capital of France?';
    const textResult = await agent.generateVerifiableText(prompt);
    console.log('Response:', textResult.content);
    console.log('Proof available:', !!textResult.proof);

    // Example 2: Log custom information
    console.log('\n📊 Logging custom information...');
    await agent.logInfo('Demo Completed', {
      timestamp: new Date().toISOString(),
      status: 'success'
    });

    console.log('\n✅ Demo completed successfully!');
  } catch (error) {
    console.error('❌ Error:', error);
    process.exit(1);
  }
}

main(); 
```

### Eigenlayer/src/server.ts

```typescript
import express from 'express';
import cors from 'cors';
import { createAgent } from './agent/createAgent.js';
import dotenv from 'dotenv';

dotenv.config();

const app = express();
const port = process.env.PORT || 3000;

let agent: Awaited<ReturnType<typeof createAgent>>;

// Initialize the agent
createAgent().then(a => {
  agent = a;
  console.log('Agent initialized successfully');
}).catch(error => {
  console.error('Failed to initialize agent:', error);
  process.exit(1);
});

// Middleware
app.use(cors());
app.use(express.json());

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ status: 'ok', agentReady: !!agent });
});

// Generate verifiable text endpoint
app.post('/api/generate', async (req, res) => {
  try {
    if (!agent) {
      return res.status(503).json({ error: 'Agent not ready' });
    }

    const { prompt } = req.body;
    
    if (!prompt) {
      return res.status(400).json({ error: 'Prompt is required' });
    }

    console.log('Generating text for prompt:', prompt);
    const result = await agent.generateVerifiableText(prompt);
    console.log('Generation result:', result);
    res.json(result);
  } catch (error) {
    console.error('Error generating text:', error);
    res.status(500).json({ 
      error: 'Failed to generate text',
      details: error instanceof Error ? error.message : String(error)
    });
  }
});

// Start server
app.listen(port, () => {
  console.log(`🚀 Server running at http://localhost:${port}`);
  console.log('Available endpoints:');
  console.log('  GET  /health');
  console.log('  POST /api/generate');
}); 
```

### TestETH/scheduler.py

```python
import schedule
import time

from main import check_do_trx

def p():
    print("Running transactions")

# schedule.every(3).seconds.do(check_do_trx)
schedule.every(3).seconds.do(p)

while True:
    schedule.run_pending()
    time.sleep(1)


```

### Eigenlayer/test.py

```python
from openai import OpenAI  # Ensure this is the latest SDK version
client = OpenAI(api_key="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")


chat_completion = client.chat.completions.create(
    messages=[
        {"role": "user", "content": "Tell me some news about ETH in 2023"}
    ],
    model="gpt-4o",
)
print(chat_completion.choices[0].message.content)


```

### WeightsVerification/ETHHash.py

```python
import pickle
import os

# Define the model path
model_path = "/Users/hanxu/Desktop/TreeHack/TreeHack2025/TestETH/TrainingModels/RandomForest/eth_price_model.pkl"

# Ensure the file exists
if not os.path.exists(model_path):
    raise FileNotFoundError(f"Model file not found at: {model_path}")

# Load the model
with open(model_path, "rb") as file:
    model = pickle.load(file)

# Print model type
print("Loaded model type:", type(model))

# Check if it's a RandomForestClassifier
if hasattr(model, "estimators_"):
    print("✅ Model is a valid RandomForestClassifier.")
else:
    raise TypeError("❌ Model is not a RandomForestClassifier. Check the saved file format!")

```

### TestETH/newsread.py

```python
import pandas as pd
import requests
from io import StringIO


def data_retrieval_news(start_time, end_time):
    url = "http://localhost:3000/api/generate"
    data = {
        "Content-Type": "application/json",
        "prompt": f"Please give me 10 news in from {start_time} to {end_time} that could affect the price of ETH, with its corresponding dates and websites. Please generate them in a dataframe, which first column is News, second is the Date, third is Website, provide it in a table in csv format. It's ok it's hypothetical."
    }
    response = requests.post(url, json=data)
    response = response.json()["content"] # we are not integrating the proof rn

    start = response.index("```")
    start = response.index("\n", start) + 1
    end = response.index("```", start) 
    csv_data = response[start:end].strip()
    # Use StringIO to convert the string into a file-like object
    csv_data = StringIO(csv_data)

    # Read the CSV data into a pandas DataFrame
    df = pd.read_csv(csv_data)
    print(f"@@@ News retrieval completed from {start_time} to {end_time} @@@")
    return df

```

[16 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]