@arken/seer-protocol 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.editorconfig +9 -0
  2. package/.eslintrc +123 -0
  3. package/.prettierrc +12 -0
  4. package/.rush/temp/shrinkwrap-deps.json +420 -0
  5. package/LICENSE +21 -0
  6. package/README.md +3 -0
  7. package/package.json +25 -0
  8. package/src/index.ts +22 -0
  9. package/src/modules/evolution/evolution.models.ts +3 -0
  10. package/src/modules/evolution/evolution.router.ts +3738 -0
  11. package/src/modules/evolution/evolution.schema.ts +1 -0
  12. package/src/modules/evolution/evolution.service.ts +2000 -0
  13. package/src/modules/evolution/evolution.types.ts +20 -0
  14. package/src/modules/evolution/index.ts +5 -0
  15. package/src/modules/infinite/index.ts +5 -0
  16. package/src/modules/infinite/infinite.models.ts +3 -0
  17. package/src/modules/infinite/infinite.router.ts +3648 -0
  18. package/src/modules/infinite/infinite.schema.ts +1 -0
  19. package/src/modules/infinite/infinite.service.ts +40 -0
  20. package/src/modules/infinite/infinite.types.ts +20 -0
  21. package/src/modules/isles/index.ts +5 -0
  22. package/src/modules/isles/isles.models.ts +3 -0
  23. package/src/modules/isles/isles.router.ts +3648 -0
  24. package/src/modules/isles/isles.schema.ts +1 -0
  25. package/src/modules/isles/isles.service.ts +40 -0
  26. package/src/modules/isles/isles.types.ts +20 -0
  27. package/src/modules/oasis/index.ts +5 -0
  28. package/src/modules/oasis/oasis.models.ts +3 -0
  29. package/src/modules/oasis/oasis.router.ts +68 -0
  30. package/src/modules/oasis/oasis.schema.ts +1 -0
  31. package/src/modules/oasis/oasis.service.ts +38 -0
  32. package/src/modules/oasis/oasis.types.ts +20 -0
  33. package/src/modules/trek/index.ts +5 -0
  34. package/src/modules/trek/trek.models.ts +1 -0
  35. package/src/modules/trek/trek.router.ts +78 -0
  36. package/src/modules/trek/trek.schema.ts +1 -0
  37. package/src/modules/trek/trek.service.ts +1031 -0
  38. package/src/modules/trek/trek.types.ts +1 -0
  39. package/src/router.ts +130 -0
  40. package/src/types.ts +106 -0
  41. package/tsconfig.json +25 -0
@@ -0,0 +1,3738 @@
1
+ import { z as zod } from 'zod';
2
+ import { initTRPC } from '@trpc/server';
3
+ import { customErrorFormatter, hasRole } from '@arken/node/util/rpc';
4
+ import * as Arken from '@arken/node';
5
+ import { Query, getQueryInput, inferRouterOutputs, inferRouterInputs } from '@arken/node/schema';
6
+ import { RouterContext } from '../../types';
7
+
8
+ export const z = zod;
9
+ export const t = initTRPC.context<RouterContext>().create();
10
+ export const router = t.router;
11
+ export const procedure = t.procedure;
12
+
13
+ export const createRouter = () =>
14
+ router({
15
+ info: procedure
16
+ .use(customErrorFormatter(t))
17
+ .input(z.any())
18
+ .query(({ input, ctx }) => (ctx.app.service.Evolution.info as any)(input, ctx)),
19
+
20
+ updateConfig: procedure
21
+ .use(hasRole('admin', t))
22
+ .use(customErrorFormatter(t))
23
+ .input(z.any())
24
+ .mutation(({ input, ctx }) => (ctx.app.service.Evolution.updateConfig as any)(input, ctx)),
25
+
26
+ updateGameStats: procedure
27
+ .use(hasRole('admin', t))
28
+ .use(customErrorFormatter(t))
29
+ .mutation(({ input, ctx }) => (ctx.app.service.Evolution.updateGameStats as any)(input, ctx)),
30
+
31
+ monitorChest: procedure
32
+ .use(hasRole('admin', t))
33
+ .use(customErrorFormatter(t))
34
+ .mutation(({ input, ctx }) => (ctx.app.service.Evolution.monitorChest as any)(input, ctx)),
35
+
36
+ monitorParties: procedure
37
+ .use(hasRole('admin', t))
38
+ .use(customErrorFormatter(t))
39
+ .query(({ input, ctx }) => (ctx.app.service.Evolution.monitorParties as any)(input, ctx)),
40
+
41
+ getParties: procedure
42
+ .use(hasRole('user', t))
43
+ .use(customErrorFormatter(t))
44
+ .input(getQueryInput(Arken.Core.Schemas.Party))
45
+ .output(z.array(Arken.Core.Schemas.Party))
46
+ .query(({ input, ctx }) => (ctx.app.service.Evolution.getParties as any)(input, ctx)),
47
+
48
+ createParty: procedure
49
+ .use(hasRole('user', t))
50
+ .use(customErrorFormatter(t))
51
+ .input(getQueryInput(Arken.Core.Schemas.Party))
52
+ .output(Arken.Core.Schemas.Party.pick({ id: true }))
53
+ .mutation(({ input, ctx }) => (ctx.app.service.Evolution.createParty as any)(input, ctx)),
54
+
55
+ joinParty: procedure
56
+ .use(hasRole('user', t))
57
+ .use(customErrorFormatter(t))
58
+ .input(getQueryInput(Arken.Core.Schemas.Party))
59
+ .output(Arken.Core.Schemas.Party.pick({ id: true }))
60
+ .mutation(({ input, ctx }) => (ctx.app.service.Evolution.joinParty as any)(input, ctx)),
61
+
62
+ leaveParty: procedure
63
+ .use(hasRole('user', t))
64
+ .use(customErrorFormatter(t))
65
+ .input(getQueryInput(Arken.Core.Schemas.Party))
66
+ .output(Arken.Core.Schemas.Party.pick({ id: true }))
67
+ .mutation(({ input, ctx }) => (ctx.app.service.Evolution.leaveParty as any)(input, ctx)),
68
+
69
+ updateSettings: procedure
70
+ .use(hasRole('user', t))
71
+ .use(customErrorFormatter(t))
72
+ .input(
73
+ z.object({
74
+ zoom: z.number().min(0).max(1).optional(),
75
+ opacity: z.number().min(0).max(1).optional(),
76
+ })
77
+ )
78
+ .query(({ input, ctx }) => (ctx.app.service.Evolution.updateSettings as any)(input, ctx)),
79
+
80
+ getPayments: procedure
81
+ .use(hasRole('user', t))
82
+ .use(customErrorFormatter(t))
83
+ .query(({ input, ctx }) => (ctx.app.service.Evolution.getPayments as any)(input, ctx)),
84
+
85
+ processPayments: procedure
86
+ .use(hasRole('admin', t))
87
+ .use(customErrorFormatter(t))
88
+ .mutation(({ input, ctx }) => (ctx.app.service.Evolution.processPayments as any)(input, ctx)),
89
+
90
+ cancelPaymentRequest: procedure
91
+ .use(hasRole('user', t))
92
+ .use(customErrorFormatter(t))
93
+ .input(
94
+ z.object({
95
+ tokenKeys: z.any(),
96
+ tokenAmounts: z.any(),
97
+ // tokenIds: z.any(),
98
+ // itemIds: z.any(),
99
+ to: z.any(),
100
+ })
101
+ )
102
+ .mutation(({ input, ctx }) => (ctx.app.service.Evolution.cancelPaymentRequest as any)(input, ctx)),
103
+
104
+ createPaymentRequest: procedure
105
+ .use(hasRole('user', t))
106
+ .use(customErrorFormatter(t))
107
+ .input(
108
+ z.object({
109
+ chain: z.string(),
110
+ tokenKeys: z.any(),
111
+ tokenAmounts: z.any(),
112
+ // tokenIds: z.any(),
113
+ // itemIds: z.any(),
114
+ to: z.any(),
115
+ })
116
+ )
117
+ .mutation(({ input, ctx }) => (ctx.app.service.Evolution.createPaymentRequest as any)(input, ctx)),
118
+
119
+ saveRound: procedure
120
+ .use(hasRole('guest', t))
121
+ .use(customErrorFormatter(t))
122
+ .input(
123
+ z.object({
124
+ shardId: z.string(),
125
+ gameKey: z.string(),
126
+ round: z.any(),
127
+ clients: z.any(),
128
+ })
129
+ )
130
+ // .output(Arken.Profile.Schemas.Profile)
131
+ .mutation(({ input, ctx }) => (ctx.app.service.Evolution.saveRound as any)(input, ctx)),
132
+
133
+ interact: t.procedure
134
+ .use(hasRole('guest', t))
135
+ .use(customErrorFormatter(t))
136
+ .input(z.object({}))
137
+ .mutation(({ input, ctx }) => (ctx.app.service.Evolution.interact as any)(input, ctx)),
138
+
139
+ getScene: t.procedure
140
+ .use(hasRole('guest', t))
141
+ .use(customErrorFormatter(t))
142
+ .input(z.object({ applicationId: z.string() }))
143
+ .mutation(({ input, ctx }) => (ctx.app.service.Evolution.getScene as any)(input, ctx)),
144
+ });
145
+
146
+ export type Router = ReturnType<typeof createRouter>;
147
+ export type RouterInput = inferRouterInputs<Router>;
148
+ export type RouterOutput = inferRouterOutputs<Router>;
149
+
150
+ // unbanClient: t.procedure
151
+ // .input(z.object({ data: z.object({ target: z.string() }), id: z.string() }))
152
+ // .mutation(({ input, ctx }) => {
153
+ // service.unbanClient(ctx.app, input);
154
+ // }),
155
+
156
+ // mod: t.procedure
157
+ // .input(
158
+ // z.object({
159
+ // data: z.object({
160
+ // body: z.object({ signature: z.object({ address: z.string() }) }),
161
+ // params: z.object({ method: z.string() }),
162
+ // }),
163
+ // })
164
+ // )
165
+ // .mutation(({ input, ctx }) => {
166
+ // service.mod(ctx.app, input);
167
+ // }),
168
+
169
+ // banClient: t.procedure
170
+ // .input(
171
+ // z.object({
172
+ // data: z.object({ target: z.string(), reason: z.string(), until: z.number().optional() }),
173
+ // id: z.string(),
174
+ // })
175
+ // )
176
+ // .mutation(({ input, ctx }) => {
177
+ // service.banClient(ctx.app, input);
178
+ // }),
179
+
180
+ // getCharacter: t.procedure
181
+ // .input(z.object({ data: z.object({ address: z.string() }), id: z.string() }))
182
+ // .mutation(({ input, ctx }) => {
183
+ // service.getCharacter(ctx.app, input);
184
+ // }),
185
+
186
+ // saveRound: t.procedure.input(z.any()).mutation(({ input, ctx }) => {
187
+ // service.saveRound(ctx.app, input);
188
+ // }),
189
+
190
+ // Add more procedures as necessary
191
+
192
+ // Add the router type export if necessary
193
+ // export type Router = ReturnType<typeof createRouter>;
194
+
195
+ // class service {
196
+ // private characters: Record<string, any> = {};
197
+
198
+ // async pingRequest(msg: any) {
199
+ // log('PingRequest', msg);
200
+ // }
201
+
202
+ // async pongRequest(msg: any) {
203
+ // log('PongRequest', msg);
204
+ // }
205
+
206
+ // async unbanClient(app: Application, req: { data: { target: string }; id: string }) {
207
+ // log('unbanClient', req);
208
+
209
+ // const user = await app.db.loadUser(req.data.target);
210
+ // delete user.isBanned;
211
+ // delete user.bannedReason;
212
+ // await app.db.saveUser(user);
213
+
214
+ // app.db.removeBanList('evolution', req.data.target);
215
+ // app.db.saveBanList();
216
+
217
+ // return { status: 1 };
218
+ // }
219
+
220
+ // async mod(app: Application, req: { data: { body: { signature: { address: string } }; params: { method: string } } }) {
221
+ // log('mod', req);
222
+
223
+ // const user = await app.db.loadUser(req.data.body.signature.address);
224
+ // app.emitAll.playerAction({
225
+ // key: 'moderator-action',
226
+ // createdAt: new Date().getTime() / 1000,
227
+ // address: user.address,
228
+ // username: user.username,
229
+ // method: req.data.params.method,
230
+ // message: `${user.username} called ${req.data.params.method}`,
231
+ // });
232
+
233
+ // return { status: 1 };
234
+ // }
235
+
236
+ // async banClient(app: Application, req: { data: { target: string; reason: string; until?: number }; id: string }) {
237
+ // log('banClient', req);
238
+
239
+ // const user = await app.db.loadUser(req.data.target);
240
+ // user.isBanned = true;
241
+ // user.bannedReason = req.data.reason;
242
+ // user.banExpireDate = req.data.until || new Date().getTime() + 100 * 365 * 24 * 60 * 60; // 100 years by default
243
+
244
+ // await app.db.saveUser(user);
245
+
246
+ // app.db.addBanList('evolution', {
247
+ // address: req.data.target,
248
+ // reason: req.data.reason,
249
+ // until: req.data.until,
250
+ // });
251
+ // app.db.saveBanList();
252
+
253
+ // return { status: 1 };
254
+ // }
255
+
256
+ // async getCharacter(app: Application, req: { data: { address: string }; id: string }) {
257
+ // log('GetCharacterRequest', req);
258
+
259
+ // let character = this.characters[req.data.address];
260
+ // if (!character) {
261
+ // character = await this.fetchCharacter(app, req.data.address);
262
+ // this.characters[req.data.address] = character;
263
+ // }
264
+
265
+ // return { status: 1 };
266
+ // }
267
+
268
+ // private async fetchCharacter(app: Application, address: string) {
269
+ // // Implement character fetching logic here based on your application's needs
270
+ // return {};
271
+ // }
272
+
273
+ // async saveRound(app: Application, req: any) {
274
+ // log('SaveRoundRequest', req);
275
+
276
+ // if (!(await isValidRequest(app.web3, req)) && app.db.evolution.modList.includes(req.signature.address)) {
277
+ // log('Round invalid');
278
+ // return { status: 0, message: 'Invalid signature' };
279
+ // return;
280
+ // }
281
+
282
+ // return { status: 1 };
283
+ // }
284
+ // }
285
+
286
+ // export const evolutionService = new EvolutionService();
287
+
288
+ // export const evolutionRouter = t.router({
289
+ // pingRequest: t.procedure.input(z.any()).mutation(({ input, ctx }) => {
290
+ // evolutionService.pingRequest(input);
291
+ // }),
292
+
293
+ // pongRequest: t.procedure.input(z.any()).mutation(({ input, ctx }) => {
294
+ // evolutionService.pongRequest(input);
295
+ // }),
296
+
297
+ // unbanClient: t.procedure
298
+ // .input(z.object({ data: z.object({ target: z.string() }), id: z.string() }))
299
+ // .mutation(({ input, ctx }) => {
300
+ // evolutionService.unbanClient(ctx.app, input);
301
+ // }),
302
+
303
+ // mod: t.procedure
304
+ // .input(
305
+ // z.object({
306
+ // data: z.object({
307
+ // body: z.object({ signature: z.object({ address: z.string() }) }),
308
+ // params: z.object({ method: z.string() }),
309
+ // }),
310
+ // })
311
+ // )
312
+ // .mutation(({ input, ctx }) => {
313
+ // evolutionService.mod(ctx.app, input);
314
+ // }),
315
+
316
+ // banClient: t.procedure
317
+ // .input(
318
+ // z.object({
319
+ // data: z.object({ target: z.string(), reason: z.string(), until: z.number().optional() }),
320
+ // id: z.string(),
321
+ // })
322
+ // )
323
+ // .mutation(({ input, ctx }) => {
324
+ // evolutionService.banClient(ctx.app, input);
325
+ // }),
326
+
327
+ // getCharacter: t.procedure
328
+ // .input(z.object({ data: z.object({ address: z.string() }), id: z.string() }))
329
+ // .mutation(({ input, ctx }) => {
330
+ // evolutionService.getCharacter(ctx.app, input);
331
+ // }),
332
+
333
+ // saveRound: t.procedure.input(z.any()).mutation(({ input, ctx }) => {
334
+ // evolutionService.saveRound(ctx.app, input);
335
+ // }),
336
+
337
+ // // Add more procedures as necessary
338
+ // });
339
+
340
+ // // Add the router type export if necessary
341
+ // export type EvolutionRouter = typeof evolutionRouter;
342
+
343
+ // const shortId = require('shortid');
344
+
345
+ // let CharacterCache = {};
346
+ // const ioCallbacks = {};
347
+
348
+ // async function rsCall(app, realm, name, data = undefined) {
349
+ // try {
350
+ // const id = shortId();
351
+ // const signature =
352
+ // data !== undefined && data !== null
353
+ // ? await getSignedRequest(
354
+ // app.web3,
355
+ // app.secrets.find((s) => s.id === 'evolution-signer'),
356
+ // data
357
+ // )
358
+ // : null;
359
+
360
+ // return new Promise(async (resolve) => {
361
+ // ioCallbacks[id] = {};
362
+
363
+ // ioCallbacks[id].resolve = resolve;
364
+
365
+ // ioCallbacks[id].reqTimeout = setTimeout(function () {
366
+ // log('Request timeout');
367
+ // resolve({ status: 0, message: 'Request timeout' });
368
+
369
+ // delete ioCallbacks[id];
370
+ // }, 60 * 1000);
371
+
372
+ // if (!realm.client.socket?.connected) {
373
+ // log('Not connected to realm server: ' + realm.key);
374
+ // return;
375
+ // }
376
+
377
+ // log('Emit Realm', realm.key, name, { id, data });
378
+
379
+ // realm.client.socket.emit(name, { id, signature, data });
380
+ // });
381
+ // } catch (e) {
382
+ // log(e);
383
+ // }
384
+ // }
385
+
386
+ // function setRealmOffline(realm) {
387
+ // if (realm.status === 'inactive' || realm.updateMode === 'manual') return;
388
+
389
+ // realm.status = 'offline';
390
+ // realm.playerCount = 0;
391
+ // realm.speculatorCount = 0;
392
+ // realm.rewardItemAmount = 0;
393
+ // realm.rewardWinnerAmount = 0;
394
+ // }
395
+
396
+ // async function setRealmConfig(app, realm) {
397
+ // const configRes = (await rsCall(app, app.games.evolution.realms[realm.key], 'SetConfigRequest', {
398
+ // config: { ...app.db.evolution.config, roundId: realm.roundId },
399
+ // })) as any;
400
+
401
+ // if (configRes.status !== 1) {
402
+ // setRealmOffline(realm);
403
+ // return;
404
+ // }
405
+ // }
406
+
407
+ // async function updateRealm(app, realm) {
408
+ // try {
409
+ // realm.games = [];
410
+
411
+ // const infoRes = (await rsCall(app, app.games.evolution.realms[realm.key], 'InfoRequest', { config: {} })) as any; // roundId: realm.roundId
412
+
413
+ // if (!infoRes || infoRes.status !== 1) {
414
+ // setRealmOffline(realm);
415
+ // return;
416
+ // }
417
+
418
+ // log('infoRes', infoRes.data.games);
419
+
420
+ // const { data } = infoRes;
421
+
422
+ // realm.playerCount = data.playerCount;
423
+ // realm.speculatorCount = data.speculatorCount;
424
+ // realm.version = data.version;
425
+
426
+ // realm.games = data.games.map((game) => ({
427
+ // id: game.id,
428
+ // playerCount: game.playerCount,
429
+ // speculatorCount: game.speculatorCount,
430
+ // version: game.version,
431
+ // rewardItemAmount: game.rewardItemAmount,
432
+ // rewardWinnerAmount: game.rewardWinnerAmount,
433
+ // gameMode: game.gameMode,
434
+ // connectedPlayers: game.connectedPlayers,
435
+ // roundId: game.round.id,
436
+ // roundStartedAt: game.round.startedAt,
437
+ // timeLeft: ~~(5 * 60 - (new Date().getTime() / 1000 - game.round.startedAt)),
438
+ // timeLeftText: fancyTimeFormat(5 * 60 - (new Date().getTime() / 1000 - game.round.startedAt)),
439
+ // endpoint: (function () {
440
+ // const url = new URL((process.env.ARKEN_ENV === 'local' ? 'http://' : 'https://') + realm.endpoint);
441
+ // url.port = game.port;
442
+ // return url.toString();
443
+ // })()
444
+ // .replace('http://', '')
445
+ // .replace('https://', '')
446
+ // .replace('/', ''),
447
+ // }));
448
+
449
+ // delete realm.timeLeftFancy;
450
+
451
+ // realm.status = 'online';
452
+ // } catch (e) {
453
+ // log('Error', e);
454
+
455
+ // setRealmOffline(realm);
456
+ // }
457
+
458
+ // // log('Updated server', server)
459
+
460
+ // return realm;
461
+ // }
462
+
463
+ // async function updateRealms(app) {
464
+ // try {
465
+ // log('Updating Evolution realms');
466
+
467
+ // let playerCount = 0;
468
+
469
+ // for (const realm of app.db.evolution.realms) {
470
+ // // if (realm.key.indexOf('ptr') !== -1 || realm.key.indexOf('tournament') !== -1) continue
471
+ // if (realm.status === 'inactive' || realm.updateMode === 'manual') continue;
472
+
473
+ // await updateRealm(app, realm);
474
+
475
+ // const hist = jetpack.read(path.resolve(`./db/evolution/${realm.key}/historical.json`), 'json') || {};
476
+
477
+ // if (!hist.playerCount) hist.playerCount = [];
478
+
479
+ // const oldTime = new Date(hist.playerCount[hist.playerCount.length - 1]?.[0] || 0).getTime();
480
+ // const newTime = new Date().getTime();
481
+ // const diff = newTime - oldTime;
482
+ // if (diff / (1000 * 60 * 60 * 1) > 1) {
483
+ // hist.playerCount.push([newTime, realm.playerCount]);
484
+ // }
485
+
486
+ // jetpack.write(path.resolve(`./db/evolution/${realm.key}/historical.json`), JSON.stringify(hist), {
487
+ // atomic: true,
488
+ // jsonIndent: 0,
489
+ // });
490
+
491
+ // playerCount += realm.playerCount;
492
+
493
+ // log(`Realm ${realm.key} updated`, realm);
494
+ // }
495
+
496
+ // app.db.evolution.playerCount = playerCount;
497
+
498
+ // for (const server of app.db.evolution.servers) {
499
+ // if (server.status === 'inactive' || server.updateMode === 'manual') continue;
500
+ // // if (server.key.indexOf('tournament') !== -1) continue
501
+
502
+ // server.status = 'offline';
503
+ // server.playerCount = 0;
504
+ // }
505
+
506
+ // const evolutionServers = app.db.evolution.realms
507
+ // .filter((r) => r.status !== 'inactive')
508
+ // .map((r) =>
509
+ // r.games.length > 0
510
+ // ? {
511
+ // ...(app.db.evolution.servers.find((e) => e.key === r.key) || {}),
512
+ // ...r.games[0],
513
+ // key: r.key,
514
+ // name: r.name,
515
+ // status: r.status,
516
+ // regionId: r.regionId,
517
+ // }
518
+ // : {}
519
+ // );
520
+
521
+ // for (const evolutionServer of evolutionServers) {
522
+ // const server = app.db.evolution.servers.find((s) => s.key === evolutionServer.key);
523
+
524
+ // if (!server) {
525
+ // if (evolutionServer.key) {
526
+ // app.db.evolution.servers.push(evolutionServer);
527
+ // }
528
+ // continue;
529
+ // }
530
+
531
+ // if (evolutionServer.status === 'inactive' || evolutionServer.updateMode === 'manual') continue;
532
+
533
+ // server.status = evolutionServer.status;
534
+ // server.version = evolutionServer.version;
535
+ // server.rewardItemAmount = evolutionServer.rewardItemAmount;
536
+ // server.rewardWinnerAmount = evolutionServer.rewardWinnerAmount;
537
+ // server.gameMode = evolutionServer.gameMode;
538
+ // server.roundId = evolutionServer.roundId;
539
+ // server.roundStartedAt = evolutionServer.roundStartedAt;
540
+ // server.roundStartedDate = evolutionServer.roundStartedDate;
541
+ // server.timeLeft = evolutionServer.timeLeft;
542
+ // server.timeLeftText = evolutionServer.timeLeftText;
543
+ // server.playerCount = evolutionServer.playerCount;
544
+ // server.speculatorCount = evolutionServer.speculatorCount;
545
+ // server.endpoint = evolutionServer.endpoint;
546
+ // }
547
+
548
+ // jetpack.write(path.resolve('./db/evolution/realms.json'), JSON.stringify(app.db.evolution.realms), {
549
+ // atomic: true,
550
+ // jsonIndent: 0,
551
+ // });
552
+
553
+ // // Update old servers file
554
+ // jetpack.write(path.resolve('./db/evolution/servers.json'), JSON.stringify(app.db.evolution.servers), {
555
+ // atomic: true,
556
+ // jsonIndent: 0,
557
+ // });
558
+
559
+ // log('Realm and server info generated');
560
+
561
+ // // Update overall historics
562
+ // const hist = jetpack.read(path.resolve(`./db/evolution/historical.json`), 'json') || {};
563
+
564
+ // if (!hist.playerCount) hist.playerCount = [];
565
+
566
+ // const oldTime = new Date(hist.playerCount[hist.playerCount.length - 1]?.[0] || 0).getTime();
567
+ // const newTime = new Date().getTime();
568
+ // const diff = newTime - oldTime;
569
+ // if (diff / (1000 * 60 * 60 * 1) > 1) {
570
+ // hist.playerCount.push([newTime, playerCount]);
571
+ // }
572
+
573
+ // jetpack.write(path.resolve(`./db/evolution/historical.json`), JSON.stringify(hist), {
574
+ // atomic: true,
575
+ // jsonIndent: 0,
576
+ // });
577
+ // } catch (e) {
578
+ // log('Error', e);
579
+ // }
580
+ // }
581
+
582
+ // function cleanupClient(client) {
583
+ // log('Cleaning up', client.key);
584
+
585
+ // client.socket?.close();
586
+ // client.isConnected = false;
587
+ // client.isConnecting = false;
588
+ // client.isAuthed = false;
589
+
590
+ // clearTimeout(client.timeout);
591
+ // clearTimeout(client.pingReplyTimeout);
592
+ // clearTimeout(client.pingerTimeout);
593
+ // }
594
+
595
+ // function disconnectClient(client) {
596
+ // log('Disconnecting client', client.key);
597
+
598
+ // cleanupClient(client);
599
+ // }
600
+
601
+ // async function getCharacter(app, address) {
602
+ // const equipment = await app.barracks.getPlayerEquipment(app, address);
603
+ // const meta = await app.barracks.getMetaFromEquipment(app, equipment);
604
+
605
+ // // if (address === '0x1a367CA7bD311F279F1dfAfF1e60c4d797Faa6eb') {
606
+ // // meta[1030] = 100
607
+ // // }
608
+
609
+ // let error;
610
+ // if (meta[1030] > 100) error = `Problem with EvolutionMovementSpeedIncrease: ${address} ${meta[1030]}`;
611
+ // if (meta[1102] > 100) error = `Problem with DeathPenaltyAvoid: ${address} ${meta[1102]}`;
612
+ // if (meta[1104] > 100) error = `Problem with EnergyDecayDecrease: ${address} ${meta[1104]}`;
613
+ // if (meta[1105] > 100) error = `Problem with EnergyDecayIncrease: ${address} ${meta[1105]}`;
614
+ // if (meta[1150] > 100) error = `Problem with WinRewardsIncrease: ${address} ${meta[1150]}`;
615
+ // if (meta[1160] > 100) error = `Problem with WinRewardsDecrease: ${address} ${meta[1160]}`;
616
+ // if (meta[1222] > 100) error = `Problem with IncreaseMovementSpeedOnKill: ${address} ${meta[1222]}`;
617
+ // if (meta[1223] > 100) error = `Problem with EvolveMovementBurst: ${address} ${meta[1223]}`;
618
+ // if (meta[1164] > 100) error = `Problem with DoublePickupChance: ${address} ${meta[1164]}`;
619
+ // if (meta[1219] > 100) error = `Problem with IncreaseHealthOnKill: ${address} ${meta[1219]}`;
620
+ // if (meta[1117] > 100) error = `Problem with SpriteFuelIncrease: ${address} ${meta[1117]}`;
621
+ // if (meta[1118] > 100) error = `Problem with SpriteFuelDecrease: ${address} ${meta[1118]}`;
622
+
623
+ // if (error) {
624
+ // log('Error with character gear:', error);
625
+ // process.exit(6);
626
+ // }
627
+
628
+ // return {
629
+ // equipment,
630
+ // meta,
631
+ // };
632
+ // }
633
+
634
+ // const runes = [
635
+ // 'el',
636
+ // 'eld',
637
+ // 'tir',
638
+ // 'nef',
639
+ // 'ith',
640
+ // 'tal',
641
+ // 'ral',
642
+ // 'ort',
643
+ // 'thul',
644
+ // 'amn',
645
+ // 'sol',
646
+ // 'shael',
647
+ // 'dol',
648
+ // 'hel',
649
+ // 'io',
650
+ // 'lum',
651
+ // 'ko',
652
+ // 'fal',
653
+ // 'lem',
654
+ // 'pul',
655
+ // 'um',
656
+ // 'mal',
657
+ // 'ist',
658
+ // 'gul',
659
+ // 'vex',
660
+ // 'ohm',
661
+ // 'lo',
662
+ // 'sur',
663
+ // 'ber',
664
+ // 'jah',
665
+ // 'cham',
666
+ // 'zod',
667
+ // ];
668
+
669
+ // export async function connectRealm(app, realm) {
670
+ // if (realm.status === 'inactive' || realm.ignore) return;
671
+
672
+ // log('Connecting to realm', realm);
673
+ // const { client } = app.games.evolution.realms[realm.key];
674
+
675
+ // if (client.isConnected || client.socket?.connected) {
676
+ // log(`Realm ${realm.key} already connected, disconnecting`);
677
+ // cleanupClient(client);
678
+ // }
679
+
680
+ // client.isConnecting = true;
681
+ // client.socket = getClientSocket((process.env.ARKEN_ENV === 'local' ? 'http://' : 'https://') + realm.endpoint); // TODO: RS should be running things
682
+
683
+ // client.socket.on('connect', async () => {
684
+ // try {
685
+ // client.isConnected = true;
686
+
687
+ // log('Connected: ' + realm.key);
688
+
689
+ // const res = (await rsCall(app, app.games.evolution.realms[realm.key], 'AuthRequest', 'myverysexykey')) as any;
690
+
691
+ // if (res.status === 1) {
692
+ // client.isAuthed = true;
693
+
694
+ // clearTimeout(client.connectTimeout);
695
+
696
+ // await setRealmConfig(app, realm);
697
+ // await updateRealm(app, realm);
698
+ // }
699
+
700
+ // client.isConnecting = false;
701
+
702
+ // const pinger = async () => {
703
+ // try {
704
+ // clearTimeout(client.pingReplyTimeout);
705
+
706
+ // client.pingReplyTimeout = setTimeout(function () {
707
+ // log(`Realm ${realm.key} didnt respond in time, disconnecting`);
708
+ // cleanupClient(client);
709
+ // }, 70 * 1000);
710
+
711
+ // await rsCall(app, app.games.evolution.realms[realm.key], 'PingRequest');
712
+
713
+ // clearTimeout(client.pingReplyTimeout);
714
+
715
+ // if (!client.isConnected) return;
716
+
717
+ // client.pingerTimeout = setTimeout(async () => await pinger(), 15 * 1000);
718
+ // } catch (e) {
719
+ // log(e);
720
+ // }
721
+ // };
722
+
723
+ // clearTimeout(client.pingerTimeout);
724
+ // clearTimeout(client.pingReplyTimeout);
725
+
726
+ // client.pingerTimeout = setTimeout(async () => await pinger(), 15 * 1000);
727
+ // } catch (e) {
728
+ // log('Error', e);
729
+ // log(`Disconnecting ${realm.key} due to error`);
730
+ // cleanupClient(client);
731
+ // }
732
+ // });
733
+
734
+ // client.socket.on('disconnect', () => {
735
+ // log('Disconnected: ' + realm.key);
736
+ // cleanupClient(client);
737
+ // });
738
+
739
+ // // client.socket.on('banClient', async function (req) {
740
+ // // console.log(req)
741
+ // // try {
742
+ // // log('Ban', realm.key, req)
743
+
744
+ // // if (await isValidRequest(app.web3, req) && app.db.evolution.modList.includes(req.signature.address)) {
745
+ // // app.db.addBanList('evolution', req.data.target)
746
+
747
+ // // app.db.saveBanList()
748
+
749
+ // // app.realm.emitAll('BanUserRequest', {
750
+ // // signature: await getSignedRequest(app.web3, app.secrets, md5(JSON.stringify({ target: req.data.target }))),
751
+ // // data: {
752
+ // // target: req.data.target
753
+ // // }
754
+ // // })
755
+
756
+ // // client.socket.emit('BanUserResponse', {
757
+ // // id: req.id,
758
+ // // data: { status: 1 }
759
+ // // })
760
+ // // } else {
761
+ // // client.socket.emit('BanUserResponse', {
762
+ // // id: req.id,
763
+ // // data: { status: 0, message: 'Invalid signature' }
764
+ // // })
765
+ // // }
766
+ // // } catch (e) {
767
+ // // log('Error', e)
768
+
769
+ // // client.socket.emit('BanUserResponse', {
770
+ // // id: req.id,
771
+ // // data: { status: 0, message: e }
772
+ // // })
773
+ // // }
774
+ // // })
775
+
776
+ // client.socket.on('PingRequest', function (msg) {
777
+ // log('PingRequest', realm.key, msg);
778
+
779
+ // client.socket.emit('PingResponse');
780
+ // });
781
+
782
+ // client.socket.on('PongRequest', function (msg) {
783
+ // log('PongRequest', realm.key, msg);
784
+
785
+ // client.socket.emit('PongResponse');
786
+ // });
787
+
788
+ // client.socket.on('unbanClient', async function (req) {
789
+ // try {
790
+ // log('Ban', realm.key, req);
791
+
792
+ // const user = await app.db.loadUser(req.data.target);
793
+
794
+ // delete user.isBanned;
795
+ // delete user.bannedReason;
796
+
797
+ // await app.db.saveUser(user);
798
+
799
+ // app.db.removeBanList('evolution', req.data.target);
800
+ // app.db.saveBanList();
801
+
802
+ // app.realm.emitAll('UnbanUserRequest', {
803
+ // data: {
804
+ // target: req.data.target,
805
+ // },
806
+ // });
807
+
808
+ // client.socket.emit('UnbanClientResponse', {
809
+ // id: req.id,
810
+ // data: { status: 1 },
811
+ // });
812
+ // } catch (e) {
813
+ // log('Error', e);
814
+
815
+ // client.socket.emit('UnbanClientResponse', {
816
+ // id: req.id,
817
+ // data: { status: 0, message: e },
818
+ // });
819
+ // }
820
+ // });
821
+
822
+ // client.socket.on('mod', async function (req) {
823
+ // try {
824
+ // log('mod', realm.key, req);
825
+
826
+ // const user = await app.db.loadUser(req.data.body.signature.address);
827
+
828
+ // app.api.emitAll('playerAction', {
829
+ // key: 'moderator-action',
830
+ // createdAt: new Date().getTime() / 1000,
831
+ // address: user.address,
832
+ // username: user.username,
833
+ // method: req.data.params.method,
834
+ // realmKey: realm.key,
835
+ // message: `${user.username} called ${req.data.params.method}`,
836
+ // });
837
+
838
+ // client.socket.emit('ModResponse', {
839
+ // id: req.id,
840
+ // data: { status: 1 },
841
+ // });
842
+ // } catch (e) {
843
+ // log('Error', e);
844
+
845
+ // client.socket.emit('ModResponse', {
846
+ // id: req.id,
847
+ // data: { status: 0, message: e },
848
+ // });
849
+ // }
850
+ // });
851
+
852
+ // client.socket.on('banClient', async function (req) {
853
+ // try {
854
+ // log('banClient', realm.key, req);
855
+
856
+ // const user = await app.db.loadUser(req.data.target);
857
+
858
+ // user.isBanned = true;
859
+ // user.bannedReason = req.data.reason;
860
+ // user.bannedUntil = req.data.until ? parseInt(req.data.until) : new Date().getTime() + 100 * 365 * 24 * 60 * 60; // 100 year ban by default
861
+
862
+ // await app.db.saveUser(user);
863
+
864
+ // app.db.addBanList('evolution', { address: req.data.target, reason: req.data.reason, until: req.data.until });
865
+ // app.db.saveBanList();
866
+
867
+ // app.realm.emitAll('BanUserRequest', {
868
+ // data: {
869
+ // target: req.data.target,
870
+ // createdAt: new Date().getTime(),
871
+ // bannedUntil: user.bannedUntil,
872
+ // bannedReason: user.bannedReason,
873
+ // },
874
+ // });
875
+
876
+ // client.socket.emit('BanPlayerResponse', {
877
+ // id: req.id,
878
+ // data: { status: 1 },
879
+ // });
880
+ // } catch (e) {
881
+ // log('Error', e);
882
+
883
+ // client.socket.emit('BanPlayerResponse', {
884
+ // id: req.id,
885
+ // data: { status: 0, message: e },
886
+ // });
887
+ // }
888
+ // });
889
+
890
+ // client.socket.on('reportClient', function (msg) {
891
+ // log('reportClient', realm.key, msg);
892
+
893
+ // const { currentGamePlayers, currentPlayer, reportedPlayer } = msg;
894
+
895
+ // if (currentPlayer.name.indexOf('Guest') !== -1 || currentPlayer.name.indexOf('Unknown') !== -1) return; // No guest reports
896
+
897
+ // if (!app.db.evolution.reportList[reportedPlayer.address]) app.db.evolution.reportList[reportedPlayer.address] = [];
898
+
899
+ // if (!app.db.evolution.reportList[reportedPlayer.address].includes(currentPlayer.address))
900
+ // app.db.evolution.reportList[reportedPlayer.address].push(currentPlayer.address);
901
+
902
+ // // if (app.db.evolution.reportList[reportedPlayer.address].length >= 6) {
903
+ // // app.db.evolution.banList.push(reportedPlayer.address)
904
+
905
+ // // disconnectPlayer(reportedPlayer)
906
+ // // // emitDirect(client.sockets[reportedPlayer.id], 'OnBanned', true)
907
+ // // return
908
+ // // }
909
+
910
+ // // if (currentGamePlayers.length >= 4) {
911
+ // // const reportsFromCurrentGamePlayers = app.db.evolution.reportList[reportedPlayer.address].filter(function(n) {
912
+ // // return currentGamePlayers.indexOf(n) !== -1;
913
+ // // })
914
+
915
+ // // if (reportsFromCurrentGamePlayers.length >= currentGamePlayers.length / 3) {
916
+ // // app.db.evolution.banList.push(reportedPlayer.address)
917
+
918
+ // // disconnectPlayer(reportedPlayer)
919
+ // // // emitDirect(client.sockets[reportedPlayer.id], 'OnBanned', true)
920
+ // // return
921
+ // // }
922
+ // // }
923
+
924
+ // // Relay the report to connected realm servers
925
+ // });
926
+
927
+ // client.socket.on('GetCharacterRequest', async function (req) {
928
+ // log('GetCharacterRequest', req);
929
+
930
+ // try {
931
+ // let character = CharacterCache[req.data.address];
932
+
933
+ // if (!character) {
934
+ // // if (req.data.address === '0x1a367CA7bD311F279F1dfAfF1e60c4d797Faa6eb') {
935
+ // // meta[1030] = 100
936
+ // // }
937
+
938
+ // // if (req.data.address === '0x6f756AFaC862A2486f4c1C96b46E00A98a70bEA2') {
939
+ // // meta[1030] = 100
940
+ // // }
941
+
942
+ // character = await getCharacter(app, req.data.address);
943
+
944
+ // CharacterCache[req.data.address] = character;
945
+ // }
946
+
947
+ // log('GetCharacterResponse', character);
948
+
949
+ // client.socket.emit('GetCharacterResponse', {
950
+ // id: req.id,
951
+ // data: { status: 1, character },
952
+ // });
953
+ // } catch (e) {
954
+ // client.socket.emit('GetCharacterResponse', {
955
+ // id: req.id,
956
+ // data: { status: 0, message: 'Error' },
957
+ // });
958
+ // }
959
+ // });
960
+
961
+ // client.socket.on('SaveRoundRequest', async function (req) {
962
+ // // Iterate the items found, add to user.evolution.rewards
963
+ // // Itereate the runes found, add to user.evolution.runes
964
+ // // Iterate the winners, add to the user.evolution.runes
965
+ // // Add winning stats to user.evolution
966
+ // try {
967
+ // log('SaveRoundRequest', realm.key, req);
968
+
969
+ // if (!(await isValidRequest(app.web3, req)) && app.db.evolution.modList.includes(req.signature.address)) {
970
+ // log('Round invalid');
971
+
972
+ // client.socket.emit('SaveRoundResponse', {
973
+ // id: req.id,
974
+ // data: { status: 0, message: 'Invalid signature' },
975
+ // });
976
+ // return;
977
+ // }
978
+
979
+ // if (!req.data.lastClients) {
980
+ // log('Round no clients');
981
+
982
+ // client.socket.emit('SaveRoundResponse', {
983
+ // id: req.id,
984
+ // data: { status: 0, message: 'Error processing' },
985
+ // });
986
+ // return;
987
+ // }
988
+
989
+ // if (req.data.round.winners.length === 0) {
990
+ // realm.roundId += 1;
991
+
992
+ // log('Round skipped');
993
+
994
+ // client.socket.emit('SaveRoundResponse', {
995
+ // id: req.id,
996
+ // data: { status: 1 },
997
+ // });
998
+ // return;
999
+ // }
1000
+
1001
+ // if (req.data.rewardWinnerAmount > app.db.evolution.config.rewardWinnerAmountMax) {
1002
+ // log(req.data.rewardWinnerAmount, app.db.evolution.config.rewardWinnerAmountMax);
1003
+ // throw new Error('Big problem with reward amount');
1004
+ // }
1005
+
1006
+ // let totalLegitPlayers = 0;
1007
+
1008
+ // for (const client of req.data.lastClients) {
1009
+ // if (client.name.indexOf('Guest') !== -1 || client.name.indexOf('Unknown') !== -1) continue;
1010
+
1011
+ // if (
1012
+ // (client.powerups > 100 && client.kills > 1) ||
1013
+ // (client.evolves > 20 && client.powerups > 200) ||
1014
+ // (client.rewards > 3 && client.powerups > 200) ||
1015
+ // client.evolves > 100 ||
1016
+ // client.points > 1000
1017
+ // ) {
1018
+ // totalLegitPlayers += 1;
1019
+ // }
1020
+ // }
1021
+
1022
+ // if (totalLegitPlayers === 0) {
1023
+ // totalLegitPlayers = 1;
1024
+ // }
1025
+
1026
+ // if (req.data.rewardWinnerAmount > app.db.evolution.config.rewardWinnerAmountPerLegitPlayer * totalLegitPlayers) {
1027
+ // log(
1028
+ // req.data.rewardWinnerAmount,
1029
+ // app.db.evolution.config.rewardWinnerAmountPerLegitPlayer,
1030
+ // totalLegitPlayers,
1031
+ // req.data.lastClients.length,
1032
+ // JSON.stringify(req.data.lastClients)
1033
+ // );
1034
+ // throw new Error('Big problem with reward amount 2');
1035
+ // }
1036
+
1037
+ // if (req.data.roundId > realm.roundId) {
1038
+ // realm.roundId = req.data.roundId;
1039
+ // } else if (req.data.roundId < realm.roundId) {
1040
+ // const err = `Round id too low (realm.roundId = ${realm.roundId})`;
1041
+
1042
+ // log(err);
1043
+
1044
+ // client.socket.emit('SaveRoundResponse', {
1045
+ // id: req.id,
1046
+ // data: { status: 0, message: err },
1047
+ // });
1048
+
1049
+ // await setRealmConfig(app, realm);
1050
+
1051
+ // return;
1052
+ // } else {
1053
+ // realm.roundId += 1;
1054
+ // }
1055
+
1056
+ // // if (req.data.roundId > realm.roundId) {
1057
+ // // client.socket.emit('SaveRoundResponse', {
1058
+ // // id: req.id,
1059
+ // // data: { status: 0, message: 'Invalid round id' }
1060
+ // // })
1061
+ // // return
1062
+ // // }
1063
+
1064
+ // const rewardWinnerMap = {
1065
+ // 0: Math.round(req.data.rewardWinnerAmount * 1 * 1000) / 1000,
1066
+ // 1: Math.round(req.data.rewardWinnerAmount * 0.25 * 1000) / 1000,
1067
+ // 2: Math.round(req.data.rewardWinnerAmount * 0.15 * 1000) / 1000,
1068
+ // 3: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
1069
+ // 4: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
1070
+ // 5: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
1071
+ // 6: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
1072
+ // 7: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
1073
+ // 8: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
1074
+ // 9: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
1075
+ // };
1076
+
1077
+ // // const users = []
1078
+
1079
+ // // Iterate the winners, determine the winning amounts, validate, save to user rewards
1080
+ // // Iterate all players and save their log / stats
1081
+
1082
+ // const removeDupes2 = (list) => {
1083
+ // const seen = {};
1084
+ // return list.filter(function (item) {
1085
+ // // console.log(item)
1086
+ // const k1 = item.address;
1087
+ // const exists = seen.hasOwnProperty(k1);
1088
+
1089
+ // if (!exists) {
1090
+ // seen[k1] = true;
1091
+ // }
1092
+
1093
+ // return !exists;
1094
+ // });
1095
+ // };
1096
+
1097
+ // req.data.round.players = removeDupes2(req.data.round.players); // [...new Set(req.data.round.players.map(obj => obj.key)) ] //
1098
+
1099
+ // const winners = req.data.round.winners.slice(0, 10);
1100
+
1101
+ // const rewardTweaks = {};
1102
+
1103
+ // for (const winner of winners) {
1104
+ // let character = CharacterCache[winner.address];
1105
+
1106
+ // if (!character) {
1107
+ // console.log('Getting char data');
1108
+ // character = await getCharacter(app, winner.address);
1109
+ // console.log('Got char data');
1110
+
1111
+ // CharacterCache[winner.address] = character;
1112
+ // }
1113
+
1114
+ // // if (character?.meta?.[1173] > 0) {
1115
+ // // const portion = 0.05
1116
+
1117
+ // // for (const kill of winner.log.kills) {
1118
+ // // const target = req.data.round.players.filter(p => p.hash === kill)
1119
+
1120
+ // // if (target?.address) {
1121
+ // // if (!rewardTweaks[target.address]) rewardTweaks[target.address] = 0
1122
+ // // if (!rewardTweaks[winner.address]) rewardTweaks[winner.address] = 0
1123
+
1124
+ // // rewardTweaks[target.address] -= portion
1125
+ // // rewardTweaks[winner.address] += portion
1126
+ // // }
1127
+ // // }
1128
+ // // }
1129
+ // }
1130
+
1131
+ // for (const player of req.data.round.players) {
1132
+ // console.log('Loading user');
1133
+ // const user = await app.db.loadUser(player.address);
1134
+ // console.log('Loaded user');
1135
+ // const now = new Date().getTime() / 1000;
1136
+
1137
+ // if (user.lastGamePlayed > now - 4 * 60) continue; // Make sure this player isn't in 2 games or somehow getting double rewards
1138
+
1139
+ // if (typeof user.username === 'object' || !user.username) user.username = await getUsername(user.address);
1140
+
1141
+ // if (!user.username) continue; // Make sure cant earn without a character
1142
+
1143
+ // app.db.setUserActive(user);
1144
+
1145
+ // if (player.killStreak >= 10) {
1146
+ // app.api.emitAll('PlayerAction', {
1147
+ // key: 'evolution1-killstreak',
1148
+ // createdAt: new Date().getTime() / 1000,
1149
+ // address: user.address,
1150
+ // username: user.username,
1151
+ // message: `${user.username} got a ${player.killStreak} killstreak in Evolution`,
1152
+ // });
1153
+ // app.notices.add('evolution1-killstreak', {
1154
+ // key: 'evolution1-killstreak',
1155
+ // address: user.address,
1156
+ // username: user.username,
1157
+ // message: `${user.username} got a ${player.killStreak} killstreak in Evolution`,
1158
+ // });
1159
+ // }
1160
+
1161
+ // for (const pickup of player.pickups) {
1162
+ // if (pickup.type === 'rune') {
1163
+ // // TODO: change to authoritative
1164
+ // if (
1165
+ // pickup.quantity >
1166
+ // req.data.round.players.length * app.db.evolution.config.rewardItemAmountPerLegitPlayer * 2
1167
+ // ) {
1168
+ // log(
1169
+ // pickup.quantity,
1170
+ // app.db.evolution.config.rewardItemAmountPerLegitPlayer,
1171
+ // req.data.round.players.length,
1172
+ // JSON.stringify(req.data.round.players)
1173
+ // );
1174
+ // throw new Error('Big problem with item reward amount');
1175
+ // }
1176
+
1177
+ // if (pickup.quantity > req.data.round.players.length * app.db.evolution.config.rewardItemAmountMax) {
1178
+ // log(pickup.quantity, req.data.round.players.length, app.db.evolution.config.rewardItemAmountMax);
1179
+ // throw new Error('Big problem with item reward amount 2');
1180
+ // }
1181
+
1182
+ // const runeSymbol = pickup.rewardItemName.toLowerCase();
1183
+
1184
+ // if (!runes.includes(runeSymbol)) {
1185
+ // continue;
1186
+ // }
1187
+
1188
+ // if (!user.rewards.runes[runeSymbol] || user.rewards.runes[runeSymbol] < 0.000000001) {
1189
+ // user.rewards.runes[runeSymbol] = 0;
1190
+ // }
1191
+
1192
+ // user.rewards.runes[runeSymbol] += pickup.quantity;
1193
+
1194
+ // if (!user.lifetimeRewards.runes[runeSymbol] || user.lifetimeRewards.runes[runeSymbol] < 0.000000001) {
1195
+ // user.lifetimeRewards.runes[runeSymbol] = 0;
1196
+ // }
1197
+
1198
+ // user.lifetimeRewards.runes[runeSymbol] += pickup.quantity;
1199
+
1200
+ // app.db.evolution.config.itemRewards.runes[runeSymbol.toLowerCase()] -= pickup.quantity;
1201
+
1202
+ // app.db.oracle.outflow.evolutionRewards.tokens.week[runeSymbol.toLowerCase()] += pickup.quantity;
1203
+ // } else {
1204
+ // user.rewards.items[pickup.id] = {
1205
+ // name: pickup.name,
1206
+ // rarity: pickup.rarity,
1207
+ // quantity: pickup.quantity,
1208
+ // };
1209
+
1210
+ // user.lifetimeRewards.items[pickup.id] = {
1211
+ // name: pickup.name,
1212
+ // rarity: pickup.rarity,
1213
+ // quantity: pickup.quantity,
1214
+ // };
1215
+ // }
1216
+
1217
+ // // user.rewardTracking.push(req.tracking)
1218
+ // }
1219
+
1220
+ // user.lastGamePlayed = now;
1221
+
1222
+ // if (!user.evolution.hashes) user.evolution.hashes = [];
1223
+ // if (!user.evolution.hashes.includes(player.hash)) user.evolution.hashes.push(player.hash);
1224
+
1225
+ // user.evolution.hashes = user.evolution.hashes.filter(function (item, pos) {
1226
+ // return user.evolution.hashes.indexOf(item) === pos;
1227
+ // });
1228
+
1229
+ // // users.push(user)
1230
+
1231
+ // if (!app.games.evolution.realms[realm.key].leaderboard.names)
1232
+ // app.games.evolution.realms[realm.key].leaderboard.names = {};
1233
+
1234
+ // app.games.evolution.realms[realm.key].leaderboard.names[user.address] = user.username;
1235
+
1236
+ // if (!app.games.evolution.realms[realm.key].leaderboard.raw.points[user.address]) {
1237
+ // // 'orbs', 'revenges', 'rounds', 'wins', 'timeSpent', 'winRatio', 'killDeathRatio', 'roundPointRatio', 'averageLatency'
1238
+ // app.games.evolution.realms[realm.key].leaderboard.raw.monetary[user.address] = 0;
1239
+ // app.games.evolution.realms[realm.key].leaderboard.raw.wins[user.address] = 0;
1240
+ // app.games.evolution.realms[realm.key].leaderboard.raw.rounds[user.address] = 0;
1241
+ // app.games.evolution.realms[realm.key].leaderboard.raw.kills[user.address] = 0;
1242
+ // app.games.evolution.realms[realm.key].leaderboard.raw.points[user.address] = 0;
1243
+ // app.games.evolution.realms[realm.key].leaderboard.raw.deaths[user.address] = 0;
1244
+ // app.games.evolution.realms[realm.key].leaderboard.raw.powerups[user.address] = 0;
1245
+ // app.games.evolution.realms[realm.key].leaderboard.raw.evolves[user.address] = 0;
1246
+ // app.games.evolution.realms[realm.key].leaderboard.raw.rewards[user.address] = 0;
1247
+ // app.games.evolution.realms[realm.key].leaderboard.raw.pickups[user.address] = 0;
1248
+ // }
1249
+
1250
+ // // Update leaderboard stats
1251
+ // app.games.evolution.realms[realm.key].leaderboard.raw.rounds[user.address] += 1;
1252
+ // app.games.evolution.realms[realm.key].leaderboard.raw.kills[user.address] += player.kills;
1253
+ // app.games.evolution.realms[realm.key].leaderboard.raw.points[user.address] += player.points;
1254
+ // app.games.evolution.realms[realm.key].leaderboard.raw.deaths[user.address] += player.deaths;
1255
+ // app.games.evolution.realms[realm.key].leaderboard.raw.powerups[user.address] += player.powerups;
1256
+ // app.games.evolution.realms[realm.key].leaderboard.raw.evolves[user.address] += player.evolves;
1257
+ // app.games.evolution.realms[realm.key].leaderboard.raw.rewards[user.address] += player.rewards;
1258
+ // app.games.evolution.realms[realm.key].leaderboard.raw.pickups[user.address] += player.pickups.length;
1259
+
1260
+ // if (!app.games.evolution.global.leaderboard.names) app.games.evolution.global.leaderboard.names = {};
1261
+
1262
+ // app.games.evolution.global.leaderboard.names[user.address] = user.username;
1263
+
1264
+ // if (!app.games.evolution.global.leaderboard.raw.points[user.address]) {
1265
+ // // 'orbs', 'revenges', 'rounds', 'wins', 'timeSpent', 'winRatio', 'killDeathRatio', 'roundPointRatio', 'averageLatency'
1266
+ // app.games.evolution.global.leaderboard.raw.monetary[user.address] = 0;
1267
+ // app.games.evolution.global.leaderboard.raw.wins[user.address] = 0;
1268
+ // app.games.evolution.global.leaderboard.raw.rounds[user.address] = 0;
1269
+ // app.games.evolution.global.leaderboard.raw.kills[user.address] = 0;
1270
+ // app.games.evolution.global.leaderboard.raw.points[user.address] = 0;
1271
+ // app.games.evolution.global.leaderboard.raw.deaths[user.address] = 0;
1272
+ // app.games.evolution.global.leaderboard.raw.powerups[user.address] = 0;
1273
+ // app.games.evolution.global.leaderboard.raw.evolves[user.address] = 0;
1274
+ // app.games.evolution.global.leaderboard.raw.rewards[user.address] = 0;
1275
+ // app.games.evolution.global.leaderboard.raw.pickups[user.address] = 0;
1276
+ // }
1277
+
1278
+ // // Update leaderboard stats
1279
+ // app.games.evolution.global.leaderboard.raw.rounds[user.address] += 1;
1280
+ // app.games.evolution.global.leaderboard.raw.kills[user.address] += player.kills;
1281
+ // app.games.evolution.global.leaderboard.raw.points[user.address] += player.points;
1282
+ // app.games.evolution.global.leaderboard.raw.deaths[user.address] += player.deaths;
1283
+ // app.games.evolution.global.leaderboard.raw.powerups[user.address] += player.powerups;
1284
+ // app.games.evolution.global.leaderboard.raw.evolves[user.address] += player.evolves;
1285
+ // app.games.evolution.global.leaderboard.raw.rewards[user.address] += player.rewards;
1286
+ // app.games.evolution.global.leaderboard.raw.pickups[user.address] += player.pickups.length;
1287
+
1288
+ // if (winners.find((winner) => winner.address === player.address)) {
1289
+ // const index = winners.findIndex((winner) => winner.address === player.address);
1290
+ // // const player = req.data.round.winners[index]
1291
+ // // const user = users.find(u => u.address === player.address)
1292
+
1293
+ // // if (!user) continue // He wasn't valid
1294
+ // if (user.username) {
1295
+ // // Make sure cant earn without a character
1296
+ // // if (req.data.round.winners[0].address === player.address) {
1297
+ // let character = CharacterCache[player.address];
1298
+
1299
+ // if (!character) {
1300
+ // console.log('Getting char data');
1301
+ // character = await getCharacter(app, player.address);
1302
+ // console.log('Got char data');
1303
+
1304
+ // CharacterCache[player.address] = character;
1305
+ // }
1306
+
1307
+ // const WinRewardsIncrease = character?.meta?.[1150] || 0;
1308
+ // const WinRewardsDecrease = character?.meta?.[1160] || 0;
1309
+
1310
+ // console.log('bbbb', rewardWinnerMap[index]);
1311
+ // const rewardMultiplier = 1 + (WinRewardsIncrease - WinRewardsDecrease) / 100;
1312
+
1313
+ // if (rewardMultiplier > 2 || rewardMultiplier < 0) {
1314
+ // log(
1315
+ // 'Error with reward multiplier.. bad things happened: ',
1316
+ // rewardMultiplier,
1317
+ // rewardMultiplier,
1318
+ // WinRewardsDecrease
1319
+ // );
1320
+ // process.exit(5);
1321
+ // }
1322
+
1323
+ // rewardWinnerMap[index] *= rewardMultiplier;
1324
+ // console.log('cccc', rewardWinnerMap[index]);
1325
+ // // }
1326
+
1327
+ // if (!user.rewards.runes['zod']) {
1328
+ // user.rewards.runes['zod'] = 0;
1329
+ // }
1330
+
1331
+ // if (user.rewards.runes['zod'] < 0) {
1332
+ // user.rewards.runes['zod'] = 0;
1333
+ // }
1334
+
1335
+ // user.rewards.runes['zod'] += rewardWinnerMap[index];
1336
+
1337
+ // if (!user.lifetimeRewards.runes['zod']) {
1338
+ // user.lifetimeRewards.runes['zod'] = 0;
1339
+ // }
1340
+
1341
+ // user.lifetimeRewards.runes['zod'] += rewardWinnerMap[index];
1342
+
1343
+ // app.db.oracle.outflow.evolutionRewards.tokens.week['zod'] += rewardWinnerMap[index];
1344
+
1345
+ // app.games.evolution.global.leaderboard.raw.monetary[user.address] += rewardWinnerMap[index];
1346
+
1347
+ // app.games.evolution.realms[realm.key].leaderboard.raw.monetary[user.address] += rewardWinnerMap[index];
1348
+
1349
+ // app.api.emitAll('PlayerAction', {
1350
+ // key: 'evolution1-winner',
1351
+ // createdAt: new Date().getTime() / 1000,
1352
+ // address: user.address,
1353
+ // username: user.username,
1354
+ // realmKey: realm.key,
1355
+ // placement: index + 1,
1356
+ // message: `${user.username} placed #${index + 1} for ${rewardWinnerMap[index].toFixed(
1357
+ // 4
1358
+ // )} ZOD in Evolution`,
1359
+ // });
1360
+
1361
+ // if (rewardWinnerMap[index] > 0.1) {
1362
+ // app.notices.add('evolution1-winner', {
1363
+ // key: 'evolution1-winner',
1364
+ // address: user.address,
1365
+ // username: user.username,
1366
+ // realmKey: realm.key,
1367
+ // placement: index + 1,
1368
+ // message: `${user.username} won ${rewardWinnerMap[index].toFixed(4)} ZOD in Evolution`,
1369
+ // });
1370
+ // }
1371
+
1372
+ // if (req.data.round.winners[0].address === player.address) {
1373
+ // if (!app.games.evolution.realms[realm.key].leaderboard.raw)
1374
+ // app.games.evolution.realms[realm.key].leaderboard.raw = {};
1375
+ // if (!app.games.evolution.realms[realm.key].leaderboard.raw.wins)
1376
+ // app.games.evolution.realms[realm.key].leaderboard.raw.wins = 0;
1377
+
1378
+ // app.games.evolution.realms[realm.key].leaderboard.raw.wins[user.address] += 1;
1379
+
1380
+ // if (!app.games.evolution.global.leaderboard.raw) app.games.evolution.global.leaderboard.raw = {};
1381
+ // if (!app.games.evolution.global.leaderboard.raw.wins) app.games.evolution.global.leaderboard.raw.wins = 0;
1382
+
1383
+ // app.games.evolution.global.leaderboard.raw.wins[user.address] += 1;
1384
+ // }
1385
+ // }
1386
+ // }
1387
+
1388
+ // await app.db.saveUser(user);
1389
+ // }
1390
+
1391
+ // log('Round saved');
1392
+
1393
+ // client.socket.emit('SaveRoundResponse', {
1394
+ // id: req.id,
1395
+ // data: { status: 1 },
1396
+ // });
1397
+ // } catch (e) {
1398
+ // log('Error', e);
1399
+
1400
+ // client.socket.emit('SaveRoundResponse', {
1401
+ // id: req.id,
1402
+ // data: { status: 0, message: e },
1403
+ // });
1404
+
1405
+ // disconnectClient(client);
1406
+ // }
1407
+ // });
1408
+
1409
+ // import type * as Arken from '@arken/node/types';
1410
+ // import { isDebug, log } from '@arken/node/util';
1411
+ // import * as dotenv from 'dotenv';
1412
+ // import { catchExceptions, subProcesses } from '@arken/node/util/process';
1413
+ // import fetch from 'node-fetch';
1414
+
1415
+ // import path from 'path';
1416
+ // import jetpack, { find } from 'fs-jetpack';
1417
+ // import beautify from 'json-beautify';
1418
+ // import { fancyTimeFormat } from '@arken/node/util/time';
1419
+ // import md5 from 'js-md5';
1420
+ // import { getClientSocket } from '@arken/node/util/websocket';
1421
+ // import { isValidRequest, getSignedRequest } from '@arken/node/util/web3';
1422
+ // import getUsername from '@arken/node/legacy/getOldUsername';
1423
+ // import { z } from 'zod';
1424
+
1425
+ // export async function monitorEvolutionRealms(app) {}
1426
+
1427
+ // export const createRouter = (t: any) =>
1428
+ // t.router({
1429
+ // saveRound: t.procedure
1430
+ // .input(
1431
+ // z.object({
1432
+ // shardId: z.string(),
1433
+ // roundId: z.number(),
1434
+ // round: z.any(),
1435
+ // rewardWinnerAmount: z.number(),
1436
+ // lastClients: z.any(),
1437
+ // })
1438
+ // )
1439
+ // .mutation(({ input, ctx }) => {
1440
+ // return { status: 1 };
1441
+ // }),
1442
+
1443
+ // getProfile: t.procedure.input(z.string()).query(({ input, ctx }) => {
1444
+ // return { status: 1, data: {} as Arken.Profile.Types.Profile };
1445
+ // }),
1446
+
1447
+ // unbanClient: t.procedure
1448
+ // .input(z.object({ data: z.object({ target: z.string() }), id: z.string() }))
1449
+ // .mutation(({ input, ctx }) => {
1450
+ // service.unbanClient(ctx.app, input);
1451
+ // }),
1452
+
1453
+ // mod: t.procedure
1454
+ // .input(
1455
+ // z.object({
1456
+ // data: z.object({
1457
+ // body: z.object({ signature: z.object({ address: z.string() }) }),
1458
+ // params: z.object({ method: z.string() }),
1459
+ // }),
1460
+ // })
1461
+ // )
1462
+ // .mutation(({ input, ctx }) => {
1463
+ // service.mod(ctx.app, input);
1464
+ // }),
1465
+
1466
+ // banClient: t.procedure
1467
+ // .input(
1468
+ // z.object({
1469
+ // data: z.object({ target: z.string(), reason: z.string(), until: z.number().optional() }),
1470
+ // id: z.string(),
1471
+ // })
1472
+ // )
1473
+ // .mutation(({ input, ctx }) => {
1474
+ // service.banClient(ctx.app, input);
1475
+ // }),
1476
+
1477
+ // getCharacter: t.procedure
1478
+ // .input(z.object({ data: z.object({ address: z.string() }), id: z.string() }))
1479
+ // .mutation(({ input, ctx }) => {
1480
+ // service.getCharacter(ctx.app, input);
1481
+ // }),
1482
+
1483
+ // saveRound: t.procedure.input(z.any()).mutation(({ input, ctx }) => {
1484
+ // service.saveRound(ctx.app, input);
1485
+ // }),
1486
+
1487
+ // Add more procedures as necessary
1488
+ // });
1489
+
1490
+ // Add the router type export if necessary
1491
+ // export type Router = ReturnType<typeof createRouter>;
1492
+
1493
+ // class service {
1494
+ // private characters: Record<string, any> = {};
1495
+
1496
+ // async pingRequest(msg: any) {
1497
+ // log('PingRequest', msg);
1498
+ // }
1499
+
1500
+ // async pongRequest(msg: any) {
1501
+ // log('PongRequest', msg);
1502
+ // }
1503
+
1504
+ // async unbanClient(app: Application, req: { data: { target: string }; id: string }) {
1505
+ // log('unbanClient', req);
1506
+
1507
+ // const user = await app.db.loadUser(req.data.target);
1508
+ // delete user.isBanned;
1509
+ // delete user.bannedReason;
1510
+ // await app.db.saveUser(user);
1511
+
1512
+ // app.db.removeBanList('evolution', req.data.target);
1513
+ // app.db.saveBanList();
1514
+
1515
+ // return { status: 1 };
1516
+ // }
1517
+
1518
+ // async mod(app: Application, req: { data: { body: { signature: { address: string } }; params: { method: string } } }) {
1519
+ // log('mod', req);
1520
+
1521
+ // const user = await app.db.loadUser(req.data.body.signature.address);
1522
+ // app.emitAll.playerAction({
1523
+ // key: 'moderator-action',
1524
+ // createdAt: new Date().getTime() / 1000,
1525
+ // address: user.address,
1526
+ // username: user.username,
1527
+ // method: req.data.params.method,
1528
+ // message: `${user.username} called ${req.data.params.method}`,
1529
+ // });
1530
+
1531
+ // return { status: 1 };
1532
+ // }
1533
+
1534
+ // async banClient(app: Application, req: { data: { target: string; reason: string; until?: number }; id: string }) {
1535
+ // log('banClient', req);
1536
+
1537
+ // const user = await app.db.loadUser(req.data.target);
1538
+ // user.isBanned = true;
1539
+ // user.bannedReason = req.data.reason;
1540
+ // user.banExpireDate = req.data.until || new Date().getTime() + 100 * 365 * 24 * 60 * 60; // 100 years by default
1541
+
1542
+ // await app.db.saveUser(user);
1543
+
1544
+ // app.db.addBanList('evolution', {
1545
+ // address: req.data.target,
1546
+ // reason: req.data.reason,
1547
+ // until: req.data.until,
1548
+ // });
1549
+ // app.db.saveBanList();
1550
+
1551
+ // return { status: 1 };
1552
+ // }
1553
+
1554
+ // async getCharacter(app: Application, req: { data: { address: string }; id: string }) {
1555
+ // log('GetCharacterRequest', req);
1556
+
1557
+ // let character = this.characters[req.data.address];
1558
+ // if (!character) {
1559
+ // character = await this.fetchCharacter(app, req.data.address);
1560
+ // this.characters[req.data.address] = character;
1561
+ // }
1562
+
1563
+ // return { status: 1 };
1564
+ // }
1565
+
1566
+ // private async fetchCharacter(app: Application, address: string) {
1567
+ // // Implement character fetching logic here based on your application's needs
1568
+ // return {};
1569
+ // }
1570
+
1571
+ // async saveRound(app: Application, req: any) {
1572
+ // log('SaveRoundRequest', req);
1573
+
1574
+ // if (!(await isValidRequest(app.web3, req)) && app.db.evolution.modList.includes(req.signature.address)) {
1575
+ // log('Round invalid');
1576
+ // return { status: 0, message: 'Invalid signature' };
1577
+ // return;
1578
+ // }
1579
+
1580
+ // return { status: 1 };
1581
+ // }
1582
+ // }
1583
+
1584
+ // export const evolutionService = new EvolutionService();
1585
+
1586
+ // export const evolutionRouter = t.router({
1587
+ // pingRequest: t.procedure.input(z.any()).mutation(({ input, ctx }) => {
1588
+ // evolutionService.pingRequest(input);
1589
+ // }),
1590
+
1591
+ // pongRequest: t.procedure.input(z.any()).mutation(({ input, ctx }) => {
1592
+ // evolutionService.pongRequest(input);
1593
+ // }),
1594
+
1595
+ // unbanClient: t.procedure
1596
+ // .input(z.object({ data: z.object({ target: z.string() }), id: z.string() }))
1597
+ // .mutation(({ input, ctx }) => {
1598
+ // evolutionService.unbanClient(ctx.app, input);
1599
+ // }),
1600
+
1601
+ // mod: t.procedure
1602
+ // .input(
1603
+ // z.object({
1604
+ // data: z.object({
1605
+ // body: z.object({ signature: z.object({ address: z.string() }) }),
1606
+ // params: z.object({ method: z.string() }),
1607
+ // }),
1608
+ // })
1609
+ // )
1610
+ // .mutation(({ input, ctx }) => {
1611
+ // evolutionService.mod(ctx.app, input);
1612
+ // }),
1613
+
1614
+ // banClient: t.procedure
1615
+ // .input(
1616
+ // z.object({
1617
+ // data: z.object({ target: z.string(), reason: z.string(), until: z.number().optional() }),
1618
+ // id: z.string(),
1619
+ // })
1620
+ // )
1621
+ // .mutation(({ input, ctx }) => {
1622
+ // evolutionService.banClient(ctx.app, input);
1623
+ // }),
1624
+
1625
+ // getCharacter: t.procedure
1626
+ // .input(z.object({ data: z.object({ address: z.string() }), id: z.string() }))
1627
+ // .mutation(({ input, ctx }) => {
1628
+ // evolutionService.getCharacter(ctx.app, input);
1629
+ // }),
1630
+
1631
+ // saveRound: t.procedure.input(z.any()).mutation(({ input, ctx }) => {
1632
+ // evolutionService.saveRound(ctx.app, input);
1633
+ // }),
1634
+
1635
+ // // Add more procedures as necessary
1636
+ // });
1637
+
1638
+ // // Add the router type export if necessary
1639
+ // export type EvolutionRouter = typeof evolutionRouter;
1640
+
1641
+ // const shortId = require('shortid');
1642
+
1643
+ // let CharacterCache = {};
1644
+ // const ioCallbacks = {};
1645
+
1646
+ // async function rsCall(app, realm, name, data = undefined) {
1647
+ // try {
1648
+ // const id = shortId();
1649
+ // const signature =
1650
+ // data !== undefined && data !== null
1651
+ // ? await getSignedRequest(
1652
+ // app.web3,
1653
+ // app.secrets.find((s) => s.id === 'evolution-signer'),
1654
+ // data
1655
+ // )
1656
+ // : null;
1657
+
1658
+ // return new Promise(async (resolve) => {
1659
+ // ioCallbacks[id] = {};
1660
+
1661
+ // ioCallbacks[id].resolve = resolve;
1662
+
1663
+ // ioCallbacks[id].reqTimeout = setTimeout(function () {
1664
+ // log('Request timeout');
1665
+ // resolve({ status: 0, message: 'Request timeout' });
1666
+
1667
+ // delete ioCallbacks[id];
1668
+ // }, 60 * 1000);
1669
+
1670
+ // if (!realm.client.socket?.connected) {
1671
+ // log('Not connected to realm server: ' + realm.key);
1672
+ // return;
1673
+ // }
1674
+
1675
+ // log('Emit Realm', realm.key, name, { id, data });
1676
+
1677
+ // realm.client.socket.emit(name, { id, signature, data });
1678
+ // });
1679
+ // } catch (e) {
1680
+ // log(e);
1681
+ // }
1682
+ // }
1683
+
1684
+ // function setRealmOffline(realm) {
1685
+ // if (realm.status === 'inactive' || realm.updateMode === 'manual') return;
1686
+
1687
+ // realm.status = 'offline';
1688
+ // realm.playerCount = 0;
1689
+ // realm.speculatorCount = 0;
1690
+ // realm.rewardItemAmount = 0;
1691
+ // realm.rewardWinnerAmount = 0;
1692
+ // }
1693
+
1694
+ // async function setRealmConfig(app, realm) {
1695
+ // const configRes = (await rsCall(app, app.games.evolution.realms[realm.key], 'SetConfigRequest', {
1696
+ // config: { ...app.db.evolution.config, roundId: realm.roundId },
1697
+ // })) as any;
1698
+
1699
+ // if (configRes.status !== 1) {
1700
+ // setRealmOffline(realm);
1701
+ // return;
1702
+ // }
1703
+ // }
1704
+
1705
+ // async function updateRealm(app, realm) {
1706
+ // try {
1707
+ // realm.games = [];
1708
+
1709
+ // const infoRes = (await rsCall(app, app.games.evolution.realms[realm.key], 'InfoRequest', { config: {} })) as any; // roundId: realm.roundId
1710
+
1711
+ // if (!infoRes || infoRes.status !== 1) {
1712
+ // setRealmOffline(realm);
1713
+ // return;
1714
+ // }
1715
+
1716
+ // log('infoRes', infoRes.data.games);
1717
+
1718
+ // const { data } = infoRes;
1719
+
1720
+ // realm.playerCount = data.playerCount;
1721
+ // realm.speculatorCount = data.speculatorCount;
1722
+ // realm.version = data.version;
1723
+
1724
+ // realm.games = data.games.map((game) => ({
1725
+ // id: game.id,
1726
+ // playerCount: game.playerCount,
1727
+ // speculatorCount: game.speculatorCount,
1728
+ // version: game.version,
1729
+ // rewardItemAmount: game.rewardItemAmount,
1730
+ // rewardWinnerAmount: game.rewardWinnerAmount,
1731
+ // gameMode: game.gameMode,
1732
+ // connectedPlayers: game.connectedPlayers,
1733
+ // roundId: game.round.id,
1734
+ // roundStartedAt: game.round.startedAt,
1735
+ // timeLeft: ~~(5 * 60 - (new Date().getTime() / 1000 - game.round.startedAt)),
1736
+ // timeLeftText: fancyTimeFormat(5 * 60 - (new Date().getTime() / 1000 - game.round.startedAt)),
1737
+ // endpoint: (function () {
1738
+ // const url = new URL((process.env.ARKEN_ENV === 'local' ? 'http://' : 'https://') + realm.endpoint);
1739
+ // url.port = game.port;
1740
+ // return url.toString();
1741
+ // })()
1742
+ // .replace('http://', '')
1743
+ // .replace('https://', '')
1744
+ // .replace('/', ''),
1745
+ // }));
1746
+
1747
+ // delete realm.timeLeftFancy;
1748
+
1749
+ // realm.status = 'online';
1750
+ // } catch (e) {
1751
+ // log('Error', e);
1752
+
1753
+ // setRealmOffline(realm);
1754
+ // }
1755
+
1756
+ // // log('Updated server', server)
1757
+
1758
+ // return realm;
1759
+ // }
1760
+
1761
+ // async function updateRealms(app) {
1762
+ // try {
1763
+ // log('Updating Evolution realms');
1764
+
1765
+ // let playerCount = 0;
1766
+
1767
+ // for (const realm of app.db.evolution.realms) {
1768
+ // // if (realm.key.indexOf('ptr') !== -1 || realm.key.indexOf('tournament') !== -1) continue
1769
+ // if (realm.status === 'inactive' || realm.updateMode === 'manual') continue;
1770
+
1771
+ // await updateRealm(app, realm);
1772
+
1773
+ // const hist = jetpack.read(path.resolve(`./db/evolution/${realm.key}/historical.json`), 'json') || {};
1774
+
1775
+ // if (!hist.playerCount) hist.playerCount = [];
1776
+
1777
+ // const oldTime = new Date(hist.playerCount[hist.playerCount.length - 1]?.[0] || 0).getTime();
1778
+ // const newTime = new Date().getTime();
1779
+ // const diff = newTime - oldTime;
1780
+ // if (diff / (1000 * 60 * 60 * 1) > 1) {
1781
+ // hist.playerCount.push([newTime, realm.playerCount]);
1782
+ // }
1783
+
1784
+ // jetpack.write(path.resolve(`./db/evolution/${realm.key}/historical.json`), JSON.stringify(hist), {
1785
+ // atomic: true,
1786
+ // jsonIndent: 0,
1787
+ // });
1788
+
1789
+ // playerCount += realm.playerCount;
1790
+
1791
+ // log(`Realm ${realm.key} updated`, realm);
1792
+ // }
1793
+
1794
+ // app.db.evolution.playerCount = playerCount;
1795
+
1796
+ // for (const server of app.db.evolution.servers) {
1797
+ // if (server.status === 'inactive' || server.updateMode === 'manual') continue;
1798
+ // // if (server.key.indexOf('tournament') !== -1) continue
1799
+
1800
+ // server.status = 'offline';
1801
+ // server.playerCount = 0;
1802
+ // }
1803
+
1804
+ // const evolutionServers = app.db.evolution.realms
1805
+ // .filter((r) => r.status !== 'inactive')
1806
+ // .map((r) =>
1807
+ // r.games.length > 0
1808
+ // ? {
1809
+ // ...(app.db.evolution.servers.find((e) => e.key === r.key) || {}),
1810
+ // ...r.games[0],
1811
+ // key: r.key,
1812
+ // name: r.name,
1813
+ // status: r.status,
1814
+ // regionId: r.regionId,
1815
+ // }
1816
+ // : {}
1817
+ // );
1818
+
1819
+ // for (const evolutionServer of evolutionServers) {
1820
+ // const server = app.db.evolution.servers.find((s) => s.key === evolutionServer.key);
1821
+
1822
+ // if (!server) {
1823
+ // if (evolutionServer.key) {
1824
+ // app.db.evolution.servers.push(evolutionServer);
1825
+ // }
1826
+ // continue;
1827
+ // }
1828
+
1829
+ // if (evolutionServer.status === 'inactive' || evolutionServer.updateMode === 'manual') continue;
1830
+
1831
+ // server.status = evolutionServer.status;
1832
+ // server.version = evolutionServer.version;
1833
+ // server.rewardItemAmount = evolutionServer.rewardItemAmount;
1834
+ // server.rewardWinnerAmount = evolutionServer.rewardWinnerAmount;
1835
+ // server.gameMode = evolutionServer.gameMode;
1836
+ // server.roundId = evolutionServer.roundId;
1837
+ // server.roundStartedAt = evolutionServer.roundStartedAt;
1838
+ // server.roundStartedDate = evolutionServer.roundStartedDate;
1839
+ // server.timeLeft = evolutionServer.timeLeft;
1840
+ // server.timeLeftText = evolutionServer.timeLeftText;
1841
+ // server.playerCount = evolutionServer.playerCount;
1842
+ // server.speculatorCount = evolutionServer.speculatorCount;
1843
+ // server.endpoint = evolutionServer.endpoint;
1844
+ // }
1845
+
1846
+ // jetpack.write(path.resolve('./db/evolution/realms.json'), JSON.stringify(app.db.evolution.realms), {
1847
+ // atomic: true,
1848
+ // jsonIndent: 0,
1849
+ // });
1850
+
1851
+ // // Update old servers file
1852
+ // jetpack.write(path.resolve('./db/evolution/servers.json'), JSON.stringify(app.db.evolution.servers), {
1853
+ // atomic: true,
1854
+ // jsonIndent: 0,
1855
+ // });
1856
+
1857
+ // log('Realm and server info generated');
1858
+
1859
+ // // Update overall historics
1860
+ // const hist = jetpack.read(path.resolve(`./db/evolution/historical.json`), 'json') || {};
1861
+
1862
+ // if (!hist.playerCount) hist.playerCount = [];
1863
+
1864
+ // const oldTime = new Date(hist.playerCount[hist.playerCount.length - 1]?.[0] || 0).getTime();
1865
+ // const newTime = new Date().getTime();
1866
+ // const diff = newTime - oldTime;
1867
+ // if (diff / (1000 * 60 * 60 * 1) > 1) {
1868
+ // hist.playerCount.push([newTime, playerCount]);
1869
+ // }
1870
+
1871
+ // jetpack.write(path.resolve(`./db/evolution/historical.json`), JSON.stringify(hist), {
1872
+ // atomic: true,
1873
+ // jsonIndent: 0,
1874
+ // });
1875
+ // } catch (e) {
1876
+ // log('Error', e);
1877
+ // }
1878
+ // }
1879
+
1880
+ // function cleanupClient(client) {
1881
+ // log('Cleaning up', client.key);
1882
+
1883
+ // client.socket?.close();
1884
+ // client.isConnected = false;
1885
+ // client.isConnecting = false;
1886
+ // client.isAuthed = false;
1887
+
1888
+ // clearTimeout(client.timeout);
1889
+ // clearTimeout(client.pingReplyTimeout);
1890
+ // clearTimeout(client.pingerTimeout);
1891
+ // }
1892
+
1893
+ // function disconnectClient(client) {
1894
+ // log('Disconnecting client', client.key);
1895
+
1896
+ // cleanupClient(client);
1897
+ // }
1898
+
1899
+ // async function getCharacter(app, address) {
1900
+ // const equipment = await app.barracks.getPlayerEquipment(app, address);
1901
+ // const meta = await app.barracks.getMetaFromEquipment(app, equipment);
1902
+
1903
+ // // if (address === '0x1a367CA7bD311F279F1dfAfF1e60c4d797Faa6eb') {
1904
+ // // meta[1030] = 100
1905
+ // // }
1906
+
1907
+ // let error;
1908
+ // if (meta[1030] > 100) error = `Problem with EvolutionMovementSpeedIncrease: ${address} ${meta[1030]}`;
1909
+ // if (meta[1102] > 100) error = `Problem with DeathPenaltyAvoid: ${address} ${meta[1102]}`;
1910
+ // if (meta[1104] > 100) error = `Problem with EnergyDecayDecrease: ${address} ${meta[1104]}`;
1911
+ // if (meta[1105] > 100) error = `Problem with EnergyDecayIncrease: ${address} ${meta[1105]}`;
1912
+ // if (meta[1150] > 100) error = `Problem with WinRewardsIncrease: ${address} ${meta[1150]}`;
1913
+ // if (meta[1160] > 100) error = `Problem with WinRewardsDecrease: ${address} ${meta[1160]}`;
1914
+ // if (meta[1222] > 100) error = `Problem with IncreaseMovementSpeedOnKill: ${address} ${meta[1222]}`;
1915
+ // if (meta[1223] > 100) error = `Problem with EvolveMovementBurst: ${address} ${meta[1223]}`;
1916
+ // if (meta[1164] > 100) error = `Problem with DoublePickupChance: ${address} ${meta[1164]}`;
1917
+ // if (meta[1219] > 100) error = `Problem with IncreaseHealthOnKill: ${address} ${meta[1219]}`;
1918
+ // if (meta[1117] > 100) error = `Problem with SpriteFuelIncrease: ${address} ${meta[1117]}`;
1919
+ // if (meta[1118] > 100) error = `Problem with SpriteFuelDecrease: ${address} ${meta[1118]}`;
1920
+
1921
+ // if (error) {
1922
+ // log('Error with character gear:', error);
1923
+ // process.exit(6);
1924
+ // }
1925
+
1926
+ // return {
1927
+ // equipment,
1928
+ // meta,
1929
+ // };
1930
+ // }
1931
+
1932
+ // const runes = [
1933
+ // 'el',
1934
+ // 'eld',
1935
+ // 'tir',
1936
+ // 'nef',
1937
+ // 'ith',
1938
+ // 'tal',
1939
+ // 'ral',
1940
+ // 'ort',
1941
+ // 'thul',
1942
+ // 'amn',
1943
+ // 'sol',
1944
+ // 'shael',
1945
+ // 'dol',
1946
+ // 'hel',
1947
+ // 'io',
1948
+ // 'lum',
1949
+ // 'ko',
1950
+ // 'fal',
1951
+ // 'lem',
1952
+ // 'pul',
1953
+ // 'um',
1954
+ // 'mal',
1955
+ // 'ist',
1956
+ // 'gul',
1957
+ // 'vex',
1958
+ // 'ohm',
1959
+ // 'lo',
1960
+ // 'sur',
1961
+ // 'ber',
1962
+ // 'jah',
1963
+ // 'cham',
1964
+ // 'zod',
1965
+ // ];
1966
+
1967
+ // export async function connectRealm(app, realm) {
1968
+ // if (realm.status === 'inactive' || realm.ignore) return;
1969
+
1970
+ // log('Connecting to realm', realm);
1971
+ // const { client } = app.games.evolution.realms[realm.key];
1972
+
1973
+ // if (client.isConnected || client.socket?.connected) {
1974
+ // log(`Realm ${realm.key} already connected, disconnecting`);
1975
+ // cleanupClient(client);
1976
+ // }
1977
+
1978
+ // client.isConnecting = true;
1979
+ // client.socket = getClientSocket((process.env.ARKEN_ENV === 'local' ? 'http://' : 'https://') + realm.endpoint); // TODO: RS should be running things
1980
+
1981
+ // client.socket.on('connect', async () => {
1982
+ // try {
1983
+ // client.isConnected = true;
1984
+
1985
+ // log('Connected: ' + realm.key);
1986
+
1987
+ // const res = (await rsCall(app, app.games.evolution.realms[realm.key], 'AuthRequest', 'myverysexykey')) as any;
1988
+
1989
+ // if (res.status === 1) {
1990
+ // client.isAuthed = true;
1991
+
1992
+ // clearTimeout(client.connectTimeout);
1993
+
1994
+ // await setRealmConfig(app, realm);
1995
+ // await updateRealm(app, realm);
1996
+ // }
1997
+
1998
+ // client.isConnecting = false;
1999
+
2000
+ // const pinger = async () => {
2001
+ // try {
2002
+ // clearTimeout(client.pingReplyTimeout);
2003
+
2004
+ // client.pingReplyTimeout = setTimeout(function () {
2005
+ // log(`Realm ${realm.key} didnt respond in time, disconnecting`);
2006
+ // cleanupClient(client);
2007
+ // }, 70 * 1000);
2008
+
2009
+ // await rsCall(app, app.games.evolution.realms[realm.key], 'PingRequest');
2010
+
2011
+ // clearTimeout(client.pingReplyTimeout);
2012
+
2013
+ // if (!client.isConnected) return;
2014
+
2015
+ // client.pingerTimeout = setTimeout(async () => await pinger(), 15 * 1000);
2016
+ // } catch (e) {
2017
+ // log(e);
2018
+ // }
2019
+ // };
2020
+
2021
+ // clearTimeout(client.pingerTimeout);
2022
+ // clearTimeout(client.pingReplyTimeout);
2023
+
2024
+ // client.pingerTimeout = setTimeout(async () => await pinger(), 15 * 1000);
2025
+ // } catch (e) {
2026
+ // log('Error', e);
2027
+ // log(`Disconnecting ${realm.key} due to error`);
2028
+ // cleanupClient(client);
2029
+ // }
2030
+ // });
2031
+
2032
+ // client.socket.on('disconnect', () => {
2033
+ // log('Disconnected: ' + realm.key);
2034
+ // cleanupClient(client);
2035
+ // });
2036
+
2037
+ // // client.socket.on('banClient', async function (req) {
2038
+ // // console.log(req)
2039
+ // // try {
2040
+ // // log('Ban', realm.key, req)
2041
+
2042
+ // // if (await isValidRequest(app.web3, req) && app.db.evolution.modList.includes(req.signature.address)) {
2043
+ // // app.db.addBanList('evolution', req.data.target)
2044
+
2045
+ // // app.db.saveBanList()
2046
+
2047
+ // // app.realm.emitAll('BanUserRequest', {
2048
+ // // signature: await getSignedRequest(app.web3, app.secrets, md5(JSON.stringify({ target: req.data.target }))),
2049
+ // // data: {
2050
+ // // target: req.data.target
2051
+ // // }
2052
+ // // })
2053
+
2054
+ // // client.socket.emit('BanUserResponse', {
2055
+ // // id: req.id,
2056
+ // // data: { status: 1 }
2057
+ // // })
2058
+ // // } else {
2059
+ // // client.socket.emit('BanUserResponse', {
2060
+ // // id: req.id,
2061
+ // // data: { status: 0, message: 'Invalid signature' }
2062
+ // // })
2063
+ // // }
2064
+ // // } catch (e) {
2065
+ // // log('Error', e)
2066
+
2067
+ // // client.socket.emit('BanUserResponse', {
2068
+ // // id: req.id,
2069
+ // // data: { status: 0, message: e }
2070
+ // // })
2071
+ // // }
2072
+ // // })
2073
+
2074
+ // client.socket.on('PingRequest', function (msg) {
2075
+ // log('PingRequest', realm.key, msg);
2076
+
2077
+ // client.socket.emit('PingResponse');
2078
+ // });
2079
+
2080
+ // client.socket.on('PongRequest', function (msg) {
2081
+ // log('PongRequest', realm.key, msg);
2082
+
2083
+ // client.socket.emit('PongResponse');
2084
+ // });
2085
+
2086
+ // client.socket.on('unbanClient', async function (req) {
2087
+ // try {
2088
+ // log('Ban', realm.key, req);
2089
+
2090
+ // const user = await app.db.loadUser(req.data.target);
2091
+
2092
+ // delete user.isBanned;
2093
+ // delete user.bannedReason;
2094
+
2095
+ // await app.db.saveUser(user);
2096
+
2097
+ // app.db.removeBanList('evolution', req.data.target);
2098
+ // app.db.saveBanList();
2099
+
2100
+ // app.realm.emitAll('UnbanUserRequest', {
2101
+ // data: {
2102
+ // target: req.data.target,
2103
+ // },
2104
+ // });
2105
+
2106
+ // client.socket.emit('UnbanClientResponse', {
2107
+ // id: req.id,
2108
+ // data: { status: 1 },
2109
+ // });
2110
+ // } catch (e) {
2111
+ // log('Error', e);
2112
+
2113
+ // client.socket.emit('UnbanClientResponse', {
2114
+ // id: req.id,
2115
+ // data: { status: 0, message: e },
2116
+ // });
2117
+ // }
2118
+ // });
2119
+
2120
+ // client.socket.on('mod', async function (req) {
2121
+ // try {
2122
+ // log('mod', realm.key, req);
2123
+
2124
+ // const user = await app.db.loadUser(req.data.body.signature.address);
2125
+
2126
+ // app.api.emitAll('playerAction', {
2127
+ // key: 'moderator-action',
2128
+ // createdAt: new Date().getTime() / 1000,
2129
+ // address: user.address,
2130
+ // username: user.username,
2131
+ // method: req.data.params.method,
2132
+ // realmKey: realm.key,
2133
+ // message: `${user.username} called ${req.data.params.method}`,
2134
+ // });
2135
+
2136
+ // client.socket.emit('ModResponse', {
2137
+ // id: req.id,
2138
+ // data: { status: 1 },
2139
+ // });
2140
+ // } catch (e) {
2141
+ // log('Error', e);
2142
+
2143
+ // client.socket.emit('ModResponse', {
2144
+ // id: req.id,
2145
+ // data: { status: 0, message: e },
2146
+ // });
2147
+ // }
2148
+ // });
2149
+
2150
+ // client.socket.on('banClient', async function (req) {
2151
+ // try {
2152
+ // log('banClient', realm.key, req);
2153
+
2154
+ // const user = await app.db.loadUser(req.data.target);
2155
+
2156
+ // user.isBanned = true;
2157
+ // user.bannedReason = req.data.reason;
2158
+ // user.bannedUntil = req.data.until ? parseInt(req.data.until) : new Date().getTime() + 100 * 365 * 24 * 60 * 60; // 100 year ban by default
2159
+
2160
+ // await app.db.saveUser(user);
2161
+
2162
+ // app.db.addBanList('evolution', { address: req.data.target, reason: req.data.reason, until: req.data.until });
2163
+ // app.db.saveBanList();
2164
+
2165
+ // app.realm.emitAll('BanUserRequest', {
2166
+ // data: {
2167
+ // target: req.data.target,
2168
+ // createdAt: new Date().getTime(),
2169
+ // bannedUntil: user.bannedUntil,
2170
+ // bannedReason: user.bannedReason,
2171
+ // },
2172
+ // });
2173
+
2174
+ // client.socket.emit('BanPlayerResponse', {
2175
+ // id: req.id,
2176
+ // data: { status: 1 },
2177
+ // });
2178
+ // } catch (e) {
2179
+ // log('Error', e);
2180
+
2181
+ // client.socket.emit('BanPlayerResponse', {
2182
+ // id: req.id,
2183
+ // data: { status: 0, message: e },
2184
+ // });
2185
+ // }
2186
+ // });
2187
+
2188
+ // client.socket.on('reportClient', function (msg) {
2189
+ // log('reportClient', realm.key, msg);
2190
+
2191
+ // const { currentGamePlayers, currentPlayer, reportedPlayer } = msg;
2192
+
2193
+ // if (currentPlayer.name.indexOf('Guest') !== -1 || currentPlayer.name.indexOf('Unknown') !== -1) return; // No guest reports
2194
+
2195
+ // if (!app.db.evolution.reportList[reportedPlayer.address]) app.db.evolution.reportList[reportedPlayer.address] = [];
2196
+
2197
+ // if (!app.db.evolution.reportList[reportedPlayer.address].includes(currentPlayer.address))
2198
+ // app.db.evolution.reportList[reportedPlayer.address].push(currentPlayer.address);
2199
+
2200
+ // // if (app.db.evolution.reportList[reportedPlayer.address].length >= 6) {
2201
+ // // app.db.evolution.banList.push(reportedPlayer.address)
2202
+
2203
+ // // disconnectPlayer(reportedPlayer)
2204
+ // // // emitDirect(client.sockets[reportedPlayer.id], 'OnBanned', true)
2205
+ // // return
2206
+ // // }
2207
+
2208
+ // // if (currentGamePlayers.length >= 4) {
2209
+ // // const reportsFromCurrentGamePlayers = app.db.evolution.reportList[reportedPlayer.address].filter(function(n) {
2210
+ // // return currentGamePlayers.indexOf(n) !== -1;
2211
+ // // })
2212
+
2213
+ // // if (reportsFromCurrentGamePlayers.length >= currentGamePlayers.length / 3) {
2214
+ // // app.db.evolution.banList.push(reportedPlayer.address)
2215
+
2216
+ // // disconnectPlayer(reportedPlayer)
2217
+ // // // emitDirect(client.sockets[reportedPlayer.id], 'OnBanned', true)
2218
+ // // return
2219
+ // // }
2220
+ // // }
2221
+
2222
+ // // Relay the report to connected realm servers
2223
+ // });
2224
+
2225
+ // client.socket.on('GetCharacterRequest', async function (req) {
2226
+ // log('GetCharacterRequest', req);
2227
+
2228
+ // try {
2229
+ // let character = CharacterCache[req.data.address];
2230
+
2231
+ // if (!character) {
2232
+ // // if (req.data.address === '0x1a367CA7bD311F279F1dfAfF1e60c4d797Faa6eb') {
2233
+ // // meta[1030] = 100
2234
+ // // }
2235
+
2236
+ // // if (req.data.address === '0x6f756AFaC862A2486f4c1C96b46E00A98a70bEA2') {
2237
+ // // meta[1030] = 100
2238
+ // // }
2239
+
2240
+ // character = await getCharacter(app, req.data.address);
2241
+
2242
+ // CharacterCache[req.data.address] = character;
2243
+ // }
2244
+
2245
+ // log('GetCharacterResponse', character);
2246
+
2247
+ // client.socket.emit('GetCharacterResponse', {
2248
+ // id: req.id,
2249
+ // data: { status: 1, character },
2250
+ // });
2251
+ // } catch (e) {
2252
+ // client.socket.emit('GetCharacterResponse', {
2253
+ // id: req.id,
2254
+ // data: { status: 0, message: 'Error' },
2255
+ // });
2256
+ // }
2257
+ // });
2258
+
2259
+ // client.socket.on('SaveRoundRequest', async function (req) {
2260
+ // // Iterate the items found, add to user.evolution.rewards
2261
+ // // Itereate the runes found, add to user.evolution.runes
2262
+ // // Iterate the winners, add to the user.evolution.runes
2263
+ // // Add winning stats to user.evolution
2264
+ // try {
2265
+ // log('SaveRoundRequest', realm.key, req);
2266
+
2267
+ // if (!(await isValidRequest(app.web3, req)) && app.db.evolution.modList.includes(req.signature.address)) {
2268
+ // log('Round invalid');
2269
+
2270
+ // client.socket.emit('SaveRoundResponse', {
2271
+ // id: req.id,
2272
+ // data: { status: 0, message: 'Invalid signature' },
2273
+ // });
2274
+ // return;
2275
+ // }
2276
+
2277
+ // if (!req.data.lastClients) {
2278
+ // log('Round no clients');
2279
+
2280
+ // client.socket.emit('SaveRoundResponse', {
2281
+ // id: req.id,
2282
+ // data: { status: 0, message: 'Error processing' },
2283
+ // });
2284
+ // return;
2285
+ // }
2286
+
2287
+ // if (req.data.round.winners.length === 0) {
2288
+ // realm.roundId += 1;
2289
+
2290
+ // log('Round skipped');
2291
+
2292
+ // client.socket.emit('SaveRoundResponse', {
2293
+ // id: req.id,
2294
+ // data: { status: 1 },
2295
+ // });
2296
+ // return;
2297
+ // }
2298
+
2299
+ // if (req.data.rewardWinnerAmount > app.db.evolution.config.rewardWinnerAmountMax) {
2300
+ // log(req.data.rewardWinnerAmount, app.db.evolution.config.rewardWinnerAmountMax);
2301
+ // throw new Error('Big problem with reward amount');
2302
+ // }
2303
+
2304
+ // let totalLegitPlayers = 0;
2305
+
2306
+ // for (const client of req.data.lastClients) {
2307
+ // if (client.name.indexOf('Guest') !== -1 || client.name.indexOf('Unknown') !== -1) continue;
2308
+
2309
+ // if (
2310
+ // (client.powerups > 100 && client.kills > 1) ||
2311
+ // (client.evolves > 20 && client.powerups > 200) ||
2312
+ // (client.rewards > 3 && client.powerups > 200) ||
2313
+ // client.evolves > 100 ||
2314
+ // client.points > 1000
2315
+ // ) {
2316
+ // totalLegitPlayers += 1;
2317
+ // }
2318
+ // }
2319
+
2320
+ // if (totalLegitPlayers === 0) {
2321
+ // totalLegitPlayers = 1;
2322
+ // }
2323
+
2324
+ // if (req.data.rewardWinnerAmount > app.db.evolution.config.rewardWinnerAmountPerLegitPlayer * totalLegitPlayers) {
2325
+ // log(
2326
+ // req.data.rewardWinnerAmount,
2327
+ // app.db.evolution.config.rewardWinnerAmountPerLegitPlayer,
2328
+ // totalLegitPlayers,
2329
+ // req.data.lastClients.length,
2330
+ // JSON.stringify(req.data.lastClients)
2331
+ // );
2332
+ // throw new Error('Big problem with reward amount 2');
2333
+ // }
2334
+
2335
+ // if (req.data.roundId > realm.roundId) {
2336
+ // realm.roundId = req.data.roundId;
2337
+ // } else if (req.data.roundId < realm.roundId) {
2338
+ // const err = `Round id too low (realm.roundId = ${realm.roundId})`;
2339
+
2340
+ // log(err);
2341
+
2342
+ // client.socket.emit('SaveRoundResponse', {
2343
+ // id: req.id,
2344
+ // data: { status: 0, message: err },
2345
+ // });
2346
+
2347
+ // await setRealmConfig(app, realm);
2348
+
2349
+ // return;
2350
+ // } else {
2351
+ // realm.roundId += 1;
2352
+ // }
2353
+
2354
+ // // if (req.data.roundId > realm.roundId) {
2355
+ // // client.socket.emit('SaveRoundResponse', {
2356
+ // // id: req.id,
2357
+ // // data: { status: 0, message: 'Invalid round id' }
2358
+ // // })
2359
+ // // return
2360
+ // // }
2361
+
2362
+ // const rewardWinnerMap = {
2363
+ // 0: Math.round(req.data.rewardWinnerAmount * 1 * 1000) / 1000,
2364
+ // 1: Math.round(req.data.rewardWinnerAmount * 0.25 * 1000) / 1000,
2365
+ // 2: Math.round(req.data.rewardWinnerAmount * 0.15 * 1000) / 1000,
2366
+ // 3: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
2367
+ // 4: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
2368
+ // 5: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
2369
+ // 6: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
2370
+ // 7: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
2371
+ // 8: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
2372
+ // 9: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
2373
+ // };
2374
+
2375
+ // // const users = []
2376
+
2377
+ // // Iterate the winners, determine the winning amounts, validate, save to user rewards
2378
+ // // Iterate all players and save their log / stats
2379
+
2380
+ // const removeDupes2 = (list) => {
2381
+ // const seen = {};
2382
+ // return list.filter(function (item) {
2383
+ // // console.log(item)
2384
+ // const k1 = item.address;
2385
+ // const exists = seen.hasOwnProperty(k1);
2386
+
2387
+ // if (!exists) {
2388
+ // seen[k1] = true;
2389
+ // }
2390
+
2391
+ // return !exists;
2392
+ // });
2393
+ // };
2394
+
2395
+ // req.data.round.players = removeDupes2(req.data.round.players); // [...new Set(req.data.round.players.map(obj => obj.key)) ] //
2396
+
2397
+ // const winners = req.data.round.winners.slice(0, 10);
2398
+
2399
+ // const rewardTweaks = {};
2400
+
2401
+ // for (const winner of winners) {
2402
+ // let character = CharacterCache[winner.address];
2403
+
2404
+ // if (!character) {
2405
+ // console.log('Getting char data');
2406
+ // character = await getCharacter(app, winner.address);
2407
+ // console.log('Got char data');
2408
+
2409
+ // CharacterCache[winner.address] = character;
2410
+ // }
2411
+
2412
+ // // if (character?.meta?.[1173] > 0) {
2413
+ // // const portion = 0.05
2414
+
2415
+ // // for (const kill of winner.log.kills) {
2416
+ // // const target = req.data.round.players.filter(p => p.hash === kill)
2417
+
2418
+ // // if (target?.address) {
2419
+ // // if (!rewardTweaks[target.address]) rewardTweaks[target.address] = 0
2420
+ // // if (!rewardTweaks[winner.address]) rewardTweaks[winner.address] = 0
2421
+
2422
+ // // rewardTweaks[target.address] -= portion
2423
+ // // rewardTweaks[winner.address] += portion
2424
+ // // }
2425
+ // // }
2426
+ // // }
2427
+ // }
2428
+
2429
+ // for (const player of req.data.round.players) {
2430
+ // console.log('Loading user');
2431
+ // const user = await app.db.loadUser(player.address);
2432
+ // console.log('Loaded user');
2433
+ // const now = new Date().getTime() / 1000;
2434
+
2435
+ // if (user.lastGamePlayed > now - 4 * 60) continue; // Make sure this player isn't in 2 games or somehow getting double rewards
2436
+
2437
+ // if (typeof user.username === 'object' || !user.username) user.username = await getUsername(user.address);
2438
+
2439
+ // if (!user.username) continue; // Make sure cant earn without a character
2440
+
2441
+ // app.db.setUserActive(user);
2442
+
2443
+ // if (player.killStreak >= 10) {
2444
+ // app.api.emitAll('PlayerAction', {
2445
+ // key: 'evolution1-killstreak',
2446
+ // createdAt: new Date().getTime() / 1000,
2447
+ // address: user.address,
2448
+ // username: user.username,
2449
+ // message: `${user.username} got a ${player.killStreak} killstreak in Evolution`,
2450
+ // });
2451
+ // app.notices.add('evolution1-killstreak', {
2452
+ // key: 'evolution1-killstreak',
2453
+ // address: user.address,
2454
+ // username: user.username,
2455
+ // message: `${user.username} got a ${player.killStreak} killstreak in Evolution`,
2456
+ // });
2457
+ // }
2458
+
2459
+ // for (const pickup of player.pickups) {
2460
+ // if (pickup.type === 'rune') {
2461
+ // // TODO: change to authoritative
2462
+ // if (
2463
+ // pickup.quantity >
2464
+ // req.data.round.players.length * app.db.evolution.config.rewardItemAmountPerLegitPlayer * 2
2465
+ // ) {
2466
+ // log(
2467
+ // pickup.quantity,
2468
+ // app.db.evolution.config.rewardItemAmountPerLegitPlayer,
2469
+ // req.data.round.players.length,
2470
+ // JSON.stringify(req.data.round.players)
2471
+ // );
2472
+ // throw new Error('Big problem with item reward amount');
2473
+ // }
2474
+
2475
+ // if (pickup.quantity > req.data.round.players.length * app.db.evolution.config.rewardItemAmountMax) {
2476
+ // log(pickup.quantity, req.data.round.players.length, app.db.evolution.config.rewardItemAmountMax);
2477
+ // throw new Error('Big problem with item reward amount 2');
2478
+ // }
2479
+
2480
+ // const runeSymbol = pickup.rewardItemName.toLowerCase();
2481
+
2482
+ // if (!runes.includes(runeSymbol)) {
2483
+ // continue;
2484
+ // }
2485
+
2486
+ // if (!user.rewards.runes[runeSymbol] || user.rewards.runes[runeSymbol] < 0.000000001) {
2487
+ // user.rewards.runes[runeSymbol] = 0;
2488
+ // }
2489
+
2490
+ // user.rewards.runes[runeSymbol] += pickup.quantity;
2491
+
2492
+ // if (!user.lifetimeRewards.runes[runeSymbol] || user.lifetimeRewards.runes[runeSymbol] < 0.000000001) {
2493
+ // user.lifetimeRewards.runes[runeSymbol] = 0;
2494
+ // }
2495
+
2496
+ // user.lifetimeRewards.runes[runeSymbol] += pickup.quantity;
2497
+
2498
+ // app.db.evolution.config.itemRewards.runes[runeSymbol.toLowerCase()] -= pickup.quantity;
2499
+
2500
+ // app.db.oracle.outflow.evolutionRewards.tokens.week[runeSymbol.toLowerCase()] += pickup.quantity;
2501
+ // } else {
2502
+ // user.rewards.items[pickup.id] = {
2503
+ // name: pickup.name,
2504
+ // rarity: pickup.rarity,
2505
+ // quantity: pickup.quantity,
2506
+ // };
2507
+
2508
+ // user.lifetimeRewards.items[pickup.id] = {
2509
+ // name: pickup.name,
2510
+ // rarity: pickup.rarity,
2511
+ // quantity: pickup.quantity,
2512
+ // };
2513
+ // }
2514
+
2515
+ // // user.rewardTracking.push(req.tracking)
2516
+ // }
2517
+
2518
+ // user.lastGamePlayed = now;
2519
+
2520
+ // if (!user.evolution.hashes) user.evolution.hashes = [];
2521
+ // if (!user.evolution.hashes.includes(player.hash)) user.evolution.hashes.push(player.hash);
2522
+
2523
+ // user.evolution.hashes = user.evolution.hashes.filter(function (item, pos) {
2524
+ // return user.evolution.hashes.indexOf(item) === pos;
2525
+ // });
2526
+
2527
+ // // users.push(user)
2528
+
2529
+ // if (!app.games.evolution.realms[realm.key].leaderboard.names)
2530
+ // app.games.evolution.realms[realm.key].leaderboard.names = {};
2531
+
2532
+ // app.games.evolution.realms[realm.key].leaderboard.names[user.address] = user.username;
2533
+
2534
+ // if (!app.games.evolution.realms[realm.key].leaderboard.raw.points[user.address]) {
2535
+ // // 'orbs', 'revenges', 'rounds', 'wins', 'timeSpent', 'winRatio', 'killDeathRatio', 'roundPointRatio', 'averageLatency'
2536
+ // app.games.evolution.realms[realm.key].leaderboard.raw.monetary[user.address] = 0;
2537
+ // app.games.evolution.realms[realm.key].leaderboard.raw.wins[user.address] = 0;
2538
+ // app.games.evolution.realms[realm.key].leaderboard.raw.rounds[user.address] = 0;
2539
+ // app.games.evolution.realms[realm.key].leaderboard.raw.kills[user.address] = 0;
2540
+ // app.games.evolution.realms[realm.key].leaderboard.raw.points[user.address] = 0;
2541
+ // app.games.evolution.realms[realm.key].leaderboard.raw.deaths[user.address] = 0;
2542
+ // app.games.evolution.realms[realm.key].leaderboard.raw.powerups[user.address] = 0;
2543
+ // app.games.evolution.realms[realm.key].leaderboard.raw.evolves[user.address] = 0;
2544
+ // app.games.evolution.realms[realm.key].leaderboard.raw.rewards[user.address] = 0;
2545
+ // app.games.evolution.realms[realm.key].leaderboard.raw.pickups[user.address] = 0;
2546
+ // }
2547
+
2548
+ // // Update leaderboard stats
2549
+ // app.games.evolution.realms[realm.key].leaderboard.raw.rounds[user.address] += 1;
2550
+ // app.games.evolution.realms[realm.key].leaderboard.raw.kills[user.address] += player.kills;
2551
+ // app.games.evolution.realms[realm.key].leaderboard.raw.points[user.address] += player.points;
2552
+ // app.games.evolution.realms[realm.key].leaderboard.raw.deaths[user.address] += player.deaths;
2553
+ // app.games.evolution.realms[realm.key].leaderboard.raw.powerups[user.address] += player.powerups;
2554
+ // app.games.evolution.realms[realm.key].leaderboard.raw.evolves[user.address] += player.evolves;
2555
+ // app.games.evolution.realms[realm.key].leaderboard.raw.rewards[user.address] += player.rewards;
2556
+ // app.games.evolution.realms[realm.key].leaderboard.raw.pickups[user.address] += player.pickups.length;
2557
+
2558
+ // if (!app.games.evolution.global.leaderboard.names) app.games.evolution.global.leaderboard.names = {};
2559
+
2560
+ // app.games.evolution.global.leaderboard.names[user.address] = user.username;
2561
+
2562
+ // if (!app.games.evolution.global.leaderboard.raw.points[user.address]) {
2563
+ // // 'orbs', 'revenges', 'rounds', 'wins', 'timeSpent', 'winRatio', 'killDeathRatio', 'roundPointRatio', 'averageLatency'
2564
+ // app.games.evolution.global.leaderboard.raw.monetary[user.address] = 0;
2565
+ // app.games.evolution.global.leaderboard.raw.wins[user.address] = 0;
2566
+ // app.games.evolution.global.leaderboard.raw.rounds[user.address] = 0;
2567
+ // app.games.evolution.global.leaderboard.raw.kills[user.address] = 0;
2568
+ // app.games.evolution.global.leaderboard.raw.points[user.address] = 0;
2569
+ // app.games.evolution.global.leaderboard.raw.deaths[user.address] = 0;
2570
+ // app.games.evolution.global.leaderboard.raw.powerups[user.address] = 0;
2571
+ // app.games.evolution.global.leaderboard.raw.evolves[user.address] = 0;
2572
+ // app.games.evolution.global.leaderboard.raw.rewards[user.address] = 0;
2573
+ // app.games.evolution.global.leaderboard.raw.pickups[user.address] = 0;
2574
+ // }
2575
+
2576
+ // // Update leaderboard stats
2577
+ // app.games.evolution.global.leaderboard.raw.rounds[user.address] += 1;
2578
+ // app.games.evolution.global.leaderboard.raw.kills[user.address] += player.kills;
2579
+ // app.games.evolution.global.leaderboard.raw.points[user.address] += player.points;
2580
+ // app.games.evolution.global.leaderboard.raw.deaths[user.address] += player.deaths;
2581
+ // app.games.evolution.global.leaderboard.raw.powerups[user.address] += player.powerups;
2582
+ // app.games.evolution.global.leaderboard.raw.evolves[user.address] += player.evolves;
2583
+ // app.games.evolution.global.leaderboard.raw.rewards[user.address] += player.rewards;
2584
+ // app.games.evolution.global.leaderboard.raw.pickups[user.address] += player.pickups.length;
2585
+
2586
+ // if (winners.find((winner) => winner.address === player.address)) {
2587
+ // const index = winners.findIndex((winner) => winner.address === player.address);
2588
+ // // const player = req.data.round.winners[index]
2589
+ // // const user = users.find(u => u.address === player.address)
2590
+
2591
+ // // if (!user) continue // He wasn't valid
2592
+ // if (user.username) {
2593
+ // // Make sure cant earn without a character
2594
+ // // if (req.data.round.winners[0].address === player.address) {
2595
+ // let character = CharacterCache[player.address];
2596
+
2597
+ // if (!character) {
2598
+ // console.log('Getting char data');
2599
+ // character = await getCharacter(app, player.address);
2600
+ // console.log('Got char data');
2601
+
2602
+ // CharacterCache[player.address] = character;
2603
+ // }
2604
+
2605
+ // const WinRewardsIncrease = character?.meta?.[1150] || 0;
2606
+ // const WinRewardsDecrease = character?.meta?.[1160] || 0;
2607
+
2608
+ // console.log('bbbb', rewardWinnerMap[index]);
2609
+ // const rewardMultiplier = 1 + (WinRewardsIncrease - WinRewardsDecrease) / 100;
2610
+
2611
+ // if (rewardMultiplier > 2 || rewardMultiplier < 0) {
2612
+ // log(
2613
+ // 'Error with reward multiplier.. bad things happened: ',
2614
+ // rewardMultiplier,
2615
+ // rewardMultiplier,
2616
+ // WinRewardsDecrease
2617
+ // );
2618
+ // process.exit(5);
2619
+ // }
2620
+
2621
+ // rewardWinnerMap[index] *= rewardMultiplier;
2622
+ // console.log('cccc', rewardWinnerMap[index]);
2623
+ // // }
2624
+
2625
+ // if (!user.rewards.runes['zod']) {
2626
+ // user.rewards.runes['zod'] = 0;
2627
+ // }
2628
+
2629
+ // if (user.rewards.runes['zod'] < 0) {
2630
+ // user.rewards.runes['zod'] = 0;
2631
+ // }
2632
+
2633
+ // user.rewards.runes['zod'] += rewardWinnerMap[index];
2634
+
2635
+ // if (!user.lifetimeRewards.runes['zod']) {
2636
+ // user.lifetimeRewards.runes['zod'] = 0;
2637
+ // }
2638
+
2639
+ // user.lifetimeRewards.runes['zod'] += rewardWinnerMap[index];
2640
+
2641
+ // app.db.oracle.outflow.evolutionRewards.tokens.week['zod'] += rewardWinnerMap[index];
2642
+
2643
+ // app.games.evolution.global.leaderboard.raw.monetary[user.address] += rewardWinnerMap[index];
2644
+
2645
+ // app.games.evolution.realms[realm.key].leaderboard.raw.monetary[user.address] += rewardWinnerMap[index];
2646
+
2647
+ // app.api.emitAll('PlayerAction', {
2648
+ // key: 'evolution1-winner',
2649
+ // createdAt: new Date().getTime() / 1000,
2650
+ // address: user.address,
2651
+ // username: user.username,
2652
+ // realmKey: realm.key,
2653
+ // placement: index + 1,
2654
+ // message: `${user.username} placed #${index + 1} for ${rewardWinnerMap[index].toFixed(
2655
+ // 4
2656
+ // )} ZOD in Evolution`,
2657
+ // });
2658
+
2659
+ // if (rewardWinnerMap[index] > 0.1) {
2660
+ // app.notices.add('evolution1-winner', {
2661
+ // key: 'evolution1-winner',
2662
+ // address: user.address,
2663
+ // username: user.username,
2664
+ // realmKey: realm.key,
2665
+ // placement: index + 1,
2666
+ // message: `${user.username} won ${rewardWinnerMap[index].toFixed(4)} ZOD in Evolution`,
2667
+ // });
2668
+ // }
2669
+
2670
+ // if (req.data.round.winners[0].address === player.address) {
2671
+ // if (!app.games.evolution.realms[realm.key].leaderboard.raw)
2672
+ // app.games.evolution.realms[realm.key].leaderboard.raw = {};
2673
+ // if (!app.games.evolution.realms[realm.key].leaderboard.raw.wins)
2674
+ // app.games.evolution.realms[realm.key].leaderboard.raw.wins = 0;
2675
+
2676
+ // app.games.evolution.realms[realm.key].leaderboard.raw.wins[user.address] += 1;
2677
+
2678
+ // if (!app.games.evolution.global.leaderboard.raw) app.games.evolution.global.leaderboard.raw = {};
2679
+ // if (!app.games.evolution.global.leaderboard.raw.wins) app.games.evolution.global.leaderboard.raw.wins = 0;
2680
+
2681
+ // app.games.evolution.global.leaderboard.raw.wins[user.address] += 1;
2682
+ // }
2683
+ // }
2684
+ // }
2685
+
2686
+ // await app.db.saveUser(user);
2687
+ // }
2688
+
2689
+ // log('Round saved');
2690
+
2691
+ // client.socket.emit('SaveRoundResponse', {
2692
+ // id: req.id,
2693
+ // data: { status: 1 },
2694
+ // });
2695
+ // } catch (e) {
2696
+ // log('Error', e);
2697
+
2698
+ // client.socket.emit('SaveRoundResponse', {
2699
+ // id: req.id,
2700
+ // data: { status: 0, message: e },
2701
+ // });
2702
+
2703
+ // disconnectClient(client);
2704
+ // }
2705
+ // });
2706
+
2707
+ // // {
2708
+ // // id: 'vLgqLC_oa',
2709
+ // // signature: {
2710
+ // // address: '0xDfA8f768d82D719DC68E12B199090bDc3691fFc7',
2711
+ // // hash: '0xaa426a32a8f0dae65f160e52d3c0004582e796942894c199255298a05b5f40a473b4257e367e5c285a1eeaf9a8f69b14b8fc273377ab4c79e256962a3434978a1c',
2712
+ // // data: '96a190dbd01b86b08d6feafc6444481b'
2713
+ // // },
2714
+ // // data: {
2715
+ // // id: '7mrEmDnd6',
2716
+ // // data: {
2717
+ // // id: 1,
2718
+ // // startedAt: 1644133312,
2719
+ // // leaders: [Array],
2720
+ // // players: [Array]
2721
+ // // }
2722
+ // // }
2723
+ // // }
2724
+ // // {
2725
+ // // id: 2,
2726
+ // // startedAt: 1644135785,
2727
+ // // leaders: [],
2728
+ // // players: [
2729
+ // // {
2730
+ // // name: 'Sdadasd',
2731
+ // // id: 'ovEbbscHo3D7aWVBAAAD',
2732
+ // // avatar: 0,
2733
+ // // network: 'bsc',
2734
+ // // address: '0x191727d22f2693100acef8e48F8FeaEaa06d30b1',
2735
+ // // device: 'desktop',
2736
+ // // position: [Object],
2737
+ // // target: [Object],
2738
+ // // clientPosition: [Object],
2739
+ // // clientTarget: [Object],
2740
+ // // rotation: null,
2741
+ // // xp: 0,
2742
+ // // latency: 12627.5,
2743
+ // // kills: 0,
2744
+ // // deaths: 0,
2745
+ // // points: 0,
2746
+ // // evolves: 0,
2747
+ // // powerups: 0,
2748
+ // // rewards: 0,
2749
+ // // orbs: 0,
2750
+ // // rewardHistory: [],
2751
+ // // isMod: false,
2752
+ // // isBanned: false,
2753
+ // // isMasterClient: false,
2754
+ // // isDisconnected: true,
2755
+ // // isDead: true,
2756
+ // // isJoining: false,
2757
+ // // isSpectating: false,
2758
+ // // isStuck: false,
2759
+ // // isInvincible: false,
2760
+ // // isPhased: false,
2761
+ // // overrideSpeed: 0.5,
2762
+ // // overrideCameraSize: null,
2763
+ // // cameraSize: 3,
2764
+ // // speed: 0.5,
2765
+ // // joinedAt: 0,
2766
+ // // hash: '',
2767
+ // // lastReportedTime: 1644135787011,
2768
+ // // lastUpdate: 1644135787016,
2769
+ // // gameMode: 'Deathmatch',
2770
+ // // phasedUntil: 1644135814266,
2771
+ // // log: [Object],
2772
+ // // startedRoundAt: 1644135785
2773
+ // // }
2774
+ // // ]
2775
+ // // }
2776
+
2777
+ // client.socket.onAny(function (eventName, res) {
2778
+ // // log('Event All', eventName, res)
2779
+ // if (!res || !res.id) return;
2780
+ // // console.log(eventName, res)
2781
+ // if (ioCallbacks[res.id]) {
2782
+ // log('Callback', eventName, res);
2783
+
2784
+ // clearTimeout(ioCallbacks[res.id].reqTimeout);
2785
+
2786
+ // ioCallbacks[res.id].resolve(res.data);
2787
+
2788
+ // delete ioCallbacks[res.id];
2789
+ // }
2790
+ // });
2791
+
2792
+ // client.socket.connect();
2793
+
2794
+ // client.connectTimeout = setTimeout(function () {
2795
+ // if (!client.isAuthed) {
2796
+ // log(`Couldnt connect/authorize ${realm.key} on ${realm.endpoint}`);
2797
+ // disconnectClient(client);
2798
+ // }
2799
+ // }, 60 * 1000);
2800
+ // }
2801
+
2802
+ // export async function connectRealms(app) {
2803
+ // log('Connecting to Evolution realms');
2804
+
2805
+ // try {
2806
+ // for (const realm of app.db.evolution.realms) {
2807
+ // if (!app.games.evolution.realms[realm.key]) {
2808
+ // app.games.evolution.realms[realm.key] = {};
2809
+ // for (const key in Object.keys(realm)) {
2810
+ // app.games.evolution.realms[realm.key][key] = realm[key];
2811
+ // }
2812
+ // }
2813
+
2814
+ // // if (!app.games.evolution.realms[realm.key].leaderboard) app.games.evolution.realms[realm.key].leaderboard = {}
2815
+ // // if (!app.games.evolution.realms[realm.key].leaderboard.raw) app.games.evolution.realms[realm.key].leaderboard.raw = {}
2816
+ // // if (!app.games.evolution.realms[realm.key].leaderboard.raw.wins) app.games.evolution.realms[realm.key].leaderboard.raw.wins = {}
2817
+ // // if (!app.games.evolution.realms[realm.key].leaderboard.raw.rounds) app.games.evolution.realms[realm.key].leaderboard.raw.rounds = {}
2818
+ // // if (!app.games.evolution.realms[realm.key].leaderboard.raw.kills) app.games.evolution.realms[realm.key].leaderboard.raw.kills = {}
2819
+ // // if (!app.games.evolution.realms[realm.key].leaderboard.raw.points) app.games.evolution.realms[realm.key].leaderboard.raw.points = {}
2820
+ // // if (!app.games.evolution.realms[realm.key].leaderboard.raw.deaths) app.games.evolution.realms[realm.key].leaderboard.raw.deaths = {}
2821
+ // // if (!app.games.evolution.realms[realm.key].leaderboard.raw.powerups) app.games.evolution.realms[realm.key].leaderboard.raw.powerups = {}
2822
+ // // if (!app.games.evolution.realms[realm.key].leaderboard.raw.evolves) app.games.evolution.realms[realm.key].leaderboard.raw.evolves = {}
2823
+ // // if (!app.games.evolution.realms[realm.key].leaderboard.raw.rewards) app.games.evolution.realms[realm.key].leaderboard.raw.rewards = {}
2824
+ // // if (!app.games.evolution.realms[realm.key].leaderboard.raw.pickups) app.games.evolution.realms[realm.key].leaderboard.raw.pickups = {}
2825
+
2826
+ // if (!app.games.evolution.global) {
2827
+ // app.games.evolution.global = {
2828
+ // key: 'global',
2829
+ // };
2830
+ // }
2831
+
2832
+ // if (!app.games.evolution.global.leaderboard) {
2833
+ // app.games.evolution.global.leaderboard = jetpack.read(
2834
+ // path.resolve(`./db/evolution/global/season${app.games.evolution.currentSeason}/leaderboard.json`),
2835
+ // 'json'
2836
+ // ) || {
2837
+ // raw: {
2838
+ // monetary: {},
2839
+ // wins: {},
2840
+ // rounds: {},
2841
+ // rewards: {},
2842
+ // points: {},
2843
+ // kills: {},
2844
+ // deaths: {},
2845
+ // powerups: {},
2846
+ // evolves: {},
2847
+ // pickups: {},
2848
+ // },
2849
+ // names: {},
2850
+ // [app.games.evolution.currentSeason]: {
2851
+ // all: [
2852
+ // {
2853
+ // name: 'Overall',
2854
+ // count: 1000,
2855
+ // data: [],
2856
+ // },
2857
+ // ],
2858
+ // monetary: [
2859
+ // {
2860
+ // name: 'Earnings',
2861
+ // count: 1000,
2862
+ // data: [],
2863
+ // },
2864
+ // ],
2865
+ // wins: [
2866
+ // {
2867
+ // name: 'Wins',
2868
+ // count: 1000,
2869
+ // data: [],
2870
+ // },
2871
+ // ],
2872
+ // rounds: [
2873
+ // {
2874
+ // name: 'Rounds',
2875
+ // count: 1000,
2876
+ // data: [],
2877
+ // },
2878
+ // ],
2879
+ // rewards: [
2880
+ // {
2881
+ // name: 'Rewards',
2882
+ // count: 1000,
2883
+ // data: [],
2884
+ // },
2885
+ // ],
2886
+ // points: [
2887
+ // {
2888
+ // name: 'Points',
2889
+ // count: 1000,
2890
+ // data: [],
2891
+ // },
2892
+ // ],
2893
+ // kills: [
2894
+ // {
2895
+ // name: 'Kills',
2896
+ // count: 1000,
2897
+ // data: [],
2898
+ // },
2899
+ // ],
2900
+ // deaths: [
2901
+ // {
2902
+ // name: 'Deaths',
2903
+ // count: 1000,
2904
+ // data: [],
2905
+ // },
2906
+ // ],
2907
+ // powerups: [
2908
+ // {
2909
+ // name: 'Powerups',
2910
+ // count: 1000,
2911
+ // data: [],
2912
+ // },
2913
+ // ],
2914
+ // evolves: [
2915
+ // {
2916
+ // name: 'Evolves',
2917
+ // count: 1000,
2918
+ // data: [],
2919
+ // },
2920
+ // ],
2921
+ // },
2922
+ // };
2923
+ // }
2924
+
2925
+ // if (!app.games.evolution.realms[realm.key].leaderboard) {
2926
+ // app.games.evolution.realms[realm.key].leaderboard = jetpack.read(
2927
+ // path.resolve(`./db/evolution/${realm.key}/season${app.games.evolution.currentSeason}/leaderboard.json`),
2928
+ // 'json'
2929
+ // ) || {
2930
+ // raw: {
2931
+ // monetary: {},
2932
+ // wins: {},
2933
+ // rounds: {},
2934
+ // rewards: {},
2935
+ // points: {},
2936
+ // kills: {},
2937
+ // deaths: {},
2938
+ // powerups: {},
2939
+ // evolves: {},
2940
+ // pickups: {},
2941
+ // },
2942
+ // names: {},
2943
+ // [app.games.evolution.currentSeason]: {
2944
+ // all: [
2945
+ // {
2946
+ // name: 'Overall',
2947
+ // count: 1000,
2948
+ // data: [],
2949
+ // },
2950
+ // ],
2951
+ // monetary: [
2952
+ // {
2953
+ // name: 'Earnings',
2954
+ // count: 1000,
2955
+ // data: [],
2956
+ // },
2957
+ // ],
2958
+ // wins: [
2959
+ // {
2960
+ // name: 'Wins',
2961
+ // count: 1000,
2962
+ // data: [],
2963
+ // },
2964
+ // ],
2965
+ // rounds: [
2966
+ // {
2967
+ // name: 'Rounds',
2968
+ // count: 1000,
2969
+ // data: [],
2970
+ // },
2971
+ // ],
2972
+ // rewards: [
2973
+ // {
2974
+ // name: 'Rewards',
2975
+ // count: 1000,
2976
+ // data: [],
2977
+ // },
2978
+ // ],
2979
+ // points: [
2980
+ // {
2981
+ // name: 'Points',
2982
+ // count: 1000,
2983
+ // data: [],
2984
+ // },
2985
+ // ],
2986
+ // kills: [
2987
+ // {
2988
+ // name: 'Kills',
2989
+ // count: 1000,
2990
+ // data: [],
2991
+ // },
2992
+ // ],
2993
+ // deaths: [
2994
+ // {
2995
+ // name: 'Deaths',
2996
+ // count: 1000,
2997
+ // data: [],
2998
+ // },
2999
+ // ],
3000
+ // powerups: [
3001
+ // {
3002
+ // name: 'Powerups',
3003
+ // count: 1000,
3004
+ // data: [],
3005
+ // },
3006
+ // ],
3007
+ // evolves: [
3008
+ // {
3009
+ // name: 'Evolves',
3010
+ // count: 1000,
3011
+ // data: [],
3012
+ // },
3013
+ // ],
3014
+ // },
3015
+ // };
3016
+ // }
3017
+
3018
+ // if (!app.games.evolution.realms[realm.key].client) {
3019
+ // app.games.evolution.realms[realm.key].key = realm.key;
3020
+
3021
+ // app.games.evolution.realms[realm.key].client = {
3022
+ // isAuthed: false,
3023
+ // isConnecting: false,
3024
+ // isConnected: false,
3025
+ // socket: null,
3026
+ // connectTimeout: null,
3027
+ // reqTimeout: null,
3028
+ // };
3029
+ // }
3030
+
3031
+ // if (!realm.roundId) {
3032
+ // realm.roundId = 1;
3033
+ // }
3034
+
3035
+ // // if (realm.key.indexOf('ptr') !== -1 || realm.key.indexOf('tournament') !== -1) continue
3036
+ // if (realm.status === 'inactive' || realm.updateMode === 'manual') continue;
3037
+
3038
+ // if (
3039
+ // !app.games.evolution.realms[realm.key].client.isConnected &&
3040
+ // !app.games.evolution.realms[realm.key].client.isConnecting &&
3041
+ // !app.games.evolution.realms[realm.key].client.isAuthed
3042
+ // ) {
3043
+ // await connectRealm(app, realm);
3044
+ // }
3045
+ // }
3046
+ // } catch (e) {
3047
+ // log('Error', e);
3048
+ // }
3049
+ // }
3050
+
3051
+ // export async function emitAll(app, ...args) {
3052
+ // for (const realm of app.db.evolution.realms) {
3053
+ // if (app.games.evolution.realms[realm.key]?.client?.isAuthed) {
3054
+ // console.log('emitAll', realm.key, ...args);
3055
+ // app.games.evolution.realms[realm.key]?.client?.socket.emit(...args);
3056
+ // }
3057
+ // }
3058
+ // }
3059
+
3060
+ // export async function monitorEvolutionRealms(app) {
3061
+ // if (!app.realm) {
3062
+ // app.realm = {};
3063
+ // app.realm.apiAddress = '0x4b64Ff29Ee3B68fF9de11eb1eFA577647f83151C';
3064
+ // app.realm.apiSignature = await getSignedRequest(
3065
+ // app.web3,
3066
+ // app.secrets.find((s) => s.id === 'evolution-signer'),
3067
+ // 'evolution'
3068
+ // );
3069
+ // app.realm.emitAll = emitAll.bind(null, app);
3070
+ // }
3071
+
3072
+ // if (!app.db.evolution.config.rewardWinnerAmountPerLegitPlayerQueued) {
3073
+ // app.db.evolution.config.rewardWinnerAmountPerLegitPlayerQueued =
3074
+ // app.db.evolution.config.rewardWinnerAmountPerLegitPlayer;
3075
+ // }
3076
+
3077
+ // if (!app.db.evolution.config.rewardWinnerAmountMaxQueued) {
3078
+ // app.db.evolution.config.rewardWinnerAmountMaxQueued = app.db.evolution.config.rewardWinnerAmountMax;
3079
+ // }
3080
+
3081
+ // if (!app.db.evolution.config.itemRewards) {
3082
+ // app.db.evolution.config.itemRewards = {
3083
+ // runes: [
3084
+ // {
3085
+ // type: 'rune',
3086
+ // symbol: 'ith',
3087
+ // quantity: 10000,
3088
+ // },
3089
+ // {
3090
+ // type: 'rune',
3091
+ // symbol: 'amn',
3092
+ // quantity: 10000,
3093
+ // },
3094
+ // {
3095
+ // type: 'rune',
3096
+ // symbol: 'ort',
3097
+ // quantity: 10000,
3098
+ // },
3099
+ // {
3100
+ // type: 'rune',
3101
+ // symbol: 'tal',
3102
+ // quantity: 10000,
3103
+ // },
3104
+ // {
3105
+ // type: 'rune',
3106
+ // symbol: 'dol',
3107
+ // quantity: 10000,
3108
+ // },
3109
+ // // {
3110
+ // // "type": "rune",
3111
+ // // "symbol": "sol",
3112
+ // // "quantity": 0
3113
+ // // },
3114
+ // // {
3115
+ // // "type": "rune",
3116
+ // // "symbol": "tir",
3117
+ // // "quantity": 0
3118
+ // // },
3119
+ // // {
3120
+ // // "type": "rune",
3121
+ // // "symbol": "nef",
3122
+ // // "quantity": 0
3123
+ // // },
3124
+ // // {
3125
+ // // "type": "rune",
3126
+ // // "symbol": "hel",
3127
+ // // "quantity": 10000
3128
+ // // },
3129
+ // // {
3130
+ // // "type": "rune",
3131
+ // // "symbol": "ral",
3132
+ // // "quantity": 0
3133
+ // // },
3134
+ // // {
3135
+ // // "type": "rune",
3136
+ // // "symbol": "thul",
3137
+ // // "quantity": 0
3138
+ // // },
3139
+ // // {
3140
+ // // "type": "rune",
3141
+ // // "symbol": "shael",
3142
+ // // "quantity": 0
3143
+ // // },
3144
+ // // {
3145
+ // // "type": "rune",
3146
+ // // "symbol": "ist",
3147
+ // // "quantity": 10000
3148
+ // // },
3149
+ // // {
3150
+ // // "type": "rune",
3151
+ // // "symbol": "mal",
3152
+ // // "quantity": 10000
3153
+ // // },
3154
+ // // {
3155
+ // // "type": "rune",
3156
+ // // "symbol": "um",
3157
+ // // "quantity": 10000
3158
+ // // },
3159
+ // // {
3160
+ // // "type": "rune",
3161
+ // // "symbol": "pul",
3162
+ // // "quantity": 10000
3163
+ // // },
3164
+ // // {
3165
+ // // "type": "rune",
3166
+ // // "symbol": "lum",
3167
+ // // "quantity": 10000
3168
+ // // },
3169
+ // // {
3170
+ // // "type": "rune",
3171
+ // // "symbol": "zod",
3172
+ // // "quantity": 0
3173
+ // // }
3174
+ // ],
3175
+ // items: [],
3176
+ // };
3177
+ // }
3178
+
3179
+ // if (!app.db.evolution.config.itemRewardsQueued) {
3180
+ // app.db.evolution.config.itemRewardsQueued = app.db.evolution.config.itemRewards;
3181
+ // }
3182
+
3183
+ // await connectRealms(app);
3184
+ // await updateRealms(app);
3185
+
3186
+ // setTimeout(() => monitorEvolutionRealms(app), 30 * 1000);
3187
+ // }
3188
+
3189
+ // setInterval(function () {
3190
+ // log('Clearing character cache...');
3191
+ // CharacterCache = {};
3192
+ // }, 30 * 60 * 1000);
3193
+
3194
+ // dotenv.config();
3195
+
3196
+ // export const router = t.router;
3197
+ // export const procedure = procedure;
3198
+ // export const createCallerFactory = t.createCallerFactory;
3199
+
3200
+ // export class Seer {
3201
+ // constructor() {}
3202
+
3203
+ // characters: Record<string, Character> = {};
3204
+ // db: any;
3205
+ // io: any;
3206
+ // app: any;
3207
+ // realm: any;
3208
+
3209
+ // pingRequest(msg: any) {
3210
+ // log('PingRequest', msg);
3211
+ // this.io.emit('PingResponse');
3212
+ // }
3213
+
3214
+ // pongRequest(msg: any) {
3215
+ // log('PongRequest', msg);
3216
+ // this.io.emit('PongResponse');
3217
+ // }
3218
+
3219
+ // async unbanClient(req: { data: { target: string }; id: string }) {
3220
+ // log('unbanClient', req);
3221
+
3222
+ // const user = await this.db.loadUser(req.data.target);
3223
+ // delete user.isBanned;
3224
+ // delete user.banReason;
3225
+ // await this.db.saveUser(user);
3226
+
3227
+ // this.db.removeBanList('evolution', req.data.target);
3228
+ // this.db.saveBanList();
3229
+
3230
+ // return { target: req.data.target };
3231
+ // }
3232
+
3233
+ // async mod(req: {
3234
+ // data: {
3235
+ // body: { signature: { address: string } };
3236
+ // params: { method: string };
3237
+ // };
3238
+ // }) {
3239
+ // log('mod', req);
3240
+
3241
+ // const user = await this.db.loadUser(req.data.body.signature.address);
3242
+ // emitAll('playerAction', {
3243
+ // key: 'moderator-action',
3244
+ // createdAt: new Date().getTime() / 1000,
3245
+ // address: user.address,
3246
+ // username: user.username,
3247
+ // method: req.data.params.method,
3248
+ // message: `${user.username} called ${req.data.params.method}`,
3249
+ // });
3250
+
3251
+ // return { status: 1 };
3252
+ // }
3253
+
3254
+ // async banClient(req: { data: { target: string; reason: string; until?: number }; id: string }) {
3255
+ // log('banClient', req);
3256
+
3257
+ // const user = await this.db.loadUser(req.data.target);
3258
+ // user.isBanned = true;
3259
+ // user.banReason = req.data.reason;
3260
+ // user.banExpireDate = req.data.until || new Date().getTime() + 100 * 365 * 24 * 60 * 60; // 100 years by default
3261
+
3262
+ // await this.db.saveUser(user);
3263
+
3264
+ // this.db.addBanList('evolution', {
3265
+ // address: req.data.target,
3266
+ // reason: req.data.reason,
3267
+ // until: req.data.until,
3268
+ // });
3269
+
3270
+ // this.db.saveBanList();
3271
+
3272
+ // return {
3273
+ // status: 1,
3274
+ // data: {
3275
+ // target: req.data.target,
3276
+ // createdAt: new Date().getTime(),
3277
+ // banExpireDate: user.banExpireDate,
3278
+ // banReason: user.banReason,
3279
+ // },
3280
+ // };
3281
+ // }
3282
+
3283
+ // reportClient(msg: any) {
3284
+ // log('reportClient', msg);
3285
+
3286
+ // const { currentGamePlayers, currentPlayer, reportedPlayer } = msg;
3287
+
3288
+ // if (currentPlayer.name.includes('Guest') || currentPlayer.name.includes('Unknown')) return; // No guest reports
3289
+
3290
+ // if (!this.db.evolution.reportList[reportedPlayer.address]) {
3291
+ // this.db.evolution.reportList[reportedPlayer.address] = [];
3292
+ // }
3293
+
3294
+ // if (!this.db.evolution.reportList[reportedPlayer.address].includes(currentPlayer.address)) {
3295
+ // this.db.evolution.reportList[reportedPlayer.address].push(currentPlayer.address);
3296
+ // }
3297
+
3298
+ // // Additional logic for handling reports and disconnects can be added here
3299
+
3300
+ // // Relay the report to connected realm servers
3301
+ // }
3302
+
3303
+ // setRealmOffline(realm) {
3304
+ // if (realm.status === 'inactive' || realm.updateMode === 'manual') return;
3305
+
3306
+ // realm.status = 'offline';
3307
+ // realm.playerCount = 0;
3308
+ // realm.speculatorCount = 0;
3309
+ // realm.rewardItemAmount = 0;
3310
+ // realm.rewardWinnerAmount = 0;
3311
+ // }
3312
+
3313
+ // async getCharacter(req: { data: { address: string }; id: string }) {
3314
+ // log('GetCharacterRequest', req);
3315
+
3316
+ // let character = this.characters[req.data.address];
3317
+ // if (!character) {
3318
+ // character = await getCharacter(this.app, req.data.address);
3319
+ // this.characters[req.data.address] = character;
3320
+ // }
3321
+
3322
+ // return { status: 1, character };
3323
+ // }
3324
+
3325
+ // async setRealmConfig(app, realm) {
3326
+ // const configRes = (await rsCall(app, app.games.evolution.realms[realm.key], 'SetConfigRequest', {
3327
+ // config: { ...app.db.evolution.config, roundId: realm.roundId },
3328
+ // })) as any;
3329
+
3330
+ // if (configRes.status !== 1) {
3331
+ // this.setRealmOffline(realm);
3332
+ // return;
3333
+ // }
3334
+ // }
3335
+
3336
+ // async saveRound(req) {
3337
+ // log('SaveRoundRequest', this.realm.key, req);
3338
+
3339
+ // if (!(await isValidRequest(this.app.web3, req)) && this.db.evolution.modList.includes(req.signature.address)) {
3340
+ // log('Round invalid');
3341
+
3342
+ // return { status: 0, message: 'Invalid signature' };
3343
+ // }
3344
+
3345
+ // if (!req.data.lastClients) {
3346
+ // log('Round no clients');
3347
+
3348
+ // return { status: 0, message: 'Error processing' };
3349
+ // }
3350
+
3351
+ // if (req.data.round.winners.length === 0) {
3352
+ // this.realm.roundId += 1;
3353
+
3354
+ // log('Round skipped');
3355
+
3356
+ // return { status: 1 };
3357
+ // }
3358
+
3359
+ // if (req.data.rewardWinnerAmount > this.db.evolution.config.rewardWinnerAmountMax) {
3360
+ // log(req.data.rewardWinnerAmount, this.db.evolution.config.rewardWinnerAmountMax);
3361
+ // throw new Error('Big problem with reward amount');
3362
+ // }
3363
+
3364
+ // let totalLegitPlayers = 0;
3365
+
3366
+ // for (const client of req.data.lastClients) {
3367
+ // if (client.name.includes('Guest') || client.name.includes('Unknown')) continue;
3368
+
3369
+ // if (
3370
+ // (client.powerups > 100 && client.kills > 1) ||
3371
+ // (client.evolves > 20 && client.powerups > 200) ||
3372
+ // (client.rewards > 3 && client.powerups > 200) ||
3373
+ // client.evolves > 100 ||
3374
+ // client.points > 1000
3375
+ // ) {
3376
+ // totalLegitPlayers += 1;
3377
+ // }
3378
+ // }
3379
+
3380
+ // if (totalLegitPlayers === 0) {
3381
+ // totalLegitPlayers = 1;
3382
+ // }
3383
+
3384
+ // if (req.data.rewardWinnerAmount > this.db.evolution.config.rewardWinnerAmountPerLegitPlayer * totalLegitPlayers) {
3385
+ // log(
3386
+ // req.data.rewardWinnerAmount,
3387
+ // this.db.evolution.config.rewardWinnerAmountPerLegitPlayer,
3388
+ // totalLegitPlayers,
3389
+ // req.data.lastClients.length,
3390
+ // JSON.stringify(req.data.lastClients)
3391
+ // );
3392
+ // throw new Error('Big problem with reward amount 2');
3393
+ // }
3394
+
3395
+ // if (req.data.roundId > this.realm.roundId) {
3396
+ // this.realm.roundId = req.data.roundId;
3397
+ // } else if (req.data.roundId < this.realm.roundId) {
3398
+ // const err = `Round id too low (realm.roundId = ${this.realm.roundId})`;
3399
+
3400
+ // log(err);
3401
+
3402
+ // await this.setRealmConfig(this.app, this.realm);
3403
+
3404
+ // return { status: 0, message: err };
3405
+ // } else {
3406
+ // this.realm.roundId += 1;
3407
+ // }
3408
+
3409
+ // const rewardWinnerMap = {
3410
+ // 0: Math.round(req.data.rewardWinnerAmount * 1 * 1000) / 1000,
3411
+ // 1: Math.round(req.data.rewardWinnerAmount * 0.25 * 1000) / 1000,
3412
+ // 2: Math.round(req.data.rewardWinnerAmount * 0.15 * 1000) / 1000,
3413
+ // 3: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
3414
+ // 4: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
3415
+ // 5: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
3416
+ // 6: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
3417
+ // 7: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
3418
+ // 8: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
3419
+ // 9: Math.round(req.data.rewardWinnerAmount * 0.05 * 1000) / 1000,
3420
+ // };
3421
+
3422
+ // const removeDupes2 = (list) => {
3423
+ // const seen = {};
3424
+ // return list.filter((item) => {
3425
+ // const k1 = item.address;
3426
+ // if (seen[k1]) {
3427
+ // return false;
3428
+ // } else {
3429
+ // seen[k1] = true;
3430
+ // return true;
3431
+ // }
3432
+ // });
3433
+ // };
3434
+
3435
+ // req.data.round.players = removeDupes2(req.data.round.players);
3436
+
3437
+ // const winners = req.data.round.winners.slice(0, 10);
3438
+
3439
+ // for (const winner of winners) {
3440
+ // let character = this.characters[winner.address];
3441
+
3442
+ // if (!character) {
3443
+ // character = await this.getCharacter(winner.address);
3444
+ // this.characters[winner.address] = character;
3445
+ // }
3446
+
3447
+ // // Additional reward logic based on character's meta data
3448
+ // }
3449
+
3450
+ // for (const player of req.data.round.players) {
3451
+ // const user = await this.db.loadUser(player.address);
3452
+ // const now = new Date().getTime() / 1000;
3453
+
3454
+ // if (user.lastGamePlayed > now - 4 * 60) continue;
3455
+
3456
+ // if (!user.username) user.username = await this.getUsername(user.address);
3457
+ // if (!user.username) continue;
3458
+
3459
+ // this.db.setUserActive(user);
3460
+
3461
+ // if (player.killStreak >= 10) {
3462
+ // this.api.emitAll('PlayerAction', {
3463
+ // key: 'evolution1-killstreak',
3464
+ // createdAt: new Date().getTime() / 1000,
3465
+ // address: user.address,
3466
+ // username: user.username,
3467
+ // message: `${user.username} got a ${player.killStreak} killstreak in Evolution`,
3468
+ // });
3469
+ // this.notices.add('evolution1-killstreak', {
3470
+ // key: 'evolution1-killstreak',
3471
+ // address: user.address,
3472
+ // username: user.username,
3473
+ // message: `${user.username} got a ${player.killStreak} killstreak in Evolution`,
3474
+ // });
3475
+ // }
3476
+
3477
+ // for (const pickup of player.pickups) {
3478
+ // if (pickup.type === 'rune') {
3479
+ // if (
3480
+ // pickup.quantity >
3481
+ // req.data.round.players.length * this.db.evolution.config.rewardItemAmountPerLegitPlayer * 2
3482
+ // ) {
3483
+ // log(
3484
+ // pickup.quantity,
3485
+ // this.db.evolution.config.rewardItemAmountPerLegitPlayer,
3486
+ // req.data.round.players.length,
3487
+ // JSON.stringify(req.data.round.players)
3488
+ // );
3489
+ // throw new Error('Big problem with item reward amount');
3490
+ // }
3491
+
3492
+ // if (pickup.quantity > req.data.round.players.length * this.db.evolution.config.rewardItemAmountMax) {
3493
+ // log(pickup.quantity, req.data.round.players.length, this.db.evolution.config.rewardItemAmountMax);
3494
+ // throw new Error('Big problem with item reward amount 2');
3495
+ // }
3496
+
3497
+ // const runeSymbol = pickup.rewardItemName.toLowerCase();
3498
+ // if (!runes.includes(runeSymbol)) continue;
3499
+
3500
+ // user.rewards.runes[runeSymbol] = (user.rewards.runes[runeSymbol] || 0) + pickup.quantity;
3501
+ // user.lifetimeRewards.runes[runeSymbol] = (user.lifetimeRewards.runes[runeSymbol] || 0) + pickup.quantity;
3502
+
3503
+ // this.db.evolution.config.itemRewards.runes[runeSymbol.toLowerCase()] -= pickup.quantity;
3504
+ // this.db.oracle.outflow.evolutionRewards.tokens.week[runeSymbol.toLowerCase()] += pickup.quantity;
3505
+ // } else {
3506
+ // user.rewards.items[pickup.id] = {
3507
+ // name: pickup.name,
3508
+ // rarity: pickup.rarity,
3509
+ // quantity: pickup.quantity,
3510
+ // };
3511
+
3512
+ // user.lifetimeRewards.items[pickup.id] = {
3513
+ // name: pickup.name,
3514
+ // rarity: pickup.rarity,
3515
+ // quantity: pickup.quantity,
3516
+ // };
3517
+ // }
3518
+ // }
3519
+
3520
+ // user.lastGamePlayed = now;
3521
+
3522
+ // if (!user.evolution.hashes) user.evolution.hashes = [];
3523
+ // if (!user.evolution.hashes.includes(player.hash)) user.evolution.hashes.push(player.hash);
3524
+
3525
+ // user.evolution.hashes = user.evolution.hashes.filter((item, pos) => user.evolution.hashes.indexOf(item) === pos);
3526
+
3527
+ // if (!this.games.evolution.realms[this.realm.key].leaderboard.names)
3528
+ // this.games.evolution.realms[this.realm.key].leaderboard.names = {};
3529
+
3530
+ // this.games.evolution.realms[this.realm.key].leaderboard.names[user.address] = user.username;
3531
+
3532
+ // if (!this.games.evolution.realms[this.realm.key].leaderboard.raw.points[user.address]) {
3533
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.monetary[user.address] = 0;
3534
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.wins[user.address] = 0;
3535
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.rounds[user.address] = 0;
3536
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.kills[user.address] = 0;
3537
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.points[user.address] = 0;
3538
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.deaths[user.address] = 0;
3539
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.powerups[user.address] = 0;
3540
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.evolves[user.address] = 0;
3541
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.rewards[user.address] = 0;
3542
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.pickups[user.address] = 0;
3543
+ // }
3544
+
3545
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.rounds[user.address] += 1;
3546
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.kills[user.address] += player.kills;
3547
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.points[user.address] += player.points;
3548
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.deaths[user.address] += player.deaths;
3549
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.powerups[user.address] += player.powerups;
3550
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.evolves[user.address] += player.evolves;
3551
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.rewards[user.address] += player.rewards;
3552
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.pickups[user.address] += player.pickups.length;
3553
+
3554
+ // if (!this.games.evolution.global.leaderboard.names) this.games.evolution.global.leaderboard.names = {};
3555
+
3556
+ // this.games.evolution.global.leaderboard.names[user.address] = user.username;
3557
+
3558
+ // if (!this.games.evolution.global.leaderboard.raw.points[user.address]) {
3559
+ // this.games.evolution.global.leaderboard.raw.monetary[user.address] = 0;
3560
+ // this.games.evolution.global.leaderboard.raw.wins[user.address] = 0;
3561
+ // this.games.evolution.global.leaderboard.raw.rounds[user.address] = 0;
3562
+ // this.games.evolution.global.leaderboard.raw.kills[user.address] = 0;
3563
+ // this.games.evolution.global.leaderboard.raw.points[user.address] = 0;
3564
+ // this.games.evolution.global.leaderboard.raw.deaths[user.address] = 0;
3565
+ // this.games.evolution.global.leaderboard.raw.powerups[user.address] = 0;
3566
+ // this.games.evolution.global.leaderboard.raw.evolves[user.address] = 0;
3567
+ // this.games.evolution.global.leaderboard.raw.rewards[user.address] = 0;
3568
+ // this.games.evolution.global.leaderboard.raw.pickups[user.address] = 0;
3569
+ // }
3570
+
3571
+ // this.games.evolution.global.leaderboard.raw.rounds[user.address] += 1;
3572
+ // this.games.evolution.global.leaderboard.raw.kills[user.address] += player.kills;
3573
+ // this.games.evolution.global.leaderboard.raw.points[user.address] += player.points;
3574
+ // this.games.evolution.global.leaderboard.raw.deaths[user.address] += player.deaths;
3575
+ // this.games.evolution.global.leaderboard.raw.powerups[user.address] += player.powerups;
3576
+ // this.games.evolution.global.leaderboard.raw.evolves[user.address] += player.evolves;
3577
+ // this.games.evolution.global.leaderboard.raw.rewards[user.address] += player.rewards;
3578
+ // this.games.evolution.global.leaderboard.raw.pickups[user.address] += player.pickups.length;
3579
+
3580
+ // if (winners.find((winner) => winner.address === player.address)) {
3581
+ // const index = winners.findIndex((winner) => winner.address === player.address);
3582
+ // if (user.username) {
3583
+ // let character = this.characters[player.address];
3584
+
3585
+ // if (!character) {
3586
+ // character = await this.getCharacter(player.address);
3587
+ // this.characters[player.address] = character;
3588
+ // }
3589
+
3590
+ // const WinRewardsIncrease = character?.meta?.[1150] || 0;
3591
+ // const WinRewardsDecrease = character?.meta?.[1160] || 0;
3592
+
3593
+ // const rewardMultiplier = 1 + (WinRewardsIncrease - WinRewardsDecrease) / 100;
3594
+
3595
+ // if (rewardMultiplier > 2 || rewardMultiplier < 0) {
3596
+ // log(
3597
+ // 'Error with reward multiplier.. bad things happened: ',
3598
+ // rewardMultiplier,
3599
+ // rewardMultiplier,
3600
+ // WinRewardsDecrease
3601
+ // );
3602
+ // process.exit(5);
3603
+ // }
3604
+
3605
+ // rewardWinnerMap[index] *= rewardMultiplier;
3606
+
3607
+ // if (!user.rewards.runes['zod']) {
3608
+ // user.rewards.runes['zod'] = 0;
3609
+ // }
3610
+
3611
+ // if (user.rewards.runes['zod'] < 0) {
3612
+ // user.rewards.runes['zod'] = 0;
3613
+ // }
3614
+
3615
+ // user.rewards.runes['zod'] += rewardWinnerMap[index];
3616
+
3617
+ // if (!user.lifetimeRewards.runes['zod']) {
3618
+ // user.lifetimeRewards.runes['zod'] = 0;
3619
+ // }
3620
+
3621
+ // user.lifetimeRewards.runes['zod'] += rewardWinnerMap[index];
3622
+
3623
+ // this.db.oracle.outflow.evolutionRewards.tokens.week['zod'] += rewardWinnerMap[index];
3624
+
3625
+ // this.games.evolution.global.leaderboard.raw.monetary[user.address] += rewardWinnerMap[index];
3626
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.monetary[user.address] += rewardWinnerMap[index];
3627
+
3628
+ // this.api.emitAll('PlayerAction', {
3629
+ // key: 'evolution1-winner',
3630
+ // createdAt: new Date().getTime() / 1000,
3631
+ // address: user.address,
3632
+ // username: user.username,
3633
+ // realmKey: this.realm.key,
3634
+ // placement: index + 1,
3635
+ // message: `${user.username} placed #${index + 1} for ${rewardWinnerMap[index].toFixed(4)} ZOD in Evolution`,
3636
+ // });
3637
+
3638
+ // if (rewardWinnerMap[index] > 0.1) {
3639
+ // this.notices.add('evolution1-winner', {
3640
+ // key: 'evolution1-winner',
3641
+ // address: user.address,
3642
+ // username: user.username,
3643
+ // realmKey: this.realm.key,
3644
+ // placement: index + 1,
3645
+ // message: `${user.username} won ${rewardWinnerMap[index].toFixed(4)} ZOD in Evolution`,
3646
+ // });
3647
+ // }
3648
+
3649
+ // if (req.data.round.winners[0].address === player.address) {
3650
+ // if (!this.games.evolution.realms[this.realm.key].leaderboard.raw)
3651
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw = {};
3652
+ // if (!this.games.evolution.realms[this.realm.key].leaderboard.raw.wins)
3653
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.wins = 0;
3654
+
3655
+ // this.games.evolution.realms[this.realm.key].leaderboard.raw.wins[user.address] += 1;
3656
+
3657
+ // if (!this.games.evolution.global.leaderboard.raw) this.games.evolution.global.leaderboard.raw = {};
3658
+ // if (!this.games.evolution.global.leaderboard.raw.wins) this.games.evolution.global.leaderboard.raw.wins = 0;
3659
+
3660
+ // this.games.evolution.global.leaderboard.raw.wins[user.address] += 1;
3661
+ // }
3662
+ // }
3663
+ // }
3664
+
3665
+ // await this.db.saveUser(user);
3666
+ // }
3667
+
3668
+ // log('Round saved');
3669
+
3670
+ // return { status: 1 };
3671
+ // }
3672
+ // }
3673
+
3674
+ // const seer = new Seer();
3675
+
3676
+ // interface ProcedureContext {}
3677
+
3678
+ // export const createRouter = (
3679
+ // handler: (input: unknown, ctx: ProcedureContext) => Promise<void> | void // Adjust the return type if needed
3680
+ // ) => {
3681
+ // return router({
3682
+ // pingRequest: t.procedure.input(z.any()).mutation(({ input }) => seer.pingRequest(input)),
3683
+
3684
+ // pongRequest: t.procedure.input(z.any()).mutation(({ input }) => seer.pongRequest(input)),
3685
+
3686
+ // unbanClient: t.procedure
3687
+ // .input(z.object({ data: z.object({ target: z.string() }) }))
3688
+ // .mutation(({ input }) => seer.unbanClient(input)),
3689
+
3690
+ // mod: t.procedure
3691
+ // .input(
3692
+ // z.object({
3693
+ // data: z.object({
3694
+ // body: z.object({ signature: z.object({ address: z.string() }) }),
3695
+ // }),
3696
+ // })
3697
+ // )
3698
+ // .mutation(({ input }) => seer.mod(input)),
3699
+
3700
+ // banClient: t.procedure
3701
+ // .input(
3702
+ // z.object({
3703
+ // data: z.object({
3704
+ // target: z.string(),
3705
+ // reason: z.string(),
3706
+ // until: z.number().optional(),
3707
+ // }),
3708
+ // id: z.string(),
3709
+ // })
3710
+ // )
3711
+ // .mutation(({ input }) => seer.banClient(input)),
3712
+
3713
+ // reportClient: t.procedure.input(z.any()).mutation(({ input }) => seer.reportClient(input)),
3714
+
3715
+ // getCharacter: t.procedure
3716
+ // .input(z.object({ data: z.object({ address: z.string() }) }))
3717
+ // .mutation(({ input }) => seer.getCharacter(input)),
3718
+
3719
+ // saveRound: t.procedure
3720
+ // .input(
3721
+ // z.object({
3722
+ // data: z.object({
3723
+ // signature: z.object({ address: z.string() }),
3724
+ // lastClients: z.array(z.any()),
3725
+ // rewardWinnerAmount: z.number(),
3726
+ // round: z.object({
3727
+ // winners: z.array(z.any()),
3728
+ // players: z.array(z.any()),
3729
+ // }),
3730
+ // roundId: z.number(),
3731
+ // }),
3732
+ // })
3733
+ // )
3734
+ // .mutation(({ input }) => seer.saveRound(input)),
3735
+ // });
3736
+ // };
3737
+
3738
+ // export type Router = ReturnType<typeof createRouter>;