-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathgear.cairo
More file actions
2053 lines (1789 loc) · 77.9 KB
/
Copy pathgear.cairo
File metadata and controls
2053 lines (1789 loc) · 77.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#[dojo::contract]
pub mod GearActions {
use crate::interfaces::gear::IGear;
use dojo::event::EventStorage;
use crate::helpers::gear::*;
use crate::helpers::session_validation::*;
use starknet::{ContractAddress, get_block_timestamp, get_contract_address, get_caller_address};
use crate::models::player::Player;
use dojo::world::WorldStorage;
use dojo::model::ModelStorage;
use crate::models::gear::{
Gear, GearProperties, GearType, UpgradeCost, UpgradeSuccessRate, UpgradeMaterial,
GearLevelStats, UpgradeConfigState, GearDetailsComplete, GearStatsCalculated, UpgradeInfo,
OwnershipStatus, GearFilters, OwnershipFilter, PaginationParams, SortParams, SortField,
PaginatedGearResult, CombinedEquipmentEffects, EquipmentSlotInfo, ItemRarity,
MarketConditions, MarketActivity,
};
use crate::models::weapon_stats::WeaponStats;
use crate::models::armor_stats::Armor;
use crate::models::vehicle_stats::VehicleStats;
use crate::models::pet_stats::PetStats;
use crate::models::core::Operator;
use crate::helpers::base::generate_id;
use crate::helpers::base::ContractAddressDefault;
// Import session model for validation
use crate::models::session::SessionKey;
use openzeppelin::token::erc1155::interface::{IERC1155Dispatcher, IERC1155DispatcherTrait};
use origami_random::dice::DiceTrait;
use core::num::traits::Zero;
const GEAR: felt252 = 'GEAR';
// A constant key for our singleton UpgradeConfigState model
const UPGRADE_CONFIG_KEY: u8 = 0;
fn dojo_init(ref self: ContractState) {
let mut world = self.world_default();
self._assert_admin();
self._initialize_gear_assets(ref world);
world
.write_model(
@UpgradeConfigState {
singleton_key: UPGRADE_CONFIG_KEY,
initialized_types_count: 0,
is_complete: false,
},
);
// Seed market models
world.write_model(@MarketConditions { id: 0, cost_multiplier: 100 });
world
.write_model(
@MarketActivity {
id: 0, activity_count: 0, last_reset_timestamp: get_block_timestamp(),
},
);
}
// Event for successful upgrades
#[derive(Drop, Copy, Serde)]
#[dojo::event]
pub struct UpgradeSuccess {
#[key]
pub player_id: ContractAddress,
pub gear_id: u256,
pub new_level: u64,
pub materials_consumed: Span<UpgradeMaterial> // Track what was consumed
}
// Event for failed upgrades
#[derive(Drop, Copy, Serde)]
#[dojo::event]
pub struct UpgradeFailed {
#[key]
pub player_id: ContractAddress,
pub gear_id: u256,
pub level: u64,
pub materials_consumed: Span<UpgradeMaterial> // Track what was consumed
}
#[abi(embed_v0)]
pub impl GearActionsImpl of IGear<ContractState> {
fn upgrade_gear(
ref self: ContractState,
item_id: u256,
session_id: felt252,
materials_erc1155_address: ContractAddress,
) {
self.validate_session_for_action(session_id);
let mut world = self.world_default();
let caller = get_caller_address();
let mut gear: Gear = world.read_model(item_id);
let player: Player = world.read_model(caller);
assert(gear.owner == caller, 'Caller is not owner');
assert(gear.upgrade_level < gear.max_upgrade_level, 'Gear at max level');
let next_level = gear.upgrade_level + 1;
let new_stats: GearLevelStats = world.read_model((gear.asset_id, next_level));
assert(new_stats.level == next_level, 'Next level stats not defined');
// Refresh market before pricing
self.update_market_conditions();
let market_conditions: MarketConditions = world.read_model(0);
let upgrade_cost = self.calculate_dynamic_upgrade_cost(gear, market_conditions);
let success_rate = self.calculate_upgrade_success_rate(gear, player.level);
assert(upgrade_cost.len() > 0, 'No upgrade path for item');
let erc1155 = IERC1155Dispatcher { contract_address: materials_erc1155_address };
let mut i = 0;
while i < upgrade_cost.len() {
let material = *upgrade_cost.at(i);
let balance = erc1155.balance_of(caller, material.token_id);
assert(balance >= material.amount, 'Insufficient materials');
erc1155
.safe_transfer_from(
caller,
get_contract_address(),
material.token_id,
material.amount,
array![].span(),
);
i += 1;
};
// Increment market activity counter
let mut market_activity: MarketActivity = world.read_model(0);
market_activity.activity_count += 1;
self.update_market_conditions();
let tx_hash: felt252 = starknet::get_tx_info().unbox().transaction_hash;
let seed: felt252 = tx_hash
+ caller.into()
+ item_id.low.into()
+ get_block_timestamp().into();
let mut dice = DiceTrait::new(100, seed);
let pseudo_random: u8 = dice.roll();
if pseudo_random < success_rate {
gear.upgrade_level = next_level;
world.write_model(@gear);
world
.emit_event(
@UpgradeSuccess {
player_id: caller,
gear_id: item_id,
new_level: gear.upgrade_level,
materials_consumed: upgrade_cost.span(),
},
);
} else {
world
.emit_event(
@UpgradeFailed {
player_id: caller,
gear_id: item_id,
level: gear.upgrade_level,
materials_consumed: upgrade_cost.span(),
},
);
}
}
fn equip(ref self: ContractState, item_id: Array<u256>, session_id: felt252) {
// Validate session before proceeding
self.validate_session_for_action(session_id);
}
fn equip_on(ref self: ContractState, item_id: u256, target: u256, session_id: felt252) {
// Validate session before proceeding
self.validate_session_for_action(session_id);
}
// unequips an item and equips another item at that slot.
fn exchange(
ref self: ContractState, in_item_id: u256, out_item_id: u256, session_id: felt252,
) {
// Validate session before proceeding
self.validate_session_for_action(session_id);
}
fn refresh(ref self: ContractState, session_id: felt252) {
// Validate session before proceeding
self.validate_session_for_action(session_id);
// might be moved to player. when players transfer off contract, then there's a problem
}
fn get_item_details(ref self: ContractState, item_id: u256, session_id: felt252) -> Gear {
// Validate session before proceeding
self.validate_session_for_action(session_id);
// might not return a gear
Default::default()
}
// Some Item Details struct.
fn total_held_of(
ref self: ContractState, gear_type: GearType, session_id: felt252,
) -> u256 {
// Validate session before proceeding
self.validate_session_for_action(session_id);
0
}
// use the caller and read the model of both the caller, and the target
// the target only refers to one target type for now
// This target type is raidable.
fn raid(ref self: ContractState, target: u256, session_id: felt252) {
// Validate session before proceeding
self.validate_session_for_action(session_id);
}
fn unequip(ref self: ContractState, item_id: Array<u256>, session_id: felt252) {
// Validate session before proceeding
self.validate_session_for_action(session_id);
}
fn get_configuration(
ref self: ContractState, item_id: u256, session_id: felt252,
) -> Option<GearProperties> {
// Validate session before proceeding
self.validate_session_for_action(session_id);
Option::None
}
// This configure should take in an enum that lists all Gear Types with their structs
// This function would be blocked at the moment, we shall use the default configuration
// of the gameplay and how items interact with each other.
// e.g. guns auto-reload once the time has run out
// and TODO: Add a delay for auto reload.
// for a base gun, we default the auto reload to exactly 6 seconds...
//
fn configure(ref self: ContractState, session_id: felt252) {
// Validate session before proceeding
self.validate_session_for_action(session_id);
// params to be completed
}
fn auction(ref self: ContractState, item_ids: Array<u256>, session_id: felt252) {
// Validate session before proceeding
self.validate_session_for_action(session_id);
}
fn dismantle(ref self: ContractState, item_ids: Array<u256>, session_id: felt252) {
// Validate session before proceeding
self.validate_session_for_action(session_id);
}
fn transfer(ref self: ContractState, item_ids: Array<u256>, session_id: felt252) {
// Validate session before proceeding
self.validate_session_for_action(session_id);
}
fn grant(ref self: ContractState, asset: GearType) {
let mut world = self.world_default();
self._assert_admin();
// Create a new gear instance based on the asset type
let new_gear_id = generate_id(GEAR, ref world);
// Implementation would create gear based on asset type
}
// These functions might be reserved for players within a specific faction
// this function forges and creates a new item id based
// normally, this function should be called only when the player is in a forging place.
fn forge(ref self: ContractState, item_ids: Array<u256>, session_id: felt252) -> u256 {
// Validate session before proceeding
self.validate_session_for_action(session_id);
// should create a new asset. Perhaps deduct credits from the player.
0
}
fn awaken(ref self: ContractState, exchange: Array<u256>, session_id: felt252) {
// Validate session before proceeding
self.validate_session_for_action(session_id);
}
fn can_be_awakened(
ref self: ContractState, item_ids: Array<u256>, session_id: felt252,
) -> Span<bool> {
// Validate session before proceeding
self.validate_session_for_action(session_id);
array![].span()
}
// AUTOMATED BATCH INITIALIZATION FUNCTION
// The admin calls this function repeatedly without arguments.
// Each call processes a batch of GearTypes until all are initialized.
fn initialize_upgrade_data(ref self: ContractState) {
self._assert_admin();
let mut world = self.world_default();
let mut config_state: UpgradeConfigState = world.read_model(UPGRADE_CONFIG_KEY);
assert(!config_state.is_complete, 'Initialization is complete');
// Define the full list of gear types to be initialized
let gear_types = array![
GearType::Weapon,
GearType::BluntWeapon,
GearType::Sword,
GearType::Bow,
GearType::Firearm,
GearType::Polearm,
GearType::HeavyFirearms,
GearType::Explosives,
GearType::Helmet,
GearType::ChestArmor,
GearType::LegArmor,
GearType::Boots,
GearType::Gloves,
GearType::Shield,
GearType::Vehicle,
GearType::Pet,
GearType::Drone,
];
let total_types = gear_types.len();
let start_index = config_state.initialized_types_count;
// Define a safe batch size to stay within gas limits.
// Processing 3 types results in ~60 writes, which is very safe.
const BATCH_SIZE: u32 = 3;
let mut end_index = start_index + BATCH_SIZE;
if end_index > total_types {
end_index = total_types;
}
// Process the batch
let mut i = start_index;
while i < end_index {
self._initialize_upgrade_data_for_gear_type(ref world, *gear_types.at(i));
i += 1;
};
// Update the config state
config_state.initialized_types_count = end_index;
if config_state.initialized_types_count == total_types {
config_state.is_complete = true;
}
world.write_model(@config_state);
}
fn get_gear_details_complete(
ref self: ContractState, item_id: u256, session_id: felt252,
) -> Option<GearDetailsComplete> {
if !self.validate_session_for_read_action(session_id) {
return Option::None;
}
let world = self.world_default();
let gear: Gear = world.read_model(item_id);
if gear.id == 0 {
return Option::None;
}
let calculated_stats = self._calculate_gear_stats(@gear);
let upgrade_info = self._get_upgrade_info(@gear);
let ownership_status = self._get_ownership_status(@gear);
Option::Some(
GearDetailsComplete { gear, calculated_stats, upgrade_info, ownership_status },
)
}
fn get_gear_details_batch(
ref self: ContractState, item_ids: Array<u256>, session_id: felt252,
) -> Array<Option<GearDetailsComplete>> {
if !self.validate_session_for_read_action(session_id) {
return array![];
}
let mut results = array![];
let mut i = 0;
while i < item_ids.len() {
let item_id = *item_ids.at(i);
let details = self.get_gear_details_complete(item_id, session_id);
results.append(details);
i += 1;
};
results
}
fn get_calculated_stats(
ref self: ContractState, item_id: u256, session_id: felt252,
) -> Option<GearStatsCalculated> {
if !self.validate_session_for_read_action(session_id) {
return Option::None;
}
let world = self.world_default();
let gear: Gear = world.read_model(item_id);
if gear.id == 0 {
return Option::None;
}
Option::Some(self._calculate_gear_stats(@gear))
}
fn get_upgrade_preview(
ref self: ContractState, item_id: u256, target_level: u64, session_id: felt252,
) -> Option<UpgradeInfo> {
if !self.validate_session_for_read_action(session_id) {
return Option::None;
}
let world = self.world_default();
let gear: Gear = world.read_model(item_id);
if gear.id == 0 || target_level > gear.max_upgrade_level {
return Option::None;
}
Option::Some(self._calculate_upgrade_preview(@gear, target_level))
}
fn get_player_inventory(
ref self: ContractState,
player: ContractAddress,
filters: Option<GearFilters>,
pagination: Option<PaginationParams>,
sort: Option<SortParams>,
session_id: felt252,
) -> PaginatedGearResult {
if !self.validate_session_for_read_action(session_id) {
return PaginatedGearResult { items: array![], total_count: 0, has_more: false };
}
self._get_filtered_gear(filters, pagination, sort, Option::Some(player))
}
fn get_equipped_gear(
ref self: ContractState, player: ContractAddress, session_id: felt252,
) -> CombinedEquipmentEffects {
if !self.validate_session_for_read_action(session_id) {
return CombinedEquipmentEffects {
total_damage: 0,
total_defense: 0,
total_weight: 0,
equipped_slots: array![],
empty_slots: array![],
set_bonuses: array![],
};
}
let world = self.world_default();
let player_data: Player = world.read_model(player);
self._calculate_combined_effects(@player_data)
}
fn get_available_items(
ref self: ContractState,
player_xp: u256,
filters: Option<GearFilters>,
pagination: Option<PaginationParams>,
session_id: felt252,
) -> PaginatedGearResult {
if !self.validate_session_for_read_action(session_id) {
return PaginatedGearResult { items: array![], total_count: 0, has_more: false };
}
// Filter for spawned items that meet XP requirements
let mut available_filters = match filters {
Option::Some(f) => f,
Option::None => GearFilters {
gear_types: Option::None,
min_level: Option::None,
max_level: Option::None,
ownership_filter: Option::Some(OwnershipFilter::Available),
min_xp_required: Option::None,
max_xp_required: Option::Some(player_xp),
spawned_only: Option::Some(true),
},
};
available_filters.spawned_only = Option::Some(true);
available_filters.max_xp_required = Option::Some(player_xp);
self
._get_filtered_gear(
Option::Some(available_filters), pagination, Option::None, Option::None,
)
}
fn calculate_upgrade_costs(
ref self: ContractState, item_id: u256, target_level: u64, session_id: felt252,
) -> Option<Array<(u256, u256)>> {
if !self.validate_session_for_read_action(session_id) {
return Option::None;
}
let world = self.world_default();
let gear: Gear = world.read_model(item_id);
if gear.id == 0
|| target_level > gear.max_upgrade_level
|| target_level <= gear.upgrade_level {
return Option::None;
}
Option::Some(self._calculate_total_upgrade_costs(@gear, target_level))
}
fn check_upgrade_feasibility(
ref self: ContractState,
item_id: u256,
target_level: u64,
player_materials: Array<(u256, u256)>,
session_id: felt252,
) -> (bool, Array<(u256, u256)>) {
if !self.validate_session_for_read_action(session_id) {
return (false, array![]);
}
let result = match self.calculate_upgrade_costs(item_id, target_level, session_id) {
Option::Some(costs) => self._check_material_availability(costs, player_materials),
Option::None => (false, array![]),
};
result
}
fn filter_gear_by_type(
ref self: ContractState,
gear_type: GearType,
pagination: Option<PaginationParams>,
session_id: felt252,
) -> PaginatedGearResult {
if !self.validate_session_for_read_action(session_id) {
return PaginatedGearResult { items: array![], total_count: 0, has_more: false };
}
let filters = GearFilters {
gear_types: Option::Some(array![gear_type]),
min_level: Option::None,
max_level: Option::None,
ownership_filter: Option::None,
min_xp_required: Option::None,
max_xp_required: Option::None,
spawned_only: Option::None,
};
self._get_filtered_gear(Option::Some(filters), pagination, Option::None, Option::None)
}
fn search_gear_by_criteria(
ref self: ContractState,
filters: GearFilters,
pagination: Option<PaginationParams>,
sort: Option<SortParams>,
session_id: felt252,
) -> PaginatedGearResult {
if !self.validate_session_for_read_action(session_id) {
return PaginatedGearResult { items: array![], total_count: 0, has_more: false };
}
self._get_filtered_gear(Option::Some(filters), pagination, sort, Option::None)
}
fn compare_gear_stats(
ref self: ContractState, item_ids: Array<u256>, session_id: felt252,
) -> Array<GearStatsCalculated> {
if !self.validate_session_for_read_action(session_id) {
return array![];
}
let world = self.world_default();
let mut stats_array = array![];
let mut i = 0;
while i < item_ids.len() {
let item_id = *item_ids.at(i);
let gear: Gear = world.read_model(item_id);
if gear.id != 0 {
let stats = self._calculate_gear_stats(@gear);
stats_array.append(stats);
}
i += 1;
};
stats_array
}
fn get_gear_summary(
ref self: ContractState, item_id: u256, session_id: felt252,
) -> Option<(Gear, u64, u64, u64)> {
if !self.validate_session_for_read_action(session_id) {
return Option::None;
}
let world = self.world_default();
let gear: Gear = world.read_model(item_id);
if gear.id == 0 {
return Option::None;
}
let stats = self._calculate_gear_stats(@gear);
Option::Some((gear, stats.damage, stats.defense, stats.weight))
}
}
#[generate_trait]
pub impl GearInternalImpl of GearInternalTrait {
fn world_default(self: @ContractState) -> WorldStorage {
self.world(@"coa")
}
fn calculate_upgrade_success_rate(
self: @ContractState, gear: Gear, player_level: u256,
) -> u8 {
let world = self.world_default();
let rarity = self.get_item_rarity(gear.asset_id);
let gear_type = parse_id(gear.asset_id);
let success_rate: UpgradeSuccessRate = world
.read_model((gear_type, gear.upgrade_level));
let base_rate = success_rate.rate;
let rarity_penalty = match rarity {
ItemRarity::Common => 0,
ItemRarity::Uncommon => 5,
ItemRarity::Rare => 10,
ItemRarity::Epic => 15,
ItemRarity::Legendary => 20,
};
let level_bonus = if player_level >= 50 {
10
} else if player_level >= 25 {
5
} else {
0
};
let final_rate = base_rate - rarity_penalty + level_bonus;
if final_rate > 95 {
95
} else if final_rate < 5 {
5
} else {
final_rate
}
}
fn get_item_rarity(self: @ContractState, asset_id: u256) -> ItemRarity {
let world = self.world_default();
let gear_stats: GearLevelStats = world.read_model((asset_id, 0));
if gear_stats.damage >= 100 {
ItemRarity::Legendary
} else if gear_stats.damage >= 75 {
ItemRarity::Epic
} else if gear_stats.damage >= 50 {
ItemRarity::Rare
} else if gear_stats.damage >= 25 {
ItemRarity::Uncommon
} else {
ItemRarity::Common
}
}
fn calculate_dynamic_upgrade_cost(
self: @ContractState, gear: Gear, market_conditions: MarketConditions,
) -> Array<UpgradeMaterial> {
let world = self.world_default();
let gear_type = parse_id(gear.asset_id);
let base_cost: UpgradeCost = world.read_model((gear_type, gear.upgrade_level));
let rarity = self.get_item_rarity(gear.asset_id);
let rarity_multiplier = match rarity {
ItemRarity::Common => 100,
ItemRarity::Uncommon => 150,
ItemRarity::Rare => 250,
ItemRarity::Epic => 400,
ItemRarity::Legendary => 600,
};
let market_multiplier = market_conditions.cost_multiplier;
let mut final_costs = array![];
let mut i = 0;
while i < base_cost.materials.len() {
let material = *base_cost.materials.at(i);
let final_amount = (material.amount * rarity_multiplier * market_multiplier)
/ 10000;
// Only include materials with a non-zero final amount.
if final_amount > 0 {
final_costs
.append(
UpgradeMaterial { token_id: material.token_id, amount: final_amount },
);
}
i += 1;
};
final_costs
}
fn update_market_conditions(ref self: ContractState) {
let mut world = self.world_default();
let mut market: MarketConditions = world.read_model(0);
let recent_activity = self.get_recent_market_activity();
let target_activity = 1000;
if recent_activity > target_activity * 120 / 100 {
market.cost_multiplier = market.cost_multiplier * 105 / 100;
} else if recent_activity < target_activity * 80 / 100 {
market.cost_multiplier = market.cost_multiplier * 95 / 100;
}
if market.cost_multiplier > 200 {
market.cost_multiplier = 200;
}
if market.cost_multiplier < 50 {
market.cost_multiplier = 50;
}
world.write_model(@market);
}
fn get_recent_market_activity(self: @ContractState) -> u256 {
let mut world = self.world_default();
let current_timestamp = get_block_timestamp();
let time_window: u64 = 86400; // 24 hours in seconds
let mut market_activity: MarketActivity = world.read_model(0);
// Check if the activity counter needs to be reset
if current_timestamp >= market_activity.last_reset_timestamp + time_window {
market_activity.activity_count = 0;
market_activity.last_reset_timestamp = current_timestamp;
world.write_model(@market_activity);
}
// Return scaled activity count or default if zero
if market_activity.activity_count == 0 {
1000 // Default value if no activity
} else {
market_activity.activity_count * 100 // Scale for balance
}
}
fn _assert_admin(self: @ContractState) { // assert the admin here.
let world = self.world_default();
let caller = get_caller_address();
let operator: Operator = world.read_model(caller);
assert(operator.is_operator, 'Caller is not admin');
}
fn validate_session_for_action(ref self: ContractState, session_id: felt252) {
// Basic validation - session_id must not be zero
assert(session_id != 0, 'INVALID_SESSION');
// Get the caller's address
let caller = get_caller_address();
// Read session from storage
let mut world = self.world_default();
let mut session: SessionKey = world.read_model((session_id, caller));
// Validate session exists
assert(session.session_id != 0, 'SESSION_NOT_FOUND');
// Validate session belongs to the caller
assert(session.player_address == caller, 'UNAUTHORIZED_SESSION');
// Validate session is active
assert(session.is_valid, 'SESSION_INVALID');
assert(session.status == 0, 'SESSION_NOT_ACTIVE');
// Validate session has not expired
let current_time = starknet::get_block_timestamp();
assert(current_time < session.expires_at, 'SESSION_EXPIRED');
// Validate session has transactions left
assert(session.used_transactions < session.max_transactions, 'NO_TRANSACTIONS_LEFT');
// Check if session needs auto-renewal (less than 5 minutes remaining)
let time_remaining = if current_time >= session.expires_at {
0
} else {
session.expires_at - current_time
};
// Auto-renew if less than 5 minutes remaining (300 seconds)
if time_remaining < 300 {
// Auto-renew session for 1 hour with 100 transactions
let mut updated_session = session;
updated_session.expires_at = current_time + 3600; // 1 hour
updated_session.last_used = current_time;
updated_session.max_transactions = 100;
updated_session.used_transactions = 0; // Reset transaction count
// Write updated session back to storage
world.write_model(@updated_session);
// Update session reference for validation
session = updated_session;
}
// Increment transaction count for this action
session.used_transactions += 1;
session.last_used = current_time;
// Write updated session back to storage
world.write_model(@session);
}
// Full implementation of upgrade data initialization
fn _initialize_upgrade_data_for_gear_type(
self: @ContractState, ref world: WorldStorage, gear_type: GearType,
) {
// ... (The logic from the previous answer is perfect and stays here)
// Material Fungible Token IDs (placeholders)
let scrap_metal: u256 = 1;
let wiring: u256 = 2;
let advanced_alloy: u256 = 3;
let cybernetic_core: u256 = 4;
// Base rates and costs
let success_rates = array![95, 90, 85, 80, 75, 50, 40, 30, 20, 10];
let costs_scrap = array![10, 20, 40, 80, 120, 180, 250, 350, 500, 750];
let costs_wiring = array![0, 5, 10, 20, 40, 80, 120, 180, 250, 350];
let costs_alloy = array![0, 0, 0, 0, 10, 20, 40, 80, 120, 180];
let costs_core = array![0, 0, 0, 0, 0, 0, 5, 10, 20, 40];
let mut level: u32 = 0;
while level != 10 {
world
.write_model(
@UpgradeSuccessRate {
gear_type: gear_type,
level: level.into(),
rate: *success_rates.at(level),
},
);
let mut materials_for_level = array![];
let scrap_cost = *costs_scrap.at(level);
if scrap_cost > 0 {
materials_for_level
.append(UpgradeMaterial { token_id: scrap_metal, amount: scrap_cost });
}
let wiring_cost = *costs_wiring.at(level);
if wiring_cost > 0 {
materials_for_level
.append(UpgradeMaterial { token_id: wiring, amount: wiring_cost });
}
let alloy_cost = *costs_alloy.at(level);
if alloy_cost > 0 {
materials_for_level
.append(UpgradeMaterial { token_id: advanced_alloy, amount: alloy_cost });
}
let core_cost = *costs_core.at(level);
if (gear_type == GearType::Pet || gear_type == GearType::Drone) && core_cost > 0 {
materials_for_level
.append(UpgradeMaterial { token_id: cybernetic_core, amount: core_cost });
}
world
.write_model(
@UpgradeCost {
gear_type: gear_type,
level: level.into(),
materials: materials_for_level,
},
);
level += 1;
};
}
fn _retrieve(
ref self: ContractState, item_id: u256,
) { // this function should probably return an enum
// or use an external function in the helper trait that returns an enum
}
// fn generate_next_gear_id(ref self: ContractState, gear_type: GearType) -> u256 {
// let mut world = self.world_default();
// let gear_type_code: u256 = gear_type.into();
// let gear_type_id = gear_type_code.high;
// let counter_entry: GearTypeCounter = world.read_model(gear_type_id);
// let next_serial = counter_entry.count + 1;
// let updated_counter = GearTypeCounter { gear_type_id, count: next_serial };
// world.write_model(@updated_counter);
// u256 { high: gear_type_id, low: next_serial }
// }
fn validate_session_for_read_action(ref self: ContractState, session_id: felt252) -> bool {
// Basic validation - session_id must not be zero
if session_id == 0 {
return false;
}
let caller = get_caller_address();
let world = self.world_default();
let session: SessionKey = world.read_model((session_id, caller));
// Use helper function for validation (read-only, so no transaction increment)
validate_session_parameters(session, caller)
}
fn _calculate_gear_stats(self: @ContractState, gear: @Gear) -> GearStatsCalculated {
let mut world = self.world_default();
// Get level-based stats
let level_stats: GearLevelStats = world
.read_model((*gear.asset_id, *gear.upgrade_level));
// Initialize with level stats
let mut calculated = GearStatsCalculated {
damage: level_stats.damage,
range: level_stats.range,
accuracy: level_stats.accuracy,
fire_rate: level_stats.fire_rate,
defense: level_stats.defense,
durability: level_stats.durability,
weight: level_stats.weight,
speed: 0,
armor: 0,
fuel_capacity: 0,
loyalty: 0,
intelligence: 0,
agility: 0,
};
// Get gear type and load specific stats
let gear_type = parse_id(*gear.asset_id);
match gear_type {
GearType::Weapon | GearType::BluntWeapon | GearType::Sword | GearType::Bow |
GearType::Firearm | GearType::Polearm | GearType::HeavyFirearms |
GearType::Explosives => {
let weapon_stats: WeaponStats = world.read_model(*gear.asset_id);
// Apply upgrade multipliers to weapon stats
calculated
.damage = self
._apply_upgrade_multiplier(weapon_stats.damage, *gear.upgrade_level);
calculated
.range = self
._apply_upgrade_multiplier(weapon_stats.range, *gear.upgrade_level);
calculated
.accuracy = self
._apply_upgrade_multiplier(weapon_stats.accuracy, *gear.upgrade_level);
calculated
.fire_rate = self
._apply_upgrade_multiplier(weapon_stats.fire_rate, *gear.upgrade_level);
},
GearType::Helmet | GearType::ChestArmor | GearType::LegArmor | GearType::Boots |
GearType::Gloves |
GearType::Shield => {
let armor_stats: Armor = world.read_model(*gear.asset_id);
// Apply upgrade multipliers to armor stats
calculated
.defense = self
._apply_upgrade_multiplier(armor_stats.defense, *gear.upgrade_level);
calculated
.durability = self
._apply_upgrade_multiplier(armor_stats.durability, *gear.upgrade_level);
calculated.weight = armor_stats.weight; // Weight doesn't scale with upgrades
},
GearType::Vehicle => {
let vehicle_stats: VehicleStats = world.read_model(*gear.asset_id);
// Apply upgrade multipliers to vehicle stats
calculated
.speed = self
._apply_upgrade_multiplier(vehicle_stats.speed, *gear.upgrade_level);
calculated
.armor = self
._apply_upgrade_multiplier(vehicle_stats.armor, *gear.upgrade_level);
calculated
.fuel_capacity = self
._apply_upgrade_multiplier(
vehicle_stats.fuel_capacity, *gear.upgrade_level,
);
},
GearType::Pet |
GearType::Drone => {
let pet_stats: PetStats = world.read_model(*gear.asset_id);
// Apply upgrade multipliers to pet stats
calculated
.loyalty = self
._apply_upgrade_multiplier(pet_stats.loyalty, *gear.upgrade_level);