All resources
Requires rsg-core rsg-inventory rsg-target oxmysql
★ 0Updated 2026-12-010 open issues

rsg-contracts3.0.0 - Technical Documentation#

Summary#

rsg-contracts lets two players sign written contracts: supply orders (deliver items) and paid jobs (the buyer approves the work). The server holds the buyer's payment and the worker's optional deposit until the contract closes. Payouts, refunds and delivered goods become claims that are collected at a post office, so nobody has to be online to be paid. For player-facing instructions see README.md.

Version3.0.0
Dependenciesrsg-core, rsg-inventory, rsg-target, oxmysql
Optionalrsg-reputation (honor), rsg-log (logging)
Database tablesrsg_contracts, rsg_contract_claims
ExportsNone
Commands/contracts (configurable)
InterfaceNUI window, rsg-target zones at offices

1. Installation#

  1. Place rsg-contracts in [framework].
  2. Check that contract_paper is in rsg-core/shared/items.lua:
contract_paper = { name = 'contract_paper', label = 'Contract Paper', weight = 10, type = 'item', image = 'contract_paper.png', unique = true, useable = true, shouldClose = true, description = 'A signed contract', category = 'document' },
  1. Optionally add contract_paper.png to rsg-inventory/html/images/.
  2. Start it after its dependencies:
ensure rsg-contracts
  1. Tables are created on first start. For a manual install set Config.AutoDatabase = false and import install.sql.

2. Architecture#

FileSidePurpose
fxmanifest.lua-Manifest
shared/config.luasharedAll settings
server/database.luaserverEnsureDatabase(), same schema as install.sql
server/server.luaserverRules, money, items, callbacks, expiry loop
server/versionchecker.luaserverConsole version check
client/client.luaclientWindow, command, office targets, NUI bridge
html/NUIContract window
locales/*.jsonsharedPlayer-facing text
install.sql-Manual schema

The client only displays data and forwards requests. Every rule is enforced in server/server.lua.

3. How it works#

Statuses#

supply:  offered -> active -> closed
job:     offered -> active -> review -> closed
                                   \-> disputed -> closed

Any unsigned offer can also go straight to closed. The buyer can approve a job while it is still active.

Actions#

ActionWhoRequired statusResult
createbuyer-Takes the payment and creates an offer. Players must be within SignDistance
signworkerofferedTakes the deposit, sets active, gives paper copies. Players must be within SignDistance
declineeither sideofferedRefund
deliverworkeractive, supplyAt an office, all goods at once
finishworkeractive, jobSets review
approvebuyeractive or review, jobPays the worker
disputebuyerreviewSets disputed and notifies on-duty arbiters
giveupworkeractiveBuyer gets payment and deposit
canceleither sideactiveBoth sides must ask. Each gets their own money back
rulearbiterdisputedWinner is worker or buyer
collectanyone with claims-At an office, pays out waiting claims

Outcomes#

OutcomeBuyer receivesWorker receivesHonor (worker)
offer_expired, offer_declined, offer_withdrawnpayment--
deliveredgoodspayment + depositHonorCompleted
approved, review_expired, ruled_worker-payment + depositHonorCompleted
deadline_missed, gave_up, ruled_buyerpayment + deposit-HonorBroken
mutual_cancelpaymentdeposit-
dispute_expired, DisputeDefault = 'split'half the paymenthalf the payment + deposit-
dispute_expired, 'worker'-payment + depositHonorCompleted
dispute_expired, 'buyer'paymentdeposit-

With split, an odd cent goes to the buyer. Honor needs rsg-reputation started, the worker online, and a payment of at least HonorMinPay.

Timers#

  • Offers last OfferHours, reviews ReviewHours, disputes DisputeHours, signed work the contract's own hours.
  • Deadlines are Unix times in due_at, so server downtime counts.
  • Expired contracts are processed every 30 seconds.

Delivery#

Matching inventory stacks are used in slot order. Stacks with info.quality <= 0 are skipped. Item metadata is kept on the buyer's claim. If any removal or the database write fails, the items already taken are returned to the worker.

Concurrency#

All actions and expiries run through one lock (Locked), so only one change happens at a time.

4. Configuration#

All options are in shared/config.lua.

OptionDefaultDescription
Config.VersionChecktrueCheck for updates on start
Config.AutoDatabasetrueCreate tables on start
Config.Command'contracts'Command name; false leaves only the office targets
Config.Offices8 post offices{ id, label, coords } used for delivery and collection
Config.TargetRadius1.5Target sphere radius (m)
Config.OfficeDistance4.0Server distance check for offices (m)
Config.SignDistance5.0Maximum distance between players to offer and sign (m)
Config.MinPay / MaxPay1 / 5000Payment range (dollars)
Config.MaxDeposit1000Highest deposit; 0 disables deposits
Config.MinHours / MaxHours1 / 168Deadline range, whole real hours
Config.MaxQuantity500Largest supply order
Config.MaxOpen5Open contracts one player can have as buyer
Config.MaxTitle / MaxDetails60 / 500Text limits in characters. Keep MaxTitle at 255 or less
Config.OfferHours1Unsigned offer lifetime
Config.ReviewHours48Worker is paid if the buyer does nothing
Config.DisputeHours72Time to decide a dispute
Config.DisputeDefault'split''split', 'worker' or 'buyer'
Config.ArbiterJobTypes{ leo = true }Job types that decide disputes (on duty)
Config.ArbiterJobs{}Job names that decide disputes, e.g. { judge = true }
Config.BlacklistItemscash items, contract_paperItems that cannot be ordered
Config.BlacklistTypes{ weapon = true }Item types that cannot be ordered
Config.PaperItem'contract_paper'false disables paper copies
Config.HonorCompleted0Honor change on success (0 = off)
Config.HonorBroken-2Honor change on failure
Config.HonorMinPay25Smallest payment that affects honor
Config.AllowPushToTalkWhileOpentrueKeep push-to-talk working in the window
Config.PushToTalkControls{ 0x4BC9DABB }Controls left enabled while the window is open

5. Items and commands#

ItemUsableMetadataNotes
contract_paperYescontractId, descriptionGiven to both players at signing if they have room. Using it shows the contract
Command / targetPermissionAction
/contractsEveryoneOpens the window on the My contracts tab
Contract office targetEveryoneOpens the window on the Collect tab

There are no key bindings. The window closes if the player dies, opens the pause menu or unloads their character.

6. Exports#

None. Use the server event in section 7 to react to closed contracts.

7. Events and callbacks#

Callbacks use the rsg-core callback system.

Server callbacks#

CallbackArgumentsReturnsCooldown per player
rsg-contracts:server:getState-state table, or nil if not ready or throttled250 ms
rsg-contracts:server:getItems-{ { value, label }, ... } or nil2000 ms
rsg-contracts:server:getPaperidcontract view, or nil. The caller must hold that paper500 ms
rsg-contracts:server:actionname, data{ ok = boolean, state = table|nil }750 ms

action data:

namedata
create{ target, type = 'supply'|'job', title, details, pay, deposit, hours, item, quantity } (target is a server ID; item and quantity are for supply; details is required for jobs)
rule{ id, winner = 'worker'|'buyer' }
collect{}
all others{ id }

The server sends the result notification itself.

State table:

{
    contracts = { view, ... },  -- contracts where you are buyer or worker, newest first
    disputes  = { view, ... },  -- other players' disputes, arbiters only
    arbiter   = false,
    claims    = { { contract = 1, cash = 25.0, item = nil, amount = 0 }, ... },
    atOffice  = true,
    nearby    = { 4, 12 },      -- server IDs within SignDistance (no names)
}

Contract view: id, type, status, title, details, buyer, worker, role (buyer/worker/other), item (label), quantity, pay, deposit (dollars), hours, secondsLeft, cancel (mine/theirs/nil). getPaper also returns outcome.

Events#

EventTypeArgumentsPurpose
rsg-contracts:client:paperclient net eventidCloses the inventory and shows a paper copy
rsg-contracts:server:closedserver local eventcontract, outcomeFired after a contract closes and is saved

NUI callbacks#

close, refresh, items, action ({ name, data }).

8. Data and database#

Open contracts are loaded into memory at start. Until that succeeds, state, paper and action requests are ignored. Closing writes the status and every claim in one transaction. A claim row is deleted before it is paid and inserted again if payment fails.

rsg_contracts#

ColumnTypeNotes
idINT, primary keyContract number
typeVARCHAR(10)supply or job
statusVARCHAR(12)offered, active, review, disputed, closed (indexed)
buyer_cid, worker_cidVARCHAR(50)Citizen IDs
buyer_name, worker_nameVARCHAR(100)Character names
titleVARCHAR(255)
detailsTEXT
itemVARCHAR(80)Empty for jobs
quantityINT
pay_cents, deposit_centsINTMoney in cents
hoursINT
due_atBIGINTUnix time of the current stage's deadline
cancel_byVARCHAR(50)Citizen ID asking to cancel
outcomeVARCHAR(30)Set on close
created_atTIMESTAMP

Closed contracts stay as history.

rsg_contract_claims#

id, citizenid (indexed), contract_id, cents, item, amount, info (JSON). Cash claims have an empty item.

9. Security#

  • The server checks role, status, distance, limits, items and cash on every action. Dead, downed (inlaststand) or cuffed players cannot act.
  • Office actions also require routing bucket 0. Offers and signing require both players in the same bucket.
  • Prices and quantities are validated server-side; NaN and out-of-range numbers are rejected.
  • Arbiters must be on duty and cannot rule on their own contract.
  • Player text is length limited, has control characters removed and is shown as plain text. SQL is parameterised.
  • Player data is saved after the player's money or items move in create, sign, deliver and collect.

10. Integration examples#

React to a closed contract (server)#

AddEventHandler('rsg-contracts:server:closed', function(contract, outcome)
    -- contract.status is still the value from before closing; use `outcome` for the result
    local pay = contract.pay_cents / 100
    local deposit = contract.deposit_cents / 100
    print(('Contract #%d (%s) closed: %s, pay $%.2f, deposit $%.2f'):format(
        contract.id, contract.type, outcome, pay, deposit))

    if outcome == 'delivered' then
        -- contract.item and contract.quantity describe the delivered goods
        print(contract.worker_cid, contract.item, contract.quantity)
    end
end)

Read your own contracts (client)#

local RSGCore = exports['rsg-core']:GetCoreObject()

CreateThread(function()
    local state = RSGCore.Functions.AwaitCallback('rsg-contracts:server:getState', 5000)
    if not state then return end
    for _, c in ipairs(state.contracts) do
        print(c.id, c.title, c.status, c.role, c.secondsLeft)
    end
end)

Count open contracts (server, read only)#

local count = MySQL.scalar.await(
    "SELECT COUNT(*) FROM rsg_contracts WHERE worker_cid = ? AND status <> 'closed'",
    { citizenid })

Do not write to these tables while the resource is running: open contracts are held in memory.

11. Localisation#

11 languages with JSON files in locales/: en, de, el, es, fr, ja, nl, pl, pt-br, ro, ru.

setr rsg:locale de

12. Server owner how-tos#

  • Add an office: add { id = 'unique_id', label = 'Name', coords = vector3(x, y, z) } to Config.Offices.
  • Let a judge decide disputes: Config.ArbiterJobs = { judge = true }. Set Config.ArbiterJobTypes = {} to exclude lawmen.
  • Block an item: Config.BlacklistItems.your_item = true.
  • Office targets only: Config.Command = false. Players then cannot send or sign offers away from an office.

13. Troubleshooting#

ProblemCause / fix
Window does not openCheck the console for database errors; requests are ignored until tables load
No one to selectPlayers must be within SignDistance before the New contract tab is opened
Deliver or Collect greyed outStand within OfficeDistance of an office, then reopen the window
Not enough goodsFully decayed items do not count
No paper copyCheck contract_paper is in the shared items and there is inventory room
No dispute tabYour job type or name is in the arbiter settings and you are on duty
Part of a collection stays behindNo inventory room, or the payout failed. Make room and collect again

14. Known limitations#

  • A server crash between a database write and a player save can lose or repeat a transfer. A crash between deleting a claim and paying it loses that claim.
  • If no arbiter is available, a buyer can dispute honest work and recover part of the payment through DisputeDefault = 'split'. Use 'worker' if this is a problem.
  • Players can use contracts to move money or goods to each other. Closed contracts are logged to the rsg-log default channel.
  • With honor rewards enabled, two players could farm them. HonorMinPay only makes this harder.
  • Item decay stored in metadata may continue while goods wait to be collected; check this against your inventory settings.

Support: https://rexshack.tebex.store

Try GetPlayer, /bandana or weather. ↑↓ to move, Enter to open, Esc to close.