Building a FiveM Drug System the Hard Way
Every developer who runs a criminal RP server ends up writing a drug script at some point. The first version usually takes a weekend and works fine in testing. The second version gets written a month later, after someone in a mod menu fires the gather event in a loop and floods the economy with a few thousand bags.
I’ve written drug selling three times now, and the code that gave me the most trouble was never the progress bars or the peds. It was deciding what the server should believe. This post is the manual build on ox_lib, ox_target and ox_inventory, written the way I’d write it today, with the checks in the places where people actually exploit it. If you’d rather compare all the routes first, including free scripts, how to make custom drugs in FiveM covers the faster options, and there’s an easy button at the end.
What You’re Actually Building
A drug system that holds up on a live server has four parts, and each one has a client half and a server half:
- Items. The raw input, the product and the dirty money the sale pays out in.
- Production. Gather spots and process stations where a player spends time and gets items back.
- Selling. Sale zones on the map, a buyer, an offer and a payout.
- Police. A minimum number of officers on duty before anyone can sell, plus an alert now and then.
Keep one rule in your head for the whole build: the client asks, the server decides. Anything the client sends (coordinates, a ped, a price, “I finished”) is a claim. The server checks it against things it knows by itself. If you haven’t worked with net events much, FiveM events explained covers why any client can fire any registered event, which is the whole reason this post exists.
What You’ll Need
- OneSync on. The server checks player and ped positions itself with
GetPlayerPedandGetEntityCoords, and that needs OneSync. - ox_lib, for zones, callbacks, progress bars and skill checks. If you want to know how it loads, how ox_lib works under the hood goes through it.
- ox_target, for the “Pick leaves” and “Offer” options.
- ox_inventory, for the item exports. QBCore and ESX inventories work too, with their own functions in place of the exports below.
- A test server and a second account, because half the bugs only show up when two players do the same thing.
Your resource manifest needs ox_lib loaded on both sides:
fx_version 'cerulean'
game 'gta5'
lua54 'yes'
shared_scripts { '@ox_lib/init.lua', 'shared/config.lua' }
client_scripts { 'client/*.lua' }
server_scripts { 'server/*.lua' }
Step 1: Define the Items
On ox_inventory, items live in ox_inventory/data/items.lua. One raw item and one product is enough to build the whole chain:
['bluesky_leaf'] = {
label = 'Blue Sky Leaf',
weight = 50,
},
['bluesky'] = {
label = 'Blue Sky',
weight = 20,
},
ox_inventory already ships black_money and money as items, so the sale can pay out in black_money without anything extra. On QBCore and ESX without ox_inventory, the items go into the framework’s own item list instead, and how to add items in FiveM walks through each one. Restart the inventory after adding items. It reads the file when it starts.
Step 2: Put the Places in a Shared Config
This is the step most tutorials skip, and it’s the one that makes every later check possible. Put every coordinate in a file both sides load, so the server knows where the spots and zones are without asking the client:
-- shared/config.lua
Config = {}
Config.Gather = {
coords = vec3(2221.3, 5577.1, 53.8),
radius = 3.0,
time = 10000, -- ms the progress bar runs
reward = { 'bluesky_leaf', 2 },
}
Config.Process = {
coords = vec3(1391.9, 3605.6, 38.9),
radius = 3.0,
time = 15000,
input = { 'bluesky_leaf', 3 },
output = { 'bluesky', 1 },
}
Config.SaleZone = {
points = {
vec3(-60.0, -1760.0, 29.0),
vec3(10.0, -1730.0, 29.0),
vec3(40.0, -1800.0, 29.0),
vec3(-30.0, -1830.0, 29.0),
},
thickness = 10.0,
}
Config.Price = { min = 80, max = 140 }
Config.MinPolice = 2
Those coordinates are placeholders. To get real ones, stand on each corner in game, print GetEntityCoords(PlayerPedId()) to the F8 console and paste the numbers in. For a zone with eight corners that’s eight trips, and you’ll redo a few when the shape comes out wrong.
Step 3: Gather and Process With a Server-Side Timer
The client side is an ox_target sphere zone with an onSelect that runs the progress bar:
-- client/production.lua
exports.ox_target:addSphereZone({
coords = Config.Gather.coords,
radius = 1.5,
options = {{
name = 'bluesky_gather',
label = 'Pick leaves',
icon = 'fa-solid fa-leaf',
onSelect = function()
if not lib.callback.await('bluesky:start', false, 'gather') then return end
if lib.progressBar({ duration = Config.Gather.time, label = 'Picking...', canCancel = true }) then
lib.callback.await('bluesky:finish', false, 'gather')
end
end,
}},
})
Notice there are two calls to the server, not one. The usual version has a single TriggerServerEvent('bluesky:gather') at the end of the progress bar, and that’s the exploit: a cheater skips the bar and fires the event as fast as they like. Even with a distance check, they stand at the spot and spam it.
The fix is that the server starts the clock. bluesky:start records when the player began, and bluesky:finish only pays out if enough time has really passed:
-- server/production.lua
local active = {}
local function near(src, coords, radius)
local ped = GetPlayerPed(src)
return ped ~= 0 and #(GetEntityCoords(ped) - coords) <= radius
end
lib.callback.register('bluesky:start', function(src, kind)
local spot = kind == 'gather' and Config.Gather or kind == 'process' and Config.Process
if not spot or not near(src, spot.coords, spot.radius) then return false end
if spot.input and exports.ox_inventory:GetItemCount(src, spot.input[1]) < spot.input[2] then
return false
end
active[src] = { kind = kind, started = GetGameTimer() }
return true
end)
lib.callback.register('bluesky:finish', function(src, kind)
local job = active[src]
active[src] = nil
if not job or job.kind ~= kind then return false end
local spot = kind == 'gather' and Config.Gather or Config.Process
if GetGameTimer() - job.started < spot.time - 500 then return false end
if not near(src, spot.coords, spot.radius) then return false end
if kind == 'gather' then
local item, count = spot.reward[1], spot.reward[2]
if not exports.ox_inventory:CanCarryItem(src, item, count) then return false end
return exports.ox_inventory:AddItem(src, item, count)
end
if exports.ox_inventory:RemoveItem(src, spot.input[1], spot.input[2]) then
return exports.ox_inventory:AddItem(src, spot.output[1], spot.output[2])
end
return false
end)
AddEventHandler('playerDropped', function()
active[source] = nil
end)
A few details in there are doing real work:
GetGameTimer()on the server, not a time the client sends. The half-second of slack covers network delay.- The distance check runs twice, at the start and at the finish, so walking off with the bar running gets nothing.
active[src] = nilhappens before anything else infinish, so the same start can’t be cashed in twice.RemoveItemcomes first and its result is checked. ox_inventory’sRemoveItemreturns whether it worked, so if two requests race, only one of them gets the product.
For a cook that can fail, put lib.skillCheck({'easy', 'medium'}) before the progress bar on the client. Just remember the skill check is client-side, so a cheater can always pass it. Treat it as gameplay, and never let a “perfect” result raise the payout without the server having its own reason to believe it.
Step 4: Draw the Sale Zone on Both Sides
ox_lib zones are shared code, so the same lib.zones.poly call works on the client and the server. On the client, it drives the UI:
-- client/selling.lua
local inZone = false
lib.zones.poly({
points = Config.SaleZone.points,
thickness = Config.SaleZone.thickness,
onEnter = function() inZone = true end,
onExit = function() inZone = false end,
})
On the server, the same zone answers one question: is this player really standing in it?
-- server/selling.lua
local saleZone = lib.zones.poly({
points = Config.SaleZone.points,
thickness = Config.SaleZone.thickness,
})
saleZone:contains(coords) is the check that matters. The client’s inZone only decides whether the “Offer” option shows up. It never decides whether a sale is allowed. Set debug = true on the client zone while you’re drawing it, so you can see the walls in game, and turn it off before you ship.
Step 5: Sell to a Ped Without Trusting the Client
On the client, ox_target’s addGlobalPed puts an option on every ped, and canInteract hides it outside the zone:
exports.ox_target:addGlobalPed({{
name = 'bluesky_sell',
label = 'Offer Blue Sky',
icon = 'fa-solid fa-hand-holding-dollar',
distance = 2.0,
canInteract = function(entity)
return inZone and not IsPedAPlayer(entity) and not IsPedDeadOrDying(entity, true)
and exports.ox_inventory:GetItemCount('bluesky') > 0
end,
onSelect = function(data)
if not NetworkGetEntityIsNetworked(data.entity) then return end
local netId = NetworkGetNetworkIdFromEntity(data.entity)
local paid = lib.callback.await('bluesky:sell', 1000, netId)
if paid then
lib.notify({ description = ('Sold for $%d'):format(paid), type = 'success' })
else
lib.notify({ description = 'Not interested.', type = 'error' })
end
end,
}})
The client sends exactly one thing: the network ID of the ped. Not a price, not a count, not its own position. The 1000 is ox_lib’s client-side delay between calls, which slows down button mashing. It doesn’t stop a cheater, so the server keeps its own cooldown too.
The server side is where the work is:
local pedCooldown, playerCooldown = {}, {}
lib.callback.register('bluesky:sell', function(src, netId)
local now = os.time()
if (playerCooldown[src] or 0) > now then return false end
playerCooldown[src] = now + 5
if type(netId) ~= 'number' then return false end
local ped = NetworkGetEntityFromNetworkId(netId)
if ped == 0 or not DoesEntityExist(ped) or GetEntityType(ped) ~= 1 or IsPedAPlayer(ped) then
return false
end
if (pedCooldown[netId] or 0) > now then return false end
local playerCoords = GetEntityCoords(GetPlayerPed(src))
if #(playerCoords - GetEntityCoords(ped)) > 3.0 then return false end
if not saleZone:contains(playerCoords) then return false end
if CountPolice() < Config.MinPolice then return false end
if not exports.ox_inventory:RemoveItem(src, 'bluesky', 1) then return false end
pedCooldown[netId] = now + 600
local price = math.random(Config.Price.min, Config.Price.max)
exports.ox_inventory:AddItem(src, 'black_money', price)
return price
end)
Walk through what a cheater can fake here, and you’ll find there isn’t much left. They can send any net ID they like, but the server checks that it’s a real ped, not a player, and within three metres of them. They can’t pick the price, because the server rolls it. They can’t sell to the same ped twice in ten minutes, or spam offers, because both cooldowns live on the server. And the zone check uses the position the server sees, not the client’s inZone.
GetEntityType returns 1 for peds, and IsPedAPlayer, DoesEntityExist and NetworkGetEntityFromNetworkId are all server-side natives under OneSync. Under OneSync most ambient peds are networked, which is why the client checks NetworkGetEntityIsNetworked first and skips any ped that isn’t.
Step 6: Count the Police
CountPolice() is the one function that changes with your framework. All three have a way to count officers on the server:
function CountPolice()
-- QBCore: counts players with the job who are on duty
-- return QBCore.Functions.GetDutyCount('police')
-- Qbox: by job type, so sheriff and state police count too
-- return exports.qbx_core:GetDutyCountType('leo')
-- ESX: everyone with the job
-- return #ESX.GetExtendedPlayers('job', 'police')
end
Uncomment the line for your framework. On QBCore, GetDutyCount only counts officers who are on duty. On Qbox, GetDutyCountType returns the count first and a list of players second, and the # length trick isn’t needed. On ESX, GetExtendedPlayers('job', 'police') returns everyone who has the job, on duty or not, so add your own duty check if your server tracks it. If selling still refuses with officers on duty, FiveM drug selling not working covers why a police count gets stuck at zero.
For the alert, send it from the server after a successful sale with whatever dispatch script you run, using the player’s server-side coordinates. Add some randomness to the position you send, so officers have to search instead of driving to the exact spot.
Step 7: Test It Like a Cheater
Run the happy path first, then try to break it. These are the tests I run on any economy script before it goes live:
- Fire the finish without the start. From a test command, call
bluesky:finishdirectly. You should get nothing. - Fire the start, then the finish straight away. Nothing, because the timer hasn’t run.
- Start at the spot, walk away, finish. Nothing.
- Sell from just outside the zone line. The option shouldn’t show, and if you force the callback, the server should refuse.
- Sell to the same ped twice. The second offer gets refused.
- Two players sell their last bag at the same moment. Each gets paid once.
- Drop out mid-progress and rejoin. No leftover state lets you finish the old job.
Then measure it. Zones and canInteract functions run often, so open resmon before and after you start the resource. The FiveM resmon guide covers how to read the numbers.
Where the Hard Way Gets Expensive
Everything above is one drug, one gather spot, one station and one zone. A real server wants five or ten drugs, each with its own chain, prices that move, labs, stashes and logs. Every one of those is more config, more callbacks and more cheater tests. And every coordinate change is still: edit the config, restart the resource, fly to the spot, check.
The manual route is the right call when you want behaviour nobody else has, you’re comfortable in Lua and you’ll maintain it. If you’re still learning, building this once is the best lesson in FiveM security you’ll get. Our free scripts are open source too, if you want more code to read alongside it.
Or: The Easy Button
Full disclosure: this is our script. I wrote this post because I think every server developer should understand these checks. But if you understand them and just need drugs on the server, you shouldn’t have to write them again for every drug.
The LMX Drug Creator is $39.99 one-time, for ESX, QBCore and Qbox. According to its docs, every price, count, distance and roll is worked out on the server, and a player’s game only asks, which is the pattern from Steps 3 to 5. It also limits requests per player (Config.RateLimits), and an optional Discord log reports things a normal game never does, like finishing a stage before its time.
The rest of the build happens in game through /drugcreator. You walk to a spot and press E to place a field, station, lab or buyer, and you draw a sale zone by walking its corners and pressing E at each one. Production chains, minigames, quality, heat per zone, a police count per drug or per stage, and alerts through ps-dispatch, cd_dispatch, core_dispatch, rcore_dispatch, qs-dispatch or a built-in alert are already there. A new drug and its places go live without a server restart.
Where it falls short, honestly: it needs OneSync, oxmysql and ox_lib, and the folder must stay named lmx_drugcreator. On ox_inventory there’s one paste step at your first publish, and each publish restarts ox_inventory for a few seconds. It runs on FiveM for GTA V Legacy only for now, because Enhanced can’t load escrowed scripts yet. And the core Lua is escrowed, so you can’t rewrite the logic the way you can with your own build. The config, bridges and locales stay open.
Built your own and stuck on a check, or weighing the two? Ask in our Discord.