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.
| Version | 3.0.0 |
| Dependencies | rsg-core, rsg-inventory, rsg-target, oxmysql |
| Optional | rsg-reputation (honor), rsg-log (logging) |
| Database tables | rsg_contracts, rsg_contract_claims |
| Exports | None |
| Commands | /contracts (configurable) |
| Interface | NUI window, rsg-target zones at offices |
Contents#
1. Installation#
- Place
rsg-contractsin[framework]. - Check that
contract_paperis inrsg-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' },
- Optionally add
contract_paper.pngtorsg-inventory/html/images/. - Start it after its dependencies:
ensure rsg-contracts
- Tables are created on first start. For a manual install set
Config.AutoDatabase = falseand importinstall.sql.
2. Architecture#
| File | Side | Purpose |
|---|---|---|
fxmanifest.lua | - | Manifest |
shared/config.lua | shared | All settings |
server/database.lua | server | EnsureDatabase(), same schema as install.sql |
server/server.lua | server | Rules, money, items, callbacks, expiry loop |
server/versionchecker.lua | server | Console version check |
client/client.lua | client | Window, command, office targets, NUI bridge |
html/ | NUI | Contract window |
locales/*.json | shared | Player-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#
| Action | Who | Required status | Result |
|---|---|---|---|
create | buyer | - | Takes the payment and creates an offer. Players must be within SignDistance |
sign | worker | offered | Takes the deposit, sets active, gives paper copies. Players must be within SignDistance |
decline | either side | offered | Refund |
deliver | worker | active, supply | At an office, all goods at once |
finish | worker | active, job | Sets review |
approve | buyer | active or review, job | Pays the worker |
dispute | buyer | review | Sets disputed and notifies on-duty arbiters |
giveup | worker | active | Buyer gets payment and deposit |
cancel | either side | active | Both sides must ask. Each gets their own money back |
rule | arbiter | disputed | Winner is worker or buyer |
collect | anyone with claims | - | At an office, pays out waiting claims |
Outcomes#
| Outcome | Buyer receives | Worker receives | Honor (worker) |
|---|---|---|---|
offer_expired, offer_declined, offer_withdrawn | payment | - | - |
delivered | goods | payment + deposit | HonorCompleted |
approved, review_expired, ruled_worker | - | payment + deposit | HonorCompleted |
deadline_missed, gave_up, ruled_buyer | payment + deposit | - | HonorBroken |
mutual_cancel | payment | deposit | - |
dispute_expired, DisputeDefault = 'split' | half the payment | half the payment + deposit | - |
dispute_expired, 'worker' | - | payment + deposit | HonorCompleted |
dispute_expired, 'buyer' | payment | deposit | - |
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, reviewsReviewHours, disputesDisputeHours, signed work the contract's ownhours. - 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.
| Option | Default | Description |
|---|---|---|
Config.VersionCheck | true | Check for updates on start |
Config.AutoDatabase | true | Create tables on start |
Config.Command | 'contracts' | Command name; false leaves only the office targets |
Config.Offices | 8 post offices | { id, label, coords } used for delivery and collection |
Config.TargetRadius | 1.5 | Target sphere radius (m) |
Config.OfficeDistance | 4.0 | Server distance check for offices (m) |
Config.SignDistance | 5.0 | Maximum distance between players to offer and sign (m) |
Config.MinPay / MaxPay | 1 / 5000 | Payment range (dollars) |
Config.MaxDeposit | 1000 | Highest deposit; 0 disables deposits |
Config.MinHours / MaxHours | 1 / 168 | Deadline range, whole real hours |
Config.MaxQuantity | 500 | Largest supply order |
Config.MaxOpen | 5 | Open contracts one player can have as buyer |
Config.MaxTitle / MaxDetails | 60 / 500 | Text limits in characters. Keep MaxTitle at 255 or less |
Config.OfferHours | 1 | Unsigned offer lifetime |
Config.ReviewHours | 48 | Worker is paid if the buyer does nothing |
Config.DisputeHours | 72 | Time 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.BlacklistItems | cash items, contract_paper | Items that cannot be ordered |
Config.BlacklistTypes | { weapon = true } | Item types that cannot be ordered |
Config.PaperItem | 'contract_paper' | false disables paper copies |
Config.HonorCompleted | 0 | Honor change on success (0 = off) |
Config.HonorBroken | -2 | Honor change on failure |
Config.HonorMinPay | 25 | Smallest payment that affects honor |
Config.AllowPushToTalkWhileOpen | true | Keep push-to-talk working in the window |
Config.PushToTalkControls | { 0x4BC9DABB } | Controls left enabled while the window is open |
5. Items and commands#
| Item | Usable | Metadata | Notes |
|---|---|---|---|
contract_paper | Yes | contractId, description | Given to both players at signing if they have room. Using it shows the contract |
| Command / target | Permission | Action |
|---|---|---|
/contracts | Everyone | Opens the window on the My contracts tab |
| Contract office target | Everyone | Opens 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#
| Callback | Arguments | Returns | Cooldown per player |
|---|---|---|---|
rsg-contracts:server:getState | - | state table, or nil if not ready or throttled | 250 ms |
rsg-contracts:server:getItems | - | { { value, label }, ... } or nil | 2000 ms |
rsg-contracts:server:getPaper | id | contract view, or nil. The caller must hold that paper | 500 ms |
rsg-contracts:server:action | name, data | { ok = boolean, state = table|nil } | 750 ms |
action data:
name | data |
|---|---|
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#
| Event | Type | Arguments | Purpose |
|---|---|---|---|
rsg-contracts:client:paper | client net event | id | Closes the inventory and shows a paper copy |
rsg-contracts:server:closed | server local event | contract, outcome | Fired 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#
| Column | Type | Notes |
|---|---|---|
id | INT, primary key | Contract number |
type | VARCHAR(10) | supply or job |
status | VARCHAR(12) | offered, active, review, disputed, closed (indexed) |
buyer_cid, worker_cid | VARCHAR(50) | Citizen IDs |
buyer_name, worker_name | VARCHAR(100) | Character names |
title | VARCHAR(255) | |
details | TEXT | |
item | VARCHAR(80) | Empty for jobs |
quantity | INT | |
pay_cents, deposit_cents | INT | Money in cents |
hours | INT | |
due_at | BIGINT | Unix time of the current stage's deadline |
cancel_by | VARCHAR(50) | Citizen ID asking to cancel |
outcome | VARCHAR(30) | Set on close |
created_at | TIMESTAMP |
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;
NaNand 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,deliverandcollect.
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) }toConfig.Offices. - Let a judge decide disputes:
Config.ArbiterJobs = { judge = true }. SetConfig.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#
| Problem | Cause / fix |
|---|---|
| Window does not open | Check the console for database errors; requests are ignored until tables load |
| No one to select | Players must be within SignDistance before the New contract tab is opened |
| Deliver or Collect greyed out | Stand within OfficeDistance of an office, then reopen the window |
| Not enough goods | Fully decayed items do not count |
| No paper copy | Check contract_paper is in the shared items and there is inventory room |
| No dispute tab | Your job type or name is in the arbiter settings and you are on duty |
| Part of a collection stays behind | No 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-logdefaultchannel. - With honor rewards enabled, two players could farm them.
HonorMinPayonly 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