/
event_job.go
77 lines (66 loc) · 1.95 KB
/
event_job.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
package jobs
import (
"context"
"github.com/berachain/offchain-sdk/job"
sdk "github.com/berachain/offchain-sdk/types"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
coretypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
)
// Compile time check to ensure that EthEventSub implements job.EthSubscribable, and optionally the
// basic job's Setup and Teardown methods.
var (
_ job.EthSubscribable = (*EthEventSub)(nil)
_ job.HasSetup = (*EthEventSub)(nil)
_ job.HasTeardown = (*EthEventSub)(nil)
)
// EthEventSub allows you to subscribe a basic job to an ethereum event.
type EthEventSub struct {
job.Basic
contractAddress common.Address
event string
sub ethereum.Subscription
}
// NewEthSub creates a new EthEventSub.
func NewEthSub(job job.Basic, contractAddr string, event string) *EthEventSub {
return &EthEventSub{
Basic: job,
contractAddress: common.HexToAddress(contractAddr),
event: event,
}
}
// Subscribe subscribes to an ethereum event.
func (j *EthEventSub) Subscribe(
ctx context.Context,
) (ethereum.Subscription, chan coretypes.Log, error) {
sCtx := sdk.UnwrapContext(ctx)
ch := make(chan coretypes.Log)
sub, err := sCtx.Chain().SubscribeFilterLogs(ctx, ethereum.FilterQuery{
Addresses: []common.Address{j.contractAddress},
Topics: [][]common.Hash{{crypto.Keccak256Hash([]byte(j.event))}},
}, ch)
if err != nil {
return nil, nil, err
}
j.sub = sub
return sub, ch, nil
}
// Unsubscribe unsubscribes from an ethereum event.
func (j *EthEventSub) Unsubscribe(_ context.Context) {
if j.sub != nil {
j.sub.Unsubscribe()
}
}
func (j *EthEventSub) Setup(ctx context.Context) error {
if setupJob, ok := j.Basic.(job.HasSetup); ok {
return setupJob.Setup(ctx)
}
return nil
}
func (j *EthEventSub) Teardown() error {
if setupJob, ok := j.Basic.(job.HasTeardown); ok {
return setupJob.Teardown()
}
return nil
}