-
Notifications
You must be signed in to change notification settings - Fork 1
/
LlamaLotteryPool.lua
353 lines (316 loc) · 9.48 KB
/
LlamaLotteryPool.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
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
-- LlamaCoinProcessId: pazXumQI-HPH7iFGfTC-4_7biSnqz_U67oFAGry5zUY
LlamaCoinProcessId = LlamaCoinProcessId or nil
LlamaCoinDenomination = 12
OneLlamaCoin = 10 ^ LlamaCoinDenomination
LlamaLotteryNpc = LlamaLotteryNpc or "7mboR6qBAs2eu3EZk6TSLChDRjqyaQ7GbSY6vzqiJY8"
local crypto = crypto or require(".crypto")
local sqlite3 = require("lsqlite3")
if db == nil then
db = sqlite3.open_memory()
end
local json = require("json")
DrawTimestamp = DrawTimestamp or 0
StartPeriod = StartPeriod or false
LlamaCoinBalance = LlamaCoinBalance or 0
Participants = Participants or {}
--[[
init
]]
db:exec[[
CREATE TABLE IF NOT EXISTS participants (
participant_id TEXT,
seq_no INTEGER
);
]]
db:exec[[
CREATE TABLE IF NOT EXISTS reward_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
round INTEGER,
total_reward INTEGER,
participant_ids TEXT,
winner_ids TEXT,
created_at INTEGER
);
]]
--[[
tool function
]]
local function getRandomNumber(seed, len)
local numbers = ""
for i = 1, len or 1 do
local n = crypto.cipher.issac.random(0, 9, tostring(i)..seed..numbers)
numbers = numbers .. n
end
return numbers
end
local function rejectToken(msg)
assert(msg.Sender ~= nil, "Missed Sender.")
assert(msg.Quantity ~= nil and tonumber(msg.Quantity) > 0, "Missed Quantity.")
local message = {
Target = msg.From,
Action = "Transfer",
Recipient = msg.Sender,
Quantity = msg.Quantity,
Tags = {["X-Transfer-Purpose"] = "Reject-Bet" }
}
ao.send(message)
end
function SendReward(winner_id, reward)
print(type(winner_id))
print(type(reward))
assert(winner_id ~= nil, "Missed winner.")
assert(reward ~= nil and reward > 0, "Reward should be greater than 0.")
local message = {
Target = LlamaCoinProcessId,
Action = "Transfer",
Recipient = winner_id,
Quantity = tostring(reward),
Tags = {["X-Transfer-Purpose"] = "Win-Reward" }
}
Send(message)
print(message)
print("sendReward: " .. winner_id .. ", " .. reward)
end
function getParticipantCount()
local sql = string.format("SELECT COUNT(1) FROM participants")
local stmt = db:prepare(sql)
stmt:step()
local total = stmt:get_value(0)
stmt:finalize()
return total
end
local function addParticipant(participant_id, seq_no)
local sql = string.format("INSERT INTO participants (participant_id, seq_no) VALUES ('%s', %d)", participant_id, seq_no)
db:exec(sql)
end
function getParticipants()
local sql = string.format("SELECT GROUP_CONCAT(participant_id, ',') FROM participants")
local stmt = db:prepare(sql)
stmt:step()
local ids = stmt:get_value(0)
stmt:finalize()
return ids
end
function getParticipantsBySeqNo(seq_no)
local sql = string.format("SELECT participant_id FROM participants WHERE seq_no = %d", seq_no)
local stmt = db:prepare(sql)
stmt:step()
local participant_id = stmt:get_value(0)
stmt:finalize()
return participant_id
end
local function clearParticipants()
local sql = string.format("DELETE FROM participants")
db:exec(sql)
end
local function addLogs(round, total_reward, participant_ids, winner_ids, created_at)
local sql = string.format("INSERT INTO reward_logs (round, total_reward, participant_ids, winner_ids, created_at) VALUES (%d, %d, '%s', '%s', %d)", round, total_reward, participant_ids, winner_ids, created_at)
db:exec(sql)
end
function getAllHistoryParticipants()
local results = {}
local sql = string.format("SELECT participant_ids FROM reward_logs")
for row in db:nrows(sql) do
table.insert(results, row)
end
return results
end
function getRewardLogs(round)
local results = {}
local sql = string.format("SELECT * FROM reward_logs WHERE round = %d", round)
for row in db:nrows(sql) do
table.insert(results, row)
end
return results
end
function getCurrentRound()
local sql = string.format("SELECT MAX(round) FROM reward_logs")
local stmt = db:prepare(sql)
stmt:step()
local round = stmt:get_value(0)
stmt:finalize()
return round
end
function execSql(sql)
local results = {}
for row in db:nrows(sql) do
table.insert(results, row)
end
return results
end
local function lotteryNotice(sender, data)
assert(sender ~= nil, "Missed sender.")
local message = {
Target = sender,
Action = "Lottery-Notice",
Data = data
}
ao.send(message)
end
--[[
handlers
]]
Handlers.add("AttendGame",
function (msg)
if msg.From == LlamaCoinProcessId
and msg.Tags.Action == "Credit-Notice"
and msg.Sender ~= LlamaCoinProcessId
and msg.Sender ~= ao.id
then
return true
else
return false
end
end,
function (msg)
if msg.Tags["X-Transfer-Purpose"] == "sponsor" then
LlamaCoinBalance = LlamaCoinBalance + tonumber(msg.Quantity)
local data = "Thanks for the sponsor from " .. msg.Sender .. ", " .. msg.Quantity .. " llama coins."
print(data)
lotteryNotice(msg.Sender, data)
return
end
if tonumber(msg.Quantity) ~= OneLlamaCoin then
rejectToken(msg)
print(
"Game ticket should be 1 llama coin. But you sent "
.. msg.Quantity
.. ", it will be transfer back to " .. msg.Sender .. "."
)
return
end
local participantCount = getParticipantCount()
if participantCount >= 10 then
rejectToken(msg)
local result = "Only 10 participants are allowed to play at the same time. Llama coins will be transfer back to " .. msg.Sender .. "."
print(result)
ao.send({
Target = LlamaLotteryNpc,
Tags = {
Action = "DrawLotteryResult"
},
Data = result
})
return
end
addParticipant(msg.Sender, participantCount + 1)
DrawTimestamp = msg.Timestamp + 1 * 60
LlamaCoinBalance = LlamaCoinBalance + tonumber(msg.Quantity)
lotteryNotice(msg.Sender, "You have attend lottery successfully.")
print(msg.Sender .. " attend to lottery.")
if participantCount >= 10 then
StartPeriod = false
print("It is time to draw lottery.")
end
end
)
Handlers.add("DrawLottery",
function (msg)
if msg.Tags.Action == "Cron" then
return true
else
return false
end
end,
function (msg)
local participantCount = getParticipantCount()
if participantCount < 10 then
print("Not enough participants to draw lottery.")
return
end
if msg.Timestamp < DrawTimestamp then
print("Not time to draw lottery yet.")
return
end
local totalReward = 0
if LlamaCoinBalance > 13 * OneLlamaCoin then
totalReward = LlamaCoinBalance * 0.8
else
totalReward = LlamaCoinBalance
end
local luckyNumber1 = getRandomNumber(msg.Timestamp, 1)
local luckyNumber2 = getRandomNumber(msg.Timestamp .. luckyNumber1, 1)
print("luckyNumber1:" .. luckyNumber1)
print("luckyNumber2:" .. luckyNumber2)
local round = getCurrentRound() or 0
round = round + 1
local participantIds = getParticipants()
local winner_ids = ""
if luckyNumber1 == luckyNumber2 then
local winner = getParticipantsBySeqNo(luckyNumber1 + 1)
winner_ids = winner
local reward = math.floor(totalReward)
SendReward(winner, reward)
addLogs(round, totalReward, participantIds, winner, msg.Timestamp)
else
local winner1 = getParticipantsBySeqNo(luckyNumber1 + 1)
local winner2 = getParticipantsBySeqNo(luckyNumber2 + 1)
local reward = math.floor(totalReward * 0.5)
winner_ids = winner1 .. "," .. winner2
SendReward(winner1, reward)
SendReward(winner2, reward)
addLogs(round, totalReward, participantIds, winner1 .. "," .. winner2, msg.Timestamp)
end
LlamaCoinBalance = LlamaCoinBalance - totalReward
clearParticipants()
local drawData = "Lottery round " .. round .. " is over. The winner is " .. winner_ids .. ". The reward is " .. totalReward / OneLlamaCoin .. " Llama Coins."
local message = {
Target = LlamaLotteryNpc,
Tags = {
Action = "DrawLotteryResult"
},
Data = drawData
}
print(message)
ao.send(message)
StartPeriod = true
print("Draw lottery successfully.")
end
)
Handlers.add("RoundInfo",
function (msg)
if msg.Tags.Action == "RoundInfo" then
return true
else
return false
end
end,
function (msg)
local count = getParticipantCount()
local balance = LlamaCoinBalance
local p_ids = getParticipants()
local data = {
count = count,
balance = balance,
p_ids = p_ids
}
ao.send({
Target = msg.From,
Tags = {
Action = "RespRoundInfo",
},
Data = json.encode(data)
})
end
)
Handlers.add("HistoryRoundInfo",
function (msg)
if msg.Tags.Action == "HistoryRoundInfo" then
return true
else
return false
end
end,
function (msg)
assert(msg.Tags.Round~=nil,"missd Round tag")
local data = getRewardLogs(msg.Tags.Round)
ao.send({
Target = LlamaLotteryNpc,
Tags = {
Action = "DrawLotteryResult"
},
Data = "History Lottery round " .. msg.Tags.Round .. ". The winner is " .. data.winner_ids .. ". The reward is "
.. data.total_reward / OneLlamaCoin .. " Llama Coins. The participants are " .. data.participant_ids .. ".",
})
end
)