-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.lua
More file actions
1149 lines (970 loc) · 54.3 KB
/
Copy pathserver.lua
File metadata and controls
1149 lines (970 loc) · 54.3 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
-- ┌───────────────────────────────────────────────────────────────────────┐
-- │ RDE Banking — Server | v1.0.0 │
-- │ RDE | SerpentsByte | rd-elite.com │
-- └───────────────────────────────────────────────────────────────────────┘
local bankNPCs = {} -- runtime cache of admin-created NPCs (id → data)
local playerAccounts = {} -- [charId] = account table (runtime cache)
-- Publish the (empty) NPC table to the state bag NOW so clients connecting
-- in the gap between script load and LoadNPCs() finishing don't read nil.
-- LoadNPCs() will overwrite this with the real data when the DB is ready.
GlobalState.bankNPCs = bankNPCs
-- Helper: best-effort human-readable name for log output. OxPlayer doesn't
-- expose `username` — pull firstName/lastName from metadata if available,
-- fall back to charId. v4.0 used `player.username` which was always nil.
local function PlayerLabel(player)
if not player then return 'unknown' end
local first = player.get and player.get('firstName')
local last = player.get and player.get('lastName')
if first or last then
return ((first or '') .. ' ' .. (last or '')):match('^%s*(.-)%s*$')
end
return ('charId:%s'):format(tostring(player.charId or '?'))
end
-- ─────────────────────────────────────────────────────────────────────────────
-- FORWARD DECLARATIONS
-- Lua resolves identifiers at function-call time via the env captured at
-- *compile* time. v3 had `GetOrCreateAccount` call `CreateTransaction`
-- before the latter's `local function` declaration — that made the call
-- fall through to a nil global and crash on first account creation.
-- Declaring the locals first fixes the upvalue capture.
-- ─────────────────────────────────────────────────────────────────────────────
local CreateTransaction
local SaveAccount
local GetOrCreateAccount
local RecalculateTier
local AddLifetimeVolume
local PushAccountUpdate
local NotifyClient
-- ─────────────────────────────────────────────────────────────────────────────
-- DEBUG HELPER
-- ─────────────────────────────────────────────────────────────────────────────
local function DbgPrint(tag, msg)
if Config.Debug then
print(string.format('^6[RDE Banking | %s]^7 %s', tag, tostring(msg)))
end
end
-- ─────────────────────────────────────────────────────────────────────────────
-- ADMIN VERIFICATION (Triple-Auth: ACE + ox_core groups + Steam)
-- ─────────────────────────────────────────────────────────────────────────────
local function IsPlayerAdmin(src)
local player = Ox.GetPlayer(src)
if not player or not player.charId then return false end
local cfg = Config.AdminSystem
for _, method in ipairs(cfg.checkOrder) do
if method == 'ace' then
if IsPlayerAceAllowed(src, cfg.acePermission) then
DbgPrint('ADMIN', PlayerLabel(player) .. ' verified via ACE')
return true
end
elseif method == 'oxcore' then
local groups = player.getGroups and player.getGroups() or {}
for groupName, grade in pairs(groups) do
if cfg.oxGroups[groupName] ~= nil then
DbgPrint('ADMIN', PlayerLabel(player) ..
' verified via ox_core group: ' .. groupName .. ' (grade ' .. grade .. ')')
return true
end
end
elseif method == 'steam' then
local identifier = GetPlayerIdentifierByType(src, 'steam')
if identifier then
for _, id in ipairs(cfg.steamIds) do
if identifier == id then
DbgPrint('ADMIN', PlayerLabel(player) .. ' verified via Steam')
return true
end
end
end
end
end
print(string.format('^1[SECURITY]^7 Unauthorized admin attempt by %s [%s]',
PlayerLabel(player),
GetPlayerIdentifierByType(src, 'steam') or 'no-steam'))
return false
end
-- ─────────────────────────────────────────────────────────────────────────────
-- ACCOUNT NUMBER GENERATION
-- ─────────────────────────────────────────────────────────────────────────────
local function GenerateAccountNumber()
local num = ''
for _ = 1, 12 do num = num .. math.random(0, 9) end
local exists = MySQL.scalar.await(
'SELECT COUNT(*) FROM rde_bank_accounts WHERE accountNumber = ?', { num })
if (exists or 0) > 0 then return GenerateAccountNumber() end
return num
end
-- ─────────────────────────────────────────────────────────────────────────────
-- DAILY LIMIT RESET
-- ─────────────────────────────────────────────────────────────────────────────
local function ResetDailyLimitsIfNeeded(account)
local midnight = os.time() - (os.time() % 86400)
if (account.lastLimitReset or 0) < midnight then
account.dailyDeposit = 0
account.dailyWithdraw = 0
account.lastLimitReset = os.time()
MySQL.update.await(
'UPDATE rde_bank_accounts SET dailyDeposit=0, dailyWithdraw=0, lastLimitReset=? WHERE charid=?',
{ account.lastLimitReset, account.charid })
end
end
-- ─────────────────────────────────────────────────────────────────────────────
-- TRANSACTION LOG (forward-declared above)
-- ─────────────────────────────────────────────────────────────────────────────
CreateTransaction = function(charid, accountNumber, txType, amount, description, targetAccount)
MySQL.insert(
'INSERT INTO rde_bank_transactions (charid,accountNumber,type,amount,description,targetAccount,timestamp) VALUES (?,?,?,?,?,?,?)',
{ charid, accountNumber, txType, amount, description or '', targetAccount or nil, os.time() })
end
-- ─────────────────────────────────────────────────────────────────────────────
-- SAVE ACCOUNT (forward-declared)
-- ─────────────────────────────────────────────────────────────────────────────
SaveAccount = function(acc)
MySQL.update.await(
'UPDATE rde_bank_accounts SET balance=?,creditScore=?,dailyDeposit=?,dailyWithdraw=?,lastLimitReset=?,lastInterest=?,lifetimeVolume=?,tier=? WHERE charid=?',
{ acc.balance, acc.creditScore, acc.dailyDeposit, acc.dailyWithdraw,
acc.lastLimitReset, acc.lastInterest, acc.lifetimeVolume or 0, acc.tier or 'bronze',
acc.charid })
end
-- ─────────────────────────────────────────────────────────────────────────────
-- NOTIFY HELPERS (forward-declared)
-- ─────────────────────────────────────────────────────────────────────────────
NotifyClient = function(src, msg, ntype)
TriggerClientEvent('rde_banking:client:notify', src, msg, ntype or 'info')
end
PushAccountUpdate = function(src, account, cash)
TriggerClientEvent('rde_banking:client:updateAccount', src, account, cash)
end
-- ─────────────────────────────────────────────────────────────────────────────
-- TIER SYSTEM
-- Recalculates the player's tier from lifetimeVolume. If the tier changed,
-- persist it, mirror it onto the player statebag, and notify the client.
-- ─────────────────────────────────────────────────────────────────────────────
RecalculateTier = function(account, src)
if not Config.Tiers.enabled then return end
local newTier = GetTierForVolume(account.lifetimeVolume or 0)
local oldTier = account.tier or 'bronze'
-- Always sync statebag (covers first login + tier changes uniformly)
if src then
local player = Ox.GetPlayer(src)
if player then
player.set('bankTier', newTier.id, true) -- replicated to client
end
end
if newTier.id ~= oldTier then
account.tier = newTier.id
MySQL.update.await(
'UPDATE rde_bank_accounts SET tier=? WHERE charid=?',
{ newTier.id, account.charid })
if src then
TriggerClientEvent('rde_banking:client:tierPromoted', src, newTier)
end
DbgPrint('TIER', string.format('charid=%s → %s', account.charid, newTier.id))
end
end
AddLifetimeVolume = function(account, amount, src)
account.lifetimeVolume = (account.lifetimeVolume or 0) + math.abs(tonumber(amount) or 0)
RecalculateTier(account, src)
end
-- ─────────────────────────────────────────────────────────────────────────────
-- GET / CREATE ACCOUNT (forward-declared)
-- ─────────────────────────────────────────────────────────────────────────────
GetOrCreateAccount = function(player)
local charId = player.charId
if not charId then return nil end
if playerAccounts[charId] then
ResetDailyLimitsIfNeeded(playerAccounts[charId])
return playerAccounts[charId]
end
local rows = MySQL.query.await(
'SELECT * FROM rde_bank_accounts WHERE charid = ?', { charId })
local isNew = false
if rows and #rows > 0 then
local acc = rows[1]
acc.balance = tonumber(acc.balance) or 0
acc.creditScore = tonumber(acc.creditScore) or 0
acc.dailyDeposit = tonumber(acc.dailyDeposit) or 0
acc.dailyWithdraw = tonumber(acc.dailyWithdraw) or 0
acc.lastLimitReset = tonumber(acc.lastLimitReset) or 0
acc.lastInterest = tonumber(acc.lastInterest) or 0
acc.lifetimeVolume = tonumber(acc.lifetimeVolume) or 0
acc.tier = acc.tier or 'bronze'
acc.charid = charId
playerAccounts[charId] = acc
else
local accountNumber = GenerateAccountNumber()
local now = os.time()
MySQL.insert.await(
'INSERT INTO rde_bank_accounts (charid,accountNumber,balance,creditScore,lastInterest,lastLimitReset,dailyDeposit,dailyWithdraw,lifetimeVolume,tier) VALUES (?,?,?,?,?,?,?,?,?,?)',
{ charId, accountNumber, Config.Banking.startingBalance, 0, now, now, 0, 0, 0, 'bronze' })
playerAccounts[charId] = {
charid = charId,
accountNumber = accountNumber,
balance = Config.Banking.startingBalance,
creditScore = 0,
lastInterest = now,
lastLimitReset = now,
dailyDeposit = 0,
dailyWithdraw = 0,
lifetimeVolume = 0,
tier = 'bronze',
}
isNew = true
CreateTransaction(charId, accountNumber, 'initial_deposit', Config.Banking.startingBalance,
'Welcome to Pacific Standard Bank — account opened')
end
ResetDailyLimitsIfNeeded(playerAccounts[charId])
-- Mirror tier to player statebag so client UI + other resources can read it
RecalculateTier(playerAccounts[charId], player.source)
playerAccounts[charId]._isNew = isNew
return playerAccounts[charId]
end
-- ─────────────────────────────────────────────────────────────────────────────
-- DATABASE INIT + NPC LOAD
-- ─────────────────────────────────────────────────────────────────────────────
local function LoadNPCs()
local rows = MySQL.query.await('SELECT * FROM rde_bank_npcs')
if rows then
for _, row in ipairs(rows) do
local c = json.decode(row.coords)
bankNPCs[row.id] = {
coords = { x = c.x, y = c.y, z = c.z, w = c.w }, -- plain table for state-bag serialisation
model = row.model,
scenario = row.scenario,
}
end
DbgPrint('NPC', string.format('Loaded %d DB NPC(s)', #rows))
end
-- Publish to clients via GlobalState — auto-syncs to every connected
-- client AND to any client that connects later. No event needed.
GlobalState.bankNPCs = bankNPCs
end
local function StartInterestSystem() end -- forward decl, body below
local function ProcessInvestments() end
CreateThread(function()
MySQL.query.await([[
CREATE TABLE IF NOT EXISTS `rde_bank_accounts` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`charid` INT NOT NULL UNIQUE,
`accountNumber` VARCHAR(50) NOT NULL UNIQUE,
`balance` DECIMAL(15,2) DEFAULT 0.00,
`creditScore` INT DEFAULT 0,
`lastInterest` BIGINT DEFAULT 0,
`lastLimitReset` BIGINT DEFAULT 0,
`dailyDeposit` DECIMAL(15,2) DEFAULT 0.00,
`dailyWithdraw` DECIMAL(15,2) DEFAULT 0.00,
`lifetimeVolume` DECIMAL(18,2) DEFAULT 0.00,
`tier` VARCHAR(20) DEFAULT 'bronze',
`createdAt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX `idx_charid` (`charid`),
INDEX `idx_account` (`accountNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
]])
MySQL.query.await([[
CREATE TABLE IF NOT EXISTS `rde_bank_transactions` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`charid` INT NOT NULL,
`accountNumber` VARCHAR(50) NOT NULL,
`type` VARCHAR(50) NOT NULL,
`amount` DECIMAL(15,2) NOT NULL,
`description` TEXT,
`targetAccount` VARCHAR(50),
`timestamp` BIGINT NOT NULL,
INDEX `idx_charid` (`charid`),
INDEX `idx_account` (`accountNumber`),
INDEX `idx_timestamp` (`timestamp`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
]])
MySQL.query.await([[
CREATE TABLE IF NOT EXISTS `rde_bank_npcs` (
`id` VARCHAR(50) PRIMARY KEY,
`coords` TEXT NOT NULL,
`model` VARCHAR(100),
`scenario` VARCHAR(100),
INDEX `idx_id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
]])
MySQL.query.await([[
CREATE TABLE IF NOT EXISTS `rde_bank_investments` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`charid` INT NOT NULL,
`investmentType` VARCHAR(50) NOT NULL,
`amount` DECIMAL(15,2) NOT NULL,
`maturityDate` BIGINT NOT NULL,
`active` TINYINT(1) DEFAULT 1,
INDEX `idx_charid` (`charid`),
INDEX `idx_active` (`active`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
]])
MySQL.query.await([[
CREATE TABLE IF NOT EXISTS `rde_bank_loans` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`charid` INT NOT NULL,
`amount` DECIMAL(15,2) NOT NULL,
`remaining` DECIMAL(15,2) NOT NULL,
`interest` DECIMAL(5,4) NOT NULL,
`dueDate` BIGINT NOT NULL,
`active` TINYINT(1) DEFAULT 1,
INDEX `idx_charid` (`charid`),
INDEX `idx_active` (`active`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
]])
-- Idempotent migrations for v3 → v4 upgrades
for _, col in ipairs({
{ name = 'dailyDeposit', spec = 'DECIMAL(15,2) DEFAULT 0' },
{ name = 'dailyWithdraw', spec = 'DECIMAL(15,2) DEFAULT 0' },
{ name = 'lastLimitReset', spec = 'BIGINT DEFAULT 0' },
{ name = 'lifetimeVolume', spec = 'DECIMAL(18,2) DEFAULT 0' },
{ name = 'tier', spec = "VARCHAR(20) DEFAULT 'bronze'" },
}) do
pcall(function()
MySQL.query.await(('ALTER TABLE rde_bank_accounts ADD COLUMN %s %s'):format(col.name, col.spec))
end)
end
LoadNPCs()
if Config.Interest.enabled then StartInterestSystem() end
ProcessInvestments()
DbgPrint('INIT', 'Server initialized — database ready, GlobalState.bankNPCs published')
end)
-- ─────────────────────────────────────────────────────────────────────────────
-- PLAYER REQUESTS
-- ─────────────────────────────────────────────────────────────────────────────
RegisterNetEvent('rde_banking:server:requestAccount', function()
local src = source
local player = Ox.GetPlayer(src)
if not player or not player.charId then return end
local account = GetOrCreateAccount(player)
if not account then return end
TriggerClientEvent('rde_banking:client:receiveAccount', src, account)
-- Hand out a bank card on first account creation
if Config.BankCard and Config.BankCard.giveOnNewAccount and account._isNew then
local cardItem = Config.BankCard.item
local hasCard = exports.ox_inventory:GetItemCount(src, cardItem) or 0
if hasCard == 0 then
local canCarry = exports.ox_inventory:CanCarryItem(src, cardItem, 1)
if canCarry then
local ok = exports.ox_inventory:AddItem(src, cardItem, 1, {
accountNumber = account.accountNumber,
label = 'Pacific Standard Bank',
tier = account.tier or 'bronze',
})
if ok then
NotifyClient(src, 'Your bank card has been added to your inventory!', 'success')
end
end
end
account._isNew = false -- consumed
end
end)
-- ─────────────────────────────────────────────────────────────────────────────
-- DEPOSIT
-- ─────────────────────────────────────────────────────────────────────────────
RegisterNetEvent('rde_banking:server:deposit', function(amount)
local src = source
local player = Ox.GetPlayer(src)
if not player or not player.charId then return end
amount = tonumber(amount)
if not amount or amount <= 0 then
NotifyClient(src, L('invalid_amount'), 'error'); return
end
local account = GetOrCreateAccount(player)
if not account then return end
local tier = GetTierForVolume(account.lifetimeVolume or 0)
local limit = math.floor(Config.Banking.dailyDepositLimit * tier.limitMultiplier)
local newDaily = account.dailyDeposit + amount
if newDaily > limit then
NotifyClient(src, L('daily_limit_reached'), 'error'); return
end
if (account.balance + amount) > Config.Banking.maxBalance then
NotifyClient(src, 'Maximum balance limit reached', 'error'); return
end
if (exports.ox_inventory:Search(src, 'count', Config.MoneyItem) or 0) < amount then
NotifyClient(src, L('insufficient_funds'), 'error'); return
end
if exports.ox_inventory:RemoveItem(src, Config.MoneyItem, amount) then
account.balance = account.balance + amount
account.dailyDeposit = newDaily
AddLifetimeVolume(account, amount, src)
SaveAccount(account)
CreateTransaction(player.charId, account.accountNumber, 'deposit', amount, 'Cash deposit')
local cash = exports.ox_inventory:Search(src, 'count', Config.MoneyItem) or 0
PushAccountUpdate(src, account, cash)
NotifyClient(src, string.format(L('deposit_success'), lib.math.groupdigits(amount)), 'success')
DbgPrint('DEPOSIT', string.format('%s deposited $%d', PlayerLabel(player), amount))
else
NotifyClient(src, 'Failed to process cash. Try again.', 'error')
end
end)
-- ─────────────────────────────────────────────────────────────────────────────
-- WITHDRAW
-- ─────────────────────────────────────────────────────────────────────────────
RegisterNetEvent('rde_banking:server:withdraw', function(amount)
local src = source
local player = Ox.GetPlayer(src)
if not player or not player.charId then return end
amount = tonumber(amount)
if not amount or amount <= 0 then
NotifyClient(src, L('invalid_amount'), 'error'); return
end
local account = GetOrCreateAccount(player)
if not account then return end
if account.balance < amount then
NotifyClient(src, L('insufficient_funds'), 'error'); return
end
local tier = GetTierForVolume(account.lifetimeVolume or 0)
local limit = math.floor(Config.Banking.dailyWithdrawLimit * tier.limitMultiplier)
local newDaily = account.dailyWithdraw + amount
if newDaily > limit then
NotifyClient(src, L('daily_limit_reached'), 'error'); return
end
if exports.ox_inventory:AddItem(src, Config.MoneyItem, amount) then
account.balance = account.balance - amount
account.dailyWithdraw = newDaily
SaveAccount(account)
CreateTransaction(player.charId, account.accountNumber, 'withdraw', amount, 'Cash withdrawal')
local cash = exports.ox_inventory:Search(src, 'count', Config.MoneyItem) or 0
PushAccountUpdate(src, account, cash)
NotifyClient(src, string.format(L('withdraw_success'), lib.math.groupdigits(amount)), 'success')
DbgPrint('WITHDRAW', string.format('%s withdrew $%d', PlayerLabel(player), amount))
else
NotifyClient(src, 'Inventory is full or unavailable.', 'error')
end
end)
-- ─────────────────────────────────────────────────────────────────────────────
-- TRANSFER — atomic via MySQL.transaction
-- ─────────────────────────────────────────────────────────────────────────────
RegisterNetEvent('rde_banking:server:transfer', function(targetAccountNum, amount)
local src = source
local player = Ox.GetPlayer(src)
if not player or not player.charId then return end
amount = tonumber(amount)
if not amount or amount < Config.Banking.minTransfer or amount > Config.Banking.maxTransfer then
NotifyClient(src, L('invalid_amount'), 'error'); return
end
local account = GetOrCreateAccount(player)
if not account then return end
if targetAccountNum == account.accountNumber then
NotifyClient(src, 'Cannot transfer to your own account', 'error'); return
end
local tier = GetTierForVolume(account.lifetimeVolume or 0)
local feePct = Config.Banking.transferFee * tier.feeMultiplier
local fee = math.floor(amount * feePct)
local total = amount + fee
if account.balance < total then
NotifyClient(src, L('insufficient_funds'), 'error'); return
end
local targetRows = MySQL.query.await(
'SELECT * FROM rde_bank_accounts WHERE accountNumber = ?', { targetAccountNum })
if not targetRows or #targetRows == 0 then
NotifyClient(src, 'Account not found', 'error'); return
end
local targetRow = targetRows[1]
local targetBalance = tonumber(targetRow.balance) + amount
local senderBalance = account.balance - total
local success = MySQL.transaction.await({
{
query = 'UPDATE rde_bank_accounts SET balance = ? WHERE charid = ?',
values = { senderBalance, player.charId },
},
{
query = 'UPDATE rde_bank_accounts SET balance = ? WHERE accountNumber = ?',
values = { targetBalance, targetAccountNum },
},
})
if not success then
NotifyClient(src, 'Transfer failed — please try again.', 'error')
return
end
account.balance = senderBalance
AddLifetimeVolume(account, total, src)
local targetCharId = tonumber(targetRow.charid)
if playerAccounts[targetCharId] then
playerAccounts[targetCharId].balance = targetBalance
end
CreateTransaction(player.charId, account.accountNumber, 'transfer_out', total,
string.format('Wire to %s (fee $%d)', targetAccountNum, fee), targetAccountNum)
CreateTransaction(targetCharId, targetAccountNum, 'transfer_in', amount,
string.format('Wire from %s', account.accountNumber), account.accountNumber)
local cash = exports.ox_inventory:Search(src, 'count', Config.MoneyItem) or 0
PushAccountUpdate(src, account, cash)
NotifyClient(src, string.format(L('transfer_success'),
lib.math.groupdigits(amount), targetAccountNum), 'success')
local targetPlayer = Ox.GetPlayerFromFilter({ charId = targetCharId })
if targetPlayer then
local tAcc = playerAccounts[targetCharId]
if tAcc then PushAccountUpdate(targetPlayer.source, tAcc, nil) end
NotifyClient(targetPlayer.source,
string.format('Received $%s from account #%s',
lib.math.groupdigits(amount), account.accountNumber), 'success')
end
DbgPrint('TRANSFER', string.format('%s → %s: $%d (fee $%d)',
PlayerLabel(player), targetAccountNum, amount, fee))
end)
-- ─────────────────────────────────────────────────────────────────────────────
-- CALLBACKS
-- ─────────────────────────────────────────────────────────────────────────────
lib.callback.register('rde_banking:cb:checkAdmin', function(src) return IsPlayerAdmin(src) end)
lib.callback.register('rde_banking:cb:getTransactions', function(src)
local player = Ox.GetPlayer(src)
if not player or not player.charId then return {} end
local rows = MySQL.query.await(
'SELECT * FROM rde_bank_transactions WHERE charid = ? ORDER BY timestamp DESC LIMIT 50',
{ player.charId })
if rows then
for _, tx in ipairs(rows) do
tx.date = os.date('%d.%m.%Y %H:%M', tx.timestamp)
tx.amount = tonumber(tx.amount)
end
end
return rows or {}
end)
lib.callback.register('rde_banking:cb:getInvestments', function(src)
local player = Ox.GetPlayer(src)
if not player or not player.charId then return {} end
local rows = MySQL.query.await(
'SELECT * FROM rde_bank_investments WHERE charid = ? AND active = 1', { player.charId })
if rows then
for _, inv in ipairs(rows) do
for _, opt in ipairs(Config.Investments.options) do
if opt.id == inv.investmentType then inv.name = opt.label; break end
end
inv.amount = tonumber(inv.amount)
inv.maturityDate = tonumber(inv.maturityDate)
end
end
return rows or {}
end)
lib.callback.register('rde_banking:cb:getLoans', function(src)
local player = Ox.GetPlayer(src)
if not player or not player.charId then return {} end
local rows = MySQL.query.await(
'SELECT * FROM rde_bank_loans WHERE charid = ? AND active = 1', { player.charId })
if rows then
for _, loan in ipairs(rows) do
loan.amount = tonumber(loan.amount)
loan.remaining = tonumber(loan.remaining)
loan.dueDate = tonumber(loan.dueDate)
end
end
return rows or {}
end)
-- ─────────────────────────────────────────────────────────────────────────────
-- INVESTMENTS
-- ─────────────────────────────────────────────────────────────────────────────
RegisterNetEvent('rde_banking:server:createInvestment', function(investmentType, amount)
local src = source
local player = Ox.GetPlayer(src)
if not player or not player.charId then return end
amount = tonumber(amount)
local option
for _, opt in ipairs(Config.Investments.options) do
if opt.id == investmentType then option = opt; break end
end
if not option then NotifyClient(src, 'Invalid investment type', 'error'); return end
if amount < option.minInvestment or amount > option.maxInvestment then
NotifyClient(src, L('invalid_amount'), 'error'); return
end
local account = GetOrCreateAccount(player)
if not account or account.balance < amount then
NotifyClient(src, L('insufficient_funds'), 'error'); return
end
account.balance = account.balance - amount
AddLifetimeVolume(account, amount, src)
SaveAccount(account)
local maturityDate = os.time() + (option.duration * 3600)
MySQL.insert('INSERT INTO rde_bank_investments (charid,investmentType,amount,maturityDate) VALUES (?,?,?,?)',
{ player.charId, investmentType, amount, maturityDate })
CreateTransaction(player.charId, account.accountNumber, 'investment', amount,
'Investment: ' .. option.label)
local cash = exports.ox_inventory:Search(src, 'count', Config.MoneyItem) or 0
PushAccountUpdate(src, account, cash)
NotifyClient(src, L('investment_active'), 'success')
end)
ProcessInvestments = function()
CreateThread(function()
while true do
Wait(60000)
local rows = MySQL.query.await(
'SELECT * FROM rde_bank_investments WHERE active = 1 AND maturityDate <= ?',
{ os.time() })
if rows then
for _, inv in ipairs(rows) do
local option
for _, opt in ipairs(Config.Investments.options) do
if opt.id == inv.investmentType then option = opt; break end
end
if option then
local success = math.random(100) > option.risk
local minRate = math.floor(option.returnRate.min * 100)
local maxRate = math.floor(option.returnRate.max * 100)
local returnRate = success
and (math.random(minRate, maxRate) / 100)
or -(math.random(10, 30) / 100)
local profit = math.floor(tonumber(inv.amount) * returnRate)
local finalAmount = tonumber(inv.amount) + profit
MySQL.update.await(
'UPDATE rde_bank_accounts SET balance = balance + ? WHERE charid = ?',
{ finalAmount, inv.charid })
MySQL.update.await(
'UPDATE rde_bank_investments SET active = 0 WHERE id = ?', { inv.id })
CreateTransaction(inv.charid, '', 'investment_return', math.abs(finalAmount),
string.format('Investment return: %s (%s)',
option.label, success and 'Profit' or 'Loss'))
local charId = tonumber(inv.charid)
if playerAccounts[charId] then
playerAccounts[charId].balance = playerAccounts[charId].balance + finalAmount
end
local targetPlayer = Ox.GetPlayerFromFilter({ charId = charId })
if targetPlayer then
local tAcc = playerAccounts[charId]
if tAcc then PushAccountUpdate(targetPlayer.source, tAcc, nil) end
TriggerClientEvent('rde_banking:client:investmentComplete',
targetPlayer.source, inv, profit)
end
end
end
end
end
end)
end
-- ─────────────────────────────────────────────────────────────────────────────
-- LOANS
-- ─────────────────────────────────────────────────────────────────────────────
RegisterNetEvent('rde_banking:server:applyLoan', function(amount)
local src = source
local player = Ox.GetPlayer(src)
if not player or not player.charId then return end
local account = GetOrCreateAccount(player)
if not account then return end
local activeCount = MySQL.scalar.await(
'SELECT COUNT(*) FROM rde_bank_loans WHERE charid = ? AND active = 1', { player.charId })
if (activeCount or 0) >= Config.Loans.maxLoans then
NotifyClient(src, 'Maximum active loans reached', 'error'); return
end
local option
for _, opt in ipairs(Config.Loans.options) do
if opt.amount == tonumber(amount) and account.creditScore >= opt.requiredCredit then
option = opt; break
end
end
if not option then NotifyClient(src, L('loan_denied'), 'error'); return end
local totalOwed = tonumber(amount) + math.floor(tonumber(amount) * option.interest)
local dueDate = os.time() + (option.duration * 86400)
MySQL.insert('INSERT INTO rde_bank_loans (charid,amount,remaining,interest,dueDate) VALUES (?,?,?,?,?)',
{ player.charId, amount, totalOwed, option.interest, dueDate })
account.balance = account.balance + tonumber(amount)
SaveAccount(account)
CreateTransaction(player.charId, account.accountNumber, 'loan', amount,
string.format('Loan — due %s', os.date('%d.%m.%Y', dueDate)))
local cash = exports.ox_inventory:Search(src, 'count', Config.MoneyItem) or 0
PushAccountUpdate(src, account, cash)
NotifyClient(src, string.format(L('loan_approved'), lib.math.groupdigits(amount)), 'success')
end)
RegisterNetEvent('rde_banking:server:payLoan', function(loanId, amount)
local src = source
local player = Ox.GetPlayer(src)
if not player or not player.charId then return end
amount = tonumber(amount)
if not amount or amount <= 0 then NotifyClient(src, L('invalid_amount'), 'error'); return end
local account = GetOrCreateAccount(player)
if not account or account.balance < amount then
NotifyClient(src, L('insufficient_funds'), 'error'); return
end
local loanRows = MySQL.query.await(
'SELECT * FROM rde_bank_loans WHERE id = ? AND charid = ? AND active = 1',
{ loanId, player.charId })
if not loanRows or #loanRows == 0 then
NotifyClient(src, 'Loan not found', 'error'); return
end
local loan = loanRows[1]
local newRemaining = tonumber(loan.remaining) - amount
account.balance = account.balance - amount
if newRemaining <= 0 then
MySQL.update.await('UPDATE rde_bank_loans SET active=0, remaining=0 WHERE id=?', { loanId })
account.creditScore = account.creditScore + 50
NotifyClient(src, L('loan_paid_off'), 'success')
else
MySQL.update.await('UPDATE rde_bank_loans SET remaining=? WHERE id=?', { newRemaining, loanId })
NotifyClient(src, string.format(L('loan_payment'), lib.math.groupdigits(amount)), 'success')
end
SaveAccount(account)
CreateTransaction(player.charId, account.accountNumber, 'loan_payment', amount, 'Loan payment')
local cash = exports.ox_inventory:Search(src, 'count', Config.MoneyItem) or 0
PushAccountUpdate(src, account, cash)
end)
-- ─────────────────────────────────────────────────────────────────────────────
-- INTEREST SYSTEM (tier-boosted)
-- ─────────────────────────────────────────────────────────────────────────────
StartInterestSystem = function()
CreateThread(function()
while true do
Wait(55000)
local t = os.date('*t')
local h, m = Config.Interest.payoutTime:match('(%d+):(%d+)')
if t.hour == tonumber(h) and t.min == tonumber(m) then
local rows = MySQL.query.await(
'SELECT * FROM rde_bank_accounts WHERE balance >= ?',
{ Config.Interest.minBalance })
if rows then
for _, acc in ipairs(rows) do
if os.time() - tonumber(acc.lastInterest or 0) >= 82800 then
local tier = GetTierForVolume(tonumber(acc.lifetimeVolume) or 0)
local interest = math.min(
math.floor(tonumber(acc.balance) * Config.Interest.rate * tier.interestBonus),
math.floor(Config.Interest.maxInterest * tier.interestBonus))
if interest > 0 then
MySQL.update.await(
'UPDATE rde_bank_accounts SET balance=balance+?, lastInterest=? WHERE charid=?',
{ interest, os.time(), acc.charid })
CreateTransaction(acc.charid, acc.accountNumber, 'interest', interest,
string.format('Daily interest (%.0f%% × %s tier)',
Config.Interest.rate * 100, tier.label))
local charId = tonumber(acc.charid)
if playerAccounts[charId] then
playerAccounts[charId].balance = playerAccounts[charId].balance + interest
playerAccounts[charId].lastInterest = os.time()
end
local target = Ox.GetPlayerFromFilter({ charId = charId })
if target then
local tAcc = playerAccounts[charId]
if tAcc then PushAccountUpdate(target.source, tAcc, nil) end
NotifyClient(target.source,
string.format(L('interest_earned'),
lib.math.groupdigits(interest)), 'success')
end
end
end
end
end
Wait(65000)
end
end
end)
end
-- ─────────────────────────────────────────────────────────────────────────────
-- ADMIN: NPC MANAGEMENT
-- ─────────────────────────────────────────────────────────────────────────────
RegisterNetEvent('rde_banking:server:createNPC', function(data)
local src = source
if not IsPlayerAdmin(src) then return end
local id = 'bank_' .. math.random(100000, 999999)
bankNPCs[id] = {
coords = { x = data.coords.x, y = data.coords.y, z = data.coords.z, w = data.coords.w },
model = data.model or Config.NPCs.model,
scenario = data.scenario or Config.NPCs.scenario,
}
MySQL.insert('INSERT INTO rde_bank_npcs (id,coords,model,scenario) VALUES (?,?,?,?)',
{ id,
json.encode({ x = data.coords.x, y = data.coords.y, z = data.coords.z, w = data.coords.w }),
bankNPCs[id].model, bankNPCs[id].scenario })
-- Publishing to GlobalState fires the AddStateBagChangeHandler on every
-- client automatically — no manual TriggerClientEvent needed.
GlobalState.bankNPCs = bankNPCs
NotifyClient(src, L('npc_created'), 'success')
local player = Ox.GetPlayer(src)
DbgPrint('ADMIN NPC', PlayerLabel(player) .. ' created NPC: ' .. id)
end)
RegisterNetEvent('rde_banking:server:deleteNPC', function(id)
local src = source
if not IsPlayerAdmin(src) then return end
if bankNPCs[id] then
bankNPCs[id] = nil
MySQL.query('DELETE FROM rde_bank_npcs WHERE id = ?', { id })
GlobalState.bankNPCs = bankNPCs
NotifyClient(src, L('npc_deleted'), 'success')
end
end)
-- ─────────────────────────────────────────────────────────────────────────────
-- ADMIN: ACCOUNT MANAGEMENT
-- ─────────────────────────────────────────────────────────────────────────────
lib.callback.register('rde_banking:cb:getAllTransactions', function(src)
if not IsPlayerAdmin(src) then return {} end
local rows = MySQL.query.await([[
SELECT t.*, c.firstname, c.lastname
FROM rde_bank_transactions t
LEFT JOIN characters c ON t.charid = c.charid
ORDER BY t.timestamp DESC LIMIT 200
]])
if rows then
for _, tx in ipairs(rows) do
tx.playerName = ((tx.firstname or '') .. ' ' .. (tx.lastname or '')):gsub('^%s+', '')
tx.date = os.date('%d.%m.%Y %H:%M', tx.timestamp)
tx.amount = tonumber(tx.amount)
end
end
return rows or {}
end)
lib.callback.register('rde_banking:cb:getAllAccounts', function(src)
if not IsPlayerAdmin(src) then return {} end
local rows = MySQL.query.await([[
SELECT a.*, c.firstname, c.lastname
FROM rde_bank_accounts a
LEFT JOIN characters c ON a.charid = c.charid
ORDER BY a.balance DESC
]])
if rows then
for _, acc in ipairs(rows) do
acc.playerName = ((acc.firstname or '') .. ' ' .. (acc.lastname or '')):gsub('^%s+', '')
acc.balance = tonumber(acc.balance)
acc.creditScore = tonumber(acc.creditScore)
acc.lifetimeVolume = tonumber(acc.lifetimeVolume) or 0
end
end
return rows or {}
end)
RegisterNetEvent('rde_banking:server:adminAddMoney', function(charid, amount)
local src = source
if not IsPlayerAdmin(src) then return end
amount = tonumber(amount)
if not amount or amount <= 0 then return end
MySQL.update.await('UPDATE rde_bank_accounts SET balance = balance + ? WHERE charid = ?', { amount, charid })
local accRow = MySQL.query.await('SELECT accountNumber FROM rde_bank_accounts WHERE charid = ?', { charid })
if accRow and #accRow > 0 then
local admin = Ox.GetPlayer(src)
CreateTransaction(charid, accRow[1].accountNumber, 'admin_add', amount,
'Admin deposit by ' .. PlayerLabel(admin))
end
if playerAccounts[charid] then
playerAccounts[charid].balance = playerAccounts[charid].balance + amount
end
local target = Ox.GetPlayerFromFilter({ charId = tonumber(charid) })
if target then
PushAccountUpdate(target.source, playerAccounts[charid], nil)
NotifyClient(target.source,
string.format('Admin added $%s to your account', lib.math.groupdigits(amount)), 'success')
end
NotifyClient(src, string.format('Added $%s to account', lib.math.groupdigits(amount)), 'success')
end)
RegisterNetEvent('rde_banking:server:adminRemoveMoney', function(charid, amount)
local src = source
if not IsPlayerAdmin(src) then return end
amount = tonumber(amount)
if not amount or amount <= 0 then return end