github.com/status-im/status-go@v1.1.0/services/rpcfilters/latest_block_provider.go (about)

     1  package rpcfilters
     2  
     3  import (
     4  	"errors"
     5  	"math/big"
     6  
     7  	"github.com/ethereum/go-ethereum/common"
     8  	"github.com/ethereum/go-ethereum/common/hexutil"
     9  
    10  	"github.com/status-im/status-go/rpc"
    11  )
    12  
    13  type rpcProvider interface {
    14  	RPCClient() *rpc.Client
    15  }
    16  
    17  // blockInfo contains the hash and the number of the latest block
    18  type blockInfo struct {
    19  	Hash        common.Hash   `json:"hash"`
    20  	NumberBytes hexutil.Bytes `json:"number"`
    21  }
    22  
    23  // Number returns a big.Int representation of the encoded block number.
    24  func (i blockInfo) Number() *big.Int {
    25  	number := big.NewInt(0)
    26  	number.SetBytes(i.NumberBytes)
    27  	return number
    28  }
    29  
    30  // latestBlockProvider provides the latest block info from the blockchain
    31  type latestBlockProvider interface {
    32  	GetLatestBlock() (blockInfo, error)
    33  }
    34  
    35  // latestBlockProviderRPC is an implementation of latestBlockProvider interface
    36  // that requests a block using an RPC client provided
    37  type latestBlockProviderRPC struct {
    38  	rpc rpcProvider
    39  }
    40  
    41  // GetLatestBlock returns the block info
    42  func (p *latestBlockProviderRPC) GetLatestBlock() (blockInfo, error) {
    43  	rpcClient := p.rpc.RPCClient()
    44  
    45  	if rpcClient == nil {
    46  		return blockInfo{}, errors.New("no active RPC client: is the node running?")
    47  	}
    48  
    49  	var result blockInfo
    50  
    51  	err := rpcClient.Call(&result, rpcClient.UpstreamChainID, "eth_getBlockByNumber", "latest", false)
    52  
    53  	if err != nil {
    54  		return blockInfo{}, err
    55  	}
    56  
    57  	return result, nil
    58  }