/
block.go
91 lines (77 loc) · 2.53 KB
/
block.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package eth
import (
"encoding/json"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/lmittmann/w3/internal/module"
"github.com/lmittmann/w3/w3types"
)
// BlockByHash requests the block with the given hash with full transactions.
func BlockByHash(hash common.Hash) w3types.CallerFactory[types.Block] {
return module.NewFactory(
"eth_getBlockByHash",
[]any{hash, true},
module.WithRetWrapper(blockRetWrapper),
)
}
// BlockByNumber requests the block with the given number with full
// transactions. If number is nil, the latest block is requested.
func BlockByNumber(number *big.Int) w3types.CallerFactory[types.Block] {
return module.NewFactory(
"eth_getBlockByNumber",
[]any{module.BlockNumberArg(number), true},
module.WithRetWrapper(blockRetWrapper),
)
}
// BlockTxCountByHash requests the number of transactions in the block with the
// given hash.
func BlockTxCountByHash(hash common.Hash) w3types.CallerFactory[uint] {
return module.NewFactory(
"eth_getBlockTransactionCountByHash",
[]any{hash},
module.WithRetWrapper(module.HexUintRetWrapper),
)
}
// BlockTxCountByNumber requests the number of transactions in the block with
// the given number.
func BlockTxCountByNumber(number *big.Int) w3types.CallerFactory[uint] {
return module.NewFactory(
"eth_getBlockTransactionCountByNumber",
[]any{module.BlockNumberArg(number)},
module.WithRetWrapper(module.HexUintRetWrapper),
)
}
// HeaderByHash requests the header with the given hash.
func HeaderByHash(hash common.Hash) w3types.CallerFactory[types.Header] {
return module.NewFactory[types.Header](
"eth_getBlockByHash",
[]any{hash, false},
)
}
// HeaderByNumber requests the header with the given number. If number is nil,
// the latest header is requested.
func HeaderByNumber(number *big.Int) w3types.CallerFactory[types.Header] {
return module.NewFactory[types.Header](
"eth_getBlockByNumber",
[]any{module.BlockNumberArg(number), false},
)
}
var blockRetWrapper = func(ret *types.Block) any { return (*rpcBlock)(ret) }
type rpcBlock types.Block
func (b *rpcBlock) UnmarshalJSON(data []byte) error {
type rpcBlockTxs struct {
Transactions []*types.Transaction `json:"transactions"`
}
var header types.Header
if err := json.Unmarshal(data, &header); err != nil {
return err
}
var blockTxs rpcBlockTxs
if err := json.Unmarshal(data, &blockTxs); err != nil {
return err
}
block := types.NewBlockWithHeader(&header).WithBody(blockTxs.Transactions, nil)
*b = (rpcBlock)(*block)
return nil
}