Skip to content

Commit

Permalink
Allow fetching of blocks by keyword (latest,safe etc.)
Browse files Browse the repository at this point in the history
  • Loading branch information
mcdee committed Mar 28, 2023
1 parent 18cf3fb commit becaa41
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 10 deletions.
34 changes: 24 additions & 10 deletions jsonrpc/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,27 @@ import (
"strings"

"github.com/attestantio/go-execution-client/spec"
"github.com/attestantio/go-execution-client/util"
"github.com/pkg/errors"
)

var blockIdentifiers = map[string]struct{}{
"earliest": {},
"latest": {},
"pending": {},
"safe": {},
"finalized": {},
}

// Block returns the block given an ID
func (s *Service) Block(ctx context.Context, blockID string) (*spec.Block, error) {
if blockID == "" || blockID == "latest" {
if blockID == "" ||
blockID == "latest" {
return s.blockAtHeight(ctx, -1)
}
if _, isIdentifier := blockIdentifiers[blockID]; isIdentifier {
return s.blockAtIdentifier(ctx, blockID)
}
if strings.HasPrefix(blockID, "0x") {
return s.blockAtHash(ctx, blockID)
}
Expand All @@ -48,18 +61,19 @@ func (s *Service) blockAtHash(ctx context.Context, hash string) (*spec.Block, er
return &block, nil
}

func (s *Service) blockAtHeight(ctx context.Context, height int64) (*spec.Block, error) {
func (s *Service) blockAtIdentifier(ctx context.Context, id string) (*spec.Block, error) {
var block spec.Block

if height == -1 {
if err := s.client.CallFor(&block, "eth_getBlockByNumber", "latest", true); err != nil {
return nil, errors.Wrap(err, "eth_getBlockByNumber for latest failed")
}
} else {
if err := s.client.CallFor(&block, "eth_getBlockByNumber", fmt.Sprintf("0x%x", height), true); err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("eth_getBlockByNumber for 0x%x failed", height))
}
if err := s.client.CallFor(&block, "eth_getBlockByNumber", id, true); err != nil {
return nil, errors.Wrapf(err, "eth_getBlockByNumber for %s failed", id)
}

return &block, nil
}

func (s *Service) blockAtHeight(ctx context.Context, height int64) (*spec.Block, error) {
if height == -1 {
return s.blockAtIdentifier(ctx, "latest")
}
return s.blockAtIdentifier(ctx, util.MarshalInt64(height))
}
8 changes: 8 additions & 0 deletions util/jsonhelpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ func PreUnmarshalHexString(input string) string {
return res
}

// MarshalInt64 marshals an int64 as per the Ethereum standard.
func MarshalInt64(input int64) string {
if input == 0 {
return "0x0"
}
return fmt.Sprintf("0x%s", strings.TrimPrefix(fmt.Sprintf("%x", input), "0"))
}

// MarshalUint64 marshals a uint64 as per the Ethereum standard.
func MarshalUint64(input uint64) string {
if input == 0 {
Expand Down

0 comments on commit becaa41

Please sign in to comment.