-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmatchApi.ts
More file actions
613 lines (523 loc) · 16.9 KB
/
matchApi.ts
File metadata and controls
613 lines (523 loc) · 16.9 KB
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
import { createHash } from 'node:crypto'
import { Buffer } from 'node:buffer'
import {
Connection,
Keypair,
LAMPORTS_PER_SOL,
PublicKey,
sendAndConfirmTransaction,
SystemProgram,
Transaction,
TransactionInstruction,
} from '@solana/web3.js'
const encoder = new TextEncoder()
const ROOM_SEED_PREFIX = 'match'
const MATCH_STATE_SEED_PREFIX = 'match-state'
const INITIALIZE_MATCH_STATE_DISCRIMINATOR = Uint8Array.from([64, 45, 172, 116, 28, 184, 229, 69])
const ARM_MATCH_DISCRIMINATOR = Uint8Array.from([65, 91, 197, 24, 239, 18, 235, 41])
const FINISH_MATCH_DISCRIMINATOR = Uint8Array.from([65, 193, 5, 71, 16, 64, 11, 186])
const SETTLE_MATCH_DISCRIMINATOR = Uint8Array.from([71, 124, 117, 96, 191, 217, 116, 24])
const MATCH_ESCROW_ACCOUNT_DISCRIMINATOR = accountDiscriminator('MatchEscrow')
const MATCH_STATE_ACCOUNT_DISCRIMINATOR = accountDiscriminator('MatchStateAccount')
export interface MatchPrepareRequest {
roomCode: string
creatorWallet: string
opponentWallet: string
stakeSol: number
startTimeMs: number
}
export interface MatchFinalizeRequest {
roomCode: string
creatorWallet: string
winnerWallet: string
reason: 'hp' | 'disconnect' | 'timeout'
}
class HttpError extends Error {
status: number
constructor(status: number, message: string) {
super(message)
this.status = status
}
}
function accountDiscriminator(name: string) {
return createHash('sha256')
.update(`account:${name}`)
.digest()
.subarray(0, 8)
}
function normalizeRoomCode(roomCode: string) {
const normalized = roomCode.trim().toUpperCase()
if (!normalized) {
throw new HttpError(400, 'Room code is required.')
}
if (encoder.encode(normalized).length > 16) {
throw new HttpError(400, 'Room code must be 16 characters or fewer.')
}
return normalized
}
function parseSecretKey(value: string) {
const trimmed = value.trim()
if (!trimmed) return null
try {
const parsed = JSON.parse(trimmed)
if (Array.isArray(parsed)) {
return Uint8Array.from(parsed.map((entry) => Number(entry)))
}
} catch {
// Fall through to comma-separated parsing.
}
const commaSeparated = trimmed
.split(',')
.map((entry) => entry.trim())
.filter(Boolean)
if (!commaSeparated.length) return null
return Uint8Array.from(commaSeparated.map((entry) => Number(entry)))
}
function getServerEnv() {
const solanaRpcHttp =
process.env.VITE_SOLANA_RPC_HTTP ?? 'https://api.devnet.solana.com'
const solanaCluster = process.env.VITE_SOLANA_CLUSTER ?? 'devnet'
const escrowProgramId = process.env.VITE_ESCROW_PROGRAM_ID ?? ''
const matchStateProgramId = process.env.VITE_MATCH_STATE_PROGRAM_ID ?? ''
const matchArbiter = process.env.VITE_MATCH_ARBITER ?? ''
const matchArbiterSecretKey = process.env.MATCH_ARBITER_SECRET_KEY ?? ''
if (!escrowProgramId) {
throw new HttpError(500, 'Server settlement is missing VITE_ESCROW_PROGRAM_ID.')
}
if (!matchStateProgramId) {
throw new HttpError(500, 'Server settlement is missing VITE_MATCH_STATE_PROGRAM_ID.')
}
if (!matchArbiter) {
throw new HttpError(500, 'Server settlement is missing VITE_MATCH_ARBITER.')
}
const parsedSecretKey = parseSecretKey(matchArbiterSecretKey)
if (!parsedSecretKey?.length) {
throw new HttpError(500, 'Server settlement is missing MATCH_ARBITER_SECRET_KEY.')
}
return {
solanaRpcHttp,
solanaCluster,
escrowProgramId: new PublicKey(escrowProgramId),
matchStateProgramId: new PublicKey(matchStateProgramId),
matchArbiter: new PublicKey(matchArbiter),
matchArbiterKeypair: Keypair.fromSecretKey(parsedSecretKey),
}
}
function getConnection() {
const env = getServerEnv()
return new Connection(env.solanaRpcHttp, 'confirmed')
}
function encodeString(value: string) {
const data = Buffer.from(encoder.encode(value))
const length = Buffer.alloc(4)
length.writeUInt32LE(data.length, 0)
return Buffer.concat([length, data])
}
function encodeU64(value: bigint) {
const data = Buffer.alloc(8)
data.writeBigUInt64LE(value, 0)
return data
}
function encodeI64(value: bigint) {
const data = Buffer.alloc(8)
data.writeBigInt64LE(value, 0)
return data
}
function encodeBool(value: boolean) {
return Buffer.from([value ? 1 : 0])
}
function decodeString(data: Buffer, offset: number) {
const length = data.readUInt32LE(offset)
const start = offset + 4
const end = start + length
return {
value: data.subarray(start, end).toString('utf8'),
offset: end,
}
}
function decodePubkey(data: Buffer, offset: number) {
return {
value: new PublicKey(data.subarray(offset, offset + 32)),
offset: offset + 32,
}
}
function decodeU64(data: Buffer, offset: number) {
return {
value: data.readBigUInt64LE(offset),
offset: offset + 8,
}
}
function decodeI64(data: Buffer, offset: number) {
return {
value: data.readBigInt64LE(offset),
offset: offset + 8,
}
}
function assertDiscriminator(data: Buffer, discriminator: Buffer, label: string) {
if (!data.subarray(0, 8).equals(discriminator)) {
throw new HttpError(409, `${label} account discriminator mismatch.`)
}
}
function deriveMatchEscrowAddress(creatorWallet: string, roomCode: string) {
const env = getServerEnv()
return PublicKey.findProgramAddressSync(
[
Buffer.from(ROOM_SEED_PREFIX),
new PublicKey(creatorWallet).toBuffer(),
Buffer.from(roomCode),
],
env.escrowProgramId,
)[0]
}
function deriveMatchStateAddress(roomCode: string) {
const env = getServerEnv()
return PublicKey.findProgramAddressSync(
[Buffer.from(MATCH_STATE_SEED_PREFIX), Buffer.from(roomCode)],
env.matchStateProgramId,
)[0]
}
function parseMatchEscrowAccount(data: Buffer) {
assertDiscriminator(data, MATCH_ESCROW_ACCOUNT_DISCRIMINATOR, 'Escrow')
let offset = 8
const creator = decodePubkey(data, offset)
offset = creator.offset
const opponent = decodePubkey(data, offset)
offset = opponent.offset
const winner = decodePubkey(data, offset)
offset = winner.offset
const arbiter = decodePubkey(data, offset)
offset = arbiter.offset
const roomCode = decodeString(data, offset)
offset = roomCode.offset
const stakeLamports = decodeU64(data, offset)
offset = stakeLamports.offset
const status = data.readUInt8(offset)
offset += 1
const bump = data.readUInt8(offset)
return {
creator: creator.value,
opponent: opponent.value,
winner: winner.value,
arbiter: arbiter.value,
roomCode: roomCode.value,
stakeLamports: stakeLamports.value,
status,
bump,
}
}
function parseMatchStateAccount(data: Buffer) {
assertDiscriminator(data, MATCH_STATE_ACCOUNT_DISCRIMINATOR, 'Match state')
let offset = 8
const roomCode = decodeString(data, offset)
offset = roomCode.offset
const authority = decodePubkey(data, offset)
offset = authority.offset
const playerOne = decodePubkey(data, offset)
offset = playerOne.offset
const playerTwo = decodePubkey(data, offset)
offset = playerTwo.offset
const winner = decodePubkey(data, offset)
offset = winner.offset
const stakeLamports = decodeU64(data, offset)
offset = stakeLamports.offset
const stage = data.readUInt8(offset)
offset += 1
const endReason = data.readUInt8(offset)
offset += 1
const matchStartedAtMs = decodeI64(data, offset)
offset = matchStartedAtMs.offset
const updatedAtSlot = decodeU64(data, offset)
return {
roomCode: roomCode.value,
authority: authority.value,
playerOne: playerOne.value,
playerTwo: playerTwo.value,
winner: winner.value,
stakeLamports: stakeLamports.value,
stage,
endReason,
matchStartedAtMs: matchStartedAtMs.value,
updatedAtSlot: updatedAtSlot.value,
}
}
async function ensureFeeBalance(connection: Connection, arbiter: Keypair) {
const balance = await connection.getBalance(arbiter.publicKey, 'confirmed')
const minimumLamports = 0.002 * 1_000_000_000
if (balance >= minimumLamports) {
return
}
throw new HttpError(
503,
`Server arbiter wallet ${arbiter.publicKey.toBase58()} is underfunded for match-state transactions. Fund it on devnet and retry.`,
)
}
async function sendServerTransaction(instructions: TransactionInstruction[]) {
const env = getServerEnv()
const connection = getConnection()
await ensureFeeBalance(connection, env.matchArbiterKeypair)
const transaction = new Transaction()
for (const instruction of instructions) {
transaction.add(instruction)
}
return sendAndConfirmTransaction(
connection,
transaction,
[env.matchArbiterKeypair],
{
commitment: 'confirmed',
preflightCommitment: 'confirmed',
},
)
}
function buildInitializeMatchStateInstruction(options: {
payer: PublicKey
authority: PublicKey
matchStateAddress: PublicKey
roomCode: string
creatorWallet: PublicKey
opponentWallet: PublicKey
stakeLamports: bigint
}) {
const env = getServerEnv()
return new TransactionInstruction({
programId: env.matchStateProgramId,
keys: [
{ pubkey: options.payer, isSigner: true, isWritable: true },
{ pubkey: options.authority, isSigner: false, isWritable: false },
{ pubkey: options.matchStateAddress, isSigner: false, isWritable: true },
{ pubkey: SystemProgram.programId, isSigner: false, isWritable: false },
],
data: Buffer.concat([
Buffer.from(INITIALIZE_MATCH_STATE_DISCRIMINATOR),
encodeString(options.roomCode),
options.creatorWallet.toBuffer(),
options.opponentWallet.toBuffer(),
encodeU64(options.stakeLamports),
]),
})
}
function buildArmMatchInstruction(options: {
authority: PublicKey
matchStateAddress: PublicKey
startTimeMs: bigint
}) {
const env = getServerEnv()
return new TransactionInstruction({
programId: env.matchStateProgramId,
keys: [
{ pubkey: options.authority, isSigner: true, isWritable: false },
{ pubkey: options.matchStateAddress, isSigner: false, isWritable: true },
],
data: Buffer.concat([
Buffer.from(ARM_MATCH_DISCRIMINATOR),
encodeI64(options.startTimeMs),
]),
})
}
function buildFinishMatchInstruction(options: {
authority: PublicKey
matchStateAddress: PublicKey
winner: PublicKey
reasonCode: number
}) {
const env = getServerEnv()
return new TransactionInstruction({
programId: env.matchStateProgramId,
keys: [
{ pubkey: options.authority, isSigner: true, isWritable: false },
{ pubkey: options.matchStateAddress, isSigner: false, isWritable: true },
],
data: Buffer.concat([
Buffer.from(FINISH_MATCH_DISCRIMINATOR),
options.winner.toBuffer(),
Buffer.from([options.reasonCode]),
]),
})
}
function buildSettleMatchInstruction(options: {
arbiter: PublicKey
escrowAddress: PublicKey
matchStateAddress: PublicKey
winner: PublicKey
disconnectWin: boolean
}) {
const env = getServerEnv()
return new TransactionInstruction({
programId: env.escrowProgramId,
keys: [
{ pubkey: options.arbiter, isSigner: true, isWritable: true },
{ pubkey: options.escrowAddress, isSigner: false, isWritable: true },
{ pubkey: options.matchStateAddress, isSigner: false, isWritable: false },
{ pubkey: options.winner, isSigner: false, isWritable: true },
],
data: Buffer.concat([
Buffer.from(SETTLE_MATCH_DISCRIMINATOR),
options.winner.toBuffer(),
encodeBool(options.disconnectWin),
]),
})
}
function mapReasonToCode(reason: MatchFinalizeRequest['reason']) {
if (reason === 'disconnect') return 1
if (reason === 'timeout') return 2
return 0
}
async function getParsedMatchState(roomCode: string) {
const connection = getConnection()
const matchStateAddress = deriveMatchStateAddress(roomCode)
const accountInfo = await connection.getAccountInfo(matchStateAddress, 'confirmed')
if (!accountInfo) {
return {
matchStateAddress,
accountInfo: null,
parsed: null,
}
}
return {
matchStateAddress,
accountInfo,
parsed: parseMatchStateAccount(Buffer.from(accountInfo.data)),
}
}
async function getParsedEscrow(roomCode: string, creatorWallet: string) {
const connection = getConnection()
const escrowAddress = deriveMatchEscrowAddress(creatorWallet, roomCode)
const accountInfo = await connection.getAccountInfo(escrowAddress, 'confirmed')
if (!accountInfo) {
throw new HttpError(404, 'Escrow PDA was not found for this room.')
}
return {
escrowAddress,
parsed: parseMatchEscrowAccount(Buffer.from(accountInfo.data)),
}
}
export async function prepareMatchStateServer(body: MatchPrepareRequest) {
const env = getServerEnv()
const roomCode = normalizeRoomCode(body.roomCode)
const creatorWallet = new PublicKey(body.creatorWallet)
const opponentWallet = new PublicKey(body.opponentWallet)
const stakeLamports = BigInt(Math.round(body.stakeSol * LAMPORTS_PER_SOL))
if (stakeLamports <= 0n) {
throw new HttpError(400, 'Stake must be greater than zero.')
}
if (creatorWallet.equals(opponentWallet)) {
throw new HttpError(400, 'Creator and opponent wallets must be different.')
}
const startTimeMs = BigInt(Math.round(body.startTimeMs))
const { matchStateAddress, parsed } = await getParsedMatchState(roomCode)
let initializeSignature: string | null = null
let armSignature: string | null = null
let currentState = parsed
if (!currentState) {
initializeSignature = await sendServerTransaction([
buildInitializeMatchStateInstruction({
payer: env.matchArbiterKeypair.publicKey,
authority: env.matchArbiterKeypair.publicKey,
matchStateAddress,
roomCode,
creatorWallet,
opponentWallet,
stakeLamports,
}),
])
currentState = (await getParsedMatchState(roomCode)).parsed
}
if (!currentState) {
throw new HttpError(500, 'Match-state account could not be loaded after initialization.')
}
if (
currentState.playerOne.toBase58() !== creatorWallet.toBase58() ||
currentState.playerTwo.toBase58() !== opponentWallet.toBase58()
) {
throw new HttpError(409, 'Match-state pilots do not match the current room wallets.')
}
if (currentState.stakeLamports !== stakeLamports) {
throw new HttpError(409, 'Match-state stake does not match the current room stake.')
}
if (currentState.stage === 0) {
armSignature = await sendServerTransaction([
buildArmMatchInstruction({
authority: env.matchArbiterKeypair.publicKey,
matchStateAddress,
startTimeMs,
}),
])
currentState = (await getParsedMatchState(roomCode)).parsed
}
return {
roomCode,
matchStateAddress: matchStateAddress.toBase58(),
initializeSignature,
armSignature,
stage: currentState?.stage ?? null,
}
}
export async function finalizeMatchServer(body: MatchFinalizeRequest) {
const env = getServerEnv()
const roomCode = normalizeRoomCode(body.roomCode)
const winnerWallet = new PublicKey(body.winnerWallet)
const reasonCode = mapReasonToCode(body.reason)
const { escrowAddress, parsed: escrow } = await getParsedEscrow(roomCode, body.creatorWallet)
const { matchStateAddress, parsed: matchState } = await getParsedMatchState(roomCode)
if (!matchState) {
throw new HttpError(409, 'Match-state PDA is missing for this room. Prepare the room before battle.')
}
if (escrow.roomCode !== roomCode || matchState.roomCode !== roomCode) {
throw new HttpError(409, 'Room code mismatch across escrow and match-state.')
}
if (
matchState.playerOne.toBase58() !== escrow.creator.toBase58() ||
matchState.playerTwo.toBase58() !== escrow.opponent.toBase58()
) {
throw new HttpError(409, 'Escrow pilots and match-state pilots do not match.')
}
if (escrow.status === 2) {
return {
roomCode,
matchStateAddress: matchStateAddress.toBase58(),
escrowAddress: escrowAddress.toBase58(),
finishSignature: null,
settleSignature: null,
alreadySettled: true,
}
}
let finishSignature: string | null = null
if (matchState.stage !== 2) {
finishSignature = await sendServerTransaction([
buildFinishMatchInstruction({
authority: env.matchArbiterKeypair.publicKey,
matchStateAddress,
winner: winnerWallet,
reasonCode,
}),
])
} else if (matchState.winner.toBase58() !== winnerWallet.toBase58()) {
throw new HttpError(409, 'Winner wallet does not match the finished on-chain match-state result.')
}
const settleSignature = await sendServerTransaction([
buildSettleMatchInstruction({
arbiter: env.matchArbiterKeypair.publicKey,
escrowAddress,
matchStateAddress,
winner: winnerWallet,
disconnectWin: body.reason === 'disconnect',
}),
])
return {
roomCode,
matchStateAddress: matchStateAddress.toBase58(),
escrowAddress: escrowAddress.toBase58(),
finishSignature,
settleSignature,
alreadySettled: false,
}
}
export function toHttpError(error: unknown) {
if (error instanceof HttpError) {
return error
}
return new HttpError(
500,
error instanceof Error ? error.message : 'Unexpected match service error.',
)
}