-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
107 lines (86 loc) · 2.21 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
103
104
105
106
107
package main
import (
"bytes"
"encoding/json"
"log"
"net/http"
"fmt"
"os"
)
type RpcRequestPayload struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params []interface{} `json:"params"`
ID int `json:"id"`
}
type RpcResponsePayload struct {
JSONRPC string `json:"jsonrpc"`
ID int `json:"id"`
Result interface{} `json:"result"`
}
var RpcURL string
func GetBlockNumber(w http.ResponseWriter, r *http.Request) {
requestBody := RpcRequestPayload{
JSONRPC: "2.0",
Method: "eth_blockNumber",
ID: 1,
}
responseBody, err := PostRPCRequest(requestBody)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(responseBody)
}
func GetBlockByNumber(w http.ResponseWriter, r *http.Request) {
requestBody := RpcRequestPayload{
JSONRPC: "2.0",
Method: "eth_getBlockByNumber",
Params: []interface{}{
"0x134e82a",
true,
},
ID: 2,
}
responseBody, err := PostRPCRequest(requestBody)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(responseBody)
}
func PostRPCRequest(requestBody RpcRequestPayload) (RpcResponsePayload, error) {
RpcURL := os.Getenv("RPC_URL")
log.Println("RPC_URL: ", RpcURL)
if RpcURL == "" {
log.Fatal("RPC_URL environment variable is not set")
}
requestBytes, err := json.Marshal(requestBody)
if err != nil {
return RpcResponsePayload{}, err
}
resp, err := http.Post(RpcURL, "application/json", bytes.NewBuffer(requestBytes))
if err != nil {
return RpcResponsePayload{}, err
}
defer resp.Body.Close()
var responseBody RpcResponsePayload
err = json.NewDecoder(resp.Body).Decode(&responseBody)
if err != nil {
return RpcResponsePayload{}, err
}
return responseBody, nil
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "TrustWallet RPC Gateway!")
})
http.HandleFunc("/getBlock", GetBlockNumber)
http.HandleFunc("/getBlockByNumber", GetBlockByNumber)
port := os.Getenv("APP_PORT")
if port == "" {
port = "3000"
}
log.Println("Gateway listening on port 3000...")
log.Fatal(http.ListenAndServe(":"+port, nil))
}