forked from cartesi/sunodo-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dapp.lua
63 lines (54 loc) · 2.02 KB
/
dapp.lua
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
local http = require("socket.http")
local ltn12 = require("ltn12")
local json = require("dkjson")
local rollup_server = assert(os.getenv("ROLLUP_HTTP_SERVER_URL"), "missing ROLLUP_HTTP_SERVER_URL")
local function info(...)
print(string.format(...))
end
local function http_post(url, body)
local request_body = json.encode(body)
local response_body = {}
local result, code = http.request {
method = "POST",
url = url,
source = ltn12.source.string(request_body),
headers = {
["Content-Type"] = "application/json",
["Content-Length"] = #request_body
},
sink = ltn12.sink.table(response_body)
}
if result == nil then error("HTTP POST Request to " .. url .. " failed. " .. code) end
return code, table.concat(response_body)
end
local handlers = {}
function handlers.advance_state(data)
info("Received advance request data %s", json.encode(data))
info("Adding notice")
local notice = {payload = data.payload}
local code, response = http_post(rollup_server .. "/notice", notice)
info("Received notice status %d body %s", code, response)
return "accept"
end
function handlers.inspect_state(data)
info("Received inspect request data %s", json.encode(data))
info("Adding report")
local report = {payload = data.payload}
local code, response = http_post(rollup_server .. "/report", report)
info("Received report status %d body %s", code, response)
return "accept"
end
local mt = {__index = function(t, k) error("Invalid request type: " .. k) end}
setmetatable(handlers, mt)
local finish = {status = "accept"}
while true do
info("Sending finish")
local code, response = http_post(rollup_server .. "/finish", finish)
info("Received finish status %d", code)
if code == 202 then
info("No pending rollup request, trying again")
else
local rollup_request = json.decode(response)
finish.status = handlers[rollup_request.request_type](rollup_request.data)
end
end