-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeploy.js
691 lines (585 loc) Β· 20.8 KB
/
deploy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
import { Account, json, RpcProvider, CallData, hash, cairo, Contract } from "starknet";
import fs from "fs";
import path from "path";
import readline from 'readline';
// Configuration constants
const CONFIG = {
RPC: {
NODE_URL: "http://localhost:9944"
},
// MADARA DEVNET ACCOUNT #1 (SEQUENCER)
SEQUENCER: {
ADDRESS: "0x5efdcd1aae7204d0922b3e99b2266c7e10da699545c4e85739ec91302c070fe",
PRIVATE_KEY: "0x7706b870befcf0b9bff497a567310f2929f0b6baf494b2a9335dbe043b7d8a9"
},
// MADARA DEVNET ACCOUNT #2 (EXECUTOR / OWNER)
EXECUTOR: {
ADDRESS: "0x461886d89834786a79b83adc989a9fcc76738028fa8cad4c71e8e4cb35aa410",
PRIVATE_KEY: "0x1a9e8ae4566611e4b315790742d72d265a70232b6df8c455ac2174b030d8ea1"
},
GAME: {
WIDTH: 1000,
HEIGHT: 1000,
NUM_DIAMONDS: 1300,
NUM_BOMBS:70,
MINING_POINTS: 10,
DIAMOND_VALUE : 5000,
BOMB_VALUE: 666
},
ASSETS_PATH: "./assets",
CONTRACT_ADDRESSES: {
GAME: "0x6138074916e01b26ee2e02c05cc8904ce664ff9e96102a3d72203ddd99cfeb9",
SPAWNERS: [
"0x32c6740708b3901ebcbb3669eeda69b6ef2ced160aa1fa6f67ac5e5d7906e8",
"0xfd681e7e8756a370d02e1c7b4fb3d54d6e43e8d9581de5895376cb64d2a347",
"0x7e6f5a53c89d3c9fa3cc7c0e895444ddc16aac12ebeb3143acae13d2f066e67",
],
BOT : "0xd82cef415f203c5de3107621e4602fca8f16ce5040be2a15e513ae90d992bf",
},
DEPLOYMENT_PER_SPAWNER: 10,
MULTICALL_SIZE: 500,
};
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
function generateRandomNumbers(width, height, count) {
// Validate input
const maxPossible = width * height;
if (count > maxPossible) {
throw new Error(`Cannot generate ${count} unique numbers within range of ${maxPossible}`);
}
// Create array of all possible numbers
const allNumbers = Array.from({ length: maxPossible }, (_, i) => i);
// Shuffle array using Fisher-Yates algorithm
for (let i = allNumbers.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[allNumbers[i], allNumbers[j]] = [allNumbers[j], allNumbers[i]];
}
// Get our random numbers
const result = allNumbers.slice(0, count);
// Extra validation to guarantee uniqueness
const uniqueSet = new Set(result);
if (uniqueSet.size !== count) {
throw new Error('Internal error: Generated numbers are not unique');
}
// Validate range
const inRange = result.every(num => num >= 0 && num < maxPossible);
if (!inRange) {
throw new Error('Internal error: Generated numbers outside valid range');
}
console.log("Bots will start from points : ", result);
return result;
}
function generateGamePoints(width, height, diamondsCount, bombCount) {
// Validate input
if (width <= 0 || height <= 0) {
throw new Error('Width and height must be positive numbers');
}
if (diamondsCount + bombCount > width * height) {
throw new Error('Total number of points requested exceeds available spaces');
}
// Function to generate a random integer between min (inclusive) and max (inclusive)
const getRandomInt = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
};
// Function to convert point to string for easy comparison
const pointToString = (point) => `${point[0]},${point[1]}`;
// Set to keep track of used points
const usedPoints = new Set();
// Generate diamond locations
const diamondLocations = [];
while (diamondLocations.length < diamondsCount) {
// Generate random x and y coordinates (0-based)
const x = getRandomInt(0, width - 1);
const y = getRandomInt(0, height - 1);
const pointStr = pointToString([x, y]);
// Only add point if it hasn't been used yet
if (!usedPoints.has(pointStr)) {
diamondLocations.push([x, y]);
usedPoints.add(pointStr);
}
}
// Generate bomb locations
const bombLocations = [];
while (bombLocations.length < bombCount) {
const x = getRandomInt(0, width - 1);
const y = getRandomInt(0, height - 1);
const pointStr = pointToString([x, y]);
// Only add point if it hasn't been used yet
if (!usedPoints.has(pointStr)) {
bombLocations.push([x, y]);
usedPoints.add(pointStr);
}
}
console.log("Diamond Locations: ", diamondLocations);
console.log("Bomb Locations: ", bombLocations);
return {
diamond_locations: diamondLocations,
bomb_locations: bombLocations
};
}
// Contract loading utility
class ContractLoader {
static loadContract(contractName) {
const basePath = path.join(CONFIG.ASSETS_PATH, `gridy_${contractName}`);
return {
sierra: json.parse(fs.readFileSync(`${basePath}.contract_class.json`).toString("ascii")),
casm: json.parse(fs.readFileSync(`${basePath}.compiled_contract_class.json`).toString("ascii"))
};
}
}
// Grid utilities
class GridUtils {
static coordinatesToBlockId([x, y]) {
return y * CONFIG.GAME.WIDTH + x;
}
static generateLocations() {
const result = generateGamePoints(CONFIG.GAME.WIDTH, CONFIG.GAME.HEIGHT, CONFIG.GAME.NUM_DIAMONDS, CONFIG.GAME.NUM_BOMBS);
console.log("Lengths: " , result.diamond_locations.length, result.bomb_locations.length);
return {
diamonds: result.diamond_locations.map(loc => ({
id: this.coordinatesToBlockId(loc),
points: CONFIG.GAME.DIAMOND_VALUE
})),
bombs: result.bomb_locations.map(loc => ({
id: this.coordinatesToBlockId(loc),
points: CONFIG.GAME.BOMB_VALUE
}))
};
}
}
class StarknetDeployer {
constructor() {
this.provider = new RpcProvider({ nodeUrl: CONFIG.RPC.NODE_URL });
this.account = new Account(
this.provider,
CONFIG.EXECUTOR.ADDRESS,
CONFIG.EXECUTOR.PRIVATE_KEY
);
// Load contracts
this.contracts = {
game: ContractLoader.loadContract('GameContract'),
bot: ContractLoader.loadContract('BotContract')
};
}
async getBotClassHash() {
return hash.computeContractClassHash(
this.contracts.bot.sierra,
this.contracts.bot.casm
);
}
async getGameClassHash() {
return hash.computeContractClassHash(
this.contracts.game.sierra,
this.contracts.game.casm
);
}
async declareContract(contract) {
const declareResponse = await this.account.declare({
contract: contract.sierra,
casm: contract.casm,
});
console.log("Contract declared with classHash =", declareResponse.class_hash);
return declareResponse;
}
async prepareGameConstructorCalldata() {
const botClassHash = await this.getBotClassHash();
const gameClassHash = await this.getGameClassHash();
console.log("Bot Class Hash: ", botClassHash);
console.log("Game Class Hash: ", gameClassHash);
const callData = new CallData(this.contracts.game.sierra.abi);
return callData.compile("constructor", {
executor: CONFIG.EXECUTOR.ADDRESS,
bot_contract_class_hash: botClassHash,
bomb_value: CONFIG.GAME.BOMB_VALUE,
mining_points: CONFIG.GAME.MINING_POINTS,
grid_width: CONFIG.GAME.WIDTH,
grid_height: CONFIG.GAME.HEIGHT,
total_diamonds_and_bombs : (CONFIG.GAME.NUM_DIAMONDS + CONFIG.GAME.NUM_BOMBS),
sequencer : CONFIG.SEQUENCER.ADDRESS,
});
}
async updateBlockPoints() {
const gameContract = new Contract(
this.contracts.game.sierra.abi,
CONFIG.CONTRACT_ADDRESSES.GAME,
this.provider
);
const { diamonds, bombs } = GridUtils.generateLocations();
// call contract's update_block_points in a multicall set of 500 only diamonds
let num_diamond_calls = (diamonds.length / CONFIG.MULTICALL_SIZE) >> 0;
if (diamonds.length % CONFIG.MULTICALL_SIZE > 0) {
num_diamond_calls++;
}
for (let i = 0; i < num_diamond_calls; i++) {
const diamondsChunk = diamonds.slice(i * CONFIG.MULTICALL_SIZE, (i + 1) * CONFIG.MULTICALL_SIZE);
const diamondCalls = diamondsChunk.map(diamond => {
return gameContract.populate("update_block_points", [
diamond.id,
diamond.points
]);
});
const estimatedFee = await this.account.estimateInvokeFee(diamondCalls);
const { transaction_hash } = await this.account.execute(
diamondCalls,
undefined,
{
maxFee: estimatedFee.suggestedMaxFee
}
);
const receipt = await this.account.waitForTransaction(transaction_hash);
console.log("Diamonds slice ", i * CONFIG.MULTICALL_SIZE , "to ", (i + 1) * CONFIG.MULTICALL_SIZE, " updated! with transaction hash: ", receipt.transaction_hash);
}
// call contract's update_block_points in a multicall set of 500 only bombs
let num_bomb_calls = (bombs.length / CONFIG.MULTICALL_SIZE) >> 0;
if (bombs.length % CONFIG.MULTICALL_SIZE > 0) {
num_bomb_calls++;
}
for (let i = 0; i < num_bomb_calls; i++) {
const bombsChunk = bombs.slice(i * CONFIG.MULTICALL_SIZE, (i + 1) * CONFIG.MULTICALL_SIZE);
const bombCalls = bombsChunk.map(bomb => {
return gameContract.populate("update_block_points", [
bomb.id,
bomb.points
]);
});
const estimatedFee = await this.account.estimateInvokeFee(bombCalls);
const { transaction_hash } = await this.account.execute(
bombCalls,
undefined,
{
maxFee: estimatedFee.suggestedMaxFee
}
);
const receipt = await this.account.waitForTransaction(transaction_hash);
console.log("Bomd slice ", i * CONFIG.MULTICALL_SIZE , "to ", (i + 1) * CONFIG.MULTICALL_SIZE, " updated! with transaction hash: ", receipt.transaction_hash);
}
}
async declareAndDeployGameContract() {
const gameCalldata = await this.prepareGameConstructorCalldata();
const declareAndDeployResponse = await this.account.declareAndDeploy({
contract: this.contracts.game.sierra,
casm: this.contracts.game.casm,
constructorCalldata: gameCalldata,
});
const receipt = await this.account.waitForTransaction(declareAndDeployResponse.deploy.transaction_hash);
console.log('Contract Address:', declareAndDeployResponse.deploy.contract_address);
console.log('Transaction Hash:', declareAndDeployResponse.deploy.transaction_hash);
return receipt;
}
async declareGameContract() {
const declareResponse = await this.declareContract(this.contracts.game);
return declareResponse;
}
async deployGameContract() {
const gameCalldata = await this.prepareGameConstructorCalldata();
const deployResponse = await this.account.deploy({
classHash : await this.getGameClassHash(),
constructorCalldata: gameCalldata,
});
const receipt = await this.account.waitForTransaction(deployResponse.transaction_hash);
console.log('Contract Address:', deployResponse.contract_address);
return deployResponse;
}
async declareBotContract() {
const declareResponse = await this.declareContract(this.contracts.bot);
return declareResponse;
}
async deployBotHelper(spawned_by, start_point, gameContract) {
// Instead of executing, just return the call data
return gameContract.populate("deploy_bot", [
spawned_by,
cairo.felt(start_point)
]);
}
async deployMultipleBots() {
const gameContract = new Contract(
this.contracts.game.sierra.abi,
CONFIG.CONTRACT_ADDRESSES.GAME,
this.provider
);
// Generate random points for all bots
const points = generateRandomNumbers(
CONFIG.GAME.WIDTH,
CONFIG.GAME.HEIGHT,
(CONFIG.CONTRACT_ADDRESSES.SPAWNERS.length * CONFIG.DEPLOYMENT_PER_SPAWNER)
);
// Create array to hold all calls
let calls = [];
// Prepare all deployment calls
for (let i = 0; i < CONFIG.CONTRACT_ADDRESSES.SPAWNERS.length; i++) {
const spawner = CONFIG.CONTRACT_ADDRESSES.SPAWNERS[i];
for (let j = 0; j < CONFIG.DEPLOYMENT_PER_SPAWNER; j++) {
const deployCall = await this.deployBotHelper(spawner, points[i * CONFIG.DEPLOYMENT_PER_SPAWNER + j], gameContract);
calls.push(deployCall);
}
}
console.log(`\nπ€ Preparing to deploy ${calls.length} bots in a using multicall...`);
// Randomly sort the calls array
calls = shuffle(calls);
// break calls into chunks of multicall size and execute
let num_calls = (calls.length / CONFIG.MULTICALL_SIZE) >> 0;
if (calls.length % CONFIG.MULTICALL_SIZE > 0) {
num_calls++;
}
for (let i = 0; i < num_calls; i++) {
const callsChunk = calls.slice(i * CONFIG.MULTICALL_SIZE, (i + 1) * CONFIG.MULTICALL_SIZE);
const estimatedFee = await this.account.estimateInvokeFee(callsChunk);
const { transaction_hash } = await this.account.execute(
callsChunk,
undefined,
{
maxFee: estimatedFee.suggestedMaxFee
}
);
const receipt = await this.account.waitForTransaction(transaction_hash);
console.log("Bot deployment chunk ", i * CONFIG.MULTICALL_SIZE , "to ", (i + 1) * CONFIG.MULTICALL_SIZE, " submitted! with transaction hash: ", transaction_hash);
}
return;
}
async callMine() {
const gameContract = new Contract(
this.contracts.game.sierra.abi,
CONFIG.CONTRACT_ADDRESSES.GAME,
this.provider
);
const deployCall = gameContract.populate("mine", [
CONFIG.CONTRACT_ADDRESSES.BOT,
cairo.felt(1232)
]);
const estimatedFee = await this.account.estimateInvokeFee(deployCall);
const { transaction_hash } = await this.account.execute(
deployCall,
undefined,
{
maxFee: estimatedFee.suggestedMaxFee
}
);
const receipt = await this.account.waitForTransaction(transaction_hash);
return { transaction_hash, receipt };
}
async callIsBotAlive() {
const botContract = new Contract(
this.contracts.bot.sierra.abi,
CONFIG.CONTRACT_ADDRESSES.BOT,
this.provider
);
const invokeCall = botContract.populate("get_owner", [
]);
// const estimatedFee = await this.account.estimateInvokeFee(deployCall);
const { transaction_hash } = await this.account.execute(
invokeCall,
undefined,
// {
// maxFee: estimatedFee.suggestedMaxFee
// }
);
const receipt = await this.account.waitForTransaction(transaction_hash);
return { transaction_hash, receipt };
}
async disableGameContract() {
const gameContract = new Contract(
this.contracts.game.sierra.abi,
CONFIG.CONTRACT_ADDRESSES.GAME,
this.provider
);
const disableCall = gameContract.populate("disable_contract");
const estimatedFee = await this.account.estimateInvokeFee(disableCall);
const { transaction_hash } = await this.account.execute(
disableCall,
undefined,
{
maxFee: estimatedFee.suggestedMaxFee
}
);
const receipt = await this.account.waitForTransaction(transaction_hash);
return { transaction_hash, receipt };
}
async enableGameContract() {
const gameContract = new Contract(
this.contracts.game.sierra.abi,
CONFIG.CONTRACT_ADDRESSES.GAME,
this.provider
);
const enableCall = gameContract.populate("enable_contract");
const estimatedFee = await this.account.estimateInvokeFee(enableCall);
const { transaction_hash } = await this.account.execute(
enableCall,
undefined,
{
maxFee: estimatedFee.suggestedMaxFee
}
);
const receipt = await this.account.waitForTransaction(transaction_hash);
return { transaction_hash, receipt };
}
}
class DeploymentCLI {
constructor() {
this.deployer = new StarknetDeployer();
this.rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
}
async showMenu() {
console.log('\nπ Starknet Deployment Menu\n');
console.log('-1. Declare and Deploy Game Contract');
console.log('0. Declare Game Contract');
console.log('1. Deploy Game Contract');
console.log('2. Add Block Points to Game Contract');
console.log('3. Enable Game Contract');
console.log('4. Declare Bot Contract');
console.log('5. Deploy Multiple Bots');
console.log('6. Call Mine');
console.log('7. Get Class Hash');
console.log('8. Disable Game Contract');
console.log("9. Check is bot alive")
console.log('10. Exit');
console.log('\nSelect an option (1-8):');
}
async handleUserInput(input) {
try {
switch (input) {
case '-1':
await this.declareAndDeployGameContract();
break;
case '0':
await this.declareGame();
break;
case '1':
await this.deployGame();
break;
case '2':
await this.updateBlockPoints();
break;
case '3':
await this.enableGame();
break;
case '4':
await this.declareBot();
break;
case '5':
await this.deployMultipleBots();
break;
case '6':
await this.callMine();
break;
case '7':
await this.getClassHash();
break;
case '8':
await this.disableGame();
break;
case '9':
await this.callIsBotAlive();
break;
case '10':
console.log('\nExiting...');
this.rl.close();
process.exit(0);
default:
console.log('\nβ Invalid option. Please try again.');
}
} catch (error) {
console.error('\nβ Operation failed:', error);
}
await this.continuePrompt();
}
async declareAndDeployGameContract() {
console.log('\nπ¦ Declaring and Deploying Game Contract...');
const result = await this.deployer.declareAndDeployGameContract();
console.log('β
Game Contract declared and deployed successfully!');
}
async declareGame() {
console.log('\nπ¦ Declaring Game Contract...');
const result = await this.deployer.declareGameContract();
console.log('Class Hash:', result.class_hash);
console.log('Transaction Hash:', result.transaction_hash);
console.log('β
Game Contract declared successfully!');
}
async deployGame() {
console.log('\nπ¦ Deploying Game Contract...');
const result = await this.deployer.deployGameContract();
console.log('β
Game Contract deployed successfully!');
}
async updateBlockPoints() {
console.log('\nπ¦ Adding Block Points...');
const result = await this.deployer.updateBlockPoints();
console.log('β
Added Block Points successfully!');
}
async declareBot() {
console.log('\nπ Declaring Bot Contract...');
const result = await this.deployer.declareBotContract();
console.log('Class Hash:', result.class_hash);
console.log('Transaction Hash:', result.transaction_hash);
console.log('β
Bot Contract declared successfully!');
}
async enableGame() {
console.log('\nπ Enabling Game Contract...');
const result = await this.deployer.enableGameContract();
console.log('β
Game Contract enabled successfully!');
console.log('Transaction Hash:', result.transaction_hash);
}
async disableGame() {
console.log('\nπ Disabling Game Contract...');
const result = await this.deployer.disableGameContract();
console.log('β
Game Contract disabled successfully!');
console.log('Transaction Hash:', result.transaction_hash);
}
async callIsBotAlive() {
console.log('\nπ Calling Is Bot Alive...');
const result = await this.deployer.callIsBotAlive();
console.log('β
Called Is Bot Alive!');
console.log('Transaction Hash:', result);
}
async deployMultipleBots() {
console.log('\nπ€ Deploying Bot...');
const result = await this.deployer.deployMultipleBots();
console.log('β
Bot deployed successfully!');
}
async callMine() {
console.log('\nπ€ Calling Mine...');
const result = await this.deployer.callMine();
console.log('β
Mined successfully!');
console.log('Transaction Hash:', result.transaction_hash);
}
async getClassHash() {
const botClassHash = await this.deployer.getBotClassHash();
const gameClassHash = await this.deployer.getGameClassHash();
console.log("Bot Class Hash: ", botClassHash);
console.log("Game Class Hash: ", gameClassHash);
}
async continuePrompt() {
return new Promise((resolve) => {
this.rl.question('\nPress Enter to continue...', () => {
this.start();
resolve();
});
});
}
async start() {
await this.showMenu();
this.rl.question('', async (input) => {
await this.handleUserInput(input);
});
}
}
// Replace the original main function with this:
async function main() {
const cli = new DeploymentCLI();
console.log('\nWelcome to Starknet Deployment CLI');
console.log('=================================\n');
await cli.start();
}
// Execute the CLI
main().catch((error) => {
console.error('Fatal error:', error);
process.exit(1);
});