Skip to content

BlockHashAndNumber

Gets both the hash and number of the most recently accepted block on Starknet in a single RPC call. This method is more efficient than calling BlockNumber and BlockHash separately when you need both values.

Method Signature

func (provider *Provider) BlockHashAndNumber(
    ctx context.Context,
) (*BlockHashAndNumberOutput, error)

Source: block.go

Parameters

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

Returns

  • *BlockHashAndNumberOutput: Contains both the block hash and number
  • error: Error if the request fails

Type Definitions

BlockHashAndNumberOutput

type BlockHashAndNumberOutput struct {
    Number uint64     `json:"block_number,omitempty"`
    Hash   *felt.Felt `json:"block_hash,omitempty"`
}

BlockHashAndNumberOutput is a struct that is returned by BlockHashAndNumber.

Source: types_block.go

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)
    }
 
    // Get latest block hash and number
    result, err := provider.BlockHashAndNumber(context.Background())
    if err != nil {
        log.Fatal(err)
    }
 
    fmt.Printf("Block Hash: %s\n", result.Hash)
    fmt.Printf("Block Number: %d\n", result.Number)
}

Error Handling

result, err := provider.BlockHashAndNumber(ctx)
if err != nil {
    switch {
    case errors.Is(err, rpc.ErrNoBlocks):
        log.Printf("Chain has no blocks yet")
    default:
        log.Printf("Failed to get block info: %v", err)
    }
    return
}
 
// Check if values are present
if result.Hash == nil {
    log.Printf("Block hash is nil")
    return
}
 
fmt.Printf("Block: %d, Hash: %s\n", result.Number, result.Hash.String())

Common Use Cases

  • Geting both hash and number in one call when you need both values. See example.
  • Verifying you have the correct block by checking both its number and hash. See example.
  • Tracking the latest block efficiently when syncing application state with the blockchain.
  • Confirming transactions have been included in a specific block by checking both block number and hash.