This repository has been archived by the owner on Jul 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathtic-tac-toe-dashboard.js
263 lines (239 loc) · 6.91 KB
/
tic-tac-toe-dashboard.js
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
/**
*
* The TicTacToe Dashboard class exported by this file is used to interact with the
* on-chain tic-tac-toe dashboard program.
*
* @flow
*/
import invariant from 'assert';
import EventEmitter from 'event-emitter';
import {
Account,
PublicKey,
Transaction,
SystemProgram,
sendAndConfirmRawTransaction,
} from '@solana/web3.js';
import type {AccountInfo, Connection} from '@solana/web3.js';
import {newSystemAccountWithAirdrop} from '../util/new-system-account-with-airdrop';
import {sleep} from '../util/sleep';
import {sendAndConfirmTransaction} from '../util/send-and-confirm-transaction';
import * as ProgramCommand from './program-command';
import {deserializeDashboardState} from './program-state';
import type {DashboardState} from './program-state';
import {TicTacToe} from './tic-tac-toe';
export class TicTacToeDashboard {
state: DashboardState;
connection: Connection;
programId: PublicKey;
publicKey: PublicKey;
_dashboardAccount: Account;
_ee: EventEmitter;
_changeSubscriptionId: number | null;
/**
* @private
*/
constructor(
connection: Connection,
programId: PublicKey,
dashboardAccount: Account,
) {
const {publicKey} = dashboardAccount;
const state = {
pendingGame: null,
completedGames: [],
totalGames: 0,
};
Object.assign(this, {
connection,
programId,
_dashboardAccount: dashboardAccount,
publicKey,
state,
_changeSubscriptionId: connection.onAccountChange(
publicKey,
this._onAccountChange.bind(this),
),
_ee: new EventEmitter(),
});
}
/**
* Creates a new dashboard
*/
static async create(
connection: Connection,
programId: PublicKey,
): Promise<TicTacToeDashboard> {
const tokens = 1000;
const tempAccount = await newSystemAccountWithAirdrop(connection, tokens);
const dashboardAccount = new Account();
const transaction = SystemProgram.createAccount(
tempAccount.publicKey,
dashboardAccount.publicKey,
tokens - 1,
255, // userdata space
programId,
);
transaction.add({
keys: [dashboardAccount.publicKey],
programId,
userdata: ProgramCommand.initDashboard(),
});
await sendAndConfirmTransaction(
'initDashboard',
connection,
transaction,
tempAccount,
dashboardAccount,
);
return new TicTacToeDashboard(connection, programId, dashboardAccount);
}
/**
* Connects to an existing dashboard
*/
static async connect(
connection: Connection,
dashboardAccount: Account,
): Promise<TicTacToeDashboard> {
const accountInfo = await connection.getAccountInfo(
dashboardAccount.publicKey,
);
const {owner} = accountInfo;
const dashboard = new TicTacToeDashboard(
connection,
owner,
dashboardAccount,
);
dashboard.state = deserializeDashboardState(accountInfo);
return dashboard;
}
/**
* @private
*/
_onAccountChange(accountInfo: AccountInfo) {
this.state = deserializeDashboardState(accountInfo);
this._ee.emit('change');
}
/**
* Register a callback for notification when the dashboard state changes
*/
onChange(fn: Function) {
this._ee.on('change', fn);
}
/**
* Remove a previously registered onChange callback
*/
removeChangeListener(fn: Function) {
this._ee.off('change', fn);
}
/**
* Request a partially signed Transaction that will enable the player to
* initiate a Game.
*
* Note: Although the current implementation of this method is inline, in
* production this function would issue an RPC request to a server somewhere
* that hosts the dashboard's secret key.
*
* Upon return, the player must sign the Transaction with their secretKey and
* send it to the cluster.
*/
async _requestPlayerAccountTransaction(
playerPublicKey: PublicKey,
): Promise<Transaction> {
const lastId = await this.connection.getLastId();
let transaction = new Transaction({lastId});
transaction.add(SystemProgram.assign(playerPublicKey, this.programId), {
keys: [this._dashboardAccount.publicKey, playerPublicKey],
programId: this.programId,
userdata: ProgramCommand.initPlayer(),
});
transaction.signPartial(this._dashboardAccount, playerPublicKey);
return transaction;
}
/**
* Finds another player and starts a game
*/
async startGame(): Promise<TicTacToe> {
const playerAccount = new Account();
const transaction = await this._requestPlayerAccountTransaction(
playerAccount.publicKey,
);
transaction.addSigner(playerAccount);
await sendAndConfirmRawTransaction(
this.connection,
transaction.serialize(),
);
let myGame: TicTacToe | null = null;
// Look for pending games from others, while trying to advertise our game.
for (;;) {
if (myGame) {
if (myGame.inProgress) {
// Another player joined our game
console.log(
`Another player accepted our game (${myGame.gamePublicKey.toString()})`,
);
return myGame;
}
if (myGame.disconnected) {
throw new Error('game disconnected');
}
}
const pendingGamePublicKey = this.state.pendingGame;
if (
pendingGamePublicKey !== null &&
(!myGame || !myGame.gamePublicKey.equals(pendingGamePublicKey))
) {
try {
console.log(`Trying to join ${pendingGamePublicKey.toString()}`);
const theirGame = await TicTacToe.join(
this.connection,
this.programId,
this.publicKey,
playerAccount,
pendingGamePublicKey,
);
if (theirGame !== null) {
console.log(`Joined game ${theirGame.gamePublicKey.toString()}`);
if (myGame) {
myGame.abandon();
}
return theirGame;
}
} catch (err) {
console.log(err.message);
}
}
if (!myGame) {
myGame = await TicTacToe.create(
this.connection,
this.programId,
this.publicKey,
playerAccount,
);
}
if (
pendingGamePublicKey === null ||
!myGame.gamePublicKey.equals(pendingGamePublicKey)
) {
// Advertise myGame as the pending game for others to see and join
console.log(
`Advertising our game (${myGame.gamePublicKey.toString()})`,
);
const transaction = new Transaction().add({
keys: [playerAccount.publicKey, this.publicKey, myGame.gamePublicKey],
programId: this.programId,
userdata: ProgramCommand.advertiseGame(),
});
await sendAndConfirmTransaction(
'advertiseGame',
this.connection,
transaction,
playerAccount,
);
}
// Wait for a bite
await sleep(500);
}
invariant(false); //eslint-disable-line no-unreachable
}
}