1
- import { STF , Transitions } from "@stackr/sdk/machine" ;
1
+ import { REQUIRE , STF , Transitions } from "@stackr/sdk/machine" ;
2
2
import { hashMessage } from "ethers" ;
3
3
import { ACTIONS , GameMode } from "../../client/game/gameMode" ;
4
4
import { World } from "../../client/game/world" ;
5
5
import { AppState } from "./machine" ;
6
6
7
- export type CreateGame = {
7
+ export type StartGameInput = {
8
8
timestamp : number ;
9
9
} ;
10
10
11
- export type ValidateGameInput = {
12
- gameId : number ;
11
+ export type EndGameInput = {
12
+ gameId : string ;
13
+ timestamp : number ;
13
14
score : number ;
14
15
gameInputs : string ;
15
16
} ;
16
17
17
- const startGame : STF < AppState , ValidateGameInput > = {
18
+ const startGame : STF < AppState , StartGameInput > = {
18
19
handler : ( { state, msgSender, block, emit } ) => {
19
20
const gameId = hashMessage (
20
21
`${ msgSender } ::${ block . timestamp } ::${ Object . keys ( state . games ) . length } `
21
22
) ;
22
23
23
24
state . games [ gameId ] = {
24
- id : gameId ,
25
25
score : 0 ,
26
- player : msgSender ,
26
+ player : String ( msgSender ) ,
27
27
} ;
28
28
29
29
emit ( {
@@ -34,22 +34,15 @@ const startGame: STF<AppState, ValidateGameInput> = {
34
34
} ,
35
35
} ;
36
36
37
- const endGame : STF < AppState , ValidateGameInput > = {
37
+ const endGame : STF < AppState , EndGameInput > = {
38
38
handler : ( { state, inputs, msgSender } ) => {
39
39
const { gameInputs, gameId, score } = inputs ;
40
40
const { games } = state ;
41
- if ( ! games [ gameId ] ) {
42
- throw new Error ( "Game not found" ) ;
43
- }
44
-
45
- if ( games [ gameId ] . score > 0 ) {
46
- throw new Error ( "Game already ended" ) ;
47
- }
48
-
49
- if ( games [ gameId ] . player !== msgSender ) {
50
- throw new Error ( "Unauthorized to end game" ) ;
51
- }
52
-
41
+ // validation checks
42
+ REQUIRE ( ! ! games [ gameId ] , "GAME_NOT_FOUND" ) ;
43
+ REQUIRE ( games [ gameId ] . score === 0 , "GAME_ALREADY_ENDED" ) ;
44
+ REQUIRE ( games [ gameId ] . player === String ( msgSender ) , "UNAUTHORIZED" ) ;
45
+ // rerun game loop
53
46
const world = new World ( ) ;
54
47
const gameMode = new GameMode ( world , { gameId } ) ;
55
48
const ticks = gameInputs
@@ -60,9 +53,10 @@ const endGame: STF<AppState, ValidateGameInput> = {
60
53
gameMode . deserializeAndUpdate ( 1 / 60 , ticks [ i ] ) ;
61
54
}
62
55
63
- if ( world . score !== score ) {
64
- throw new Error ( `Failed to replay: ${ world . score } !== ${ score } ` ) ;
65
- }
56
+ REQUIRE (
57
+ world . score === score ,
58
+ `FAILED_TO_REPLAY: ${ world . score } !== ${ score } `
59
+ ) ;
66
60
67
61
games [ gameId ] . score = score ;
68
62
0 commit comments