# Deploy Oracle to Railway - Step by Step

**Follow these exact steps to deploy your oracle service. Takes 10 minutes.**

---

## Why This Matters

Once you deploy the oracle:
- ✅ Users never need to start oracle service
- ✅ Just `pip install` and `loggerheads` - done!
- ✅ True plug-and-play experience
- ✅ Production-ready, scalable

---

## Step 1: Prepare Oracle Keypair

### Generate Keypair

```bash
python3 -m loggerheads.oracle_secure --generate
```

Output:
```
✅ Oracle keypair generated: /Users/you/.loggerheads/oracle-keypair.json
🔑 Public key: 3fRGj4mzWot9Vmdb6Asxk692WZkhQybU8oNme1MjkYVJ
```

### Convert for Deployment

```bash
python3 oracle_service/prepare_deploy.py
```

You'll see:
```
Key: ORACLE_KEYPAIR_JSON
Value: [10, 210, 172, 31, 46, 171, ...]
```

**Copy this entire JSON array!** You'll need it in step 3.

---

## Step 2: Deploy to Railway

### Create Railway Account

1. Go to https://railway.app
2. Click "Start a New Project"
3. Sign up with GitHub (easiest)

### Create New Project

1. Click "New Project"
2. Select "Deploy from GitHub repo"
3. Connect your kapture repository
4. Select the repository

### Configure Service

Railway will detect your code automatically. Now configure it:

1. Click on the deployed service
2. Go to "Settings" tab
3. Under "Service Name", name it: `kapture-oracle`
4. Under "Root Directory", set: `oracle_service`

---

## Step 3: Add Environment Variable

Still in Railway dashboard:

1. Go to "Variables" tab
2. Click "New Variable"
3. Key: `ORACLE_KEYPAIR_JSON`
4. Value: Paste the entire JSON array from Step 1

Example:
```
[10, 210, 172, 31, 46, 171, 211, 89, 67, 47, 82, 47, 216, 76, 198, 158, ...]
```

**Important:** Paste the ENTIRE array, including the brackets `[` and `]`

5. Click "Add"

---

## Step 4: Deploy

1. Go back to "Deployments" tab
2. Click "Deploy" (or it may auto-deploy)
3. Wait 2-3 minutes for build

You'll see:
```
✅ Oracle loaded: 3fRGj4mzWot9Vmdb...
🔮 KAPTURE ORACLE SERVICE
📡 Starting API server...
```

---

## Step 5: Get Your Oracle URL

1. In Railway dashboard, go to "Settings"
2. Click "Generate Domain"
3. Railway will give you a URL like:

```
kapture-oracle-production.up.railway.app
```

**Copy this URL!**

---

## Step 6: Test Your Deployed Oracle

Test that it's working:

```bash
curl https://kapture-oracle-production.up.railway.app/health
```

Should return:
```json
{
  "status": "healthy",
  "oracle_pubkey": "3fRGj4mzWot9Vmdb...",
  "timestamp": "2025-10-27..."
}
```

✅ **If you see this, your oracle is live!**

---

## Step 7: Update Client to Use Deployed Oracle

Edit `loggerheads/oracle_client.py` line 29:

**Before:**
```python
return os.getenv('KAPTURE_ORACLE_URL', 'http://localhost:5001')
```

**After:**
```python
return os.getenv('KAPTURE_ORACLE_URL', 'https://kapture-oracle-production.up.railway.app')
```

Replace with YOUR Railway URL from Step 5.

---

## Step 8: Commit and Push

```bash
git add loggerheads/oracle_client.py
git commit -m "Update oracle to production deployment"
git push
```

---

## Step 9: Test End-to-End

Test that everything works:

### Test Client Connection

```bash
python3 -c "
from loggerheads.oracle_client import get_oracle_client

oracle = get_oracle_client()
health = oracle.health_check()
print(f'✅ Connected to oracle: {health[\"oracle_pubkey\"][:16]}...')
print(f'✅ Status: {health[\"status\"]}')
"
```

### Test Vault Creation

```bash
# Create test wallet
solana-keygen new --outfile /tmp/test-wallet.json

# Try creating vault
loggerheads
# Choose: Employer
```

If vault creation works, oracle is working perfectly!

---

## Step 10: Update Documentation

Now that oracle is deployed, update user-facing docs to remove oracle setup:

### Update README.md

Replace current README with simpler version:

```bash
cp README_SIMPLE.md README.md
git add README.md
git commit -m "Simplify README - oracle now deployed"
git push
```

### Update TESTING_GUIDE.md

Remove "Oracle Setup" section from `docs/TESTING_GUIDE.md`

Users don't need to know about oracle anymore!

---

## Result: True Plug-and-Play

**Before (Complex):**
```
User:
1. Clone repo
2. Install dependencies
3. Generate oracle keypair
4. Start oracle service (keep terminal open)
5. Set environment variable
6. Run app
```

**After (Simple):**
```
User:
1. Clone repo
2. pip install -e .
3. loggerheads
```

**That's it!** Oracle is already running in the cloud.

---

## Monitoring Your Oracle

### View Logs

In Railway dashboard:
1. Click on your service
2. Go to "Deployments" tab
3. Click latest deployment
4. View logs in real-time

### Check Metrics

Railway shows:
- CPU usage
- Memory usage
- Request count
- Response times

### Alerts

Set up in Railway:
1. Go to Project Settings
2. Notifications
3. Add webhook or email alerts

---

## Cost

### Railway Free Tier

- **$5 credit/month** (no credit card required initially)
- **Enough for:** ~500 hours of runtime
- **Perfect for:** Development and testing

### After Free Tier

- **~$0.01/hour** when running
- **Monthly cost:** ~$7 if running 24/7
- **Pay as you go:** Only pay for actual usage

### Cost Optimization

Oracle only needs to be running when users submit hours:
- Peak usage: 6 PM (auto-submit time)
- Can scale to zero during idle times
- Railway handles this automatically

---

## Security Checklist

- [x] Oracle keypair not in git (checked .gitignore)
- [x] Keypair stored as environment variable (Railway encrypts)
- [x] HTTPS enabled (Railway provides free SSL)
- [x] Logs don't expose keypair
- [x] Only necessary environment variables set

---

## Troubleshooting

### Build Failed

**Check:**
- Is `oracle_service/requirements.txt` present?
- Are all dependencies listed?
- Python version compatible?

**Solution:**
View build logs in Railway dashboard

### Oracle Not Loading

**Check environment variable:**
1. Go to Variables tab in Railway
2. Verify `ORACLE_KEYPAIR_JSON` is set
3. Verify it's the full JSON array with brackets

**Test locally:**
```bash
export ORACLE_KEYPAIR_JSON='[10, 210, ...]'
python3 oracle_service/app.py
```

### Cannot Connect from Client

**Check:**
1. Is oracle deployed and running? (Check Railway dashboard)
2. Is URL correct in `oracle_client.py`?
3. Is domain generated in Railway settings?

**Test:**
```bash
curl https://your-oracle-url/health
```

### "Vault trusts different oracle"

**You regenerated the oracle keypair!**

This breaks existing vaults. Solutions:
- Use original oracle keypair
- Or: Delete test vaults and create new ones

---

## Next Steps

### Share With Testers

Tell your 3 testers:

```
Just run:
  git clone https://github.com/stElmitchay/kapture
  cd kapture
  pip3 install -e .
  loggerheads

That's it! No oracle setup needed.
```

### For Production

When ready for mainnet:
1. Deploy oracle to production tier ($7/month)
2. Update smart contract to mainnet
3. Change USDC mint to mainnet USDC
4. Add monitoring and alerts
5. Set up backups

---

## Success Verification

You've successfully deployed when:

✅ Railway dashboard shows oracle running
✅ `/health` endpoint returns 200
✅ Oracle pubkey matches your keypair
✅ Test vault creation works
✅ `oracle_client.py` points to Railway URL
✅ Users can install and run without oracle setup

---

## Support

**Railway Issues:**
- Railway Docs: https://docs.railway.app
- Railway Discord: https://discord.gg/railway

**Kapture Issues:**
- GitHub Issues: https://github.com/stElmitchay/kapture/issues

---

**Congratulations! Your oracle is now production-ready and deployed. 🎉**

Users can now just install and use Kapture with zero oracle complexity!
