-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathescrow.ts
More file actions
369 lines (316 loc) · 9.61 KB
/
escrow.ts
File metadata and controls
369 lines (316 loc) · 9.61 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
import type { WalletContextState } from '@solana/wallet-adapter-react'
import { Buffer } from 'buffer'
import {
Connection,
LAMPORTS_PER_SOL,
PublicKey,
SystemProgram,
Transaction,
TransactionInstruction,
} from '@solana/web3.js'
import type { PilotId } from '../game/types'
import env from '../config/env'
const ROOM_SEED_PREFIX = 'match'
const INITIALIZE_MATCH_DISCRIMINATOR = Uint8Array.from([156, 133, 52, 179, 176, 29, 64, 124])
const JOIN_MATCH_DISCRIMINATOR = Uint8Array.from([244, 8, 47, 130, 192, 59, 179, 44])
const DEFAULT_PUBKEY_STRING = new PublicKey(new Uint8Array(32)).toBase58()
export interface EscrowStatus {
liveEscrowReady: boolean
liveSettlementReady: boolean
programId: string | null
arbiter: string | null
note: string
}
export interface StakeApprovalOptions {
connection: Connection
sendTransaction: WalletContextState['sendTransaction']
walletPublicKey: PublicKey
roomCode: string
stakeSol: number
localPilotId: PilotId
creatorWallet: string | null
}
export interface StakeApprovalResult {
txLabel: string
simulated: false
escrowAddress: string
creatorWallet: string
role: 'creator' | 'opponent'
}
export interface MatchEscrowAccountState {
escrowAddress: string
creator: string
opponent: string | null
winner: string | null
arbiter: string
roomCode: string
stakeLamports: number
status: number
}
function requireEscrowProgramId() {
if (!env.escrowProgramId) {
throw new Error('Set VITE_ESCROW_PROGRAM_ID to your deployed devnet escrow program.')
}
return new PublicKey(env.escrowProgramId)
}
function getConfiguredArbiterPublicKey() {
if (env.matchArbiter) {
return new PublicKey(env.matchArbiter)
}
return null
}
function normalizeRoomCode(roomCode: string) {
const normalized = roomCode.trim().toUpperCase()
if (!normalized) {
throw new Error('Room code is missing.')
}
if (encodeUtf8(normalized).length > 16) {
throw new Error('Room code must be 16 characters or fewer for the escrow PDA.')
}
return normalized
}
function encodeUtf8(value: string) {
return new TextEncoder().encode(value)
}
function encodeString(value: string) {
const data = encodeUtf8(value)
const length = Buffer.alloc(4)
length.writeUInt32LE(data.length, 0)
return Buffer.concat([length, Buffer.from(data)])
}
function encodeU64(value: number) {
const encoded = Buffer.alloc(8)
let remaining = BigInt(value)
for (let index = 0; index < 8; index += 1) {
encoded[index] = Number(remaining & 0xffn)
remaining >>= 8n
}
return encoded
}
function getStakeLamports(stakeSol: number) {
const lamports = Math.round(stakeSol * LAMPORTS_PER_SOL)
if (lamports <= 0) {
throw new Error('Stake must be greater than zero.')
}
return lamports
}
function buildInitializeMatchInstruction(options: {
creator: PublicKey
arbiter: PublicKey
escrowAddress: PublicKey
roomCode: string
stakeLamports: number
programId: PublicKey
}) {
const data = Buffer.concat([
Buffer.from(INITIALIZE_MATCH_DISCRIMINATOR),
encodeString(options.roomCode),
encodeU64(options.stakeLamports),
])
return new TransactionInstruction({
programId: options.programId,
keys: [
{ pubkey: options.creator, isSigner: true, isWritable: true },
{ pubkey: options.arbiter, isSigner: false, isWritable: false },
{ pubkey: options.escrowAddress, isSigner: false, isWritable: true },
{ pubkey: SystemProgram.programId, isSigner: false, isWritable: false },
],
data,
})
}
function buildJoinMatchInstruction(options: {
opponent: PublicKey
escrowAddress: PublicKey
programId: PublicKey
}) {
return new TransactionInstruction({
programId: options.programId,
keys: [
{ pubkey: options.opponent, isSigner: true, isWritable: true },
{ pubkey: options.escrowAddress, isSigner: false, isWritable: true },
{ pubkey: SystemProgram.programId, isSigner: false, isWritable: false },
],
data: Buffer.from(JOIN_MATCH_DISCRIMINATOR),
})
}
export function deriveMatchEscrowAddress(creatorWallet: string, roomCode: string) {
const programId = requireEscrowProgramId()
const creator = new PublicKey(creatorWallet)
const normalizedRoomCode = normalizeRoomCode(roomCode)
return PublicKey.findProgramAddressSync(
[
Buffer.from(ROOM_SEED_PREFIX),
creator.toBuffer(),
Buffer.from(normalizedRoomCode),
],
programId,
)[0]
}
export function getEscrowStatus(): EscrowStatus {
const arbiterPublicKey = getConfiguredArbiterPublicKey()
const depositsReady = Boolean(env.escrowProgramId && arbiterPublicKey)
const settlementReady = Boolean(
env.escrowProgramId &&
arbiterPublicKey &&
env.matchStateProgramId,
)
if (settlementReady) {
return {
liveEscrowReady: true,
liveSettlementReady: true,
programId: env.escrowProgramId || null,
arbiter: arbiterPublicKey?.toBase58() ?? null,
note: 'Real devnet escrow is live. Deposits happen on-chain and payout can route through the secure match service.',
}
}
if (depositsReady) {
return {
liveEscrowReady: true,
liveSettlementReady: false,
programId: env.escrowProgramId || null,
arbiter: arbiterPublicKey?.toBase58() ?? null,
note: 'Real devnet deposits are ready, but secure payout still needs the deployed match-state program.',
}
}
return {
liveEscrowReady: false,
liveSettlementReady: false,
programId: env.escrowProgramId || null,
arbiter: arbiterPublicKey?.toBase58() ?? null,
note: 'Escrow is not configured. Set VITE_ESCROW_PROGRAM_ID and VITE_MATCH_ARBITER for real devnet staking.',
}
}
function decodePubkey(data: Buffer, offset: number) {
return {
value: new PublicKey(data.subarray(offset, offset + 32)).toBase58(),
offset: offset + 32,
}
}
function decodeString(data: Buffer, offset: number) {
const length = data.readUInt32LE(offset)
const start = offset + 4
const end = start + length
return {
value: Buffer.from(data.subarray(start, end)).toString('utf8'),
offset: end,
}
}
function decodeU64(data: Buffer, offset: number) {
return {
value: Number(data.readBigUInt64LE(offset)),
offset: offset + 8,
}
}
function maybePubkey(value: string) {
return value === DEFAULT_PUBKEY_STRING ? null : value
}
export async function fetchEscrowAccountState(
connection: Connection,
creatorWallet: string,
roomCode: string,
): Promise<MatchEscrowAccountState | null> {
const escrowAddress = deriveMatchEscrowAddress(creatorWallet, roomCode)
const accountInfo = await connection.getAccountInfo(escrowAddress, 'confirmed')
if (!accountInfo) {
return null
}
const data = Buffer.from(accountInfo.data)
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 decodedRoomCode = decodeString(data, offset)
offset = decodedRoomCode.offset
const stakeLamports = decodeU64(data, offset)
offset = stakeLamports.offset
const status = data.readUInt8(offset)
return {
escrowAddress: escrowAddress.toBase58(),
creator: creator.value,
opponent: maybePubkey(opponent.value),
winner: maybePubkey(winner.value),
arbiter: arbiter.value,
roomCode: decodedRoomCode.value,
stakeLamports: stakeLamports.value,
status,
}
}
export async function requestStakeApproval({
connection,
sendTransaction,
walletPublicKey,
roomCode,
stakeSol,
localPilotId,
creatorWallet,
}: StakeApprovalOptions): Promise<StakeApprovalResult> {
const status = getEscrowStatus()
if (!status.liveEscrowReady) {
throw new Error(status.note)
}
const programId = requireEscrowProgramId()
const arbiter = getConfiguredArbiterPublicKey()
if (!arbiter) {
throw new Error('VITE_MATCH_ARBITER must be configured for real devnet deposits.')
}
const normalizedRoomCode = normalizeRoomCode(roomCode)
const stakeLamports = getStakeLamports(stakeSol)
const creatorPublicKey =
localPilotId === 'blue'
? walletPublicKey
: creatorWallet
? new PublicKey(creatorWallet)
: null
if (!creatorPublicKey) {
throw new Error('Host wallet is missing. Wait for the room host to sync before staking.')
}
const escrowAddress = deriveMatchEscrowAddress(
creatorPublicKey.toBase58(),
normalizedRoomCode,
)
const transaction = new Transaction()
const accountInfo = await connection.getAccountInfo(escrowAddress, 'confirmed')
if (localPilotId === 'blue') {
if (accountInfo) {
throw new Error('This room already has an escrow PDA. Create a fresh room code before staking again.')
}
transaction.add(
buildInitializeMatchInstruction({
creator: walletPublicKey,
arbiter,
escrowAddress,
roomCode: normalizedRoomCode,
stakeLamports,
programId,
}),
)
} else {
if (!accountInfo) {
throw new Error('The host must lock their stake first so the escrow account exists on devnet.')
}
transaction.add(
buildJoinMatchInstruction({
opponent: walletPublicKey,
escrowAddress,
programId,
}),
)
}
const signature = await sendTransaction(transaction, connection, {
preflightCommitment: 'confirmed',
maxRetries: 3,
})
await connection.confirmTransaction(signature, 'confirmed')
return {
txLabel: signature,
simulated: false,
escrowAddress: escrowAddress.toBase58(),
creatorWallet: creatorPublicKey.toBase58(),
role: localPilotId === 'blue' ? 'creator' : 'opponent',
}
}