viem-goviem-go

Introduction to Public Actions

A brief introduction on what Public Actions are in viem-go

Introduction to Public Actions

A Public Action is an action that maps one-to-one with a "public" Ethereum RPC method (eth_blockNumber, eth_getBalance, etc). They are used with a Public Client.

Public Actions do not require any special permissions nor do they provide signing capabilities to the user. Examples of Public Actions include getting the balance of an account, retrieving the details of a specific transaction, and getting the current block number of the network.

Public Actions provide a simple and secure way to access public data on the Ethereum blockchain. They are widely used by dapps and other applications that need to retrieve information about transactions, accounts, blocks and other data on the network.

Organization

Public Actions in viem-go are organized into logical groups:

Usage Pattern

All Public Actions follow a consistent pattern:

  1. Accept context.Context as the first parameter for cancellation and timeouts
  2. Accept a Client as the second parameter
  3. Accept a Parameters struct containing all options
  4. Return a result value and an error
import (
"context"
"log"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ChefBingbong/viem-go/actions/public"
"github.com/ChefBingbong/viem-go/client"
"github.com/ChefBingbong/viem-go/client/transport"
"github.com/ChefBingbong/viem-go/chain/definitions"
)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
publicClient, err := client.CreatePublicClient(client.PublicClientConfig{
Chain: definitions.Mainnet,
Transport: transport.HTTP("https://eth.llamarpc.com"),
})
if err != nil {
log.Fatal(err)
}
defer func() { _ = publicClient.Close() }()
// Example: Get balance
balance, err := public.GetBalance(ctx, publicClient, public.GetBalanceParameters{
Address: common.HexToAddress("0xA0Cf798816D4b9b9866b5330EEa46a18382f251e"),
})
if err != nil {
log.Fatal(err)
}
log.Printf("Balance: %s", balance.String())

Error Handling

All Public Actions return errors that should be checked. Common error patterns include:

  • Network errors (connection failures, timeouts)
  • RPC errors (invalid parameters, method not supported)
  • Parsing errors (invalid response format)
  • Not found errors (block, transaction, etc. not found)

Always handle errors appropriately in your application.