-
Notifications
You must be signed in to change notification settings - Fork 3
/
moonstream.go
326 lines (268 loc) · 10.9 KB
/
moonstream.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strconv"
"time"
)
type RegisteredContract struct {
Id string `json:"id"`
Blockchain string `json:"blockchain"`
ChainId int64 `json:"chain_id"`
Address string `json:"address"`
MetatxRequesterId string `json:"metatx_requester_id"`
Title string `json:"title"`
Description string `json:"description"`
ImageURI string `json:"image_uri"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type CallRequest struct {
Id string `json:"id"`
ContractId string `json:"contract_id"`
ContractAddress string `json:"contract_address"`
MetatxRequesterId string `json:"metatx_requester_id"`
CallRequestType string `json:"call_request_type"`
Caller string `json:"caller"`
Method string `json:"method"`
RequestId string `json:"request_id"`
Parameters interface{} `json:"parameters"`
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
UpdateAt time.Time `json:"updated_at"`
}
type CallRequestSpecification struct {
Caller string `json:"caller"`
Method string `json:"method"`
RequestId string `json:"request_id"`
Parameters interface{} `json:"parameters"`
}
type CreateCallRequestsRequest struct {
ContractID string `json:"contract_id,omitempty"`
ContractAddress string `json:"contract_address,omitempty"`
TTLDays int `json:"ttl_days"`
Specifications []CallRequestSpecification `json:"specifications"`
}
type DropperCallRequestParameters struct {
DropId string `json:"dropId"`
BlockDeadline string `json:"blockDeadline"`
Amount string `json:"amount"`
Signer string `json:"signer"`
Signature string `json:"signature"`
}
type MoonstreamEngineAPIClient struct {
BaseURL string
HTTPClient *http.Client
}
type CallRequestsCheck struct {
ExistingRequests [][]string `json:"existing_requests"`
}
func InitMoonstreamEngineAPIClient() (*MoonstreamEngineAPIClient, error) {
if MOONSTREAM_API_URL == "" {
MOONSTREAM_API_URL = "https://api.moonstream.to"
}
if MOONSTREAM_API_TIMEOUT_SECONDS == "" {
MOONSTREAM_API_TIMEOUT_SECONDS = "30"
}
timeoutSeconds, conversionErr := strconv.Atoi(MOONSTREAM_API_TIMEOUT_SECONDS)
if conversionErr != nil {
return nil, conversionErr
}
timeout := time.Duration(timeoutSeconds) * time.Second
httpClient := http.Client{Timeout: timeout}
return &MoonstreamEngineAPIClient{
BaseURL: MOONSTREAM_API_URL,
HTTPClient: &httpClient,
}, nil
}
func (client *MoonstreamEngineAPIClient) ListRegisteredContracts(accessToken, blockchain, address, contractType string, limit, offset int) ([]RegisteredContract, error) {
var contracts []RegisteredContract
request, requestCreationErr := http.NewRequest("GET", fmt.Sprintf("%s/metatx/contracts/", client.BaseURL), nil)
if requestCreationErr != nil {
return contracts, requestCreationErr
}
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", accessToken))
request.Header.Add("Accept", "application/json")
queryParameters := request.URL.Query()
if blockchain != "" {
queryParameters.Add("blockchain", blockchain)
}
if address != "" {
queryParameters.Add("address", address)
}
if contractType != "" {
queryParameters.Add("contract_type", contractType)
}
queryParameters.Add("limit", strconv.Itoa(limit))
queryParameters.Add("offset", strconv.Itoa(offset))
request.URL.RawQuery = queryParameters.Encode()
response, responseErr := client.HTTPClient.Do(request)
if responseErr != nil {
return contracts, responseErr
}
defer response.Body.Close()
responseBody, responseBodyErr := io.ReadAll(response.Body)
if response.StatusCode < 200 || response.StatusCode >= 300 {
if responseBodyErr != nil {
return contracts, fmt.Errorf("unexpected status code: %d -- could not read response body: %s", response.StatusCode, responseBodyErr.Error())
}
responseBodyString := string(responseBody)
return contracts, fmt.Errorf("unexpected status code: %d -- response body: %s", response.StatusCode, responseBodyString)
}
if responseBodyErr != nil {
return contracts, fmt.Errorf("could not read response body: %s", responseBodyErr.Error())
}
unmarshalErr := json.Unmarshal(responseBody, &contracts)
if unmarshalErr != nil {
return contracts, fmt.Errorf("could not parse response body: %s", unmarshalErr.Error())
}
return contracts, nil
}
func (client *MoonstreamEngineAPIClient) GetRegisteredContract(accessToken, contractId string) (int, RegisteredContract, string) {
var contract RegisteredContract
request, requestCreationErr := http.NewRequest("GET", fmt.Sprintf("%s/metatx/contracts/%s", client.BaseURL, contractId), nil)
if requestCreationErr != nil {
log.Printf("Unable to create request, error: %v", requestCreationErr)
return 500, contract, ""
}
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", accessToken))
request.Header.Add("Accept", "application/json")
response, responseErr := client.HTTPClient.Do(request)
if responseErr != nil {
log.Printf("Unable to do request, error: %v", responseErr)
return 500, contract, ""
}
defer response.Body.Close()
responseBody, responseBodyErr := io.ReadAll(response.Body)
if responseBodyErr != nil {
log.Printf("Unable to parse response body, error: %v", responseBodyErr)
return response.StatusCode, contract, response.Status
}
if response.StatusCode != 200 {
return response.StatusCode, contract, string(responseBody)
}
unmarshalErr := json.Unmarshal(responseBody, &contract)
if unmarshalErr != nil {
log.Printf("Could not parse response body, error: %s", unmarshalErr)
return response.StatusCode, contract, response.Status
}
return response.StatusCode, contract, response.Status
}
func (client *MoonstreamEngineAPIClient) ListCallRequests(accessToken, contractId, contractAddress, caller string, limit, offset int, showExpired bool) ([]CallRequest, error) {
var callRequests []CallRequest
if caller == "" {
return callRequests, fmt.Errorf("you must specify caller when listing call requests")
}
request, requestCreationErr := http.NewRequest("GET", fmt.Sprintf("%s/metatx/requests", client.BaseURL), nil)
if requestCreationErr != nil {
return callRequests, requestCreationErr
}
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", accessToken))
request.Header.Add("Accept", "application/json")
queryParameters := request.URL.Query()
if contractId != "" {
queryParameters.Add("contract_id", contractId)
}
if contractAddress != "" {
queryParameters.Add("contract_address", contractAddress)
}
queryParameters.Add("caller", caller)
queryParameters.Add("limit", strconv.Itoa(limit))
queryParameters.Add("offset", strconv.Itoa(offset))
queryParameters.Add("show_expired", strconv.FormatBool(showExpired))
request.URL.RawQuery = queryParameters.Encode()
response, responseErr := client.HTTPClient.Do(request)
if responseErr != nil {
return callRequests, responseErr
}
defer response.Body.Close()
responseBody, responseBodyErr := io.ReadAll(response.Body)
if response.StatusCode < 200 || response.StatusCode >= 300 {
if responseBodyErr != nil {
return callRequests, fmt.Errorf("unexpected status code: %d -- could not read response body: %s", response.StatusCode, responseBodyErr.Error())
}
responseBodyString := string(responseBody)
return callRequests, fmt.Errorf("unexpected status code: %d -- response body: %s", response.StatusCode, responseBodyString)
}
if responseBodyErr != nil {
return callRequests, fmt.Errorf("could not read response body: %s", responseBodyErr.Error())
}
unmarshalErr := json.Unmarshal(responseBody, &callRequests)
if unmarshalErr != nil {
return callRequests, fmt.Errorf("could not parse response body: %s", unmarshalErr.Error())
}
return callRequests, nil
}
func (client *MoonstreamEngineAPIClient) checkCallRequests(accessToken string, contractId,
contractAddress string, callRequests []CallRequestSpecification) (int, CallRequestsCheck, string) {
var callRequestsCheck CallRequestsCheck
requestBody := CreateCallRequestsRequest{
Specifications: callRequests,
}
if contractId != "" {
requestBody.ContractID = contractId
}
if contractAddress != "" {
requestBody.ContractAddress = contractAddress
}
requestBodyBytes, requestBodyBytesErr := json.Marshal(requestBody)
if requestBodyBytesErr != nil {
log.Printf("Unable to prepare request body, error: %v", requestBodyBytesErr)
return 0, callRequestsCheck, ""
}
request, requestCreationErr := http.NewRequest("GET", fmt.Sprintf("%s/metatx/requests/check", client.BaseURL), bytes.NewBuffer(requestBodyBytes))
if requestCreationErr != nil {
log.Printf("Unable to create request, error: %v", requestCreationErr)
return 0, callRequestsCheck, ""
}
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", accessToken))
request.Header.Add("Accept", "application/json")
request.Header.Add("Content-Type", "application/json")
response, responseErr := client.HTTPClient.Do(request)
if responseErr != nil {
log.Printf("Unable to do request, error: %v", responseErr)
return 0, callRequestsCheck, ""
}
defer response.Body.Close()
responseBody, responseBodyErr := io.ReadAll(response.Body)
if responseBodyErr != nil {
log.Printf("Unable to parse response body, error: %v", responseBodyErr)
return response.StatusCode, callRequestsCheck, response.Status
}
if response.StatusCode != 200 {
return response.StatusCode, callRequestsCheck, string(responseBody)
}
unmarshalErr := json.Unmarshal(responseBody, &callRequestsCheck)
if unmarshalErr != nil {
log.Printf("Could not parse response body, error: %s", unmarshalErr)
return response.StatusCode, callRequestsCheck, response.Status
}
return response.StatusCode, callRequestsCheck, response.Status
}
// sendCallRequests sends a POST request to metatx API
func (client *MoonstreamEngineAPIClient) sendCallRequests(accessToken string, requestBodyBytes []byte) (int, string) {
request, requestCreationErr := http.NewRequest("POST", fmt.Sprintf("%s/metatx/requests", client.BaseURL), bytes.NewBuffer(requestBodyBytes))
if requestCreationErr != nil {
log.Printf("Unable to create request, error: %v", requestCreationErr)
return 0, ""
}
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", accessToken))
request.Header.Add("Accept", "application/json")
request.Header.Add("Content-Type", "application/json")
response, responseErr := client.HTTPClient.Do(request)
if responseErr != nil {
log.Printf("Unable to do request, error: %v", responseErr)
return 0, ""
}
defer response.Body.Close()
responseBody, responseBodyErr := io.ReadAll(response.Body)
if responseBodyErr != nil {
log.Printf("Unable to parse response body, error: %v", responseBodyErr)
return response.StatusCode, ""
}
return response.StatusCode, string(responseBody)
}