/
ethfilter.go
59 lines (47 loc) · 1.23 KB
/
ethfilter.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
package ethfilter
import (
"context"
"errors"
"math/big"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
)
type factory struct {
p BlockNumberProvider
addresses []common.Address
topics [][]common.Hash
margin int64
}
type BlockNumberProvider func(context.Context) (*big.Int, error)
func Factory() *factory { return &factory{} }
func (f *factory) WithFromBlockNumberProvider(provider BlockNumberProvider) *factory {
f.p = provider
return f
}
func (f *factory) WithFromBlockNumberSafetyMargin(margin int64) *factory {
f.margin = margin
return f
}
func (f *factory) WithAddresses(addresses ...common.Address) *factory {
f.addresses = addresses
return f
}
func (f *factory) WithTopics(topics ...[]common.Hash) *factory {
f.topics = topics
return f
}
func (f *factory) Filter(context.Context) (ethereum.FilterQuery, error) {
if f.p == nil {
return ethereum.FilterQuery{}, errors.New("missing from block number provider")
}
b, err := f.p(context.Background())
if err != nil {
return ethereum.FilterQuery{}, err
}
fromBlock := big.NewInt(0).Sub(b, big.NewInt(f.margin))
return ethereum.FilterQuery{
Addresses: f.addresses,
Topics: f.topics,
FromBlock: fromBlock,
}, nil
}