forked from ashwinYardi/ethereum-lottery-smart-contract
-
Notifications
You must be signed in to change notification settings - Fork 1
/
LotteryContract.sol
427 lines (390 loc) · 15.2 KB
/
LotteryContract.sol
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
pragma solidity ^0.6.0;
import "../interfaces/IERC20.sol";
// import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./VRFConsumerBase.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
contract LotteryContract is VRFConsumerBase, ReentrancyGuard {
using Address for address;
using SafeMath for uint256;
struct LotteryConfig {
uint256 numOfWinners;
uint256 playersLimit;
uint256 registrationAmount;
uint256 adminFeePercentage;
// address lotteryTokenAddress;
uint256 randomSeed;
uint256 startedAt;
}
address[] public lotteryPlayers;
address public adminAddress;
enum LotteryStatus {NOTSTARTED, INPROGRESS, CLOSED}
mapping(uint256 => address) public winnerAddresses;
uint256[] public winnerIndexes;
uint256 public totalLotteryPool;
uint256 public adminFeesAmount;
uint256 public rewardPoolAmount;
IERC20 lotteryToken;
IERC20 buyToken;
LotteryStatus public lotteryStatus;
LotteryConfig lotteryConfig;
bytes32 internal keyHash;
uint256 internal fee;
uint256 internal randomResult;
bool internal areWinnersGenerated;
bool internal isRandomNumberGenerated;
bool public isOnlyETHAccepted;
event MaxParticipationCompleted(address indexed _from);
event RandomNumberGenerated(uint256 indexed randomness);
event WinnersGenerated(uint256[] winnerIndexes);
event LotterySettled();
event LotteryStarted(
// address indexed lotteryTokenAddress,
uint256 playersLimit,
uint256 numOfWinners,
uint256 registrationAmount,
uint256 startedAt
);
event LotteryReset();
/**
* @dev Sets the value for adminAddress which establishes the Admin of the contract
* Only the adminAddress will be able to set the lottery configuration,
* start the lottery and reset the lottery.
*
* It also sets the required fees, keyHash etc. for the ChainLink Oracle RNG
*
* Also initializes the LOT ERC20 TOKEN that is minted/burned by the participating lottery players.
*
* The adminAdress value is immutable along with the initial
* configuration of VRF Smart Contract. They can only be set once during
* construction.
*/
constructor(IERC20 _buyToken, IERC20 _lotteryToken, bool _isOnlyETHAccepted)
public
VRFConsumerBase(
0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9, // VRF Coordinator
0xa36085F69e2889c224210F603D836748e7dC0088 // LINK Token
)
// ERC20("LotteryTokens", "LOT") //Internal LOT ERC20 token
{
adminAddress = msg.sender;
lotteryStatus = LotteryStatus.NOTSTARTED;
totalLotteryPool = 0;
keyHash = 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4;
fee = 0.1 * 10**18; // 0.1 LINK
areWinnersGenerated = false;
isRandomNumberGenerated = false;
buyToken = _buyToken; // ERC20 contract
lotteryToken = _lotteryToken; // ERC20 contract
isOnlyETHAccepted = _isOnlyETHAccepted;
}
/**
* @dev Calls ChainLink Oracle's inherited function for
* Random Number Generation.
*
* Requirements:
*
* - the contract must have a balance of at least `fee` required for VRF.
*/
function getRandomNumber(uint256 userProvidedSeed)
internal
returns (bytes32 requestId)
{
require(
LINK.balanceOf(address(this)) >= fee,
"Not enough LINK - fill contract with faucet"
);
isRandomNumberGenerated = false;
return requestRandomness(keyHash, fee, userProvidedSeed);
}
/**
* @dev The callback function of ChainLink Oracle when the
* Random Number Generation is completed. An event is fired
* to notify the same and the randomResult is saved.
*
* Emits an {RandomNumberGenerated} event indicating the random number is
* generated by the Oracle.
*
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal
override
{
randomResult = randomness;
isRandomNumberGenerated = true;
emit RandomNumberGenerated(randomness);
}
/**
* @dev Sets the Lottery Config, initializes an instance of
* ERC20 contract that the lottery is based on and starts the lottery.
*
* Emits an {LotteryStarted} event indicating the Admin has started the Lottery.
*
* Requirements:
*
* - Cannot be called if the lottery is in progress.
* - Only the address set at `adminAddress` can call this function.
* - Number of winners `numOfWinners` should be less than or equal to half the number of
* players `playersLimit`.
*/
function setLotteryRules(
uint256 numOfWinners,
uint256 playersLimit,
uint256 registrationAmount,
uint256 adminFeePercentage,
uint256 randomSeed
) public {
require(
msg.sender == adminAddress,
"Starting the Lottery requires Admin Access"
);
require(
lotteryStatus == LotteryStatus.NOTSTARTED,
"Error: An existing lottery is in progress"
);
// require(
// numOfWinners <= playersLimit.div(2),
// "Number of winners should be less than or equal to half the number of players"
// );
lotteryConfig = LotteryConfig(
numOfWinners,
playersLimit,
registrationAmount,
adminFeePercentage,
// lotteryTokenAddress,
randomSeed,
block.timestamp
);
lotteryStatus = LotteryStatus.INPROGRESS;
// lotteryToken = IERC20(lotteryTokenAddress);
emit LotteryStarted(
// lotteryTokenAddress,
playersLimit,
numOfWinners,
registrationAmount,
block.timestamp
);
}
/**
* @dev Player enters the lottery and the registration amount is
* transferred from the player to the contract.
*
* Returns participant's index. This is similar to unique registration id.
* Emits an {MaxParticipationCompleted} event indicating that all the required players have entered the lottery.
*
* The participant is also issued an equal amount of LOT tokens once he registers for the lottery.
* This LOT tokens are fundamental to the lottery contract and are used internally.
* The winners will need to burn their LOT tokens to claim the lottery winnings.
* The other participants of the lottery can keep hold of these tokens and use for other applications.
*
* Requirements:
*
* - The player has set the necessary allowance to the Contract.
* - The Lottery is in progress.
* - Number of players allowed to enter in the lottery should be
* less than or equal to the allowed players `lotteryConfig.playersLimit`.
*/
function enterLottery() payable public returns (uint256) {
require(
lotteryPlayers.length < lotteryConfig.playersLimit,
"Max Participation for the Lottery Reached"
);
require(
lotteryStatus == LotteryStatus.INPROGRESS,
"The Lottery is not started or closed"
);
lotteryPlayers.push(msg.sender);
if(isOnlyETHAccepted) {
require(msg.value == lotteryConfig.registrationAmount, "Insufficent registration amount provided");
} else {
buyToken.transferFrom(
msg.sender,
address(this),
lotteryConfig.registrationAmount
);
}
totalLotteryPool = totalLotteryPool.add(
lotteryConfig.registrationAmount
);
// call _mint from constructor ERC20
// Not giving loser lottery tokens !!
// lotteryToken.mint(msg.sender, lotteryConfig.registrationAmount);
if (lotteryPlayers.length == lotteryConfig.playersLimit) {
emit MaxParticipationCompleted(msg.sender);
getRandomNumber(lotteryConfig.randomSeed);
}
return (lotteryPlayers.length).sub(1);
}
/**
* @dev Settles the lottery, the winners are calculated based on
* the random number generated. The Admin fee is calculated and
* transferred back to Admin `adminAddress`.
*
* Emits an {WinnersGenerated} event indicating that the winners for the lottery have been generated.
* Emits {LotterySettled} event indicating that the winnings have been transferred to the Admin and the Lottery is closed.
*
* Requirements:
*
* - The random number has been generated
* - The Lottery is in progress.
*/
function settleLottery() payable public {
require(
isRandomNumberGenerated,
"Lottery Configuration still in progress. Please try in a short while"
);
require(
lotteryStatus == LotteryStatus.INPROGRESS,
"The Lottery is not started or closed"
);
for (uint256 i = 0; i < lotteryConfig.numOfWinners; i = i.add(1)) {
uint256 winningIndex = randomResult.mod(lotteryConfig.playersLimit);
uint256 counter = 0;
while (winnerAddresses[winningIndex] != address(0)) {
randomResult = getRandomNumberBlockchain(i, randomResult);
winningIndex = randomResult.mod(lotteryConfig.playersLimit);
counter = counter.add(1);
if (counter == lotteryConfig.playersLimit) {
while (winnerAddresses[winningIndex] != address(0)) {
winningIndex = (winningIndex.add(1)).mod(
lotteryConfig.playersLimit
);
}
counter = 0;
}
}
winnerAddresses[winningIndex] = lotteryPlayers[winningIndex];
winnerIndexes.push(winningIndex);
randomResult = getRandomNumberBlockchain(i, randomResult);
}
areWinnersGenerated = true;
emit WinnersGenerated(winnerIndexes);
adminFeesAmount = (
(totalLotteryPool.mul(lotteryConfig.adminFeePercentage)).div(100)
);
rewardPoolAmount = (totalLotteryPool.sub(adminFeesAmount)).div(
lotteryConfig.numOfWinners
);
lotteryStatus = LotteryStatus.CLOSED;
if(isOnlyETHAccepted) {
(bool status, ) = payable(adminAddress).call{value: adminFeesAmount}("");
require(status, "Admin fees not transferred");
} else {
buyToken.transfer(adminAddress, adminFeesAmount);
}
collectRewards();
emit LotterySettled();
}
/**
* @dev The winners of the lottery can call this function to transfer their winnings
* from the lottery contract to their own address. The winners will need to burn their
* LOT tokens to claim the lottery rewards. This is executed by the lottery contract itself.
*
*
* Requirements:
*
* - The Lottery is settled i.e. the lotteryStatus is CLOSED.
*/
/**
* @dev The winners of the lottery can call this function to transfer their winnings
* from the lottery contract to their own address. The winners will need to burn their
* LOT tokens to claim the lottery rewards. This is executed by the lottery contract itself.
*
*
* Requirements:
*
* - The Lottery is settled i.e. the lotteryStatus is CLOSED.
*/
function collectRewards() private nonReentrant {
require(
lotteryStatus == LotteryStatus.CLOSED,
"The Lottery is not settled. Please try in a short while."
);
bool isWinner = false;
for (uint256 i = 0; i < lotteryConfig.playersLimit; i = i.add(1)) {
address player = lotteryPlayers[i];
// if (address(msg.sender) == winnerAddresses[winnerIndexes[i]]) {
for(uint256 j = 0; j < lotteryConfig.numOfWinners; j = j.add(1)) {
address winner = winnerAddresses[winnerIndexes[j]];
if(winner != address(0) && winner == player) {
isWinner = true;
break;
}
}
if(isWinner) {
// _burn(address(msg.sender), lotteryConfig.registrationAmount);
// lotteryToken.burnFrom(msg.sender, lotteryConfig.registrationAmount);
if(isOnlyETHAccepted) {
(bool status, ) = payable(player).call{value: rewardPoolAmount}("");
require(status, "Amount not transferred to winner");
} else {
buyToken.transfer(address(player), rewardPoolAmount);
}
winnerAddresses[winnerIndexes[i]] = address(0);
} else {
lotteryToken.mint(player, lotteryConfig.registrationAmount);
}
isWinner = false;
}
resetLottery();
}
/**
* @dev Generates a random number based on the blockHash and random offset
*/
function getRandomNumberBlockchain(uint256 offset, uint256 randomness)
internal
view
returns (uint256)
{
bytes32 offsetBlockhash = blockhash(block.number.sub(offset));
uint256 randomBlockchainNumber = uint256(offsetBlockhash);
uint256 finalRandomNumber = randomness + randomBlockchainNumber;
if (finalRandomNumber >= randomness) {
return finalRandomNumber;
} else {
if (randomness >= randomBlockchainNumber) {
return randomness.sub(randomBlockchainNumber);
}
return randomBlockchainNumber.sub(randomness);
}
}
/**
* @dev Resets the lottery, clears the existing state variable values and the lottery
* can be initialized again.
*
* Emits {LotteryReset} event indicating that the lottery config and contract state is reset.
*
* Requirements:
*
* - Only the address set at `adminAddress` can call this function.
* - The Lottery has closed.
*/
function resetLottery() private {
// require(
// msg.sender == adminAddress,
// "Resetting the Lottery requires Admin Access"
// );
// require(
// lotteryStatus == LotteryStatus.CLOSED,
// "Lottery Still in Progress"
// );
uint256 tokenBalance = lotteryToken.balanceOf(address(this));
if (tokenBalance > 0) {
buyToken.transfer(adminAddress, tokenBalance);
}
delete lotteryConfig;
delete randomResult;
delete lotteryStatus;
delete totalLotteryPool;
delete adminFeesAmount;
delete rewardPoolAmount;
for (uint256 i = 0; i < lotteryPlayers.length; i = i.add(1)) {
delete winnerAddresses[i];
}
isRandomNumberGenerated = false;
areWinnersGenerated = false;
delete winnerIndexes;
delete lotteryPlayers;
emit LotteryReset();
}
}