Solana Integration

Technical guide to Veyra's Solana blockchain implementation.

Why Solana?

Performance Advantages

Speed:

Transaction Time: < 1 second
Throughput: 65,000+ TPS
Finality: ~0.4 seconds

Vs Ethereum:
Time: 12-15 seconds
Throughput: ~15 TPS
Finality: 13 minutes

Cost:

Average Transaction Fee: $0.00025
Trade cost: < $0.01
Withdrawal: ~$0.01

Vs Ethereum:
Average: $5-50
Peak times: $100+

Scalability:

✅ No congestion issues
✅ Consistent speeds
✅ Low fees at any volume
✅ Parallel transaction processing

Technical Architecture

Consensus Mechanism:

Proof of History (PoH):
- Cryptographic timestamp
- Orders events without waiting
- Enables parallel processing
- 400ms block times

+ Proof of Stake (PoS):
- Validator network
- Energy efficient
- Secure & decentralized

Network Specifications:

Launch: 2020
Block Time: 400ms
Max TPS: 65,000+
Validators: 1,900+
Total Staked: 60%+ of supply

Veyra Smart Contracts

Contract Architecture

Main Contracts:

1. Market Factory

pub struct MarketFactory {
    pub authority: Pubkey,
    pub market_count: u64,
    pub fee_percentage: u16,
    pub treasury: Pubkey,
}

Functions:
- create_market()
- update_market()
- resolve_market()
- collect_fees()

2. Market Contract

pub struct Market {
    pub id: Pubkey,
    pub question: String,
    pub outcomes: Vec<Outcome>,
    pub end_date: i64,
    pub resolved: bool,
    pub winning_outcome: Option<u8>,
    pub total_volume: u64,
}

Functions:
- buy_shares()
- sell_shares()
- get_price()
- get_balance()

3. Order Book

pub struct OrderBook {
    pub market: Pubkey,
    pub bids: Vec<Order>,
    pub asks: Vec<Order>,
}

Functions:
- place_order()
- cancel_order()
- match_orders()
- get_depth()

4. Position Manager

pub struct Position {
    pub user: Pubkey,
    pub market: Pubkey,
    pub outcome: u8,
    pub shares: u64,
    pub avg_price: u64,
}

Functions:
- create_position()
- update_position()
- close_position()
- calculate_pnl()

Transaction Flow

1. Buy Shares Transaction

User Action:
→ Click "Buy YES"
→ Enter 100 shares

 Frontend:
→ Calculate total cost
→ Build transaction
→ Request wallet signature

Wallet:
→ Display transaction details
→ User approves
→ Sign transaction

Blockchain:
→ Submit to Solana network
→ Validate transaction
→ Execute smart contract
→ Update balances
→ Confirm (< 1 sec)

Backend:
→ Listen for confirmation
→ Verify on-chain
→ Update database
→ Notify frontend

Frontend:
→ Update UI
→ Show success message
→ Refresh portfolio

2. Sell Shares Transaction

User Action:
→ Click "Sell YES"
→ Enter 50 shares

Smart Contract:
→ Check user has 50+ shares
→ Calculate payout
→ Transfer SOL to user
→ Burn shares
→ Update positions

Confirmation:
→ Transaction confirmed
→ User receives SOL
→ Shares deducted

3. Market Resolution

Oracle/Admin:
→ Submit resolution
→ Specify winning outcome

Smart Contract:
→ Verify authority
→ Mark market resolved
→ Lock further trading
→ Enable claims

Winners:
→ Claim winnings
→ Receive 1 SOL per share
→ Automatic payout option

Wallet Integration

Solana Wallet Adapter

Implementation:

import {
  ConnectionProvider,
  WalletProvider
} from '@solana/wallet-adapter-react';
import { WalletModalProvider } from '@solana/wallet-adapter-react-ui';
import {
  PhantomWalletAdapter,
  SolflareWalletAdapter,
} from '@solana/wallet-adapter-wallets';

const wallets = [
  new PhantomWalletAdapter(),
  new SolflareWalletAdapter(),
];

const endpoint = 'https://api.mainnet-beta.solana.com';

<ConnectionProvider endpoint={endpoint}>
  <WalletProvider wallets={wallets} autoConnect>
    <WalletModalProvider>
      <App />
    </WalletModalProvider>
  </WalletProvider>
</ConnectionProvider>

Connecting Wallet

Frontend Code:

import { useWallet } from '@solana/wallet-adapter-react';

const { 
  connect, 
  disconnect, 
  publicKey, 
  connected,
  signTransaction 
} = useWallet();

// Connect
await connect();

// Get address
const address = publicKey?.toBase58();

// Disconnect
await disconnect();

Signing Transactions

Example:

import { 
  Transaction, 
  SystemProgram,
  PublicKey
} from '@solana/web3.js';

// Build transaction
const transaction = new Transaction().add(
  SystemProgram.transfer({
    fromPubkey: publicKey,
    toPubkey: new PublicKey(TREASURY_ADDRESS),
    lamports: amount * LAMPORTS_PER_SOL,
  })
);

// Get recent blockhash
const { blockhash } = await connection.getRecentBlockhash();
transaction.recentBlockhash = blockhash;
transaction.feePayer = publicKey;

// Sign transaction
const signed = await signTransaction(transaction);

// Send transaction
const signature = await connection.sendRawTransaction(
  signed.serialize()
);

// Confirm
await connection.confirmTransaction(signature);

Backend Integration

Solana RPC Connection

Python Implementation:

from solders.rpc.requests import GetTransaction
from solders.signature import Signature
import httpx

SOLANA_RPC = "https://api.mainnet-beta.solana.com"

async def get_transaction(signature: str):
    async with httpx.AsyncClient() as client:
        response = await client.post(
            SOLANA_RPC,
            json={
                "jsonrpc": "2.0",
                "id": 1,
                "method": "getTransaction",
                "params": [
                    signature,
                    {"encoding": "json"}
                ]
            }
        )
        return response.json()

Transaction Verification

Backend Verification:

async def verify_trade_transaction(
    signature: str,
    expected_amount: float,
    user_wallet: str,
    treasury_wallet: str
):
    # Get transaction from blockchain
    tx_data = await get_transaction(signature)
    
    if "error" in tx_data:
        raise ValueError("Transaction not found")
    
    result = tx_data["result"]
    
    # Verify transaction succeeded
    if result["meta"]["err"] is not None:
        raise ValueError("Transaction failed")
    
    # Verify sender
    sender = result["transaction"]["message"]["accountKeys"][0]
    if sender != user_wallet:
        raise ValueError("Wrong sender")
    
    # Verify receiver (treasury)
    accounts = result["transaction"]["message"]["accountKeys"]
    if treasury_wallet not in accounts:
        raise ValueError("Treasury not in transaction")
    
    # Verify amount
    pre_balances = result["meta"]["preBalances"]
    post_balances = result["meta"]["postBalances"]
    
    treasury_index = accounts.index(treasury_wallet)
    amount_received = (
        post_balances[treasury_index] - pre_balances[treasury_index]
    ) / 1e9  # Convert lamports to SOL
    
    if abs(amount_received - expected_amount) > 0.001:
        raise ValueError("Amount mismatch")
    
    return True

Listening for Events

WebSocket Connection:

import websockets
import json

async def listen_to_wallet(wallet_address: str):
    uri = "wss://api.mainnet-beta.solana.com"
    
    async with websockets.connect(uri) as websocket:
        # Subscribe to account changes
        await websocket.send(json.dumps({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "accountSubscribe",
            "params": [
                wallet_address,
                {"encoding": "json"}
            ]
        }))
        
        # Listen for updates
        while True:
            response = await websocket.recv()
            data = json.loads(response)
            
            if "result" in data:
                # New transaction detected
                await process_transaction(data)

Security Measures

Transaction Security

Validation Checks:

// Smart Contract Validation
pub fn buy_shares(
    ctx: Context<BuyShares>,
    shares: u64,
) -> Result<()> {
    // 1. Check market is active
    require!(
        !ctx.accounts.market.resolved,
        ErrorCode::MarketResolved
    );
    
    // 2. Check not past end date
    let clock = Clock::get()?;
    require!(
        clock.unix_timestamp < ctx.accounts.market.end_date,
        ErrorCode::MarketExpired
    );
    
    // 3. Check sufficient funds
    let cost = calculate_cost(shares, price);
    require!(
        ctx.accounts.user.lamports() >= cost,
        ErrorCode::InsufficientFunds
    );
    
    // 4. Check no overflow
    let new_total = ctx.accounts.position.shares
        .checked_add(shares)
        .ok_or(ErrorCode::Overflow)?;
    
    // Execute trade
    execute_trade(ctx, shares)?;
    
    Ok(())
}

Private Key Security

NEVER Store Private Keys:

❌ Don't: Store in database
❌ Don't: Store in backend code
❌ Don't: Transmit over network
❌ Don't: Log private keys

✅ Do: User keeps in wallet
✅ Do: Sign in browser
✅ Do: Use wallet adapter
✅ Do: Request signature only

Backend Only Needs:

✅ Transaction signatures (public)
✅ Wallet addresses (public)
✅ Transaction results (public)
❌ Never private keys

Smart Contract Audits

Security Checklist:

✅ Formal verification
✅ Third-party audit
✅ Bug bounty program
✅ Test coverage > 95%
✅ Fuzz testing
✅ Mainnet monitoring
✅ Emergency pause function
✅ Upgrade mechanism

Network Configuration

Mainnet vs Devnet

Mainnet (Production):

RPC: https://api.mainnet-beta.solana.com
Explorer: https://explorer.solana.com
Real SOL required
Production data

Devnet (Development):

RPC: https://api.devnet.solana.com
Explorer: https://explorer.solana.com/?cluster=devnet
Free test SOL
Testing only

Testnet (Beta Testing):

RPC: https://api.testnet.solana.com
For final testing before mainnet

RPC Endpoints

Public RPCs:

Solana Labs:
- https://api.mainnet-beta.solana.com
- Free but rate limited
- Suitable for development

GenesysGo:
- https://ssc-dao.genesysgo.net
- Better performance
- Rate limits

QuickNode:
- https://your-endpoint.solana-mainnet.quiknode.pro
- Paid service
- High performance
- No rate limits

Rate Limits:

Public RPCs:
- 100 requests/10 seconds
- Bursts allowed
- May throttle

Paid RPCs:
- 1000+ requests/second
- Guaranteed uptime
- Premium support

Performance Optimization

Transaction Optimization

Reduce Transaction Size:

// Bad: Multiple transactions
let tx1 = buy_shares(50);
let tx2 = buy_shares(50);
// Cost: 2 × fees

// Good: Single transaction
let tx = buy_shares(100);
// Cost: 1 × fee

Batch Operations:

// Bundle multiple operations
const transaction = new Transaction()
  .add(instruction1)
  .add(instruction2)
  .add(instruction3);

// Single signature, single fee
const signature = await sendTransaction(transaction);

Caching Strategies

Cache Market Data:

from functools import lru_cache
from datetime import timedelta

@lru_cache(maxsize=1000)
def get_market_data(market_id: str):
    # Cache for 30 seconds
    return fetch_from_blockchain(market_id)

WebSocket for Real-Time:

// Subscribe to market updates
const subscription = connection.onAccountChange(
  marketAddress,
  (accountInfo) => {
    updateMarketData(accountInfo);
  }
);

Monitoring & Analytics

Transaction Monitoring

Track Metrics:

metrics = {
    "total_transactions": 0,
    "successful": 0,
    "failed": 0,
    "avg_confirmation_time": 0,
    "total_volume": 0,
    "total_fees_paid": 0,
}

async def track_transaction(signature: str):
    start_time = time.time()
    
    # Wait for confirmation
    result = await connection.confirm_transaction(signature)
    
    confirmation_time = time.time() - start_time
    
    # Update metrics
    metrics["total_transactions"] += 1
    if result.value:
        metrics["successful"] += 1
    else:
        metrics["failed"] += 1
    
    metrics["avg_confirmation_time"] = (
        (metrics["avg_confirmation_time"] * (metrics["total_transactions"] - 1)
        + confirmation_time) / metrics["total_transactions"]
    )

Network Health

Monitor Solana Network:

async def check_network_health():
    # Get cluster performance
    perf = await connection.get_recent_performance_samples(1)
    
    metrics = {
        "tps": perf[0].num_transactions / perf[0].sample_period_secs,
        "slot": perf[0].slot,
        "block_time": perf[0].sample_period_secs,
    }
    
    # Check if healthy
    if metrics["tps"] < 1000:
        alert("Low TPS warning")
    
    if metrics["block_time"] > 1.0:
        alert("Slow blocks warning")

Troubleshooting

Common Issues

Transaction Failed:

Error: "Transaction simulation failed"

Causes:
1. Insufficient balance
2. Invalid instruction
3. Account not found
4. Slippage too low

Solutions:
1. Check SOL balance
2. Verify transaction structure
3. Ensure account exists
4. Increase slippage tolerance

Network Congestion:

Error: "Transaction timeout"

Causes:
1. Network congested
2. Low priority fee
3. RPC overloaded

Solutions:
1. Wait and retry
2. Increase priority fee
3. Use different RPC
4. Implement retry logic

Rate Limiting:

Error: "429 Too Many Requests"

Causes:
1. Exceeded RPC limits
2. Too many requests

Solutions:
1. Implement backoff
2. Use paid RPC
3. Cache data
4. Batch requests

Best Practices

Development

Test on Devnet firstUse TypeScript for type safetyImplement error handlingAdd transaction retriesMonitor transaction statusCache blockchain dataValidate all inputsLog all transactions

Production

Use dedicated RPCImplement monitoringSet up alertingHave backup RPCsRegular security auditsMaintain upgrade pathDocument all contractsVersion control


Related Documentation:

  • Wallet Integration - User wallet setup

  • API Reference - API endpoints

  • Smart Contracts - Contract details

Last updated