Skip to content

Commit

Permalink
Return notFound error if response is null
Browse files Browse the repository at this point in the history
  • Loading branch information
chenzhijie committed Jan 7, 2022
1 parent 2c3e114 commit 439840a
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
5 changes: 4 additions & 1 deletion eth/block.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package eth

import (
"bytes"
"encoding/json"
"errors"
"fmt"
Expand All @@ -23,6 +24,8 @@ func (e *Eth) getBlock(method string, args ...interface{}) (*types.Block, error)
return nil, err
} else if len(raw) == 0 {
return nil, ethereum.NotFound
} else if bytes.Equal([]byte(raw), []byte("null")) {
return nil, ethereum.NotFound
}

// Decode header and transactions.
Expand All @@ -35,7 +38,7 @@ func (e *Eth) getBlock(method string, args ...interface{}) (*types.Block, error)
return nil, err
}
if head == nil {
return nil, errors.New("nil header")
return nil, errors.New("json.Unmarshal header failed")
}
if head.UncleHash == types.EmptyUncleHash && len(body.UncleHashes) > 0 {
return nil, fmt.Errorf("server returned non-empty uncle list but block header indicates no uncles")
Expand Down
49 changes: 49 additions & 0 deletions eth/block_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package eth

import (
"fmt"
"math/big"
"testing"
"time"

"github.com/chenzhijie/go-web3/rpc"
)

func TestGetBlockByNumber(t *testing.T) {
c, err := rpc.NewClient("https://rpc.flashbots.net", "http://127.0.0.1:7890")
if err != nil {
t.Fatal(err)
}
eth := NewEth(c)
blockNumber, err := eth.GetBlockNumber()
if err != nil {
t.Fatal(err)
}
block, err := eth.GetBlocByNumber(big.NewInt(int64(blockNumber)), true)
if err != nil {
t.Fatal(err)
}
fmt.Printf("block hash %s has %v txs\n", block.Hash(), len(block.Transactions()))
}

func TestPollBlock(t *testing.T) {
c, err := rpc.NewClient("https://rpc.flashbots.net", "http://127.0.0.1:7890")
if err != nil {
t.Fatal(err)
}
eth := NewEth(c)
for {
blockNumber, err := eth.GetBlockNumber()
if err != nil {
t.Fatal(err)
}
fmt.Printf("get block %v\n", blockNumber)
block, err := eth.GetBlocByNumber(big.NewInt(int64(blockNumber)), true)
if err != nil {
t.Fatal(err)
}
fmt.Printf("block hash %s has %v txs\n", block.Hash(), len(block.Transactions()))
time.Sleep(time.Duration(5) * time.Second)
}

}

0 comments on commit 439840a

Please sign in to comment.