learn.sol

Getting Started with GetBlock RPC

Complete guide to integrating GetBlock RPC into your Solana apps. Learn to set up endpoints, configure connections, handle rate limits, and monitor performance.

Complete guide to setting up GetBlock RPC for reliable, high-performance Solana network access. GetBlock is a leading Blockchain-as-a-Service platform providing instant API access to 100+ blockchain protocols.

What You'll Learn

By the end of this tutorial, you'll be able to:

  • Set up GetBlock RPC endpoints for mainnet, devnet, and testnet
  • Configure connection parameters for optimal performance
  • Handle rate limiting and authentication
  • Monitor your RPC usage and performance metrics

Prerequisites

  • Node.js 16+ installed
  • Basic understanding of Solana and @solana/web3.js
  • A GetBlock account (sign up at getblock.io)

Why Choose GetBlock?

GetBlock is a leading Blockchain-as-a-Service platform providing instant access to blockchain nodes:

  • Multi-Chain Support: Access to 100+ blockchain protocols including Solana, Ethereum, Bitcoin
  • Highly Reliable: 99.9%+ uptime guarantee serving 100,000+ active users
  • Multiple API Formats: JSON-RPC, REST, WebSocket, and GraphQL support
  • Developer Friendly: Easy integration with comprehensive documentation
  • Scalable: Processes 50+ billion API requests monthly

Step 1: Get Your API Key

  1. Sign up at getblock.io
  2. Navigate to your dashboard
  3. Select Solana from the list of blockchains
  4. Copy your endpoint URLs (they'll look like: https://go.getblock.io/{your-access-token}/)

Pro Tip: Create separate API keys for development and production environments to better track usage and maintain security.


Step 2: Basic Connection Setup

Here's how to connect to Solana using GetBlock:

connection.ts
import { Connection, ConnectionConfig } from "@solana/web3.js";

// Configuration for optimal performance
const config: ConnectionConfig = {
  commitment: "confirmed",
  confirmTransactionInitialTimeout: 60000,
  disableRetryOnRateLimit: false,
  httpHeaders: {
    "Content-Type": "application/json",
  },
};

// Create connection with GetBlock endpoint
const connection = new Connection(
  "https://go.getblock.io/{your-access-token}/",
  config
);

// Test the connection
async function testConnection() {
  try {
    const version = await connection.getVersion();
    const slot = await connection.getSlot();
    
    console.log("✅ Connected to Solana via GetBlock");
    console.log(`Version: ${JSON.stringify(version)}`);
    console.log(`Current Slot: ${slot}`);
  } catch (error) {
    console.error("❌ Connection failed:", error);
  }
}

testConnection();

Step 3: Environment Configuration

Store your API keys securely using environment variables:

.env.local
# GetBlock RPC Endpoints
NEXT_PUBLIC_SOLANA_RPC_MAINNET=https://go.getblock.io/{your-mainnet-token}/
NEXT_PUBLIC_SOLANA_RPC_DEVNET=https://go.getblock.io/{your-devnet-token}/
NEXT_PUBLIC_SOLANA_RPC_TESTNET=https://go.getblock.io/{your-testnet-token}/

Then create a connection helper:

lib/solana/connection.ts
import { Connection, Cluster } from "@solana/web3.js";

type Network = "mainnet-beta" | "devnet" | "testnet";

const RPC_ENDPOINTS: Record<Network, string> = {
  "mainnet-beta": process.env.NEXT_PUBLIC_SOLANA_RPC_MAINNET!,
  "devnet": process.env.NEXT_PUBLIC_SOLANA_RPC_DEVNET!,
  "testnet": process.env.NEXT_PUBLIC_SOLANA_RPC_TESTNET!,
};

export function createConnection(network: Network = "mainnet-beta") {
  const endpoint = RPC_ENDPOINTS[network];
  
  if (!endpoint) {
    throw new Error(`No RPC endpoint configured for ${network}`);
  }

  return new Connection(endpoint, {
    commitment: "confirmed",
    confirmTransactionInitialTimeout: 60000,
  });
}

// Usage
const mainnetConnection = createConnection("mainnet-beta");
const devnetConnection = createConnection("devnet");

Step 4: Performance Optimization

Configure your connection for maximum performance:

optimized-connection.ts
import { Connection } from "@solana/web3.js";

const connection = new Connection(
  process.env.NEXT_PUBLIC_SOLANA_RPC_MAINNET!,
  {
    // Use "confirmed" for speed, "finalized" for absolute certainty
    commitment: "confirmed",
    
    // Increase timeout for complex transactions
    confirmTransactionInitialTimeout: 60000,
    
    // Disable retry on rate limit if you have rate limit alerts
    disableRetryOnRateLimit: false,
    
    // Add custom headers if needed
    httpHeaders: {
      "Content-Type": "application/json",
    },
    
    // WebSocket endpoint (optional, for subscriptions)
    wsEndpoint: "wss://go.getblock.io/{your-access-token}/",
  }
);

Commitment Levels Explained

  • processed: Fastest, but transactions can still be rolled back
  • confirmed: Good balance of speed and reliability (recommended)
  • finalized: Slowest, but guaranteed to not be rolled back

Step 5: Error Handling and Retries

Implement robust error handling:

error-handling.ts
import { Connection } from "@solana/web3.js";

class RobustConnection {
  private connection: Connection;
  private maxRetries = 3;
  
  constructor(endpoint: string) {
    this.connection = new Connection(endpoint, "confirmed");
  }
  
  async executeWithRetry<T>(
    operation: () => Promise<T>,
    retries = this.maxRetries
  ): Promise<T> {
    try {
      return await operation();
    } catch (error) {
      if (retries > 0) {
        console.log(`Retrying... (${this.maxRetries - retries + 1}/${this.maxRetries})`);
        await new Promise(resolve => setTimeout(resolve, 1000));
        return this.executeWithRetry(operation, retries - 1);
      }
      throw error;
    }
  }
  
  async getAccountInfo(publicKey: string) {
    return this.executeWithRetry(async () => {
      const account = await this.connection.getAccountInfo(
        new PublicKey(publicKey)
      );
      return account;
    });
  }
}

// Usage
const robustConnection = new RobustConnection(
  process.env.NEXT_PUBLIC_SOLANA_RPC_MAINNET!
);

Step 6: Monitoring and Analytics

Track your RPC usage:

monitoring.ts
import { Connection } from "@solana/web3.js";

class MonitoredConnection extends Connection {
  private requestCount = 0;
  private errorCount = 0;
  
  override async _rpcRequest(method: string, args: any[]) {
    this.requestCount++;
    const startTime = Date.now();
    
    try {
      const result = await super._rpcRequest(method, args);
      const duration = Date.now() - startTime;
      
      console.log(`[RPC] ${method} completed in ${duration}ms`);
      return result;
    } catch (error) {
      this.errorCount++;
      console.error(`[RPC] ${method} failed:`, error);
      throw error;
    }
  }
  
  getStats() {
    return {
      totalRequests: this.requestCount,
      totalErrors: this.errorCount,
      errorRate: (this.errorCount / this.requestCount) * 100,
    };
  }
}

Common Issues and Solutions

Rate Limiting
GetBlock offers flexible pricing tiers with different rate limits. The free plan includes 50K CU monthly. For high-volume applications, upgrade to higher tiers or contact GetBlock support for enterprise solutions.

Connection Timeouts
If you experience timeouts, increase confirmTransactionInitialTimeout or check your network connectivity. GetBlock's infrastructure is optimized for reliable, high-performance access.

Stale Data
Using processed commitment can return data that gets rolled back. For production applications handling transactions, use confirmed or finalized.


Next Steps

Now that you've integrated GetBlock RPC, explore:

  • Advanced Configuration: Learn about WebSocket subscriptions and event listeners
  • Load Balancing: Set up multiple endpoints for high availability
  • Performance Tuning: Optimize for your specific use case (DeFi, NFTs, gaming)

Check out the Advanced GetBlock Features tutorial to level up your infrastructure.


Summary

You've successfully integrated GetBlock's premium RPC infrastructure! Key takeaways:

✅ Configured GetBlock RPC endpoints for all networks
✅ Implemented environment-based configuration
✅ Added performance optimizations and error handling
✅ Set up monitoring and analytics

Your application is now running on reliable Blockchain-as-a-Service infrastructure trusted by 100,000+ developers with 99.9%+ uptime.

Solana Assistant

AI-powered documentation helper

Welcome to Solana Assistant

Ask specific questions about Solana development:

Ask specific questions for better results400px
    Getting Started with GetBlock RPC | learn.sol