Skip to content

Exports & events ​

All sibling resources are optional. nil/false or an empty list is returned until the resource is ready or when a provider is unavailable. Money changes and vehicle ownership transfers are server-owned. Permissions use npAdmin.can with the nodes listed below; there are no ACE permissions.

Server exports ​

Export Returns Description
GetTrack(idOrSlug) Track? Published/draft track, current version.
CreateEvent(def) eventId? Create a lobby from {trackId?,type,kind?,settings,host?}; supply the player server id in host for this server export.
AddRacer(eventId, src, opts?) LobbyData?, error Add a player to an open lobby.
StartEvent(eventId, src) boolean, error Start with the required authorized host/staff player server id src.
CancelEvent(eventId, reason, src) boolean, error Cancel using the required authorized host/staff actor src; pass nil for an omitted reason.
GetSession(eventId) Standings? Current event snapshot.
GetProfile(srcOrIdentifier) Profile? Rating, rep, crew and counters.
GetRecords(trackId, class, limit?) RecordRow[] Fastest validated records.
GetPI(vehicleBuild) pi, class, stats Compute PI from handling, installed parts and tune values.
IsRacing(src) eventId? Whether a player is entered in an event.
IsVehicleLocked(plate) boolean Whether this plate is reserved by an active race/escrow provider.
useItem(event,item,slot,metadata) boolean, error Inventory USB/flare callback. Provider argument shape and consumption must be verified with the selected inventory.
registerHook(name, fn) hook id Register one of the veto hooks below. Callbacks receive the server-owned action payload and are removed when their invoking resource stops.
registerRaceType(id, definition) boolean Add an owner-scoped race type to the local registry; removed when its invoking resource stops. The np_addon vendor is unavailable in this checkout; use the resource export until its library is supplied.

CreateEvent returns an id; other methods may return nil, errorCode. Call GetTrack and GetSession for plain Lua tables suitable for serialization. Exports that move money may fail when the active framework has no money API.

Client exports ​

Export Returns Description
IsInRace() boolean Local race state.
GetRaceState() table Latest server standings/state packet.
SetHudVisible(bool) nil Hide/show the resource's race overlays.
OpenCreator(trackId?) nil Open an existing track in the creator.
Spectate(eventId) nil Request allowed spectator access.

Hooks ​

Hooks run synchronously in registration order. A veto callback returns false, reason to stop the action. Exceptions are logged and veto the action with hook_error.

Hook Payload Use
beforeJoin {source,identifier,event,opts} Decline an entry before the fee is collected.
beforeStart {event} Decline a start.
beforePayout {event,driver,position,prize} Hold/decline a payout.
beforePinkSlip {event,from,to,plate} Decline a vehicle transfer.
beforeRecord {event,driver,lapMs} Decline a record submission.
beforeDispatch {event,heat,coords} Decline a dispatch report.

Events ​

Public server-local events are np_racing:server:<name>; they are not network events. Payloads follow docs/ARCHITECTURE.md §9.

Event Payload
ready {version}
eventCreated {event}
raceStarted {event,standings}
gateCrossed {eventId,identifier,gate,lap,t,progress} (low-frequency checkpoints only)
lapCompleted {eventId,identifier,lap,lapMs,sectors}
racerFinished {eventId,identifier,result}
raceFinished {eventId,results}
recordSet {trackId,identifier,record}
flagRaised {flag}
pinkSlipTransferred {eventId,plate,from,to,auditId}
heatChanged {identifier,heat,reason}
dispatch Street incident payload including {kind,coords,eventId}; emitted locally for a server-owned dispatch listener

Client-local np_racing:client:raceStarted, :lapCompleted, and :raceFinished events allow HUD, music and phone resources to react. Net events are private transport and must not be treated as public API.

Permissions ​

Node Purpose
np_racing.admin Staff dashboard and moderation.
np_racing.creator.verify Verify/hide tracks.
np_racing.host.sanctioned Host restricted sanctioned events.
np_racing.records Void records.
np_racing.flags Review anti-cheat flags.
np_racing.spectate.all Spectate restricted sessions.
np_racing.debug Calibration/debug endpoints.

Resolution order: npAdmin.can → configured identifiers → framework admin groups → configured Discord roles (where an adapter is available). No ACE fallback exists.

RPC ​

The RPC method and exact request/response shapes, including phone aliases and client-local NUI callbacks, are defined in docs/ARCHITECTURE.md in the resource. The client NUI posts to https://np_racing/rpc; phone app calls use the racing.<method> namespace through np_phone's own authenticated dispatcher.

Runtime boundaries ​

The local vehicle service creates bounded, non-owned rental vehicles from Config.RentalModels; it does not implement database ownership transfers. Pink-slip methods return pinkslip_unavailable until a verified ownership provider is supplied. Crypto is disabled without a provider.

np_dispatch is planning-only in this checkout. Listen for np_racing:server:dispatch and route its payload to your actual dispatch system; racing does not call an invented np_dispatch export.

Prize and refund intents are durable; pending/failed intents are retried on login. Framework money APIs have no idempotency key: a crash after a successful deposit but before the database acknowledgement leaves an ambiguous paying intent requiring reconciliation. Those intents return reconciliation_required and are excluded from automatic retry. Do not assume exactly-once financial delivery.

The Lua test harness and NUI build do not replace a live FiveM/OneSync/database/inventory integration run.

Matchmaking RPCs and phone aliases ​

Server method Phone alias Request Result
queue.status (core.queue.status alias) racing.queueStatus {discipline?, class?} QueueStatus
queue.join (core.queue.join alias) racing.queueJoin {discipline?, class?} {queue, position, estimatedWait, voteEndsAt}
queue.leave (core.queue.leave alias) racing.queueLeave {discipline?, class?} QueueStatus with queued:false
queue.vote racing.queueVote {trackId} {voted, voteEndsAt}

QueueStatus={queued:boolean, discipline:string, class:string, candidates:{id,name}[], position?:number, estimatedWait?:number}. Candidate tracks are valid, verified and compatible with the selected discipline (at most eight). A queued driver's current group overrides the status request filters. When not queued, filters default to circuit/D. Queue position is one-based; wait estimates are advisory seconds. voteEndsAt is Unix seconds.

Joining accepts circuit/sprint/drift/drag and configured classes, requires the current supported vehicle to match the requested class, and rejects an existing session or queue entry. Errors include invalid_class, already_queued, already_joined, vehicle_invalid, unsupported_model and class_mismatch. Vote requires an existing queue entry and a valid verified track compatible with its discipline (not_queued, track_unverified or track_incompatible on failure). Leave requires an entry and returns fresh unqueued status; pass the desired filters to retain the matching candidate group. Phone aliases use the same authenticated dispatcher and do not bypass these checks.

Street quick-route limits ​

Both event creation and street.quickCreate validate generated routes on the server. A route contains 2–512 dense ordered finite points, measures 100 m–30 km, has segments at most 2.5 km, and produces at most 720 interpolated gates (about 150 m spacing). Quick routes are street-only quick/sprint tracks; they cannot also specify a saved track. Saved creator tracks retain the separate configured gate limit (default 256).

street.quickCreate accepts {destination:Vec3, route:Vec3[], buyIn?:number, type?:'quick'|'sprint', visibility?:'invite'|'public'|'crew'} and returns the numeric event ID. It also checks endpoint proximity (160 m), world bounds, nonzero segments and plausible route length relative to the direct distance. Errors include route_unavailable, route_invalid, invalid_args and the normal event-creation errors. GPS sampling is client-side; acceptance remains server-side.

Lobby settings and cancellation ​

Settings can change only before start, while no join or refund mutation is in flight. A ranked-kind lobby keeps its ranked status, discipline and class; hosts cannot turn ranked off or switch its matchmaking group. Every discipline must be supported by the track. Class and PI-cap changes must admit all joined drivers, and entry fees/buy-ins cannot change after creation. Changed settings other than visibility clear driver readiness; start rechecks the current vehicle/build and eligibility, and rechecks phase/cancellation after awaited database, hook and provider work.

Start reserves the lobby throughout awaited validation, so new joins, readiness/settings changes, leave/kick and host transfer cannot overlap it. Join reserves capacity and rechecks phase, cancellation and crew access after awaited hooks, vehicle/provider checks and escrow charge. If eligibility disappears after charging, the server records a compensating exact-escrow refund; a persistence failure retains the obligation for cancel-pending recovery rather than accepting a late driver.

Crew visibility uses the host's authoritative stored membership captured by the server; callers do not supply a crew ID to authorize an event. Creation requires membership, joins must belong to the captured crew, switching an existing lobby to crew visibility requires every joined driver to belong to the host's crew, and start rechecks membership. Crew-restricted events are filtered from player event listings when the requester is outside that crew.

Concurrent membership/start/cancel requests can return join_pending or refund_pending; retry after the outstanding operation finishes. Leave and kick keep the driver, pot and escrow intact if the refund intent cannot be persisted. A successful leave/cancel means the refund was delivered or durably recorded; it does not prove a pending provider deposit has completed.

Cancellation applies before a live start. It persists the event's cancel_pending marker before recording per-escrow refunds and closes only once those refund obligations are durable. Failed persistence retains the in-memory membership for retry; cancel-pending events block joins/start/settings. The server retries these events every 15 seconds. Login recovery also scans held escrow for persisted cancel-pending events, creates the missing exact-key refund intents and closes the event once no held escrow remains. Pending/failed refund delivery uses the normal reconnect outbox; ambiguous delivery still requires the staff decision below.

Startup marks stale persisted lobby/staging/countdown events cancel_pending and closes those with no held escrow; drivers recover remaining obligations on login. Resource stop attempts the same pre-start cancellation protocol. Pre-start unwind restores buckets, unfreezes/unlocks vehicles and removes session props before attempting the cancellation marker write/read. Physical cleanup completes even if marker persistence fails; financial cancellation remains pending and retryable. Stale live/results events are not automatically refunded by this sweep.

Crew invitations ​

crew.invites accepts {} and returns {invites:{crewId:number,name:string,tag:string,token:string,expiresAt:number}[]} for the authenticated identifier only (up to 20 unexpired invitations). expiresAt is Unix seconds; the phone alias is racing.crewInvites. Phone/tablet invitation cards show crew names and expiry and submit the stored token through crew.join when accepted. Players do not need to enter a numeric crew ID; the backend still verifies the invitation's recipient, token and expiry before consuming it.

Settlement persistence ​

Settlement caches payout decisions and records authoritative result obligations plus each nonzero prize's unique held intent before applying profile/season effects. While the resource keeps the session in memory, per-driver/per-step progress tracks completed writes and retries failures. Rating/stat retries reapply immutable absolute profile targets, season rounds replace/deduplicate by event ID, and lap/replay writes look up existing rows before inserting. The event becomes settled/results only after required writes complete; physical race cleanup can already have completed. A paid intent can repair result/escrow metadata without another provider deposit.

After a restart, validated result rows with payment_status='pending' and a positive prize rebuild missing held prize intents on login, then use the normal flag review and payout claim flow. Prize obligations/results are durable; the settlement progress and profile targets are in memory, so complete rating/statistics recovery across a restart is not guaranteed. This uses the existing results/payout tables; no new settlement table is required.

Review flags are persisted by kind; a failed flag write keeps the result in review rather than approving it from an empty flag query. Held prize activation and delivery require an authoritative validated result with payment status pending/paid, and zero open or void flags. Reconnect releases only validated pending obligations through these same checks. Staff resolution compares every kind in the result's flags_json with durable flag rows; missing evidence returns review_pending. After all flags are cleared, staff approval must successfully persist result validation before activating/delivering the held prize. If that validation write fails, retrying the same already-cleared flag decision can finish approval; clearing a flag alone does not authorize payment.

Recovering an ambiguous payout ​

admin.payout.reconcile requires np_racing.flags and accepts {eventId:number, identifier:string, decision:'paid'|'retry', intentKind?:string, intentKey?:string}. The four fields (eventId, identifier, intentKind, intentKey) identify one durable payout intent. Omitting the optional fields selects the race prize (prize / prize). Supply keys as strings:

Intent intentKind intentKey
Race prize prize prize
Escrow refund refund Exact escrow row ID as a string
Ambiguous migrated payment legacy legacy

The RPC accepts only an identified row in paying or reconciliation state. Confirm the money provider's actual outcome for that specific intent before choosing:

Decision Required confirmation Effect
paid Deposit was delivered Marks the intent paid without depositing money. For a prize, also marks the result paid and held event/driver escrow settled. For a refund, marks only its exact held escrow row released. Legacy reconciliation makes no guessed result/escrow changes.
retry Deposit was not delivered Changes the intent to failed with staff_confirmed_unpaid. Normal reconnect retry can deliver it later; this RPC does not immediately deposit money.

Success returns {eventId, identifier, status:'paid'|'failed'}. Errors include permission_denied, invalid_args, database_error, result_not_found, and reconciliation_required (the row is neither paying nor reconciliation, or its state changed during the decision). This staff decision resolves provider uncertainty; it is not an automatic guarantee of exactly-once money delivery.

Startup upgrades the old event/driver payout key to unique (event_id, identifier, intent_kind, intent_key), so refunds and prizes for the same driver/event can coexist. Existing paid history remains paid under legacy / legacy; unfinished old pending/failed/paying rows move to reconciliation under that key and are never automatically retried. Held review prize rows retain prize / prize and held. Back up the database before upgrading and review legacy money records against provider history.