-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.lua
More file actions
2164 lines (1852 loc) · 74.7 KB
/
Copy pathserver.lua
File metadata and controls
2164 lines (1852 loc) · 74.7 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
---@diagnostic disable: undefined-global, lowercase-global
-- ╔═══════════════════════════════════════════════════════════╗
-- ║ RDE | IPL MANAGER v1.0.1-alpha ║
-- ║ Author: RDE | SerpentsByte ║
-- ║ "The most advanced IPL server ever created for FiveM" ║
-- ║ 100% Statebag-First | Triple Admin | Exploit-Proof ║
-- ╚═══════════════════════════════════════════════════════════╝
-- ============================================
-- 📌 IMPORTS & INITIALIZATION
-- ============================================
local Ox = require '@ox_core/lib/init'
local Config = require 'config'
-- ============================================
-- 🎯 TYPED STATE MANAGEMENT (FULL COVERAGE!)
-- ============================================
---@class RDE_IPL_Property
---@field id number
---@field iplIndex number
---@field owner string|nil
---@field coords vector4
---@field price number
---@field forSale boolean
---@field locked boolean
---@field instanceId string
---@field customization table<string, string>
---@field accessList string[]
---@field lastEntered string|nil
---@field totalVisits number
---@field createdAt number
---@field updatedAt number
---@class RDE_IPL_ActiveInstance
---@field instanceId string
---@field propertyId number
---@field iplIndex number
---@field coords vector4
---@field routingBucket number
---@field players table<number, {joined: number, source: number, identifier: string, name: string}>
---@field created number
---@field lastActivity number
---@field customization table<string, string>
---@field iplData table
---@class RDE_IPL_ServerState
local State = {
properties = {}, -- instanceId → Property
activeInstances = {}, -- instanceId → ActiveInstance
playerInstances = {}, -- source → instanceId
propertyOwners = {}, -- identifier → instanceId[]
routingBuckets = {}, -- bucketId → {used, assignedAt, instanceId}
rateLimits = {}, -- key → {count, resetAt}
performanceMetrics = {
totalTransactions = 0,
successfulPurchases = 0,
failedPurchases = 0,
instancesCreated = 0,
instancesDestroyed = 0,
playersServed = 0,
averageInstanceDuration = 0,
peakConcurrentInstances = 0,
totalRevenue = 0
},
nextBucketId = Config.RoutingBuckets.StartBucketId,
debugMode = Config.Statebag.Debug or false,
initialized = false
}
-- ============================================
-- 🌐 LANGUAGE SYSTEM (BEAUTIFUL!)
-- ============================================
---Get localized string
---@param key string
---@param ... any
---@return string
local function L(key, ...)
local lang = Config.Languages[Config.DefaultLanguage] or Config.Languages['en']
local str = lang[key] or key
if ... then
return string.format(str, ...)
end
return str
end
-- ============================================
-- 📢 NOTIFICATION SYSTEM (OX_LIB V3!)
-- ============================================
---Send notification to player
---@param source number
---@param title string
---@param description string
---@param type 'success'|'error'|'info'|'warning'
---@param icon string|nil (lucide icon name)
---@param iconColor string|nil (hex color)
---@param duration number|nil (milliseconds)
local function Notify(source, title, description, type, icon, iconColor, duration)
TriggerClientEvent('ox_lib:notify', source, {
title = title,
description = description,
type = type or 'info',
icon = icon,
iconColor = iconColor,
duration = duration or 5000,
position = 'top-right'
})
end
---Send notification to all players
---@param title string
---@param description string
---@param type 'success'|'error'|'info'|'warning'
---@param icon string|nil
local function NotifyAll(title, description, type, icon)
TriggerClientEvent('ox_lib:notify', -1, {
title = title,
description = description,
type = type or 'info',
icon = icon,
duration = 5000
})
end
-- ============================================
-- 🐉 RDE NOSTR LOGGER (OPTIONAL – GRACEFUL FALLBACK)
-- ============================================
-- Works with or without rde_nostr_log installed.
-- If the resource is not running, all log calls become no-ops.
-- API: exports['rde_nostr_log']:postLog(message, tags)
-- Tags: {{'key', 'value'}, ...} -- same format as rde_nostr_log EXAMPLES.lua
-- ============================================
local RDELog = {}
-- Internal: check once if nostr log resource is available
local _nostrAvailable = nil
local function _isNostrAvailable()
if _nostrAvailable ~= nil then return _nostrAvailable end
-- GetResourceState returns 'started'|'stopped'|'missing'|'uninitialized'
_nostrAvailable = GetResourceState('rde_nostr_log') == 'started'
return _nostrAvailable
end
-- Internal: reset availability cache on resource state changes so hot-restarts work
AddEventHandler('onResourceStart', function(res)
if res == 'rde_nostr_log' then _nostrAvailable = true end
end)
AddEventHandler('onResourceStop', function(res)
if res == 'rde_nostr_log' then _nostrAvailable = false end
end)
-- Internal: safely call the export, never error
local function _post(msg, tags)
if not _isNostrAvailable() then return end
local ok, err = pcall(function()
exports['rde_nostr_log']:postLog(msg, tags)
end)
if not ok and State.debugMode then
print(('[RDE|IPL] Nostr log failed (non-critical): ' .. tostring(err)))
end
end
-- ─── Public helpers ────────────────────────────────────────────────────────
---Log a property purchase
---@param player table ox_core OxPlayer
---@param instanceId string
---@param iplName string
---@param price number
function RDELog.purchase(player, instanceId, iplName, price)
_post(
('💰 PROPERTY PURCHASED | %s bought [%s] for $%d'):format(
player.username, iplName, price),
{
{'event', 'property_purchase'},
{'resource', 'rde_ipl'},
{'identifier', player.identifier},
{'player', player.username},
{'instance_id', instanceId},
{'ipl_name', iplName},
{'price', tostring(price)},
}
)
end
---Log a property sale
---@param player table
---@param instanceId string
---@param iplName string
---@param price number
function RDELog.sale(player, instanceId, iplName, price)
_post(
('💵 PROPERTY SOLD | %s sold [%s] for $%d'):format(
player.username, iplName, price),
{
{'event', 'property_sale'},
{'resource', 'rde_ipl'},
{'identifier', player.identifier},
{'player', player.username},
{'instance_id', instanceId},
{'ipl_name', iplName},
{'payout', tostring(price)},
}
)
end
---Log a player entering a property
---@param player table
---@param instanceId string
---@param iplName string
---@param bucket number
function RDELog.enter(player, instanceId, iplName, bucket)
_post(
('🚪 ENTERED PROPERTY | %s → [%s] (bucket %d)'):format(
player.username, iplName, bucket),
{
{'event', 'property_enter'},
{'resource', 'rde_ipl'},
{'identifier', player.identifier},
{'player', player.username},
{'instance_id', instanceId},
{'ipl_name', iplName},
{'bucket', tostring(bucket)},
}
)
end
---Log a player exiting a property
---@param player table
---@param instanceId string
---@param iplName string
function RDELog.exit(player, instanceId, iplName)
_post(
('🚶 EXITED PROPERTY | %s ← [%s]'):format(player.username, iplName),
{
{'event', 'property_exit'},
{'resource', 'rde_ipl'},
{'identifier', player.identifier},
{'player', player.username},
{'instance_id', instanceId},
{'ipl_name', iplName},
}
)
end
---Log an admin action (create / delete / update / teleport)
---@param admin table
---@param action string
---@param instanceId string
---@param detail string|nil
function RDELog.adminAction(admin, action, instanceId, detail)
_post(
('👑 ADMIN ACTION | %s → %s on [%s]%s'):format(
admin.username, action, instanceId,
detail and (' | ' .. detail) or ''),
{
{'event', 'admin_action'},
{'resource', 'rde_ipl'},
{'identifier', admin.identifier},
{'admin', admin.username},
{'action', action},
{'instance_id', instanceId},
{'detail', detail or ''},
}
)
end
---Log a property deletion
---@param admin table
---@param instanceId string
---@param iplName string
function RDELog.deleteProperty(admin, instanceId, iplName)
_post(
('🗑️ PROPERTY DELETED | %s deleted [%s] (%s)'):format(
admin.username, iplName, instanceId),
{
{'event', 'property_deleted'},
{'resource', 'rde_ipl'},
{'identifier', admin.identifier},
{'admin', admin.username},
{'instance_id', instanceId},
{'ipl_name', iplName},
}
)
end
---Log a property creation by admin
---@param admin table
---@param instanceId string
---@param iplName string
---@param price number
function RDELog.createProperty(admin, instanceId, iplName, price)
_post(
('🏗️ PROPERTY CREATED | %s created [%s] @ $%d'):format(
admin.username, iplName, price),
{
{'event', 'property_created'},
{'resource', 'rde_ipl'},
{'identifier', admin.identifier},
{'admin', admin.username},
{'instance_id', instanceId},
{'ipl_name', iplName},
{'price', tostring(price)},
}
)
end
---Log a lock toggle
---@param player table
---@param instanceId string
---@param locked boolean
function RDELog.lockToggle(player, instanceId, locked)
_post(
('%s LOCK TOGGLE | %s %s [%s]'):format(
locked and '🔒' or '🔓',
player.username,
locked and 'locked' or 'unlocked',
instanceId),
{
{'event', 'property_lock_toggle'},
{'resource', 'rde_ipl'},
{'identifier', player.identifier},
{'player', player.username},
{'instance_id', instanceId},
{'locked', tostring(locked)},
}
)
end
---Log a security violation attempt
---@param source number
---@param action string
---@param detail string|nil
function RDELog.securityViolation(source, action, detail)
local name = GetPlayerName(source) or 'unknown'
local steam = GetPlayerIdentifierByType(source, 'steam') or 'unknown'
_post(
('⚠️ SECURITY VIOLATION | src:%d [%s] attempted: %s%s'):format(
source, name, action,
detail and (' | ' .. detail) or ''),
{
{'event', 'security_violation'},
{'resource', 'rde_ipl'},
{'source', tostring(source)},
{'player', name},
{'steam', steam},
{'action', action},
{'detail', detail or ''},
}
)
end
---Log custom message (for debugging / misc events)
---@param level 'info'|'warn'|'error'
---@param msg string
---@param tags table|nil
function RDELog.custom(level, msg, tags)
local prefix = level == 'error' and '❌' or level == 'warn' and '⚠️' or 'ℹ️'
local combined = { {'event', 'custom'}, {'resource', 'rde_ipl'}, {'level', level} }
if tags then
for _, t in ipairs(tags) do table.insert(combined, t) end
end
_post(('%s [IPL] %s'):format(prefix, msg), combined)
end
local AdminSystem = {}
---Check if player is admin (ANY of the three methods)
---@param source number
---@return boolean
function AdminSystem.isAdmin(source)
local player = Ox.GetPlayer(source)
if not player then return false end
local adminConfig = Config.AdminSystem
local identifier = GetPlayerIdentifierByType(source, 'steam')
-- Check in configured order
for _, method in ipairs(adminConfig.checkOrder) do
if method == 'ace' then
-- ✅ Method 1: ACE Permissions
if IsPlayerAceAllowed(source, adminConfig.acePermission) then
if State.debugMode then
print(('🔐 [ADMIN] %s verified via ACE: %s'):format(player.username, adminConfig.acePermission))
end
return true
end
elseif method == 'oxcore' then
-- ✅ Method 2: ox_core Groups
if player.getGroups then
local groups = player.getGroups()
for groupName, minGrade in pairs(adminConfig.oxGroups) do
if groups[groupName] and groups[groupName] >= minGrade then
if State.debugMode then
print(('🔐 [ADMIN] %s verified via ox_core: %s (grade %s)'):format(player.username, groupName, groups[groupName]))
end
return true
end
end
end
elseif method == 'steam' then
-- ✅ Method 3: Steam ID Whitelist
if identifier then
for _, allowedId in ipairs(adminConfig.steamIds) do
if identifier == allowedId then
if State.debugMode then
print(('🔐 [ADMIN] %s verified via Steam: %s'):format(player.username, identifier))
end
return true
end
end
end
end
end
-- ❌ Access denied - log attempt
if State.debugMode then
print(('⚠️ [SECURITY] Unauthorized admin attempt: %s [%s]'):format(player.username, identifier or 'unknown'))
end
return false
end
---Check if player is admin with detailed reason
---@param source number
---@return boolean isAdmin
---@return string method
---@return string detail
function AdminSystem.isAdminWithReason(source)
local player = Ox.GetPlayer(source)
if not player then return false, 'invalid_player', nil end
local adminConfig = Config.AdminSystem
local identifier = GetPlayerIdentifierByType(source, 'steam')
for _, checkMethod in ipairs(adminConfig.checkOrder) do
if checkMethod == 'ace' and IsPlayerAceAllowed(source, adminConfig.acePermission) then
return true, 'ace', adminConfig.acePermission
elseif checkMethod == 'oxcore' then
if player.getGroups then
local groups = player.getGroups()
for groupName, minGrade in pairs(adminConfig.oxGroups) do
if groups[groupName] and groups[groupName] >= minGrade then
return true, 'oxcore', ('%s:%s'):format(groupName, groups[groupName])
end
end
end
elseif checkMethod == 'steam' and identifier then
for _, allowedId in ipairs(adminConfig.steamIds) do
if identifier == allowedId then
return true, 'steam', identifier
end
end
end
end
return false, 'unauthorized', identifier or 'unknown'
end
-- ============================================
-- ⚡ RATE LIMITING SYSTEM (ANTI-SPAM!)
-- ============================================
local RateLimit = {}
---Check if action is allowed (rate limiting)
---@param source number
---@param action string
---@param limit number|nil
---@param window number|nil
---@return boolean allowed
---@return string|nil errorMsg
function RateLimit.check(source, action, limit, window)
if not Config.Performance.EnableRateLimiting then
return true
end
limit = limit or Config.Performance.RateLimitMax
window = window or Config.Performance.RateLimitWindow
local player = Ox.GetPlayer(source)
local identifier = player and (player.identifier) or tostring(source)
local key = ('%s:%s'):format(identifier, action)
local now = os.time() * 1000
if not State.rateLimits[key] then
State.rateLimits[key] = { count = 0, resetAt = now + window }
end
local limitData = State.rateLimits[key]
-- Reset if window expired
if now >= limitData.resetAt then
limitData.count = 0
limitData.resetAt = now + window
end
-- Check limit
if limitData.count >= limit then
if State.debugMode then
print(('[RDE | IPL] 🚫 Rate limit: %s for %s'):format(action, identifier))
end
return false, L('warning') .. ' ' .. ('Rate limit exceeded. Try again in %d seconds'):format(math.ceil((limitData.resetAt - now) / 1000))
end
limitData.count = limitData.count + 1
return true
end
-- ============================================
-- 💰 MONEY SYSTEM (DUAL MODE: INVENTORY OR BANKING!)
-- ============================================
local MoneySystem = {}
---Check if player has enough money
---@param source number
---@param amount number
---@return boolean
function MoneySystem.hasMoney(source, amount)
local player = Ox.GetPlayer(source)
if not player then return false end
if Config.MoneySystem.Source == 'inventory' then
-- ox_inventory: GetItemCount(inv, itemName) → returns total count
local count = exports.ox_inventory:GetItemCount(source, Config.MoneySystem.InventoryItemName)
return (count or 0) >= amount
elseif Config.MoneySystem.Source == 'banking' then
-- ox_core: player.getAccount() takes NO param, returns OxAccount object
-- Use account.get('balance') to read the numeric balance
local account = player.getAccount()
if not account then return false end
local balance = account.get('balance') or 0
return balance >= amount
end
return false
end
---Remove money from player
---@param source number
---@param amount number
---@param reason string|nil
---@return boolean success
function MoneySystem.removeMoney(source, amount, reason)
local player = Ox.GetPlayer(source)
if not player then return false end
local success = false
if Config.MoneySystem.Source == 'inventory' then
-- ox_inventory: RemoveItem returns success (boolean), response (string?)
local ok, _ = exports.ox_inventory:RemoveItem(source, Config.MoneySystem.InventoryItemName, amount)
success = ok == true
elseif Config.MoneySystem.Source == 'banking' then
-- ox_core: account.removeBalance({amount, message}) → {success, message}
local account = player.getAccount()
if account then
local result = account.removeBalance({ amount = amount, message = reason or 'Property Transaction' })
success = result and result.success == true
end
end
if success and State.debugMode then
print(('[RDE | IPL] 💰 Money removed: %s - $%d (%s)'):format(player.username, amount, reason or 'Unknown'))
end
return success
end
---Add money to player
---@param source number
---@param amount number
---@param reason string|nil
---@return boolean success
function MoneySystem.addMoney(source, amount, reason)
local player = Ox.GetPlayer(source)
if not player then return false end
local success = false
if Config.MoneySystem.Source == 'inventory' then
-- ox_inventory: AddItem returns success (boolean), response (string?)
local ok, _ = exports.ox_inventory:AddItem(source, Config.MoneySystem.InventoryItemName, amount)
success = ok == true
elseif Config.MoneySystem.Source == 'banking' then
-- ox_core: account.addBalance({amount, message}) → {success, message}
local account = player.getAccount()
if account then
local result = account.addBalance({ amount = amount, message = reason or 'Property Transaction' })
success = result and result.success == true
end
end
if success and State.debugMode then
print(('[RDE | IPL] 💰 Money added: %s + $%d (%s)'):format(player.username, amount, reason or 'Unknown'))
end
return success
end
---Calculate final price with fees/discounts
---@param basePrice number
---@param isSelling boolean
---@return number finalPrice
function MoneySystem.calculatePrice(basePrice, isSelling)
if isSelling then
-- Selling: apply discount
if Config.MoneySystem.EnableSellDiscount then
local discount = (basePrice * Config.MoneySystem.SellDiscountPercent) / 100
return math.floor(basePrice - discount)
end
return basePrice
else
-- Buying: apply fee
if Config.MoneySystem.EnablePurchaseFee then
local fee = (basePrice * Config.MoneySystem.PurchaseFeePercent) / 100
return math.floor(basePrice + fee)
end
return basePrice
end
end
-- ============================================
-- 📊 DATABASE MANAGER (AUTO-CREATE, MIGRATION!)
-- ============================================
local Database = {}
---Initialize database tables
function Database.initialize()
print('^3[RDE | IPL] 💾 Initializing database...^7')
-- Create properties table
MySQL.query.await([[
CREATE TABLE IF NOT EXISTS `rde_iplproperties` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`instance_id` VARCHAR(64) NOT NULL UNIQUE,
`ipl_index` INT(11) NOT NULL,
`owner_identifier` VARCHAR(60) DEFAULT NULL,
`coords` TEXT NOT NULL,
`price` INT(11) NOT NULL DEFAULT 100000,
`for_sale` TINYINT(1) NOT NULL DEFAULT 1,
`locked` TINYINT(1) NOT NULL DEFAULT 1,
`customization` TEXT DEFAULT NULL,
`access_list` TEXT DEFAULT NULL,
`last_entered` VARCHAR(60) DEFAULT NULL,
`total_visits` INT(11) NOT NULL DEFAULT 0,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `idx_owner` (`owner_identifier`),
INDEX `idx_instance` (`instance_id`),
INDEX `idx_forsale` (`for_sale`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
]])
-- Create transactions table (for analytics)
MySQL.query.await([[
CREATE TABLE IF NOT EXISTS `rde_ipl_transactions` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`instance_id` VARCHAR(64) NOT NULL,
`buyer_identifier` VARCHAR(60) DEFAULT NULL,
`seller_identifier` VARCHAR(60) DEFAULT NULL,
`transaction_type` ENUM('purchase', 'sale', 'transfer') NOT NULL,
`amount` INT(11) NOT NULL,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `idx_buyer` (`buyer_identifier`),
INDEX `idx_seller` (`seller_identifier`),
INDEX `idx_instance` (`instance_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
]])
print('^2[RDE | IPL] ✅ Database initialized successfully^7')
end
---Save property to database
---@param property RDE_IPL_Property
---@return boolean success
function Database.saveProperty(property)
local success = MySQL.query.await(
'INSERT INTO rde_iplproperties (instance_id, ipl_index, owner_identifier, coords, price, for_sale, locked, customization, access_list, last_entered, total_visits) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE owner_identifier = VALUES(owner_identifier), price = VALUES(price), for_sale = VALUES(for_sale), locked = VALUES(locked), customization = VALUES(customization), access_list = VALUES(access_list), last_entered = VALUES(last_entered), total_visits = VALUES(total_visits)',
{
property.instanceId,
property.iplIndex,
property.owner,
json.encode({x = property.coords.x, y = property.coords.y, z = property.coords.z, w = property.coords.w}),
property.price,
property.forSale,
property.locked,
json.encode(property.customization or {}),
json.encode(property.accessList or {}),
property.lastEntered,
property.totalVisits or 0
}
)
return success ~= nil
end
---Delete property from database
---@param instanceId string
---@return boolean success
function Database.deleteProperty(instanceId)
-- MySQL.update.await returns affectedRows as a plain number (not a table like MySQL.query.await)
local affectedRows = MySQL.update.await('DELETE FROM rde_iplproperties WHERE instance_id = ?', {instanceId})
return type(affectedRows) == 'number' and affectedRows > 0
end
---Log transaction
---@param instanceId string
---@param buyerIdentifier string|nil
---@param sellerIdentifier string|nil
---@param transactionType string
---@param amount number
function Database.logTransaction(instanceId, buyerIdentifier, sellerIdentifier, transactionType, amount)
MySQL.insert('INSERT INTO rde_ipl_transactions (instance_id, buyer_identifier, seller_identifier, transaction_type, amount) VALUES (?, ?, ?, ?, ?)',
{instanceId, buyerIdentifier, sellerIdentifier, transactionType, amount})
end
-- ============================================
-- 🌐 ROUTING BUCKET MANAGER (SMART ALLOCATION!)
-- ============================================
local RoutingBuckets = {}
---Allocate a routing bucket
---@return number|nil bucketId
function RoutingBuckets.allocate()
local startId = Config.RoutingBuckets.StartBucketId
local maxBuckets = Config.RoutingBuckets.MaxBuckets
-- Find first available bucket
for i = startId, startId + maxBuckets - 1 do
if not State.routingBuckets[i] then
State.routingBuckets[i] = {
used = true,
assignedAt = os.time(),
instanceId = nil
}
if State.debugMode then
print(('[RDE | IPL] 🌐 Bucket allocated: %d'):format(i))
end
return i
end
end
-- No buckets available
print('^3[RDE | IPL] ⚠️ No routing buckets available!^7')
return nil
end
---Free a routing bucket
---@param bucketId number
function RoutingBuckets.free(bucketId)
if State.routingBuckets[bucketId] then
State.routingBuckets[bucketId] = nil
if State.debugMode then
print(('[RDE | IPL] 🌐 Bucket freed: %d'):format(bucketId))
end
end
end
---Get bucket statistics
---@return table stats
function RoutingBuckets.getStats()
local used = 0
for _ in pairs(State.routingBuckets) do
used = used + 1
end
return {
used = used,
total = Config.RoutingBuckets.MaxBuckets,
available = Config.RoutingBuckets.MaxBuckets - used
}
end
-- ============================================
-- 🏠 PROPERTY MANAGER (CORE LOGIC!)
-- ============================================
local PropertyManager = {}
---Create a new property
---@param iplIndex number
---@param coords vector4
---@param price number
---@param forSale boolean
---@return string|nil instanceId
function PropertyManager.create(iplIndex, coords, price, forSale)
local iplData = Config.IPLDatabase[iplIndex]
if not iplData then return nil end
-- Generate unique instance ID (timestamp + random suffix to avoid same-second collisions)
local instanceId = ('ipl_%s_%d_%04x'):format(iplData.id, os.time(), math.random(0, 65535))
local property = {
id = 0, -- Will be set by database
iplIndex = iplIndex,
owner = nil,
coords = coords,
price = price,
forSale = forSale,
locked = Config.Property.LockByDefault,
instanceId = instanceId,
customization = {},
accessList = {},
lastEntered = nil,
totalVisits = 0,
createdAt = os.time(),
updatedAt = os.time()
}
-- Save to database
if not Database.saveProperty(property) then
print('^1[RDE | IPL] ❌ Failed to save property to database^7')
return nil
end
-- Add to state
State.properties[instanceId] = property
if State.debugMode then
print(('[RDE | IPL] ✅ Property created: %s (%s)'):format(iplData.name, instanceId))
end
return instanceId
end
---Update property
---@param instanceId string
---@param updates table
---@return boolean success
function PropertyManager.update(instanceId, updates)
local property = State.properties[instanceId]
if not property then return false end
-- Apply updates
for key, value in pairs(updates) do
property[key] = value
end
property.updatedAt = os.time()
-- Save to database
if not Database.saveProperty(property) then
return false
end
if State.debugMode then
print(('[RDE | IPL] ✅ Property updated: %s'):format(instanceId))
end
return true
end
---Delete property
---@param instanceId string
---@return boolean success
function PropertyManager.delete(instanceId)
local property = State.properties[instanceId]
if not property then return false end
-- Delete from database
if not Database.deleteProperty(instanceId) then
return false
end
-- Remove from owner list
if property.owner and State.propertyOwners[property.owner] then
for i, id in ipairs(State.propertyOwners[property.owner]) do
if id == instanceId then
table.remove(State.propertyOwners[property.owner], i)
break
end
end
end
-- Remove from state
State.properties[instanceId] = nil
if State.debugMode then
print(('[RDE | IPL] 🗑️ Property deleted: %s'):format(instanceId))
end
return true
end
---Purchase property
---@param source number
---@param instanceId string
---@return boolean success
---@return string|nil errorMsg
function PropertyManager.purchase(source, instanceId)
local player = Ox.GetPlayer(source)
if not player then return false, 'Player not found' end
local property = State.properties[instanceId]
if not property then return false, L('invalid_property') end
if not property.forSale then return false, 'Property not for sale' end
if property.owner then return false, 'Property already owned' end
local identifier = player.identifier
-- Check max properties
local ownedCount = 0
if State.propertyOwners[identifier] then
ownedCount = #State.propertyOwners[identifier]
end
if ownedCount >= Config.Property.MaxPropertiesPerPlayer then
return false, L('max_properties_reached', ownedCount, Config.Property.MaxPropertiesPerPlayer)
end
-- Calculate final price
local finalPrice = MoneySystem.calculatePrice(property.price, false)
-- Check money
if not MoneySystem.hasMoney(source, finalPrice) then
return false, L('not_enough_money', finalPrice)
end
-- Remove money
if not MoneySystem.removeMoney(source, finalPrice, 'Property Purchase: ' .. instanceId) then
return false, 'Failed to remove money'
end
-- Update property
property.owner = identifier
property.forSale = false
property.updatedAt = os.time()
-- Save to database
Database.saveProperty(property)
-- Update owner list
State.propertyOwners[identifier] = State.propertyOwners[identifier] or {}
table.insert(State.propertyOwners[identifier], instanceId)
-- Log transaction
Database.logTransaction(instanceId, identifier, nil, 'purchase', finalPrice)
-- Update metrics
State.performanceMetrics.successfulPurchases = State.performanceMetrics.successfulPurchases + 1
State.performanceMetrics.totalTransactions = State.performanceMetrics.totalTransactions + 1
State.performanceMetrics.totalRevenue = State.performanceMetrics.totalRevenue + finalPrice
-- Log to Nostr
local iplData = Config.IPLDatabase[property.iplIndex]
RDELog.purchase(player, instanceId, iplData and iplData.name or instanceId, finalPrice)
if State.debugMode then
print(('[RDE | IPL] Property purchased: %s by %s for $%d'):format(instanceId, player.username, finalPrice))
end
return true
end
---Sell property
---@param source number
---@param instanceId string
---@return boolean success
---@return string|nil errorMsg
function PropertyManager.sell(source, instanceId)
if not Config.Property.AllowPropertySale then
return false, 'Property sales are disabled'
end
local player = Ox.GetPlayer(source)
if not player then return false, 'Player not found' end
local property = State.properties[instanceId]
if not property then return false, L('invalid_property') end
local identifier = player.identifier
if property.owner ~= identifier then
return false, L('not_owner')
end
-- Calculate sale price
local salePrice = MoneySystem.calculatePrice(property.price, true)
-- Add money
if not MoneySystem.addMoney(source, salePrice, 'Property Sale: ' .. instanceId) then
return false, 'Failed to add money'
end
-- Update property
property.owner = nil
property.forSale = true
property.locked = true
property.accessList = {}
property.updatedAt = os.time()
-- Save to database
Database.saveProperty(property)
-- Update owner list
if State.propertyOwners[identifier] then
for i, id in ipairs(State.propertyOwners[identifier]) do
if id == instanceId then
table.remove(State.propertyOwners[identifier], i)
break
end