Skip to content

Connection Examples

This guide provides examples of how to connect to SpeedyNodes RPC endpoints using various programming languages and libraries.

JavaScript / TypeScript

Web3.js

Web3.js is a popular JavaScript library for interacting with Ethereum nodes.

const Web3 = require('web3');

// Connect to Ethereum
const web3 = new Web3('https://api.speedynodes.net/http/eth-http?apikey=YOUR_API_KEY');

// Check connection
web3.eth.net.isListening()
  .then(() => console.log('Connected to the Ethereum network'))
  .catch(e => console.log('Failed to connect to the Ethereum network:', e));

// Get latest block number
web3.eth.getBlockNumber()
  .then(blockNumber => console.log('Current block number:', blockNumber))
  .catch(e => console.log('Error getting block number:', e));

// Get account balance
web3.eth.getBalance('0x742d35Cc6634C0532925a3b844Bc454e4438f44e')
  .then(balance => console.log('Account balance:', web3.utils.fromWei(balance, 'ether'), 'ETH'))
  .catch(e => console.log('Error getting balance:', e));

// WebSocket connection
const webSocketWeb3 = new Web3('wss://api.speedynodes.net/ws/eth-ws?apikey=YOUR_API_KEY');

// Subscribe to new blocks
const subscription = webSocketWeb3.eth.subscribe('newBlockHeaders', (error, blockHeader) => {
  if (error) {
    console.error('Error in subscription:', error);
    return;
  }
  console.log('New block:', blockHeader.number);
});

// Unsubscribe after 5 minutes
setTimeout(() => {
  subscription.unsubscribe((error, success) => {
    if (success) {
      console.log('Successfully unsubscribed');
    }
  });
}, 5 * 60 * 1000);

Ethers.js

Ethers.js provides a more compact library for Ethereum interaction.

const { ethers } = require('ethers');

// Connect to Ethereum
const provider = new ethers.providers.JsonRpcProvider('https://api.speedynodes.net/http/eth-http?apikey=YOUR_API_KEY');

// Check connection
provider.getNetwork()
  .then(network => console.log('Connected to network:', network.name))
  .catch(e => console.log('Failed to connect to the network:', e));

// Get latest block number
provider.getBlockNumber()
  .then(blockNumber => console.log('Current block number:', blockNumber))
  .catch(e => console.log('Error getting block number:', e));

// Get account balance
provider.getBalance('0x742d35Cc6634C0532925a3b844Bc454e4438f44e')
  .then(balance => console.log('Account balance:', ethers.utils.formatEther(balance), 'ETH'))
  .catch(e => console.log('Error getting balance:', e));

// WebSocket connection
const wsProvider = new ethers.providers.WebSocketProvider('wss://api.speedynodes.net/ws/eth-ws?apikey=YOUR_API_KEY');

// Subscribe to new blocks
wsProvider.on('block', (blockNumber) => {
  console.log('New block:', blockNumber);
});

// Disconnect after 5 minutes
setTimeout(() => {
  wsProvider.removeAllListeners();
  wsProvider.disconnect();
}, 5 * 60 * 1000);

Python

Web3.py

Web3.py is the Python library for interacting with Ethereum.

from web3 import Web3

# Connect to Ethereum
w3 = Web3(Web3.HTTPProvider('https://api.speedynodes.net/http/eth-http?apikey=YOUR_API_KEY'))

# Check connection
if w3.is_connected():
    print('Connected to the Ethereum network')
else:
    print('Failed to connect to the Ethereum network')

# Get latest block number
block_number = w3.eth.block_number
print(f'Current block number: {block_number}')

# Get account balance
balance = w3.eth.get_balance('0x742d35Cc6634C0532925a3b844Bc454e4438f44e')
print(f'Account balance: {w3.from_wei(balance, "ether")} ETH')

# WebSocket connection
ws_w3 = Web3(Web3.WebsocketProvider('wss://api.speedynodes.net/ws/eth-ws?apikey=YOUR_API_KEY'))

# Subscribe to new blocks (requires web3>=5.17.0 with WebSocket subscription support)
def handle_event(event):
    print(event)

event_filter = ws_w3.eth.filter('latest')
for event in event_filter.get_new_entries():
    handle_event(event)

Java

Web3j

Web3j is the Java library for Ethereum.

import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;
import org.web3j.protocol.core.methods.response.EthBlockNumber;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.utils.Convert;
import java.math.BigDecimal;
import java.math.BigInteger;

public class SpeedyNodesExample {
    public static void main(String[] args) {
        // Connect to Ethereum
        Web3j web3 = Web3j.build(new HttpService("https://api.speedynodes.net/http/eth-http?apikey=YOUR_API_KEY"));

        try {
            // Check connection
            web3.ethBlockNumber().send();
            System.out.println("Connected to the Ethereum network");

            // Get latest block number
            EthBlockNumber blockNumber = web3.ethBlockNumber().send();
            System.out.println("Current block number: " + blockNumber.getBlockNumber());

            // Get account balance
            EthGetBalance balance = web3.ethGetBalance("0x742d35Cc6634C0532925a3b844Bc454e4438f44e", 
                                                       DefaultBlockParameterName.LATEST).send();
            BigDecimal ethBalance = Convert.fromWei(new BigDecimal(balance.getBalance()), Convert.Unit.ETHER);
            System.out.println("Account balance: " + ethBalance + " ETH");

        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Go

Go-Ethereum

Go-Ethereum provides Go bindings for Ethereum.

package main

import (
    "context"
    "fmt"
    "log"
    "math"
    "math/big"

    "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
    // Connect to Ethereum
    client, err := ethclient.Dial("https://api.speedynodes.net/http/eth-http?apikey=YOUR_API_KEY")
    if err != nil {
        log.Fatal(err)
    }

    // Check connection
    _, err = client.BlockNumber(context.Background())
    if err != nil {
        log.Fatal("Failed to connect to the Ethereum network:", err)
    }
    fmt.Println("Connected to the Ethereum network")

    // Get latest block number
    blockNumber, err := client.BlockNumber(context.Background())
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Current block number: %d\n", blockNumber)

    // Get account balance
    account := common.HexToAddress("0x742d35Cc6634C0532925a3b844Bc454e4438f44e")
    balance, err := client.BalanceAt(context.Background(), account, nil)
    if err != nil {
        log.Fatal(err)
    }

    // Convert wei to ether
    fbalance := new(big.Float)
    fbalance.SetString(balance.String())
    ethValue := new(big.Float).Quo(fbalance, big.NewFloat(math.Pow10(18)))
    fmt.Printf("Account balance: %f ETH\n", ethValue)
}

PHP

Web3.php

Web3.php is a PHP implementation for Ethereum interaction.

<?php
require 'vendor/autoload.php';

use Web3\Web3;
use Web3\Providers\HttpProvider;
use Web3\RequestManagers\HttpRequestManager;

// Connect to Ethereum
$web3 = new Web3(new HttpProvider(new HttpRequestManager('https://api.speedynodes.net/http/eth-http?apikey=YOUR_API_KEY')));

// Get latest block number
$web3->eth->blockNumber(function ($err, $blockNumber) {
    if ($err !== null) {
        echo 'Error: ' . $err->getMessage();
        return;
    }
    echo 'Current block number: ' . hexdec($blockNumber) . PHP_EOL;
});

// Get account balance
$web3->eth->getBalance('0x742d35Cc6634C0532925a3b844Bc454e4438f44e', function ($err, $balance) {
    if ($err !== null) {
        echo 'Error: ' . $err->getMessage();
        return;
    }
    // Convert wei to ether
    $ethBalance = $balance / 1000000000000000000;
    echo 'Account balance: ' . $ethBalance . ' ETH' . PHP_EOL;
});
?>

Command Line

Curl

You can use curl to directly interact with the JSON-RPC API:

# Get the latest block number
curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' https://api.speedynodes.net/http/eth-http?apikey=YOUR_API_KEY

# Get account balance
curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x742d35Cc6634C0532925a3b844Bc454e4438f44e", "latest"],"id":1}' https://api.speedynodes.net/http/eth-http?apikey=YOUR_API_KEY

# Get transaction by hash
curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getTransactionByHash","params":["0xb2fea9c4b24775af6990237aa90228e5e092c56bdaee7c3e80f31fe42bc8b4c8"],"id":1}' https://api.speedynodes.net/http/eth-http?apikey=YOUR_API_KEY

Wallet Connection

MetaMask

To add SpeedyNodes RPC to MetaMask:

  1. Open MetaMask
  2. Click the network dropdown at the top
  3. Click "Add Network"
  4. Fill in the following details:
  5. Network Name: (e.g., "Ethereum via SpeedyNodes")
  6. RPC URL: https://api.speedynodes.net/http/eth-http?apikey=YOUR_API_KEY
  7. Chain ID: (e.g., 1 for Ethereum Mainnet)
  8. Currency Symbol: (e.g., ETH)
  9. Block Explorer URL: (optional, e.g., https://etherscan.io)
  10. Click "Save"

Hardhat

For Hardhat development environment, add to your hardhat.config.js:

module.exports = {
  networks: {
    mainnet: {
      url: "https://api.speedynodes.net/http/eth-http?apikey=YOUR_API_KEY",
      accounts: [process.env.PRIVATE_KEY]
    },
    bsc: {
      url: "https://api.speedynodes.net/http/bsc-http?apikey=YOUR_API_KEY",
      accounts: [process.env.PRIVATE_KEY],
      chainId: 56
    },
    polygon: {
      url: "https://api.speedynodes.net/http/polygon-http?apikey=YOUR_API_KEY",
      accounts: [process.env.PRIVATE_KEY],
      chainId: 137
    }
  }
};

Truffle

For Truffle development framework, add to your truffle-config.js:

const HDWalletProvider = require('@truffle/hdwallet-provider');
const privateKey = process.env.PRIVATE_KEY;

module.exports = {
  networks: {
    mainnet: {
      provider: () => new HDWalletProvider(privateKey, "https://api.speedynodes.net/http/eth-http?apikey=YOUR_API_KEY"),
      network_id: 1,
      gas: 5500000,
      confirmations: 2,
      timeoutBlocks: 200,
      skipDryRun: true
    },
    bsc: {
      provider: () => new HDWalletProvider(privateKey, "https://api.speedynodes.net/http/bsc-http?apikey=YOUR_API_KEY"),
      network_id: 56,
      gas: 5500000,
      confirmations: 10,
      timeoutBlocks: 200,
      skipDryRun: true
    },
    polygon: {
      provider: () => new HDWalletProvider(privateKey, "https://api.speedynodes.net/http/polygon-http?apikey=YOUR_API_KEY"),
      network_id: 137,
      gas: 5500000,
      confirmations: 2,
      timeoutBlocks: 200,
      skipDryRun: true
    }
  }
};