-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
88 lines (75 loc) · 2.09 KB
/
main.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
package main
import (
"context"
"fmt"
"log"
"math/big"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/shopspring/decimal"
"github.com/rrobrms/go-ethereum-event-subscribe/abis"
)
type updatePriceData struct {
description string
price float64
blockNumber uint64
blockTime uint64
}
func main() {
client, err := ethclient.Dial("wss://eth-mainnet.g.alchemy.com/v2/")
if err != nil {
fmt.Println("Failed client", err)
}
defer client.Close()
ctx := context.Background()
chainId, err := client.ChainID(ctx)
if err != nil {
fmt.Println("Failed chainId", err)
}
blockNumber, err := client.BlockNumber(ctx)
if err != nil {
fmt.Println("Failed chainId", err)
}
// contract to watch over BTC / USD
contractAddress := common.HexToAddress("0xAe74faA92cB67A95ebCAB07358bC222e33A34dA7")
// created a instance of the Compiled abi
instance, err := abis.NewAbis(contractAddress, client)
if err != nil {
log.Fatal(err)
}
description, err := instance.Description(&bind.CallOpts{})
if err != nil {
log.Fatal(err)
}
decimals, err := instance.Decimals(&bind.CallOpts{})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Opened Listener [%s] on chain ID [%v] -- block [%v]\n", description, int(chainId.Int64()), big.NewInt(int64(blockNumber)))
// create channel to accept event types "Transmission" from compiled abi
wntChan := make(chan *abis.AbisNewTransmission)
e, err := instance.WatchNewTransmission(&bind.WatchOpts{},wntChan, []uint32{})
if err != nil {
fmt.Print(err)
}
for {
select {
case err := <-e.Err():
log.Fatal(err)
case wt := <-wntChan:
answer := decimal.NewFromBigInt(wt.Answer, int32(decimals)*-1)
b, err := client.BlockByNumber(ctx, nil)
if err != nil {
fmt.Println(err)
}
d := updatePriceData{
description: description,
price: answer.Round(5).InexactFloat64(),
blockNumber: b.NumberU64(),
blockTime: b.Time(),
}
fmt.Printf("Update Price Data: %v\n", d)
}
}
}