Skip to content

Commit e98114d

Browse files
zhiqiangxukaralabe
andauthored
ethclient: add CallContractAtHash (ethereum#24355)
* add CallContractAtHash to ethclient * add docstring and test * optimize test * ethclient: nits Co-authored-by: Péter Szilágyi <[email protected]>
1 parent f01e2fa commit e98114d

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

Diff for: ethclient/ethclient.go

+11
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,17 @@ func (ec *Client) CallContract(ctx context.Context, msg ethereum.CallMsg, blockN
456456
return hex, nil
457457
}
458458

459+
// CallContractAtHash is almost the same as CallContract except that it selects
460+
// the block by block hash instead of block height.
461+
func (ec *Client) CallContractAtHash(ctx context.Context, msg ethereum.CallMsg, blockHash common.Hash) ([]byte, error) {
462+
var hex hexutil.Bytes
463+
err := ec.c.CallContext(ctx, &hex, "eth_call", toCallArg(msg), rpc.BlockNumberOrHashWithHash(blockHash, false))
464+
if err != nil {
465+
return nil, err
466+
}
467+
return hex, nil
468+
}
469+
459470
// PendingCallContract executes a message call transaction using the EVM.
460471
// The state seen by the contract call is the pending state.
461472
func (ec *Client) PendingCallContract(ctx context.Context, msg ethereum.CallMsg) ([]byte, error) {

Diff for: ethclient/ethclient_test.go

+30
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,9 @@ func TestEthClient(t *testing.T) {
285285
"CallContract": {
286286
func(t *testing.T) { testCallContract(t, client) },
287287
},
288+
"CallContractAtHash": {
289+
func(t *testing.T) { testCallContractAtHash(t, client) },
290+
},
288291
"AtFunctions": {
289292
func(t *testing.T) { testAtFunctions(t, client) },
290293
},
@@ -507,6 +510,33 @@ func testStatusFunctions(t *testing.T, client *rpc.Client) {
507510
}
508511
}
509512

513+
func testCallContractAtHash(t *testing.T, client *rpc.Client) {
514+
ec := NewClient(client)
515+
516+
// EstimateGas
517+
msg := ethereum.CallMsg{
518+
From: testAddr,
519+
To: &common.Address{},
520+
Gas: 21000,
521+
Value: big.NewInt(1),
522+
}
523+
gas, err := ec.EstimateGas(context.Background(), msg)
524+
if err != nil {
525+
t.Fatalf("unexpected error: %v", err)
526+
}
527+
if gas != 21000 {
528+
t.Fatalf("unexpected gas price: %v", gas)
529+
}
530+
block, err := ec.HeaderByNumber(context.Background(), big.NewInt(1))
531+
if err != nil {
532+
t.Fatalf("BlockByNumber error: %v", err)
533+
}
534+
// CallContract
535+
if _, err := ec.CallContractAtHash(context.Background(), msg, block.Hash()); err != nil {
536+
t.Fatalf("unexpected error: %v", err)
537+
}
538+
}
539+
510540
func testCallContract(t *testing.T, client *rpc.Client) {
511541
ec := NewClient(client)
512542

0 commit comments

Comments
 (0)