# Solana Meme Coin Sniper Bot — Setup & Deployment Guide

## Prerequisites

- **Node.js** >= 18.0.0 (tested on v24+)
- **MySQL** >= 8.0
- **npm** or yarn
- **PM2** (global): `npm install -g pm2`

## Local Development Setup (Windows)

### 1. Create project directory
```powershell
mkdir C:\Users\VICTUS\Desktop\sniper-bot
cd C:\Users\VICTUS\Desktop\sniper-bot
```

### 2. Install dependencies
```powershell
npm install
```

### 3. Create logs directory
```powershell
mkdir logs
```

### 4. Verify .env file
The `.env` file is already created with all necessary credentials:
```
PRIVATE_KEY_BASE58=39yuZMK2QerpPqBKVJHKesUNkYNEuPNfrrYrWophCMEQupUCWVaBjd5KmxPXqjHHe7juACKpnapcjRS5D5FmDmEV
WALLET_PUBLIC_KEY=77GVgV6P5Xe4sGj6adRC7hE4sMUVLpQLPurbs3FL4nZb
HELIUS_RPC_URL=https://mainnet.helius-rpc.com/?api-key=c6243350-97dd-4d36-9c5d-3b4be3306f08
HELIUS_WS_URL=wss://mainnet.helius-rpc.com/?api-key=c6243350-97dd-4d36-9c5d-3b4be3306f08
BIRDEYE_API_KEY=e13b0f82e3c44306a2a0d5ee4ea606cf
DB_HOST=localhost
DB_NAME=flasbqkj_dieselcannabis
DB_USER=flasbqkj_dieselcannabis
DB_PASSWORD=YoungestD@1@2
```

### 5. MySQL Setup (Local)

If MySQL is not running locally, the bot will fail to connect. Set up MySQL on your development machine:

**Option A: Windows MySQL Service**
```powershell
# If MySQL is installed via installer, it should run as a service
# Check status:
Get-Service MySQL*

# If service is stopped, start it:
Start-Service MySQL
```

**Option B: XAMPP/WAMP Stack**
- Download XAMPP from https://www.apachefriends.org/
- Start the MySQL service from the Control Panel
- Default credentials: user=`root`, password=`` (empty)

**Option C: WSL MySQL**
```bash
# In WSL terminal
sudo apt update
sudo apt install mysql-server
sudo service mysql start
```

**Create database and user:**
```sql
CREATE DATABASE flasbqkj_dieselcannabis;
CREATE USER 'flasbqkj_dieselcannabis'@'localhost' IDENTIFIED BY 'YoungestD@1@2';
GRANT ALL PRIVILEGES ON flasbqkj_dieselcannabis.* TO 'flasbqkj_dieselcannabis'@'localhost';
FLUSH PRIVILEGES;
```

### 6. Test database connection
```powershell
npm test
```
Expected output: `Database connection successful`

### 7. Start the bot (development mode)
```powershell
npm run dev
```

You should see output like:
```
[TIMESTAMP] [INFO] Initializing bot...
[TIMESTAMP] [INFO] Database connection successful
[TIMESTAMP] [INFO] Database tables initialized successfully
[TIMESTAMP] [INFO] Bot initialized successfully
[TIMESTAMP] [INFO] Starting trading bot...
[TIMESTAMP] [INFO] Connected to Pump.fun WebSocket
[TIMESTAMP] [INFO] Connected to Helius WebSocket
[TIMESTAMP] [INFO] Starting pool listener
[TIMESTAMP] [INFO] API server listening on port 3000
```

### 8. Open dashboard
Open your browser and navigate to: **http://localhost:3000**

You should see:
- Green status indicator (RUNNING)
- Real-time execution logs
- Settings panel
- Start/Stop controls

## VPS Deployment (dieselcannabis.co)

### 1. SSH to VPS
```bash
ssh user@dieselcannabis.co
cd /home/user/projects/
```

### 2. Clone/upload bot files
```bash
git clone <repo> solana-sniper-bot
cd solana-sniper-bot
npm install --production
mkdir logs
```

### 3. MySQL setup on VPS
Most shared hosting comes with MySQL pre-installed. Use your hosting panel (cPanel, Plesk, etc.) to:
- Create database: `flasbqkj_dieselcannabis`
- Create user: `flasbqkj_dieselcannabis` with password `YoungestD@1@2`
- Grant all privileges on the database

Verify connection from VPS:
```bash
mysql -h localhost -u flasbqkj_dieselcannabis -p -e "USE flasbqkj_dieselcannabis; SHOW TABLES;"
```

### 4. PM2 startup
```bash
pm2 start ecosystem.config.js
pm2 save
pm2 startup systemd -u <username> --hp /home/<username>
```

Verify bot is running:
```bash
pm2 status
pm2 logs sniper-bot
```

### 5. Apache reverse proxy (if needed)
Add to your Apache VirtualHost configuration:
```apache
<Location /bot>
    ProxyPreserveHost On
    ProxyPass http://localhost:3000/
    ProxyPassReverse http://localhost:3000/
    
    # WebSocket support
    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} websocket [NC]
    RewriteCond %{HTTP:Connection} upgrade [NC]
    RewriteRule ^/bot/?(.*) "ws://localhost:3000/$1" [P,L]
</Location>
```

Then access dashboard at: **https://dieselcannabis.co/bot**

### 6. Enable HTTPS
Use Let's Encrypt (usually free with hosting):
```bash
certbot certonly --apache -d dieselcannabis.co
```

## Configuration (via Dashboard)

Once the bot is running, access the dashboard and adjust these settings:

| Setting | Default | Description |
|---------|---------|-------------|
| Trade Amount (SOL) | 0.05 | SOL spent per trade |
| Max Positions | 3 | Maximum concurrent open positions |
| Max Trades/Hour | 15 | Rate limit (trades per hour) |
| Daily Loss Limit (SOL) | 2.0 | Auto-pause if daily loss exceeds this |
| Take Profit % | 200 | Exit when position reaches +X% profit |
| Stop Loss % | 50 | Exit when position drops -X% |
| Position Timeout (min) | 6 | Close position if held longer than X minutes |
| Min Liquidity (USD) | 150 | Ignore pools with less liquidity |
| Max Liquidity (USD) | 500000 | Ignore pools with more liquidity |
| Max Token Age (min) | 5 | Only buy tokens < X minutes old |
| Slippage (BPS) | 1500 | Slippage tolerance for swaps (in basis points) |

Changes are saved to the database immediately.

## Monitoring

### Dashboard
Open browser to **http://localhost:3000**

**Displayed information:**
- Bot status (green=running, red=stopped)
- Today's P&L (profit/loss in SOL)
- Trades executed today
- Win rate %
- Open positions with live price updates
- Real-time execution logs (color-coded)
- Recent 50 closed trades

### Logs
```bash
# Development mode
tail -f logs/combined.log

# PM2 (production)
pm2 logs sniper-bot
pm2 monit
```

### Database queries
```sql
-- View open positions
SELECT * FROM open_positions;

-- View closed trades today
SELECT * FROM trades WHERE DATE(created_at) = DATE(NOW());

-- View bot status
SELECT * FROM bot_status WHERE id = 1;

-- View settings
SELECT * FROM settings;
```

## Troubleshooting

### Bot won't start
1. Check database connection: `npm test`
2. Verify MySQL is running
3. Check .env credentials
4. Review logs: `npm run dev` and look for error messages

### WebSocket connection fails
1. Check Helius RPC URL is correct in .env
2. Verify firewall allows outbound WebSocket (port 443)
3. Check logs for specific error from Helius

### No trades are executing
1. Check Pump.fun WebSocket is connected (log says "Connected to Pump.fun WebSocket")
2. Verify RugCheck API is accessible
3. Check that pools are being detected (look for "New pool detected" logs)
4. Ensure wallet balance is sufficient (>=0.1 SOL for trading)

### Dashboard not loading
1. Verify API server is listening: `curl http://localhost:3000`
2. Check Socket.io is working: open browser console, should show `socket.id` in Network tab
3. Review console errors in browser DevTools

### High slippage on swaps
1. Reduce TRADE_AMOUNT_SOL (swaps on smaller amounts have better execution)
2. Increase SLIPPAGE_BPS (currently 1500 = 15%)
3. Consider executing during low-congestion times on Solana

## Stop the bot gracefully
```bash
# Local
Ctrl+C

# PM2
pm2 stop sniper-bot
```

## Restart after a crash
```bash
# PM2 auto-restarts on crash after 5s delay
pm2 logs sniper-bot
```

## Uninstall / Remove bot
```bash
# PM2
pm2 delete sniper-bot
pm2 save

# Files
rm -rf /path/to/sniper-bot
```

## Performance expectations

**Real-world results (baseline, not guaranteed):**
- Pool detection latency: 2-5 seconds from creation
- Trade execution: 5-15 seconds from pool detection
- Position monitoring: updates every 5 seconds
- Dashboard latency: <500ms (real-time via Socket.io)

**Solana network conditions affect:**
- Transaction confirmation time (2-10 seconds)
- API response times
- Pool discovery timing

**Network bandwidth:**
- Incoming: ~2-5 MB/day (WebSocket streams + API calls)
- Outgoing: ~1-2 MB/day (transactions + logs)

## Safety Notes

⚠️ **IMPORTANT:**
- Never share your `.env` file or PRIVATE_KEY_BASE58
- Keep backups of your private key in a secure location
- Test with small SOL amounts (0.01-0.05) before scaling up
- The bot is **educational** — real trading carries financial risk
- Solana network fees apply to every transaction
- Failed transactions may still consume SOL

## Support

For issues:
1. Check logs: `pm2 logs sniper-bot`
2. Verify all APIs are accessible
3. Confirm MySQL is running and reachable
4. Review the error messages in the dashboard

## Version Info

- Bot version: 1.0.0
- Node.js: >=18.0.0
- Solana Web3.js: 1.98.4
- Jupiter API: v6 (REST only)
