-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
102 lines (81 loc) · 2.36 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
_ "github.com/lib/pq"
)
type AggregatedFee struct {
Hour int64 `json:"t"`
HourlyFee float64 `json:"v"`
}
type ethDB interface {
AggregateFeeByHour() ([]AggregatedFee, error)
}
const query string = `
SELECT CAST(extract(EPOCH FROM date_trunc('hour', sub.ts)) AS INT) AS hour, SUM(gas_payed)* 10 ^ -18 AS hourly_fee FROM
(SELECT t.gas_used*t.gas_price AS gas_payed, t.block_time AS ts FROM
(SELECT gas_used, gas_price, t.from, t.to, t.block_time FROM transactions AS t where t.to != '0x0000000000000000000000000000000000000000' and t.from != '0x0000000000000000000000000000000000000000') as t
LEFT JOIN contracts AS c ON t.from = c.address OR t.to = c.address WHERE c.address IS NULL) AS sub
GROUP BY hour;
`
type psqlDB struct {
con *sql.DB
}
func (pDB psqlDB) AggregateFeeByHour() (result []AggregatedFee, err error) {
rows, err := pDB.con.Query(query)
if err != nil {
return
}
for rows.Next() {
dest := AggregatedFee{}
err = rows.Scan(&dest.Hour, &dest.HourlyFee)
if err != nil {
return
}
result = append(result, dest)
}
return
}
type handler struct {
db ethDB
}
func (h handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(rw, "Invalid HTTP Method, only HTTP GET is allowed", http.StatusMethodNotAllowed)
return
}
data, err := h.db.AggregateFeeByHour()
if err != nil {
log.Println(err)
http.Error(rw, "Error communicating with datasource", http.StatusInternalServerError)
return
}
encoder := json.NewEncoder(rw)
encoder.SetIndent("", " ")
rw.Header().Add("Content-Type", "application/json")
if err := encoder.Encode(&data); err != nil {
log.Println(err)
http.Error(rw, "Unexpected internal error", http.StatusInternalServerError)
return
}
}
func main() {
host := os.Getenv("ETH_DB_HOST")
user := os.Getenv("ETH_DB_USER")
pwd := os.Getenv("ETH_DB_PASSWORD")
dbname := os.Getenv("ETH_DB_NAME")
cStr := fmt.Sprintf("user=%s dbname=%s password=%s host=%s sslmode=disable", user, dbname, pwd, host)
con, err := sql.Open("postgres", cStr)
if err != nil {
log.Fatal("error connecting to database", err)
}
h := handler{psqlDB{con}}
log.Println("API starts listening")
if err := http.ListenAndServe(":8081", h); err != nil {
log.Println("Error starting webserver: ", err)
}
}