-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransitions.ts
622 lines (526 loc) · 15.1 KB
/
transitions.ts
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
import { SolidityType, Transitions } from "@stackr/sdk/machine";
import { League, LeagueState } from "./state";
export enum LogAction {
GOAL = "GOAL",
BLOCK = "BLOCK",
DELETED_GOAL = "DELETED_GOAL",
PENALTY_HIT = "PENALTY_HIT", // in case of a overtime (penalty shootout)
PENALTY_MISS = "PENALTY_MISS", // in case of a overtime (penalty shootout)
FOUL = "FOUL",
}
export type LeaderboardEntry = {
won: number;
lost: number;
byes: number;
points: number;
id: number;
name: string;
};
export const canAddressSubmitAction = (
state: LeagueState,
address: string
): boolean => {
return state.admins.includes(address);
};
const areAllMatchesComplete = (state: LeagueState) => {
return state.matches.every((m) => m.endTime);
};
const hasTournamentEnded = (state: LeagueState) => {
return state.meta.winnerTeamId !== 0 && state.meta.endTime !== 0;
};
const getPlayerToTeam = (state: LeagueState) => {
return state.players.reduce((acc, p) => {
acc[p.id] = p.teamId;
return acc;
}, {} as Record<number, number>);
};
export const getLeaderboard = (state: LeagueState): LeaderboardEntry[] => {
const { teams, matches, meta } = state;
const completedMatches = matches.filter((m) => m.endTime);
const leaderboard = teams.map((team) => ({
...team,
won: 0,
lost: 0,
byes: 0,
points: 0,
}));
// a bye is given 1 point
meta.byes.forEach((bye) => {
const teamIndex = leaderboard.findIndex((l) => l.id === bye.teamId);
leaderboard[teamIndex].byes += 1;
leaderboard[teamIndex].points += 1;
});
completedMatches.forEach((match) => {
const { winnerTeamId, scores } = match;
const loserTeamId = Object.keys(scores).find((k) => +k !== winnerTeamId);
if (!loserTeamId) {
return;
}
const winnerIndex = leaderboard.findIndex((l) => l.id === +winnerTeamId);
const loserIndex = leaderboard.findIndex((l) => l.id === +loserTeamId);
leaderboard[winnerIndex].won += 1;
leaderboard[loserIndex].lost += 1;
leaderboard[winnerIndex].points += 3;
});
return leaderboard.sort((a, b) => {
if (a.points === b.points) {
if (a.won === b.won) {
return a.byes - b.byes; // Sort by most byes last
}
return b.won - a.won; // Sort by most wins first
}
return b.points - a.points; // Sort by most points first
});
};
const getTopNTeams = (state: LeagueState, n?: number) => {
if (!n) {
n = state.teams.length;
}
const leaderboard = getLeaderboard(state);
return leaderboard.slice(0, n);
};
const getTeamsInCurrentRound = (state: LeagueState) => {
const { meta, teams } = state;
const totalTeams = teams.length;
// Calculate the number of teams in the current round by halving the teams each round
const numTeamsInCurrentRound = Math.ceil(
totalTeams / Math.pow(2, meta.round)
);
const topTeams = getTopNTeams(state, numTeamsInCurrentRound);
return topTeams;
};
const isByeRequiredInCurrentRound = (state: LeagueState): boolean => {
const { meta } = state;
// If the tournament has ended or not all matches are complete, return false
if (!areAllMatchesComplete(state) || !!meta.endTime) {
return false;
}
const teamsInCurrentRound = getTeamsInCurrentRound(state);
// If only one team is left, return false
if (teamsInCurrentRound.length === 1) {
return false;
}
// If the number of remaining teams is odd, check if a bye is required
if (teamsInCurrentRound.length % 2 !== 0) {
const allTeamsHaveSamePoints = teamsInCurrentRound.every(
(t, _, arr) => t.points === arr[0].points
);
// If all teams have the same points, return true
if (allTeamsHaveSamePoints) {
return true;
}
}
return false;
};
const computeMatchFixtures = (state: LeagueState, blockTime: number) => {
const { meta, teams } = state;
// If the tournament has ended, return without scheduling matches
if (!areAllMatchesComplete(state) || !!meta.endTime) {
return;
}
const totalTeams = teams.length;
// Calculate the number of teams in the current round by halving the teams each round
const teamsInCurrentRound = Math.ceil(totalTeams / Math.pow(2, meta.round));
// this is assuming that the bye will be given to the team with lower score, and they'll get a chance to play with the top 3 teams
const shouldIncludeOneBye =
teamsInCurrentRound !== 1 &&
teamsInCurrentRound % 2 === 1 &&
meta.byes.filter(({ round }) => round === meta.round).length === 1
? 1
: 0;
const topTeams = getTopNTeams(
state,
teamsInCurrentRound + shouldIncludeOneBye
);
// If only one team is left, declare it the winner and end the tournament
if (topTeams.length === 1) {
state.meta.winnerTeamId = topTeams[0].id;
state.meta.endTime = blockTime;
return;
}
// If the number of top teams is odd, handle the odd team out
if (topTeams.length % 2 !== 0) {
const allTeamsHaveSamePoints =
topTeams[0].points === topTeams[teamsInCurrentRound - 1].points;
// If all teams have the same points, return without scheduling matches
// This situation requires a bye to be given in current round
if (allTeamsHaveSamePoints) {
return;
}
const oneTeamHasHigherPoints =
topTeams[0].points > topTeams[1].points &&
topTeams[0].points > topTeams[2].points;
// Remove the team with the highest points to ensure competitive balance
// Otherwise, remove the team with the lowest points
if (oneTeamHasHigherPoints) {
topTeams.shift();
} else {
topTeams.pop();
}
}
// Generate match fixtures for the remaining teams
for (let i = 0; i < topTeams.length; i += 2) {
const team1 = topTeams[i];
const team2 = topTeams[i + 1];
state.matches.push({
id: state.matches.length + 1,
scores: { [team1.id]: 0, [team2.id]: 0 },
startTime: 0,
endTime: 0,
penaltyStartTime: 0,
winnerTeamId: 0,
});
}
// Increment round
state.meta.round += 1;
};
const getValidMatchAndTeam = (
state: LeagueState,
matchId: number,
playerId: number
) => {
if (hasTournamentEnded(state)) {
throw new Error("TOURNAMENT_ENDED");
}
const match = state.matches.find((m) => m.id === matchId);
if (!match) {
throw new Error("MATCH_NOT_FOUND");
}
if (!match.startTime) {
throw new Error("MATCH_NOT_STARTED");
}
if (match.endTime) {
throw new Error("MATCH_ENDED");
}
const player = state.players.find((p) => p.id === playerId);
if (!player) {
throw new Error("PLAYER_NOT_FOUND");
}
const teams = Object.keys(match.scores);
const teamId = player.teamId;
if (!teams.includes(String(teamId))) {
throw new Error("INVALID_TEAM");
}
return { match, teamId };
};
const logPlayerAction = (
state: LeagueState,
matchId: number,
playerId: number,
action: LogAction,
timestamp: number
) => {
getValidMatchAndTeam(state, matchId, playerId);
state.logs.push({
playerId,
matchId,
timestamp,
action,
});
};
// State Transition Functions
const startTournament = League.STF({
schema: {
timestamp: SolidityType.UINT, // nonce
},
handler: ({ state, block }) => {
if (hasTournamentEnded(state)) {
throw new Error("TOURNAMENT_ALREADY_ENDED");
}
if (state.meta.round !== 0) {
throw new Error("TOURNAMENT_ALREADY_STARTED");
}
computeMatchFixtures(state, block.timestamp);
state.meta.startTime = block.timestamp;
return state;
},
});
const startMatch = League.STF({
schema: {
matchId: SolidityType.UINT,
timestamp: SolidityType.UINT, // nonce
},
handler: ({ state, inputs, block }) => {
if (hasTournamentEnded(state)) {
throw new Error("TOURNAMENT_ENDED");
}
const { matchId } = inputs;
const match = state.matches.find((m) => m.id === matchId);
if (!match) {
throw new Error("MATCH_NOT_FOUND");
}
if (match.startTime) {
throw new Error("MATCH_ALREADY_STARTED");
}
match.startTime = block.timestamp;
return state;
},
});
const penaltyShootout = League.STF({
schema: {
matchId: SolidityType.UINT,
timestamp: SolidityType.UINT, // nonce
},
handler: ({ state, inputs, block }) => {
if (hasTournamentEnded(state)) {
throw new Error("TOURNAMENT_ENDED");
}
const { matchId } = inputs;
const match = state.matches.find((m) => m.id === matchId);
if (!match) {
throw new Error("MATCH_NOT_FOUND");
}
if (!match.startTime) {
throw new Error("MATCH_NOT_STARTED");
}
if (match.penaltyStartTime) {
throw new Error("SHOOTOUT_ALREADY_STARTED");
}
const [a, b] = Object.keys(match.scores);
if (match.scores[a] !== match.scores[b]) {
throw new Error("SCORES_NOT_EQUAL");
}
match.penaltyStartTime = block.timestamp;
return state;
},
});
const logGoal = League.STF({
schema: {
matchId: SolidityType.UINT,
playerId: SolidityType.UINT,
timestamp: SolidityType.UINT, // nonce
},
handler: ({ state, inputs, block }) => {
const { matchId, playerId } = inputs;
const { match, teamId } = getValidMatchAndTeam(state, matchId, playerId);
match.scores[teamId] += 1;
state.logs.push({
playerId,
matchId,
timestamp: block.timestamp,
action: LogAction.GOAL,
});
return state;
},
});
const removeGoal = League.STF({
schema: {
matchId: SolidityType.UINT,
playerId: SolidityType.UINT,
timestamp: SolidityType.UINT, // nonce
},
handler: ({ state, inputs, block }) => {
const { matchId, playerId } = inputs;
const { match, teamId } = getValidMatchAndTeam(state, matchId, playerId);
if (match.scores[teamId] === 0) {
throw new Error("NO_GOALS_TO_REMOVE");
}
const correspondingGoalIdx = state.logs.findIndex(
(l) =>
l.matchId === matchId &&
l.playerId === playerId &&
l.action === LogAction.GOAL
);
if (correspondingGoalIdx === -1) {
throw new Error("NO_GOALS_TO_REMOVE");
}
match.scores[teamId] -= 1;
state.logs.push({
playerId,
matchId,
timestamp: block.timestamp,
action: LogAction.DELETED_GOAL,
});
return state;
},
});
const endMatch = League.STF({
schema: {
matchId: SolidityType.UINT,
timestamp: SolidityType.UINT, // nonce
},
handler: ({ state, inputs, block }) => {
if (hasTournamentEnded(state)) {
throw new Error("TOURNAMENT_ENDED");
}
const { matchId } = inputs;
const { matches, logs } = state;
const match = matches.find((m) => m.id === matchId);
if (!match) {
throw new Error("MATCH_NOT_FOUND");
}
if (!match.startTime) {
throw new Error("MATCH_NOT_STARTED");
}
if (match.endTime) {
throw new Error("MATCH_ALREADY_ENDED");
}
const teamScores = { ...match.scores };
if (match.penaltyStartTime) {
const playerIdToTeamId = getPlayerToTeam(state);
const penalties = logs.filter(
(l) => l.matchId === matchId && l.action === LogAction.PENALTY_HIT
);
for (const penalty of penalties) {
const teamId = playerIdToTeamId[penalty.playerId];
teamScores[teamId] += 1;
}
}
const [a, b] = Object.keys(teamScores);
if (teamScores[a] === teamScores[b]) {
throw new Error("MATCH_NOT_CONCLUDED");
}
const winner = teamScores[a] > teamScores[b] ? a : b;
match.winnerTeamId = +winner;
match.endTime = block.timestamp;
computeMatchFixtures(state, block.timestamp);
return state;
},
});
const logPenaltyHit = League.STF({
schema: {
matchId: SolidityType.UINT,
playerId: SolidityType.UINT,
timestamp: SolidityType.UINT, // nonce
},
handler: ({ state, inputs, block }) => {
const { matchId, playerId } = inputs;
const { match } = getValidMatchAndTeam(state, matchId, playerId);
if (!match.penaltyStartTime) {
throw new Error("PENALTY_NOT_STARTED");
}
state.logs.push({
playerId,
matchId,
timestamp: block.timestamp,
action: LogAction.PENALTY_HIT,
});
return state;
},
});
const logPenaltyMiss = League.STF({
schema: {
matchId: SolidityType.UINT,
playerId: SolidityType.UINT,
timestamp: SolidityType.UINT, // nonce
},
handler: ({ state, inputs, block }) => {
const { matchId, playerId } = inputs;
const { match } = getValidMatchAndTeam(state, matchId, playerId);
if (!match.penaltyStartTime) {
throw new Error("PENALTY_NOT_STARTED");
}
state.logs.push({
playerId,
matchId,
timestamp: block.timestamp,
action: LogAction.PENALTY_MISS,
});
return state;
},
});
const logBlock = League.STF({
schema: {
matchId: SolidityType.UINT,
playerId: SolidityType.UINT,
timestamp: SolidityType.UINT, // nonce
},
handler: ({ state, inputs, block }) => {
const { matchId, playerId } = inputs;
logPlayerAction(state, matchId, playerId, LogAction.BLOCK, block.timestamp);
return state;
},
});
const logFoul = League.STF({
schema: {
matchId: SolidityType.UINT,
playerId: SolidityType.UINT,
timestamp: SolidityType.UINT, // nonce
},
handler: ({ state, inputs, block }) => {
const { matchId, playerId } = inputs;
logPlayerAction(state, matchId, playerId, LogAction.FOUL, block.timestamp);
return state;
},
});
const logByes = League.STF({
schema: {
teamId: SolidityType.UINT,
timestamp: SolidityType.UINT, // nonce
},
handler: ({ state, inputs, block }) => {
const { teamId } = inputs;
if (hasTournamentEnded(state)) {
throw new Error("TOURNAMENT_ENDED");
}
// Is Bye required in the current round?
if (!isByeRequiredInCurrentRound(state)) {
throw new Error("BYE_NOT_REQUIRED_IN_THIS_ROUND");
}
state.meta.byes.push({ teamId, round: state.meta.round });
computeMatchFixtures(state, block.timestamp);
return state;
},
});
const addPlayer = League.STF({
schema: {
teamId: SolidityType.UINT,
playerName: SolidityType.STRING,
timestamp: SolidityType.UINT, // nonce
},
handler: ({ state, inputs }) => {
const { logs } = state;
const { teamId, playerName } = inputs;
const maxPlayerIdFromLogs = logs.reduce((acc, l) => {
if (l.playerId > acc) {
return l.playerId;
}
return acc;
}, 0);
const lastMaxId = Math.max(
state.players.at(-1)?.id || 0,
state.players.length,
maxPlayerIdFromLogs
);
state.players.push({
id: lastMaxId + 1,
name: playerName,
teamId,
});
return state;
},
});
const removePlayer = League.STF({
schema: {
teamId: SolidityType.UINT,
playerId: SolidityType.UINT,
timestamp: SolidityType.UINT, // nonce
},
handler: ({ state, inputs, block }) => {
const { teamId, playerId } = inputs;
const player = state.players.find((p) => p.id === playerId);
if (!player) {
throw new Error("PLAYER_NOT_FOUND");
}
if (player.teamId !== teamId) {
throw new Error("INVALID_TEAM");
}
player.removedAt = block.timestamp;
return state;
},
});
export const transitions: Transitions<League> = {
startMatch,
penaltyShootout,
endMatch,
logGoal,
removeGoal,
startTournament,
logByes,
logBlock,
logFoul,
logPenaltyHit,
logPenaltyMiss,
addPlayer,
removePlayer,
};