Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
271 changes: 256 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,263 @@
# OpenGradient Examples and Templates

Welcome to the Examples and Templates repository! 🚀 This repo is designed to help developers quickly get started with our products by providing examples and templates.

## What You Will Find Here
Welcome to the Examples and Templates repository! This repo provides production-ready examples demonstrating how to integrate OpenGradient's decentralized AI infrastructure into smart contracts.

- Code Examples: Real-world use cases demonstrating how to use OpenGradient products, from basic setups to advanced integrations.
## Overview

## Coming soon
- Templates: Ready-to-use project templates that can serve as a starting point for building your own applications, including boilerplate code and pre-configured settings.
- Step-by-Step Guides: Detailed instructions to help you understand how each example works and how to adapt the templates for your specific needs.
- Best Practices: Tips and recommendations on optimizing your code, following security guidelines, and making the most of our tools.
OpenGradient enables **verifiable AI inference on-chain** through:
- **TEE-secured ML models**: Run machine learning models with hardware-level security guarantees
- **LLM chat inference**: Use language models for natural language processing tasks
- **ZK-verified computations**: Cryptographic proofs for AI model outputs
- **Historical data access**: Query on-chain price feeds and market data

## How to Use This Repository
- Clone or download the examples and templates that match your project requirements.
- Follow OpenGradient [documentation](https://docs.opengradient.ai/) to set up and customize the code for your own use case.
## Examples

### DeFi Examples

#### 1. Dynamic Fee AMM (`contracts/defi/DynamicFeeAMM.sol`)

An Automated Market Maker that uses ML-predicted volatility to adjust swap fees dynamically.

**Features:**
- Real-time volatility prediction using OGHistorical price data
- Dynamic fee calculation (1-100 bps based on volatility)
- ZK-verified ML model inference
- Statistical preprocessing with OGPreprocessing

**Architecture:**
```
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ User Swap │────▶│ OGHistorical │────▶│ Price History │
│ Request │ │ (Last 24 Prices)│ │ (24h Window) │
└─────────────────┘ └──────────────────┘ └─────────────────┘
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Execute Swap │◀────│ Calculate Fee │◀────│ ML Volatility │
│ with Fee │ │ (1-100 bps) │ │ Prediction │
└─────────────────┘ └──────────────────┘ └─────────────────┘
```

**Use Cases:**
- DEX protocols seeking fair, market-responsive fees
- Liquidity providers wanting volatility-adjusted returns
- DeFi protocols needing on-chain volatility oracles

---

#### 2. Lending Risk Assessor (`contracts/defi/LendingRiskAssessor.sol`)

An ML-powered lending protocol that assesses borrower risk and sets personalized rates.

**Features:**
- User profiling based on collateral, debt, and transaction history
- TEE-verified ML risk scoring (0-100 scale)
- Dynamic interest rates (5-30% based on risk)
- Dynamic collateral ratios (150-300% based on risk)
- Real-time position health monitoring

**Architecture:**
```
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Borrower │────▶│ Build Profile │────▶│ ML Risk Model │
│ Request │ │ (History/Stats) │ │ (TEE-Secured) │
└─────────────────┘ └──────────────────┘ └─────────────────┘
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Loan Issued │◀────│ Risk-Adjusted │◀────│ Risk Score │
│ w/ Terms │ │ Rate & Ratio │ │ (0-100) │
└─────────────────┘ └──────────────────┘ └─────────────────┘
```

**Use Cases:**
- DeFi lending protocols (Aave, Compound style)
- Under-collateralized lending with ML credit scoring
- Risk-based insurance protocols

---

### NFT Examples

#### 3. Sentiment-Gated NFT Mint (`contracts/nft/SentimentGatedMint.sol`)

An NFT collection where minting eligibility is determined by LLM sentiment analysis.

**Features:**
- LLM-powered sentiment analysis of mint applications
- TEE-secured inference for tamper-proof decisions
- Configurable sentiment threshold
- Appeal mechanism for rejected applications
- Full audit trail of AI decisions

**Architecture:**
```
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ User Submits │────▶│ LLM Sentiment │────▶│ Parse Response │
│ Statement │ │ Analysis (TEE) │ │ APPROVED/ │
└─────────────────┘ └──────────────────┘ │ REJECTED │
└─────────────────┘
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ NFT Minted │◀────│ Threshold Check │◀────│ Application │
│ (if approved) │ │ (configurable) │ │ Stored │
└─────────────────┘ └──────────────────┘ └─────────────────┘
```

**Use Cases:**
- Curated NFT collections with quality control
- Community membership NFTs with values alignment
- Soulbound token issuance based on sentiment

---

### Governance Examples

#### 4. AI Governance (`contracts/governance/AIGovernance.sol`)

A DAO governance system with AI-powered proposal analysis and Q&A.

**Features:**
- Automatic proposal summarization using LLM
- AI-generated impact analysis (benefits & risks)
- Interactive Q&A about proposals
- Standard voting mechanics (For/Against/Abstain)
- Quorum and execution logic

**Architecture:**
```
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Proposal │────▶│ LLM Summary │────▶│ LLM Impact │
│ Created │ │ Generation │ │ Analysis │
└─────────────────┘ └──────────────────┘ └─────────────────┘
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Execute │◀────│ Voting Period │◀────│ AI-Enhanced │
│ if Passed │ │ (For/Against) │ │ Proposal │
└─────────────────┘ └──────────────────┘ └─────────────────┘

┌──────────────────────────────────────────┐
│ Interactive Q&A (Ask AI about Proposal)│
└──────────────────────────────────────────┘
```

**Use Cases:**
- DAO governance (MakerDAO, Compound Governance style)
- Corporate shareholder voting
- Community decision-making with AI assistance

---

## Quick Start

### Prerequisites

- Foundry or Hardhat for Solidity development
- Access to OpenGradient testnet
- [solid-ml](https://github.com/OpenGradient/solid-ml) library

### Installation

```bash
# Clone the repository
git clone https://github.com/OpenGradient/opengradient-examples.git
cd opengradient-examples

# Install dependencies (Foundry)
forge install OpenGradient/solid-ml

# Or with npm/yarn
npm install @opengradient/solid-ml
```

### Deployment

```bash
# Set environment variables
export RPC_URL=https://og-testnet.rpc.url
export PRIVATE_KEY=your_private_key

# Deploy DynamicFeeAMM
forge create contracts/defi/DynamicFeeAMM.sol:DynamicFeeAMM \
--constructor-args <token0> <token1> <volatilityModelCID> \
--rpc-url $RPC_URL \
--private-key $PRIVATE_KEY

# Deploy LendingRiskAssessor
forge create contracts/defi/LendingRiskAssessor.sol:LendingRiskAssessor \
--constructor-args <collateralToken> <lendingToken> <riskModelCID> \
--rpc-url $RPC_URL \
--private-key $PRIVATE_KEY

# Deploy SentimentGatedMint
forge create contracts/nft/SentimentGatedMint.sol:SentimentGatedMint \
--constructor-args "Collection Name" "SYMBOL" "ipfs://base-uri/" \
--rpc-url $RPC_URL \
--private-key $PRIVATE_KEY

# Deploy AIGovernance
forge create contracts/governance/AIGovernance.sol:AIGovernance \
--rpc-url $RPC_URL \
--private-key $PRIVATE_KEY
```

## OpenGradient Interfaces Used

| Interface | Description | Examples Using It |
|-----------|-------------|-------------------|
| `OGInference` | ML model and LLM inference | All examples |
| `OGHistorical` | Historical price/data feeds | DynamicFeeAMM |
| `OGPreprocessing` | Statistical operations | DynamicFeeAMM, LendingRiskAssessor |
| `TensorLib` | Tensor data structures | All ML examples |

## Inference Modes

| Mode | Description | Use Case |
|------|-------------|----------|
| `TEE` | Trusted Execution Environment | Most secure, tamper-proof |
| `ZK` | Zero-Knowledge Proofs | Verifiable without revealing inputs |
| `VANILLA` | Standard inference | Development/testing |

## Best Practices

1. **Model Selection**: Choose appropriate models for your use case
- LLMs for text analysis and generation
- Numerical models for predictions and scoring

2. **Error Handling**: Always handle inference failures gracefully
- Implement fallback values
- Use try-catch patterns

3. **Gas Optimization**:
- Cache inference results when possible
- Batch operations where applicable

4. **Security**:
- Use TEE mode for production deployments
- Validate all inputs before inference
- Implement access controls

## Resources

- [OpenGradient Documentation](https://docs.opengradient.ai/)
- [SolidML Library](https://github.com/OpenGradient/solid-ml)
- [OpenGradient SDK](https://github.com/OpenGradient/OpenGradient-SDK)

## Community
* Read our [Documentation](https://docs.opengradient.ai/)
* Join us on [Discord](https://discord.gg/axammqTRDz)
* Follow us on [Twitter](https://x.com/OpenGradient)
* Read our [Blogs](https://opengradient.ai/blog)

- [Discord](https://discord.gg/axammqTRDz)
- [Twitter](https://x.com/OpenGradient)
- [Blog](https://opengradient.ai/blog)

## Contributing

We welcome contributions! Please see our contributing guidelines and submit PRs for:
- New example contracts
- Improved documentation
- Bug fixes

## License

MIT License - see [LICENSE](LICENSE) for details.
Loading