Skip to content

Commit 2b54666

Browse files
fjlkaralabe
authored andcommitted
ethclient, internal/ethapi: add support for EIP-695 (eth_chainId) (#19694)
EIP-695 was written in 2017. Parity and Infura have support for this method and we should, too.
1 parent c420dcb commit 2b54666

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

ethclient/ethclient.go

+10
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,16 @@ func (ec *Client) Close() {
6161

6262
// Blockchain Access
6363

64+
// ChainId retrieves the current chain ID for transaction replay protection.
65+
func (ec *Client) ChainID(ctx context.Context) (*big.Int, error) {
66+
var result hexutil.Big
67+
err := ec.c.CallContext(ctx, &result, "eth_chainId")
68+
if err != nil {
69+
return nil, err
70+
}
71+
return (*big.Int)(&result), err
72+
}
73+
6474
// BlockByHash returns the given full block.
6575
//
6676
// Note that loading full blocks requires two requests. Use HeaderByHash

ethclient/ethclient_test.go

+16
Original file line numberDiff line numberDiff line change
@@ -319,3 +319,19 @@ func TestTransactionInBlockInterrupted(t *testing.T) {
319319
t.Fatal("error should not be nil")
320320
}
321321
}
322+
323+
func TestChainID(t *testing.T) {
324+
backend, _ := newTestBackend(t)
325+
client, _ := backend.Attach()
326+
defer backend.Stop()
327+
defer client.Close()
328+
ec := NewClient(client)
329+
330+
id, err := ec.ChainID(context.Background())
331+
if err != nil {
332+
t.Fatalf("unexpected error: %v", err)
333+
}
334+
if id == nil || id.Cmp(params.AllEthashProtocolChanges.ChainID) != 0 {
335+
t.Fatalf("ChainID returned wrong number: %+v", id)
336+
}
337+
}

internal/ethapi/api.go

+5
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,11 @@ func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
529529
return &PublicBlockChainAPI{b}
530530
}
531531

532+
// ChainId returns the chainID value for transaction replay protection.
533+
func (s *PublicBlockChainAPI) ChainId() *hexutil.Big {
534+
return (*hexutil.Big)(s.b.ChainConfig().ChainID)
535+
}
536+
532537
// BlockNumber returns the block number of the chain head.
533538
func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
534539
header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available

0 commit comments

Comments
 (0)