Skip to content

ChainID

Returns the chain ID for transaction replay protection. The chain ID is used to ensure that transactions signed for one network cannot be replayed on another network. Common chain IDs include SN_MAIN for Starknet Mainnet and SN_SEPOLIA for Starknet Sepolia testnet. This method caches the result after the first call for improved performance.

Method Signature

func (provider *Provider) ChainID(ctx context.Context) (string, error)

Source: chain.go

Parameters

  • ctx (context.Context): Context for request cancellation and timeout

Returns

  • string: The chain ID (e.g., "SN_MAIN" for mainnet, "SN_SEPOLIA" for testnet)
  • error: Error if the request fails

Usage Example

package main
 
import (
    "context"
    "fmt"
    "log"
    "os"
 
    "github.com/NethermindEth/starknet.go/rpc"
    "github.com/joho/godotenv"
)
 
func main() {
    // Load environment variables from .env file
    err := godotenv.Load()
    if err != nil {
        log.Fatal("Error loading .env file")
    }
 
    // Get RPC URL from environment variable
    rpcURL := os.Getenv("STARKNET_RPC_URL")
    if rpcURL == "" {
        log.Fatal("STARKNET_RPC_URL not found in .env file")
    }
 
    // Initialize provider
    provider, err := rpc.NewProvider(context.Background(), rpcURL)
    if err != nil {
        log.Fatal(err)
    }
 
    ctx := context.Background()
 
    // Get chain ID
    chainID, err := provider.ChainID(ctx)
    if err != nil {
        log.Fatal(err)
    }
 
    fmt.Printf("Chain ID: %s\n", chainID)
}

Error Handling

chainID, err := provider.ChainID(ctx)
if err != nil {
    log.Printf("Failed to get chain ID: %v", err)
    return
}
 
fmt.Printf("Connected to network: %s\n", chainID)

Common Use Cases

  • Verifying you're signing transactions for the correct network.
  • Confirming your application is connected to the expected network (mainnet vs testnet).
  • Determinin which network the provider is connected to for multi-network applications.